text:
Q: Github contribution bug In the last two days, I made a couple of contributions in my repo.
But those contributions are not showing in my GitHub contributions chart.
Also in a repo, there is a wired thing going on...my image on the commit is not there.

A: In your case, the email is key.
Your commits are done with the right user.name, but the user.email must be off, meaning not the one used by your GitHub account.
Go to your repo folder and type:
cd /path/to/my/local/repo
git config user.email

Make sure the email is the correct one (the one used in your GitHub account page)
As explained in "Personalizing your profile", the email is what allows the Gravatar service to associate your user profile picture.


text:
Q: Multiple Page Development in Java with Eclipse and GWT I have been writing some basic code for an application I am designing.  I have learned the basics and gotten some simple database connection working with RPC calls etc.  What I need to do now and am completely lost (as I am traditionally a c# developer with windows forms).
In c# if I wanted a new form I would just create it, and then call the show method.
How does one create multiple pages in GWT, and switch between them?
Thanks in advance,
Chris

A: The simplest way would be to

*

*Make a new java class (GwtHome.java, GwtHelp.java etc)

*Extend these classes by using the Composite class

*Make the equivalent of a Master Page and add it to the rootPanel as a class with the appropriate headers, menu, footer and Content Placeholder (Could be any of the AbsolutePanel, VerticalPanel, HorizontalPanel objects provided by the GWT Framework)

*By clicking on the menu clear the Placeholder and add the appropriate object of GwtHome, GwtHelp etc.

After getting aquanted with the above procedure, you might want to break up the code in many files using a design pattern as suggested by Andrei.

A: Simply clear the root panel (RootPanel.get().clear()) and add the widget for your new "page", the same way you added your first one.
If you're using LayoutPanels, do RootLayoutPanel.get().clear() instead.

A: Look at Activities and Places design pattern: https://developers.google.com/web-toolkit/doc/latest/DevGuideMvpActivitiesAndPlaces
I highly recommend it for a multipage GWT app. It explains pretty well how you create different "views", that are driven by their "activities", and tied to specific "places" (pages) that users can navigate.
Typically you use a LayoutPanel as your "page" container that occupies the entire available browser window. You split this LayoutPanel into 2-3 layers (zones), like top menu, side menu, main area. Each area contains one widget, usually a ScrollPanel, FlowPanel,  or HtmlPanel. Then you use different widgets or HTML inside each of these widgets to display whatever you need. You may also create your own composite widgets that you can reuse in different pages.

redpajama_set_name: RedPajamaStackExchange


text:
Q: (Lubuntu) Play/pause key and volume keys not working I am unable to get the forward and backward keys, volume keys working, nor the play pause keys. I am using lubuntu 14.04 LTS

A: Possible solutions:

*

*Try another music player (for example, audacious, banshee,etc)
(sudo apt-get install audaciuos or sudo apt-get install banshee)

*Try another desktop environment (gnome, xfce)
(sudo apt-get install gnome or sudo apt-get install xfce)
Xfce would be a better option if your machine is rather weak (less than 4 gb RAM)
In XFCE  go to Settings Manager > Keyboard Preferences > Shortcuts.
Also your keyboard button may not not be supported yet. Then you will have to wait for updates.


text:
Q: Retrieve values from a RESTORE LABELONLY operation I want to retrieve the resulting value of the following query :
RESTORE LABELONLY FROM DISK = 'C:\folder\db-backup.bak';

After doing some search I tried:
string connection = @"data source=.\SQLExpress;initial catalog=DB;persist security info=False;user id=sa;password=12356;MultipleActiveResultSets=True;App=EntityFramework";
ExecuteSQL(connection , @"RESTORE LABELONLY FROM DISK = 'C:\folder\db-backup.bak'");

And, the ExecuteSQL is:
private void ExecuteSQL(string ConnString, string sqlText)
    {
        string result = "";
        using (SqlConnection sqlCon = new SqlConnection(ConnString))
        {
            sqlCon.Open();
            using (SqlCommand sqlCom = sqlCon.CreateCommand())
            {
                sqlCom.CommandType = CommandType.Text;
                sqlCom.CommandText = sqlText;
                sqlCom.CommandTimeout = 0;
                try
                {
                    string str = Convert.ToString(sqlCom.ExecuteScalar());
                }
                catch (Exception e)
                {
                    result = e.Message;
                }
            }
        }
    }

BUT .. the str always empty !!
The result of the query in SQL Server Management Studio is:

What I want is how can I retrieve the MediaSetID field?

A: MSDN says about the RESTORE LABELONLY operations:

Result Sets
The result set from RESTORE LABELONLY consists of a single row with
  this information.
MediaName nvarchar(128)   Name of the media.

...
So you have to use ExecuteReader method and process the columns in the returned reader (or load it to DataTable and do the same).

A: You should be using ExecuteReader() instead like below since your said command returning non-scalar value. You probably getting empty string cause the first column value of the RESTORE command is NULL per your posted SSMS result image
sqlCom.ExecuteReader()


text:
Q: Define a macro that returns the operator of an expression in Scheme? I'm looking for functionality like this:
(op (+ 1 2))
; +

I can't for the life of me seem to figure out how to do this using define-macro. Any help?
Thanks,
Edit:
It's especially confusing cause I can do:
(car '(+ 1 2))
; +

But if I do:
(define-macro (op expr)
    (car expr))

(op '(+ 1 2))

It doesn't work.

A: OP has defined the macro op as if it were a function, but Lisp macros do not work this way. The macro form is evaluated to produce a new form which substitutes for the original macro call, yet the macro arguments are passed into the macro body unevaluated. This means that within the macro body of op, car operates not on the data (+ 1 2), but rather on the data (quote (+ 1 2)).
The goal of the macro op is not to evaluate (car expr), but to produce the form (car expr) (where expr is replaced by the value of the macro argument), which is then evaluated in the REPL after the macro expansion has taken place. One could do this either using list:
(define-macro (opl expr)
  (list 'car expr))

or using quasiquotation:
(define-macro (opq expr)
  `(car ,expr))

Here, the backquote introduces a template for a list, and the comma causes the symbol expr to be evaluated to its value ((quote (+ 1 2))), and the result inserted into the list. A simple quoted list, e.g. '(car expr) would evaluate to the list (car expr), where expr is just the symbol expr. With quasiquotation, ,expr evaluates to the value of the argument provided in a macro call, e.g. `(car ,expr) --> (car '(+ 1 2)). Note that (list 'car expr) produces the same form when expr is '(+ 1 2), as with (opl '(+ 1 2))
This define-macro syntax is almost identical to the traditional defmacro syntax of Common Lisp, the difference there being that with defmacro the name of the macro goes before a list of formal parameters, e.g. (defmacro op (expr) ;...). define-macro is not available in Standard Scheme, but some Scheme implementations do support it. Guile Scheme supports both defmacro and define-macro. Both of the above macro solutions work in Guile:
scheme@(guile-user)> (opl '(+ 1 2))
$2 = +
scheme@(guile-user)> (opq '(+ 1 2))
$3 = +


text:
Q: dompdf absolte positioned elemnts pagebreak I have a dynamically generated page made up of some divs and tables and other elements inside those divs, all absolutely positioned. The lower divs can potentially have more contents in them, like comments/description, so they'll be longer then a page.
The problem is dompdf doesn't insert a page break, it just spans till end of first page and the rest of my html gets cut off...
Obviously page-break-before/after allways is not going to work since the content is dynamic, it may or may not span multiple pages depending on every entry.
Does anyone know of a simpler way to make it behave, apart from measuring content height, inserting page breaks with JS before html is generated and sent over to dompdf?

A: The issue was a large div containing all elements with in the body. Dompdf is not able to comprehend div to break into pieces. Once that was gone it arranged separate elements within the body tag just fine.

A: The reason is that dompdf doesn't insert an auto page break in elements with position:absolute. Here's the bug report: Auto page break in "position:absolute" elements not working
So without knowing the details of your CSS, I would say that the problem is not about "breaking the div into pieces" but about treating absolute as literally absolute on this very page.


text:
Q: Where can I find the AirPrint firmware update for my HP 8500A printer? I was excited when my new HP 8500A arrived this weekend because I wanted to try out its recently added AirPrint compatibility. However, I can't seem to find the requisite firmware update for the printer. Since I haven't updated the firmware when I tap print from Safari I'm told no printer can be found. What am I missing to enable AirPrint on my HP 8500a?

A: As noted in my question the printer requires a firmware upgrade to become AirPrint compatible. What is not clear on HP's AirPrint website is how one goes about updating the firmware. Playing with the menus on the printer I finally found that attempting to access the web apps menu causes the printer to check if it has the latest firmware. The printer then determined that it did not and proceeded to download and install the firmware update. After the update the iPad lists the printer as an option for printing. My programmer brain was probably making this too hard looking for a non-consumer friendly way of doing the update. That said can't say opening up the web apps menu is the most obvious way to check for a firmware update.

A: Sorry to answer a question with a question, but are these the drivers you're after?
If not have you followed the network setup for your printer (via your computer or the printer itself) and turned on ePrint / AirPrint?


text:
Q: JPA Populate Data on App Start I am working on developing a mechanism to load data into the database on boot for JPA. We are using the code first approach with JPA/Hibernate, so hibernate is actually generating the schema every time the applications starts. The kicker is I only want this to happen when the active profile is "dev" however I think I'm on the right track there. I have seen suggestions of using a bean to do this but I think I'm not quite getting it.
This is the code I has so far.
@Configuration
@Profile("dev")
public class DataInitializer {

    @Autowired
    UserService userService;

    @Autowired
    UserRepository userRepository;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Bean
    public DataInitializer dataInitializer() {

        User user = userRepository.findByUserName("admin");
        if (user == null) {
            User newUser = new User();
            newUser.setUserName("admin");
            newUser.setEmail("admin@app.com");
            newUser.setFirstName("Application");
            newUser.setLastName("Admin");
            newUser.setPassword(passwordEncoder.encode("password"));
            userRepository.save(newUser);
        }
    }
}

A: Not sure if this is the best approach but I was able to get it working with the following code.
@Component
@Profile("dev")
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public void onApplicationEvent(final ContextRefreshedEvent event) {
        User user = new User();
        user.setFirstName("Test");
        user.setLastName("User");
        user.setEmail("email@google.com");
        user.setUserName("admin");
        user.setPassword(passwordEncoder.encode("PASSWORD"));
        userRepository.save(user);
    }
}


text:
Q: show text If special user is logged I want to check if special user id is logged in WordPress. i know we have a function name is_user_logged_in() but we can't change the id of user logged in, in this function.
I need a function like this:
is_special_user_logged_in();
and check it like this:
if ( is_special_user_logged_in() ){
    echo 'special user is online';
}
i can get the user id in one of bbpress file (loop-single-reply.php) by this code. get_post_field( 'post_author', bbp_get_reply_id() ); .Now i want to check if this user id logged in wordpress show a text like "this user is online". Note that i want to check it in another user logged in WordPress. it's mean if "USER A" logged in wordpress show a text to "USER B" that "USER A" is now logged in wordpress.
finally want to inform USER A about login status of USER B

A: I am not sure exactly what you are asking for, but, if you want to target a specific user ID, just do something like:
// set special user id
$special_user_id = 5;

$current_user_id = get_current_user_id();

if ( $special_user_id == $current_user_id ){
    echo 'special user is online';
}

You get the idea.


text:
Q: 16-bit integer unsigned number into an ASCII string representing the number in hex For Asembly (68hc11) This is an assigment to handle in paper.
Write a program to convert a 16-bit integer unsigned number into an ASCII string representing the number in hexadecimal. The number is in register D0 and the string is in put in memory starting at the address in register A0.
How can i separated the bit number into 4 bits to represent the hex number in assembly, is there an instruction for doing this?
I have a problem to visualize the logic of the program, also. After separated the four bits how do i make the assembly to convert it to hex?? And to when I get the hex characters I need to compare them to each ascii possible character??
I really dont know where to start.

A: You can use bitwise shift and masking to separate the 4 bits for each hex digit. Then you can use a lookup table to map them to ascii, or use the fact that 0-9 and A-F are consecutive in the character table.


text:
Q: Determine real coordinates of an object in a video file i'm doing a project to determine the distance of a ship from camera through a video file.Only information i have is distance to horizon, is about 15 km from camera. I can track and detect the ship but how can i find the real distance to the ship

A: If you know the focal length and sensor height of the camera you can try below relation as this  discussion suggest.
distance to object (mm) = focal length (mm) * real height of the object (mm) * image height (pixels)
                          ---------------------------------------------------------------------------
                          object height (pixels) * sensor height (mm)

And the other is especially  for distant object, here you can use the equation by THE RULE OF 57 some think like
Distance of object= (Size of object * 360)/(2 * 3.14 * Angular size in degree).

And you can see more information on these link.
Hope these helpful...


text:
Q: How to refresh current view in ViewPager I am using ViewPager with views V1, V2, V3 ..... I am trying to set visibility of a LinearLayout used in each view, by clicking on a button. Through this code it apply the change on the next view instead of the current view. e.g. I am on V5. When I click it hides/show the object on V6. If I am going backwards from V6 to V5, then it applies the change on V4.
Here is the code:
public class FragmentStatePagerSupport extends FragmentActivity {
    static final int NUM_ITEMS = 10;
    MyAdapter mAdapter;
    ViewPager mPager;
    static int mNum;

    private Button btn_zoom;
    static LinearLayout LL_Head;

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

        mAdapter = new MyAdapter(getSupportFragmentManager());

        mPager = (ViewPager)findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);
        mPager.setCurrentItem(5);

        btn_zoom = (Button)findViewById(R.id.btn_zoom);
    btn_zoom.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v) {
                if (LL_Head.getVisibility() == View.VISIBLE) {
                    LL_Head.setVisibility(View.GONE);
                }else{
                    LL_Head.setVisibility(View.VISIBLE);
                }
            }
        });

.
.
.

    }

    public static class MyAdapter extends FragmentStatePagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return NUM_ITEMS;
        }

        @Override
        public Fragment getItem(int position) {
            return ArrayListFragment.newInstance(position);
        }
    }

    public static class ArrayListFragment extends ListFragment {
        static ArrayListFragment newInstance(int num) {
            ArrayListFragment f = new ArrayListFragment();
            Bundle args = new Bundle();
            args.putInt("num", num);
            f.setArguments(args);
            return f;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mNum = getArguments() != null ? getArguments().getInt("num") : 1;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.sura_vpager, container, false);

            TextView tv1=(TextView) v.findViewById(R.id.txtHead);
            tv1.setText("Fragment #" + mNum);

            LL_Head = (LinearLayout)v.findViewById(R.id.LL_Head);

            return v;
        }

Please advise
Thanks

A: In order to make a fluent experience the ViewPager not only loads the view you are currently looking at, but also the adjacent views. That means, that if you are scrolling from position 0 to position 1, what actually happens is that position 2 is loaded, so it will be ready when you scroll on. This is why the change is applied to the "next" view, rather than the current one (if you scroll from view 2 to 1, then view 0 is created).
Since you are setting the static LinearLayout in OnCreate, then it's only the last view to be created that is changed - and this will only ever be the one you are looking at, if you have scrolled to the end of the pager. Instead you should keep track of which fragment the user is looking at (ViewPager.setOnPageChangeListener()) and cache the fragment in your adapter. You then know which fragment position you want, and when you ask for it, you will just return the one you previously created (don't create a new one, then it won't work :)).
Or, the tl;dr version:
LL_Head is almost always set to be the next fragment, not the current one. Don't set it statically. Cache it in your PagerAdapter and reget it when you need it.
Edit:
Alternatively you may want to have the fragments listen to an event of sorts, which tells them whether they should show or hide the layout in question. Otherwise it will only be the current fragment that is affected by this, rather than all fragments.

A: The numbering in Java starts from 0. Thus when you want to set the 5th item, you have to call mPager.setCurrentItem(4);
Hope this helps!


text:
Q: Отправка .xls-файла в сервлете На JSP я отправляю .xls-файл по запросу пользователя. Хочу так же сделать в сервлете:
out.clear();
out = pageContext.pushBody();
response.setHeader("Content-type","application/vnd.ms-excel");
response.setHeader("Content-disposition","attachment; filename=AirAstana - Sessions.xls");
wb.write(response.getOutputStream());

Но в сервлете нет pageContext и out.clear() - есть только out.close() и out.flush().
Как можно в сервлете отправить файл?

A: А так?
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
    resp.setContentType("application/vnd.ms-excel");
    resp.setHeader("Content-disposition","attachment; filename=\"AirAstana - Sessions.xls\"");
}


text:
Q: How can I stop the results from this SQL query replacing prior results? I'm using the following HTML form
<form method="POST">
    <input type="number" placeholder="first" name="first">
    <input type="number" placeholder="last" name="last">
    <input type="submit">
</form>

Along with this PHP
$first = $_POST["first"];
$last = $_POST["last"];

$query = "SELECT * FROM posts ORDER BY TimeStamp DESC LIMIT $first, $last";

This successfully returns the entries between first and last when the values are posted through the form. However any priory fetched results disappear when a new query is made. How can I make it so that new results are added to the BOTTOM of the list of old results when a new request is posted through the form?

A: Let me show you a very basic example of what you would have to try.
We have a page in HTML with a form and a div to store the results.
In that document we have aswell a little Javascript code to handle the form submit event.
For the Ajax query I did it the lazy way using jQuery. If you are not able to use that library in your code please let me know it.
myPage.html
<!DOCTYPE html>

    <meta charset="UTF-8">

      <form id="myForm">
        <input id="inputFirst" type="number" placeholder="first" name="first">
        <input id="inputLast" type="number" placeholder="last" name="last">
        <input type="submit">
      </form>

Javascript code at the same document (myPage.html).

Now some PHP in a different document (myAmazingScript.php).
(You could do it in the same document but it's a little more tricky and not necessary at all).
I don't know which method are you using to make the queries to the database. I chose prepared staments for the example because it's safe, easy and still very extended.
<?php

// Creating connection
$mysqli = new mysqli('localhost', 'user', 'password', 'myAmazingDatabase');

// Checking connection
if (mysqli_connect_errno()) {
  echo "Connect failed: %s\n", mysqli_connect_error();
  exit();
}

$first = $_POST["first"];
$last = $_POST["last"];

$query = "SELECT * FROM posts ORDER BY TimeStamp DESC LIMIT ?, ?";

if ($stmt = $mysqli->prepare($query)) {
  $stmt->bind_param('ii', $first, $last);
  $stmt->execute();
  $result = $stmt->get_result();

  while ($row = $result->fetch_assoc()) {

    echo 'First field: ' . $row['myAmazingFirstField'] . '
';
    echo 'Second field: ' . $row['myAmazingSecondField'] . '
';
    // Etc...
  }

  $stmt->free_result();
  $stmt->close();
}

I didn't try it but I think I didn't forget anything important. Let me know if you have any questions.
(Of course, you would have to change many "amazing names")


text:
Q: How can I open the Contacts activity just to view the contact's information, not allowing the user to click (or touch) anything? I want to open the native Contact activity, not the Contacts list as I already have done that, but a particular contact information using the native activity.
The special requirement here is that all I want is to display the contact's information but not allowing the user to click anything.
I can open the activity with this code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode != 1) {
        return;
    }

    if(resultCode != Activity.RESULT_OK) {
        return;
    }

    Uri selectedUserUri = data.getData();
    this.onContactSelected(selectedUserUri);
}

private void onContactsButtonClick() {
    startActivityForResult(new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI), 1);
}

private void onContactSelected(Uri selectedUserUri) {
    startActivityForResult(new Intent(Intent.ACTION_VIEW, selectedUserUri), 2);
}

I need the user not to be able to click anything because that's not part of the functionalities of my application, in the worst case I would need the activity to report me the clicked phone number or e-mail address instead of opening the dialer or a web browser.
Any help will be greatly appreciated.
Mike

A: Try this below code for start pick contacts activity like this code write button click event contacts:
try
{
     Intent intent = new Intent(Intent.ACTION_PICK);
     intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
     startActivityForResult(intent, PICK_CONTACT);
}
catch (Exception e) {
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}

after get contact phone number below code:
@Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
      try
      {

      if (requestCode == PICK_CONTACT)
      {
          Cursor cursor =  managedQuery(intent.getData(), null, null, null, null);
          cursor.moveToNext();
          String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
           String  name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
           String phone=cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
           String phoneNumber="test";

          if ( phone.equalsIgnoreCase("1"))
              phone = "true";
          else
              phone = "false" ;

          if (Boolean.parseBoolean(phone))
          {
           Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
           while (phones.moveToNext())
           {
             phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
           }
           phones.close();
          }
          Toast.makeText(this, "You are selected Contact name "+name, Toast.LENGTH_LONG).show();
          if(phone_no.getText().length()!=0)
          {
              phone_no.setText(phone_no.getText().toString()+","+phoneNumber);
          }
          else
          {
              phone_no.setText(phoneNumber);
          }

      }
        }
      catch (Exception e) {
        // TODO: handle exception
        }
    }

this function pick a contact assign phone_no Editext this is not allow make a call!
Note:this function copy paste after onCreate() method  like below format:
@Override
   public void onCreate(Bundle savedInstanceState) {
     ------------Your Code ---------
}
@Override
   public void onActivityResult(int requestCode, int resultCode, Intent intent)
   {
       ------------
   }


text:
Q: ASP.NET Add-migration issue I moved from one PC to a new PC where I had to re-install every thing including VS2017. But when I run my same project from old PC to new PC (both Windows 10) app runs fine. I then added a new model and when I run the following Package Manager console command I get the following error.
PM> add-migration myMigration -context TestProjContext

Error:

An error occurred while calling method 'ConfigureServices' on startup class 'Startup'. Consider using IDbContextFactory to override the initialization of the DbContext at design-time. Error: Could not find 'UserSecretsIdAttribute' on assembly 'ef, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
  No parameterless constructor was found on 'MyProjContext'. Either add a parameterless constructor to 'MyProjContext' or add an implementation of 'IDbContextFactory' in the same assembly as 'MyProjContext'.

UPDATE

*

*This project was upgraded from VS2015 to VS2017 and hence the project.json was gone (replaced by .csproj. And if I recall correctly this is the first time since moving to VS2017 that I've run the add-migration command

Startup.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using TestProj.Data;
using TestProj.Models;
using TestProj.Services;

namespace TestProj
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsDevelopment())
            {
                // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets();
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connection = @"Server=MyWin10Desktop;Database=MySQL2012Db;Trusted_Connection=True;";
            services.AddDbContext<TestProjContext>(options => options.UseSqlServer(connection));

            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();
            services.AddDistributedMemoryCache();
            services.AddSession();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseIdentity();
            app.UseSession(); //me: must come before app.UseMvc()

            // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

UPDATE 2:
TestProj.csproj file: [Note: Since app was upgraded from VS2015 to VS2017 the upgrade wizard removed the project.json and added this .csproj file instead
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <PreserveCompilationContext>true</PreserveCompilationContext>
    <AssemblyName>ABCTest</AssemblyName>
    <OutputType>Exe</OutputType>
    <PackageId>ABCTest</PackageId>
    <UserSecretsId>aspnet-ABCTest-6af8ade3-87ff-4468-a9ce-8bb69c696ab8</UserSecretsId>
    <RuntimeFrameworkVersion>1.1.1</RuntimeFrameworkVersion>
    <PackageTargetFallback>$(PackageTargetFallback);dotnet5.6;portable-net45+win8</PackageTargetFallback>
  </PropertyGroup>

  <ItemGroup>
    <None Remove="Properties\PublishProfiles\ABCTestP.pubxml" />
    <None Remove="Properties\PublishProfiles\FolderProfile.pubxml" />
    <None Remove="Properties\PublishProfiles\FolderProfile1.pubxml" />
  </ItemGroup>

  <ItemGroup>
    <None Update="wwwroot\**\*;Views\**\*;Areas\**\Views">
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </None>
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="bootstrap" Version="2.3.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration.Tools" Version="1.1.0-preview4-final" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.1" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0">
      <PrivateAssets>All</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="1.1.1" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />
    <PackageReference Include="BundlerMinifier.Core" Version="2.3.327" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="1.1.2" />
    <PackageReference Include="EPPlus.Core" Version="1.4.0" />
  </ItemGroup>

 <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />
  </ItemGroup>

</Project>

A: The relevant part is this:

No parameterless constructor was found on MyProjContext. Either add a parameterless constructor to MyProjContext or add an implementation of IDbContextFactory in the same assembly as MyProjContext

The IDbContextFactory way is the prefered way of achieving this in Entity Framework Core, because you can use the same tooling as in Startup.cs.
From the EF Core documentation:

You may also provide an implementation of IDbContextFactory<TContext>. EF tools can use this factory to create an instance of your DbContext. This may be required in order to enable specific design-time experiences such as migrations.
  Implement this interface to enable design-time services for context types that do not have a public default constructor. Design-time services will automatically discover implementations of this interface that are in the same assembly as the derived context.

For example:
public class DbContextFactory : IDbContextFactory<MyProjContext>
{
    public MyProjContext Create()
    {
        var environmentName = Environment.GetEnvironmentVariable("Hosting:Environment");
        return Create(Directory.GetCurrentDirectory(), environmentName);
    }

    public MyProjContext Create(DbContextFactoryOptions options)
    {
        return Create(
            options.ContentRootPath,
            options.EnvironmentName);
    }

    public MyProjContext Create(string basePath, string environmentName)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(basePath)
            .AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.{environmentName}.json", true)
            .AddEnvironmentVariables();

        var Configuration = builder.Build();

        var connectionName = nameof(MyProjContext);
        var connectionString = Configuration.GetConnectionString(connectionName);
        if (String.IsNullOrWhiteSpace(connectionString) == true)
            throw new InvalidOperationException($"Could not find a connection string named '{connectionName}'.");

        // init SQL server
        var optionsBuilder = new DbContextOptionsBuilder<MyProjContext>();
        optionsBuilder.UseSqlServer(connectionString);

        return new MyProjContext(optionsBuilder.Options);
    }
}


text:
Q: why 0.0f/0.0f doesn't generate any runtime error? Recently i tested following program & i was expecting runtime error but it shows "nan" as output. Why & How? I am using g++ compiler.
#include <iostream>
int main()
{
   float f=0.0f/0.0f;
   std::cout<<f;
   return 0;
}

Same way i also tried similar type of program in Java & C# & it shows again "nan" as output.
class Test
{
   public static void main(String args[])
   {
       float f=0.0f/0.0f;
       System.out.println(f);
   }
}

class Test
{
   public static void Main(string[] args)
   {
       float f=0.0f/0.0f;
       Console.Write(f);
   }
}

I want to know that how floating point arithmetic is implemented & how it differes from integer arithmetic. Is it undefined behaviour in case of C++? If yes, why?
Please help me.

A: From http://en.wikipedia.org/wiki/NaN#Operations_generating_NaN:

Operations generating NaN
There are three kinds of operations that can return NaN:

*

*Operations with a NaN as at least one operand.

*Indeterminate forms

*

*The divisions 0/0 and ±∞/±∞

*The multiplications 0×±∞ and ±∞×0

*The additions ∞ + (−∞), (−∞) + ∞ and equivalent subtractions

  ... etc.

A: It is because that by default, the C++ run-time libraries mask all floating-point exceptions. Therefore, computations result in NAN or INFINITY, rather than an exception.  If you want exceptions, you can use function _controlfp_s on Windows to unmask the floating-point.  exceptions
The following code raise the exception. Compiled and Run with VS2010, Win32 configuration.
#include <float.h>

int main()
{
    _controlfp_s(NULL, 0, _MCW_EM); // enable all floating point exceptions

    float n = 0;
    float f= 0.0f/n;

    return 0;
}

A: nan stands for not a number. Dividing by the integer 0 is always a mistake, because you cannot divide by 0 in mathematics. Therefore many languages throw an exception when you divide by the integer 0.
It would be less reasonable to do this with floating point numbers because floating point calculations are not exact. For example, a calculation could result in 0.0f because 0.0f is the closest floating point value to the answer, not because the true value of the answer is mathematically 0. Therefore trying to divide by the floating point value 0.0f might not be a consequence of an incorrect algorithm. nan essentially means that the answer to your calculation could not be determined because it involved the division of two numbers so small it was impossible for the computer to distinguish them from 0.

A: you must know that division on zero is allowed with floats so this:
1.0/0.0

is equal to infinity and this:
1.0/-0.0

is equal to negative infinity (-0.0 is negative zero like 1/0- in mathematics) and this:
0.0/0.0

is NAN which means not a number, this is exactly undetermined in mathematics abbreviation.
that's with floats but ints will throw a runtime error, you may ask why, it's because of how floats are represented in binary form, you can read about it here:
http://floating-point-gui.de/formats/fp/
in c#, you can say Double.PositiveInfinity, Double.NegativeInfinity and Double.NaN


text:
Q: What is the best way to set ports in PM2? I'm unsure of the best way to set ports in PM2. I don't see this documented anywhere. I'm using a front-facing nginx server which listens on proxys to specific ports on the backend that represent the node servers. How do I best set this type of configuration up?

A: One method is with env in process.json
{
        "name"       : "MyApp",
        "script"     : "./MyApp/app.js",
        "instances"  : "1",
        "exec_mode"  : "cluster_mode",
        "env": {"PORT": 3030}
}


text:
Q: Networking stop/waiting error I wanted to set up a bridge connection for my VMs (I am using KVM).
I modified my etc/network/interfaces file and its contents are:
auto lo
iface lo inet loopback
auto br0
iface br0 inet dhcp
bridge_ports eth0
bridge_fd 9
bridge_hello 2
bridge_maxage 12
bridge_stp off

After modifying the etc/network/interfaces file I wanted to make them active so I run the following command:
sudo /etc/init.d/networking restart

but I got the following output:
Running /etc/init.d/networking restart is deprecated because it may not enable again some interfaces

so I tried restarting network by the following command:
sudo service networking stop && sudo service networking start

I get the following output:
stop: unknown instance:

If I do :
sudo service networking start

I get :
networking stop/waiting

and my net has stopped working after that. I am using Ubuntu 12.04 and have a wired DHCP connection.
Please try to resolve this issue so that I can successfully configure bridge for my VMs and get back my net connection.

A: As you found you are getting a warning doing it the way you mentioned. If your physically at your computer do this:
sudo ifdown -a
sudo ifup -a

For SSH session one should read:
http://codeghar.wordpress.com/2011/07/18/debian-running-etcinit-dnetworking-restart-is-deprecated-because-it-may-not-enable-again-some-interfaces/
Anyhow for SSH you might do this:
sudo nohup sh -c "ifdown eth0 -a && ifup eth0 -a"

another suggestion about bridging is mentioned here:
http://codeghar.wordpress.com/2011/07/18/debian-running-etcinit-dnetworking-restart-is-deprecated-because-it-may-not-enable-again-some-interfaces/#comment-2108

A: I did sudo /etc/init.d/networking restart and my net started working.
Also, the command:
brctl show
shows my bridge is created.
My problem is solved!


text:
Q: Python is not existing when ran from System Scheduler I have made a batch script which runs a Python application. This batch script is triggered by a program called System Scheduler, but when the program runs the batch script, it says that Python is not exisiting.
When I run my batch script manually, I get no error.
Can anyone explain this or come up with a solution?

A: Probably the $PATH is not set properly when called from scheduler. Try changing the command called from
python yourscript.py

to
/usr/bin/python yourscript.py

(Substitute the actual path to python on your system, which you can find with:
$ which python

A: Check the user context that System Scheduler is running under and ensure the location of Python is in it's PATH.


text:
Q: select one element & not select parent I use in listener jquery,i want some thing $(".parentClass:not(.childClass)").on("click",function(){}),but this code not work and when I click child div listener is run,I want only  parent is run;

A: You can use  event.stopPropagation() for preventing parent event handler action

// Handler for parent
$(".parentClass").on("click", function(e) {
  alert('hi')
});

// Handler for child
$('.childClass').click(function(e) {
  e.stopPropagation();
  // preventing any parent handlers action
});

  parent1

    child

event.stopPropagation() : Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Taken from https://api.jquery.com/event.stoppropagation/

A: You need to check event target like so:
$(".parentClass").on("click",function(e){
   if($(e.target).hasClass('childClass')){
       return;
   }

   //do staff on exectly parent click
})


text:
Q: How to format longs in android to always display two digits I have a countdown timer which shows seconds from 60 to 0 (1 min countdown timer). When it reaches 1 digit numbers such as 9,8,7.. it shows 9 instead of 09. I tried using String.format("%[B]02d[/B]", x);   where I converted x from long to string. It didn't work.
I want an equivalent of String.format("%2d", 1)

A: You can accomplish it with DecimalFormat:
NumberFormat f = new DecimalFormat("00");
long time = 9;
textView.setText(f.format(time));

Output:
09

Or you can use String.format() as well:
String format = "%1$02d"; // two digits
textView.setText(String.format(format, time));

A: Why not just use an if statement?
String str = x < 10 ? "0" + String.valueOf(x) : String.valueOf(x);

That should do the trick.

A: Use: text.setText(String.format("%02d", i)); where i is the integer value

A: TextView time;
int hour=0,minute=0,second=0;
time.setText((String.format("%02d", hour))+":"+(String.format("%02d", minute))+":"+(String.format("%02d", second)));

time to TextView

A: Try using this:
tv.setText(new DecimalFormat("##").format(var));


text:
Q: How to select random words with unique starting characters I need a MySQL query to select random words from English dictionary database. However, in my case, the words produced by the query need to be unique in terms of their first two starting characters.
For example, this query does the job of selecting random words, but as you can see, it produces results where the words start with the same characters.
SELECT DISTINCT(word) FROM en_english479k WHERE CHAR_LENGTH(word)>=12 ORDER BY RAND() LIMIT 10

The effect is visible in this screenshot:

I need to generate words that are completely unique in terms of their starting characters (first two in my case).

A: I don't generally recommend this approach, but it might be the simplest way to do what you want:
select e.word
from (select e.*
      from en_english479k e
      where char_length(word) >= 12
      order by rand()
     ) e
group by left(word, 2)
order by e.word
limit 10;

This uses the MySQL (mis)feature of allowing the group by and select to not be compatible.  Because you want a random word -- and not say the first alphabetically -- I'm more comfortable recommending using this feature in this case.

A: It took me a while, but I think I just figured it out.
SELECT
word, left(word, 2)
FROM en_english479k
WHERE word IN
(
SELECT word FROM en_english479k WHERE CHAR_LENGTH(word) >= 12
)
group by left(word, 2)
ORDER BY RAND()
LIMIT 50


text:
Q: How to send any data over python3 sockets? I am new in python sockets, and I want to write a send(data: any), which will any types of data over a socket, but there are some problems. I did it like this:
    def send(self, data: any):
        if type(data) is not bytearray:
            b = bytearray()
            b.extend(map(ord, data))
            self.__s__.sendall(b) # s is the socket
        else:
            self.__s__.sendall(data)

    def recv(self, len_of_packet: int):
        buf = bytearray()
        while len(buf) < len_of_packet:
            buf = buf.append(self.__s__.recv(len_of_packet - len(buf)))
        return buf

but it gives me
    buf = buf.append(self.__s__.recv(len_of_packet - len(buf)))
TypeError: 'bytes' object cannot be interpreted as an integer

I did this loop in recv() because TCP sockets can send only part of the data, I also did if type(data) is not bytearray: because sendall() wants only bytes, but for some reason it does not work. I tried to use bytes(), but there were another errors. So, what is the most pythonic way to send any data and receive it all at the other end? Particularly i want to send pictures and text. And how to handle the fact recv() returns str(), which I want to be bytes?
Calling example:
image = open('image.jpg', 'rb').read()
con.send(image)

and at the other end:
image = con.recv(size)

A: You are misinterpreting how bytearray.append() works:

help(bytearray.append)
B.append(int) -> None

Append a single item to the end of B.

You want to use bytearray.extend():

help(bytearray.extend)
B.extend(iterable int) -> None

Append all the elements from the iterator or sequence to the end of B.

There are a few other problems with you code. E.g. a TCP socket's recv will return an empty bytearray once the connection is closed. You'd have an infinite loop in this case if the connection was disrupted prematurely.

A: I have probably fixed the issue by making functions like this:
def send(self, data: any):
    if type(data) is int:
        data = str(data)
    if type(data) is bytes or type(data) is bytearray:
        self.__s__.sendall(data)
    else:
        b = bytearray()
        b.extend(map(ord, data))
        self.__s__.sendall(b)

def recv(self, len_of_packet: int):
    data = bytearray()
    while len(data) < len_of_packet:
        packet = self.__s__.recv(len_of_packet - len(data))
        if not packet:
            return None
        data.extend(packet)
    return data

At least this code solves my problem because I've successfully sent a picture over a socket


text:
Q: JavaFX runtime components are missing error in Java Gradle Project I started a Gradle project with java and I wanted to add JavaFx Library but when I run my application I'd got "JavaFX runtime components are missing, and are required to run this application".
This is my Gradle file:
plugins {
    id 'java'
    id 'org.openjfx.javafxplugin' version '0.0.9'
}

group 'org.personal'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

javafx {
    version = "15.0.1"
    modules = [ 'javafx.controls', 'javafx.fxml' ]
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
}

test {
    useJUnitPlatform()
}

And this is the main class:

package client;

import javafx.application.Application;
import javafx.stage.Stage;

public class ClientApp extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

    }
}

And this is my "Edit Configuration": Edit Configuration here

A: you need to add the JavaFX JDK libs to the path. Otherwise, you need to use JDK 8 (JDK1.8) which integrates the JavaFX SDK


text:
Q: Configure repeatInterval for local notifications in iOS in react-native I am using PushNotificationIOS API in react-native to schedule local notifications for my mobile app. I want to configure repeating local notifications for the app and I see that there is an option to configure repeatInterval for local notifications in native iOS but I didn't find any such option in the PushNotificationIOS API. If anyone has configured repeatInterval for local notifications in react-native, please let me know.
I think I would need to add the functionality into the PushNotificationIOS API to also accept a repeatInterval. So, I checked how to configure repeatInterval in native iOS and found that I need to use instance of NSCalendarUnit to configure the repeat interval. I don't have any experience in objective-c and not sure how to convert the repeatInterval from js to objective-c.


text:
Q: Typescript trying update a boolean property in my object receives "TypeError: Cannot assign to read only property" If I have object that has been already defined, how can I change the value of a property? Do I have any other alternatives?
export interface myTest {
    shouldChange: boolean; // <-- not using readonly
}

const testObj = {
    shouldChange: false
} as myTest;

// later on
testObj.shouldChange = true // <-- this throws the following error

TypeError: Cannot assign to read only property 'shouldChange' of object '[object Object]'

A: I'm not sure whether this code is being used in an NGRX context or not, but eitherway, consider trying the following:
testObj = {...testObj};

In the NGRX context, the data you get from the store is in a freeze-state and is readonly. With this code (which is the spread operator and the equivalent of testObj = Object.Assign({}, testObj)) you basically create a brand new object that looks identical to the previous testObj. The only difference is, this object does not have the freeze-state and can be adjusted freely.
If you have deeper objects and you need to adjust those you have to use cloneDeep from lodash
export interface myTest {
    shouldChange: boolean;
    somethingElse: DeepObject;
}

export class DeepObject {
    index: number;
}

testObj = _.cloneDeep(testObj);
testObj.somethingElse.index = 42; // <-- Does not throw errors

A: one of options you can do here, is to access to property with [] brackets and assign to it type any
export interface myTest {
    shouldChange: boolean; // <-- readonly
}

const testObj = {
    shouldChange: false
} as myTest;

testObj['shouldChange' as any] = true;


text:
Q: Toggle activated window in React I am new to React and can not figure out the best way how to toggle the active state between two elements. Here is my code:
import React from 'react';
import styled from 'styled-components';
import Icon1 from '../../../../img/icon1.png';
import Icon2 from '../../../../img/icon2.png';

const Container = styled.div `
    width: 100%;
    height: 180px;
    margin-top: 30px;
    display: flex;
`;

const Option1 = styled.div `
    width:50%;
    padding: 15px;
    background-color: ${props => props.active ? 'var(--primary)' : 'var(--background)'};
    border-radius: 24px 0px 0px 24px;
    border: var(--border_primary);
`;

const Option2 = styled.div `
    width:50%;
    padding: 15px;
    background-color: ${props => props.active ? 'var(--primary)' : 'var(--background)'};
    overflow: hidden;
    border-radius: 0px 24px  24px 0px;
    border: var(--border_primary);
    color: white;
`;

const Image = styled.img `
    border-radius: 50%;
    background-color: var(--subtle)
`

const Text = styled.p `
    color: ${props => props.active ? 'var(--on_primary)' : "black"};
`

class Contribution extends React.Component {

    toggleActive = () => {
        console.log('activated')
        this.props.active = !this.props.active;
    };

    render() {
        return(
            <Container>
                <Option1 onClick={this.toggleActive}>
                    <Image src={Icon1}/>
                    <Text>Chcem finančne prispieť konkrétnemu útulku</Text>
                </Option1>
                <Option2 active onClick={this.toggleActive}>
                    <Image src={Icon2}/>
                    <Text>Chcem finančne prispieť celej nadácii</Text>
                </Option2>
            </Container>
        )
    }
}

export default Contribution;

Obviously the way I have it now throws an error when I click either on Option1 or Option2 element. I am sure there is a good and painless way how to make this work. One of them must be pre-set active on loadout.
What I need to achieve is, when user clicks on either of the elements, it's background and text color will change and It will pass the property of either element based on this active state to state - but did not get to this point yet.
What is the best way to approach this?

A: Updated Code (Added 2 states for individual options):-
import React from "react";
import styled from "styled-components";

const Container = styled.div`
  width: 100%;
  height: 180px;
  margin-top: 30px;
  display: flex;
`;

const Option1 = styled.div`
  width: 50%;
  padding: 15px;
  background-color: ${({ active }) =>
    active ? "var(--primary)" : "var(--background)"};
  border-radius: 24px 0px 0px 24px;
  border: var(--border_primary);
`;

const Option2 = styled.div`
  width: 50%;
  padding: 15px;
  background-color: ${({ active }) =>
    active ? "var(--primary)" : "var(--background)"};
  overflow: hidden;
  border-radius: 0px 24px 24px 0px;
  border: var(--border_primary);
  color: white;
`;

const Image = styled.img`
  border-radius: 50%;
  background-color: var(--subtle);
`;

const Text = styled.p`
  color: ${({ active }) => (active ? "var(--on_primary)" : "black")};
`;

class Contribution extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeOption1: false,
      activeOption2: false,
    };
  }
  toggleActiveOption1 = () => {
    this.setState({
      activeOption1: true,
      activeOption2: false,
    });
    console.log("activated", this.state);
  };
  toggleActiveOption2 = () => {
    this.setState({
      activeOption2: true,
      activeOption1: false,
    });
    console.log("activated", this.state);
  };

  render() {
    return (
      <Container>
        <Option1
          active={this.state.activeOption1}
          onClick={this.toggleActiveOption1}
        >
          <Text>Chcem finančne prispieť konkrétnemu útulku</Text>
        </Option1>
        <Option2
          active={this.state.activeOption2}
          onClick={this.toggleActiveOption2}
        >
          <Text>Chcem finančne prispieť celej nadácii</Text>
        </Option2>
      </Container>
    );
  }
}

export default Contribution;


text:
Q: SQL performance for a returning stored procedure I have been asked the following question, what would you look into when you want to improve a stored procedure performance? The stored procedure is returning some value and have three joins in it.
Other than making sure the joins are well written what one can do to make it perform better? This was a general question and no code was provided.
Any ideas?

A: Check the indexes on the tables used in the joins.  Particularly, are the columns used in the joins indexed?
Example -
SELECT     *
FROM       SomeTable a
    JOIN   SomeOtherTable b on a.ItemId = b.ItemId

If these tables are large, indexing ItemId in both tables will typically help performance a lot.
You should do the same thing for any columns that are used in the WHERE clause, if your query has one.
WHERE  a.ProductId = @SomeVariableYouPassedToTheStoredProc

Indexing ProductId may help in this case.
Query performance is something you could go into a rabbit hole on, but this is a logical (and quick) place to start.

A: The fact that it's a stored procedure has little to nothing to do with it. Optimise the sql inside.
As to how, all the usual suspects, including written by the sort of eejit who thinks you can guess what's wrong.
Copy the sql from the proc into a suitable tool, prefix it with Explain to see what's going on.

A: I presume there are others options. For example:
1. each of those joins could use restrict conditions which  looks like 'and permited_used_name = (select user_name from user_list where )'. The value could be derived once during procedure start (I mean the first string of procedure) to not overload the DB by many similar queries.
2. starting from Oracle11 you could declare a function as function with cached results (i.e. function is calculated once and isn't recalculated each time when it is invoked) defining a set of tables which changes invalidate cache.
At any case the question is mostly DB-specific.

A: Run the Query Analyser on the SQL statement

A: There are a lot of things you can do to optimize procedures, but it sounds like your SQL statement is pretty simple. Some things to watch out for:

*

*Inline functions. These can cause SQL to do a row by row evaluation and slow things down

*Data conversions on join statements. These can prevent indexes from being used.

*Make sure columns being joined on/in the where clause are indexed (for large data sets)

You can check out this website for more performance tips, but I think I covered most of what you need for simple statements:
SQL Optimizations School


text:
Q: Flexible array member in C-structure Quoting from the C-std section 6.7.2.1,
struct s { int n; double d[]; };

This is a valid structure declaration. I am looking for some practical use of this kind of syntax. To be precise, how is this construct any more or less powerful than keeping a double* as the 2nd element? Or is this another case of 'you-can-do-it-in-multiple-ways'?
Arpan

A: The primary advantage is that a flexible array member allows you to allocate a single block of memory for the array along with the other data in the struct (with a pointer, you'd typically end up with two separately allocated blocks).
It's also useful with data transmitted by quite a few network protocols, where the incoming stream is defined the same way -- an integer defining a length, followed by that many units (typically bytes/octets) of data. You can (typically) use a type-pun to overlay a struct with a flexible array member onto a buffer filled with such data, and work with it directly instead of having to parse it out into pieces and then work with the pieces individually.

A: You can use it to add header fields to dynamically allocated arrays, the most common one of which would be its size:
struct int_array
{
    size_t size;
    int values[];
};

struct int_array *foo = malloc(sizeof *foo + 42 * sizeof *foo->values);
foo->size = 42;

...

for(size_t i = 0; i < foo->size; ++i)
    foo->values[i] = i * i;

You could achieve similar results by using an int * member instead and allocating the array seperately, but it would be less efficient both in terms of memory (additional pointer, heap management for 2nd memory block) and runtime (additional indirection, 2nd allocation).

A: The C FAQ answers precisely this question.  The quick answer is that this structure will include the double array inside the structure rather than a pointer to an array outside the structure.  As a quick example, you could use your structure as in this example:
struct s mystruct = malloc(sizeof(struct s) + 5 * sizeof(double));
s.n = 12;
s.d[0] = 4.0;
s.d[1] = 5.0;
s.d[2] = 6.0;
s.d[3] = 7.0;
s.d[4] = 8.0;

And so on - the size of the array you care about is included in the allocation, and then you can use it just like any array.  Normally such a type contains the size as part of the structure, since using the + trick to skip through an array of type s will be necessarily complicated by this situation.
To your added question 'how is this construct any more or less powerful than keeping a [pointer] as the 2nd element?', it's no more powerful per se, but you don't need to keep a pointer around, so you would save at least that much space - also when you are copying the structure, you would also copy the array, rather than a pointer to an array - a subtle difference sometimes, but very important other times.  'You-can-do-it-in-multiple-ways' is probably a good explanation, but there are cases where you would specifically want one design or the other.

A: I've seen this used on Windows for strings which are tagged by their length. The character data is stored directly after the length in memory, keeping everything together neatly.
typedef struct {
    SIZE_T bytes;
    TCHAR chars[];
} tagged_string;


text:
Q: How to map an object's properties to an ordered list of objects? How can one map an object's properties to an ordered list of objects using automapper? The source type and it's properties are known at compile time. The index at which each property should be in the destination must be resolved at runtime. Validation that every source property is mapped is important.
Consider this example of what I'm trying to achieve:
public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Id { get; set; }
}

var configuration = new MapperConfiguration(cfg =>
{
    var map = cfg.CreateMap<Employee, List<object>>(MemberList.Source);
    //  some map configuration should go here.
    //  Preferrably one that maps a source property to an object in list at specified index.
}
configuration.AssertConfigurationIsValid();
var mapper = configuration.CreateMapper();
listOfProperties = mapper.Map(new Employee() { FirstName = "foo", LastName = "bar", Id = 0 });
// listOfProperties is a list of elements: { 0, "foo", "bar" };
// Order of elements in list should be a part of configuration

Can something like that be accomplished with automapper at all? If there is more than one suitable way to accomplish this, what are they?

A: It is not very pretty but something like this will do:
var configuration = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Employee, List<object>>(MemberList.Source).ConvertUsing(
        (employee, _) => new List<object>()
        {
            employee.Id,
            employee.FirstName,
            employee.LastName
        });
});


text:
Q: Scraped image not displaying using Simple_HTML_DOM Alright. I am scraping a poster from IMDb, and for the life of me, I cannot figure out why it is not displaying — I just get a little question mark like the image is missing. This is my current code:
<?php
$p = 1;
foreach($movie_html->find("div[class=image]") as $poster1)
{
    foreach($poster1->find("img") as $poster2)
    {
        $p++;
        if ($p == 1) break;
    }
}
$poster3 = $poster2->src;
?>

<img src="<?php echo($poster3); ?>" height="300"/>

When I simply echo the $poster3 variable it returns the proper URL of the image (so I know that code is working like it should), but on the actual webpage, I don't see the image. Instead, all I get is a little question mark as if the image is not at the specified URL. When I right click on that box, and force Safari to open the image in a new tab, I see the image just sitting there all nice and pretty! But for some reason, it is not displaying on my site.
Any ideas? Is IMDb locking me out to prevent scrapers? Or is there something in my code?

A: How does this work for you?
<?php
/* getIMDB.php
   -- displays movie poster (and its url as a tool-tip) from an IMDB page
*/
    include_once('../simpleHTML/simple_html_dom.php');

    $url = "http://www.imdb.com/title/tt0246578/";
    $movie_html = file_get_html($url);
    outputImg($movie_html);

function outputImg($movie_html)
{
    $p = 1;
    foreach($movie_html->find("div[class=image]") as $poster1)
    {
        foreach($poster1->find("img") as $poster2)
        {
            $p++;
            if ($p == 1) break;
        }
    }
    $poster3 = $poster2->src;
    echo "";
}
?>


text:
Q: Creation Aggregate Using Value Object Can value object create an aggregate?
i think if a value object can reference to another aggregate root it will can create another aggregate.

A: There's no design rule that I know of which discourages to place a factory method for ARs on a VO. I see it the same as having a factory method on an AR to create another AR.
However, if the creation process becomes complex enough to require external dependencies then a VO may not good home for that factory method.
In that case it may be better to pass the VO as a dependency to the creation process living in a dedicated factory class.


text:
Q: Run method from jar file they have extends a Class Can i run a method from am Plugin like onEnable(), my script doesnt work. :(
The extended Class:
package de.R3N3PDE.X.API;
import de.R3N3PDE;

public class JavaPlugin{
    Server server;
    public ServerManager getServer(){
        return new ServerManager(server);
    }

    public ServerManager setServer(Server s){
        server = s;
    }

    public PluginLogger getLogger(){
        return new PluginLogger(server);
    }
}

The Plugin:
package de.R3N3PDE.PluginExample;
import de.R3N3PDE.X.API.JavaPlugin;

public class PluginExample extends JavaPlugin{
    public void onEnable(){
        getLogger().info("Plugin Enabled!");
    }
}

The PluginLoader:
package de.R3N3PDE.X.Plugin;
imports de.R3N3PDE.X.API.JavaPlugin;

public void initPlugins(){
    try {
        File loc = new File("plugins");
        extendClasspath(loc);

        ServiceLoader<JavaPlugin> sl = ServiceLoader.load(JavaPlugin.class);
        Iterator<JavaPlugin> apit = sl.iterator();
        while (apit.hasNext()){;
            JavaPlugin met = apit.next();
            //Set the Server
            med.setServer(s);
            //run void onEnable(); in the Plugin????
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

====================
EDIT:
Thanks. I have a new Problem...
The URLClassLoader find Plugins but the ServiceLoader can´t load the Plugin.
I think the ServiceLoader cant fint the extended class.
The Plugin:
package de.R3N3PDE.PluginExampleName;
import de.CodingDev.X.Server.API.JavaPlugin;

public class PluginExampleName extends JavaPlugin{
    @Override
    public void onEnable() {
        System.out.println("Test");
        getLogger().info("Plugin Enabled!");
    }
}

I have make a new Plugin Loader the old version dosen´t work:
public void onLoad(){
    File loc = new File("plugins");

    File[] flist = loc.listFiles(new FileFilter() {
        public boolean accept(File file) {return file.getPath().toLowerCase().endsWith(".jar");}
    });
    URL[] urls = new URL[flist.length];
    for (int i = 0; i < flist.length; i++)
        urls[i] = flist[i].toURI().toURL();
    URLClassLoader ucl = new URLClassLoader(urls);
    for(URL url : ucl.getURLs()){
        s.getLogger().info("PluginLoader", "Found Plugin: " + url.getFile());
    }
    ServiceLoader<JavaPlugin> sl = ServiceLoader.load(JavaPlugin.class, ucl);

    Iterator<JavaPlugin> apit = sl.iterator();
    while (apit.hasNext()){
        s.getLogger().info("PluginLoader", "Loading Plugin");
        apit.next().onEnable();
    }
}

The Log:
[LOG] [02.11.2013 15:26:09] [PluginLoader] [INFO] Loading Plugins...
[LOG] [02.11.2013 15:26:09] [PluginLoader] [INFO] Found Plugin: /C:/Users/René/Desktop/Server/plugins/CommandLogger.jar

A: What about making your class abstract with abstract onEnable method?
public abstract class JavaPlugin{
    Server server;
    public ServerManager getServer(){
        return new ServerManager(server);
    }

    public ServerManager setServer(Server s){
        server = s;
    }

    public PluginLogger getLogger(){
        return new PluginLogger(server);
    }

    public abstract void onEnable();
}

And then you have to implement onEnable method in your subclasses.
You could then call the onEnable method of any dynamically generated subclass that extends the JavaPlugin.
The second way could be implementing the onEnable method in Javaplugin and then overriding the method in an extended class.
public class JavaPlugin {
    ...
    public void onEnable(){
        getLogger().info("JavaPlugin onEnable default implementation!");
    }
}

In your PluginExample file:
public class PluginExample extends JavaPlugin{
    @Override
    public void onEnable(){
        getLogger().info("Plugin Enabled!");
    }
}


text:
Q: Picard iterations to find $\dot{y}=\sqrt{y}$ I have to find the solution $y_n(t;0)$ of the differential equation of $\dot{y}=\sqrt{y}$ with $y(0)=0$ using the Picard iteration. Finding $y_1,y_2,...$ shouldn't be that hard. But I never find it easy to get the general $y_n(t;0)$. Can you tell me what it is for $y(0)=0$ and for $y(0)=\alpha$ with $\alpha\in\mathbb{R}\setminus\{0\}$?
P.S. I don't like the Picard iteration, I prefer Kirk ;)


text:
Q: How can I use Regex to match optional characters only if the previous optional character matched? For example: How do I match the words kein, keine, keiner or keines with regex.
I know how I can check for optional characters:
\bkein(?:e)?(?:r|s)?\b

But this way I would also match keins and keinr which is not what I want.

A: You may use this regex:
\bkein(?:e[rs]?)?\b

RegEx Demo
Breakdown:

*

*\b: Word boundary

*kein: Match kein

*(?:e[rs]?)?: Optional non-capture group to match e or er or es

*\b: Word boundary

A: You can create a list of possible suffixes like:
\bkein(e|er|es)?\b


text:
Q: Multiple monitors and position of startup object in Winforms app I've taken over maintenance of a Winforms application running on .Net version 4. The startup object is the login form. I have three monitors. The login form opens centered on whatever monitor my mouse pointer is sitting on. I can't find any code in the form that sets it's position. I haven't seen a form do this before. Is there a setting that makes this happen or is this just normal behavior?

A: Check the form's StartPosition - seems like it's set on FormStartPosition.CenterScreen.
From MSDNs page on FormStartPosition Enumeration:

Member name             Description
CenterParent            The form is centered within the bounds of its parent form.
CenterScreen            The form is centered on the current display, and has the dimensions specified in the form's size.
Manual                  The position of the form is determined by the Location property.
WindowsDefaultBounds    The form is positioned at the Windows default location and has the bounds determined by Windows default.
WindowsDefaultLocation  The form is positioned at the Windows default location and has the dimensions specified in the form's size.

Note that CenterScreen describes exactly what you described.


text:
Q: What is the default application to open .ttf font files on Windows 10? I've installed an application that comes with its own font viewer utility. The application has set it as the default for opening fonts.
Here's a screenshot:

I would like to know what the Windows 10 default is for opening font files, so that I can set it back as the default.

A:
The application is called Windows Font Viewer, and is located in C:\Windows\System32\Fontview.exe


text:
Q: Nilradical of absolutely flat ring Suppose $A$ is an absolutely flat ring (i.e. every $A$-module is flat). Is it true that nilradical of $A$ is trivial, i.e. $\mathfrak{N}(A)=\{0\}$?
I believe the answer is yes. Here is my attempted proof:

We use the following characterization of absolutely flat rings (Chapter
  2, Exercise 27 in Atiyah & Macdonald). $A$ is absolutely flat ring $\Leftrightarrow$
  $(x)=(x^2)$ for each $x\in A$. Now, suppose $x^{n}=0$ for
  $n\in\mathbb{N}$, where $n$ is minimal. If $x\neq 0$, we necessarily
  have $n\ge 2$. Since $(x)=(x^2)$, we have $x=ax^2$ for some $a\in A$. Thus,
  $x^{n-1}=ax^{n}=0$, contradicting minimality of $n$. Hence, $x=0$ is
  the only nilpotent element of $A$.

Is my proof correct?
I have done Chapter 2, Exercise 28 in Atiyah & Macdonald, which lists important properties of absolutely flat rings, but this simple property was not mentioned there.

A: That looks ok.
Another way is to note (or learn now) that a ring has no nonzero nilpotents if it has no nonzero elements with square zero (exercise!) then you can say "suppose a is nonzero but $a^2=0$. Then there exists an x such that $a=a^2x=0$ a contradiction."
Another path, if you know that the Jacobson radical of an absolutely flat ring is zero, is notice that the intersection of all prime ideals (equal to the nil radical) is contained in the intersection of maximal ideals (the Jacobson radical) and hence both are zero.

Bonus noncommutative info
Not all Von Neumann regular rings lack nilpotents (any matrix ring $M_n(F)$ over a field with n>1 has nilpotents). The ones that don't have any nilpotents are called strongly regular rings, and they are exactly the VNR rings whose idempotents are all central.

A: Here is another bit of information that you can get out of absolutely flat rings that is very useful.

If $A$ is absolutely flat then for any multiplicative subset $S \subseteq A$, we have $S^{-1}A$ being absolutely flat.

Thus in particular for any maximal ideal $\mathfrak{m} \subseteq A$, we have $A_{\mathfrak{m}}$ being absolutely flat. However a local ring that is absolutely flat is a field and so this means that $\operatorname{Jac}(A)_{\mathfrak{m}} \subseteq A_{\mathfrak{m}}$ is zero for all maximal ideals $\mathfrak{m}$. The Jacobson radical is an ideal in the localization because $\operatorname{Jac}(A) \subseteq \mathfrak{m}$ for any maximal ideal of $A$. Since being zero is a local property this means that $\operatorname{Jac}(A) = 0$. The same proof mutadis mutants also works to show that the nilradical of an absolutely flat ring is zero.

Exercise: Proof the result mentioned above. Hint: You will not believe it, but for any two $S^{-1}A$ - modules $M$ and $N$, the modules $M \otimes_A N $ and $M \otimes_{S^{-1}A} N$ are isomorphic as $S^{-1}A$ - modules!! Now why is $M \otimes_A N$ a $S^{-1}A$ - module?
Proof the a local ring that is absolutely flat is a field: Let $A$ be a local ring with maximal ideal $\mathfrak{m}$. Choose any $x \in \mathfrak{m}$. Then we have $\mathfrak{m}(x) = (x)$. Indeed, $\mathfrak{m}(x) \subseteq (x)$ and the other inclusion follows from $(x) = (x^2)$. By the Nakayama Lemma it follows $x = 0$ and since this was any element of $\mathfrak{m}$, we have $\mathfrak{m} = 0$. In other words, $A$ is a field.


text:
Q: SPF record e-mail appearing as SOFTFAIL instead of FAIL? I added a SPF record a few days ago to our company DNS
"v=spf1 include:spf.messagelabs.com -all"

and now I am sending a fake e-mail with my company e-mail address as the from address using the website at https://emkei.cz
Then I check my personal e-mail (iCloud) and see the fake e-mail supposedly from my company e-mail in my Inbox and when I check the headers it says
Received SPF: softfail

but that website uses mail server emkei.cz [46.167.245.118] which is not defined in our SPF record, so the fail should be a HARDFAIL because we use -all (and message put in Junk or something), right?
Why doesn't it work?

A: Because you're using include, your SPF will be redirected to the SPF of "included" domain. SPF for spf.messagelabs.com is
"v=spf1 include:nets1.spf.messagelabs.com include:nets2.spf.messagelabs.com ~all"

~all is the reason, why you have softfail instead of hardfail.


text:
Q: How to print strings with quotations in VB.NET
Possible Duplicate:
Escape double quote in VB string

I am assigning variables below with string values, and I would like to print these with quotations, although I am not sure how to accomplish this. So far everything prints fine, except for without quotations. What I have is below:
    Dim tU As String = "Print_Me"
    Dim tU2 As String = ""
    Dim str1 As Integer = 1
    Dim str2 As String = tU
    Dim str3 As Single = 3.5
    Dim str4 As String = tU2

    Dim fw As New System.IO.StreamWriter("testfile.txt")
    fw.WriteLine(str1 & "," & str2 & "," & str3 & "," & str4 & "," & 0)

    fw.Close()
    fw.Dispose()
    'prints>>>1,Print_Me,3.5,,0<<<
    'I like to print>>>1,"Print_Me",3.5,"",0<<<

EDIT
    Dim tU As String = "Print_Me"
    Dim tU2 As String = ""
    Dim str1 As Integer = 1
    Dim str2 As String = tU
    Dim str3 As Single = 3.5
    Dim str4 As String = tU2
    Dim str5 As Integer = 0

    Using fw As New System.IO.StreamWriter("testfile.txt")
        fw.WriteLine(String.Format("""{0}"",""{1}"",""{2}"",""{3}"",""0""", str1, str2, str3, str4, str5))
    End Using

    ''Currently prints>>> "1","Print_Me","3.5","","0"

    ''I would like to print>>> 1,"Print_Me",3.5,"",0

I am indirectly populating str1 through str5, but I do not want to print all of the items with quotations, so how might I adjust the solution to accomplish this?

A: Try escaping your double quotes by typing the " twice. Also I find String.Format is tidier than concatenation, and if you wrap your StreamWriter in a using block, you don't need to dispose of it, as this is done by the garbage collector.
Dim str1 As Integer = 1
Dim str2 As String = "Print_Me"
Dim str3 As Single = 3.5
Dim str4 As String = ""

Using fw As New System.IO.StreamWriter("testfile.txt")
    fw.WriteLine(String.Format("""{0}"",""{1}"",""{2}"",""{3}"",""0""", str1, str2, str3, str4))
End Using

Also, you could probably give your variables clearer names. Naming them after the type is considered bad practice, as it doesn't really give us any information about what information the variable holds. Prefixing an Integer or a Single with str is worse, as somebody reading your code could wrongly think that the variable is a string, and thus try and treat it like such.
Edit: In response to your comment, first of all, in a VB.Net string, "" represents a single instance of a double quote, if you want to remove a double quote, just remove the "" and leave everything else intact. Secondly, it really doesn't matter if some of your strings are indirectly populated, you don't need to create a new variable to use them in a new string. In your code tu and str2 are pointing at the same piece of data, as are tu2 and str4, there is no need to create a new variable. If you have a piece of data held in a variable, you don't need to create a new variable to use it in a different way.

A: When your output is so regular (and possibly may contain many more strings) then an alternative that you may want to consider is this:
Dim str1 As Integer = 1
Dim str2 As String = "Print_Me"
Dim str3 As Single = 3.5
Dim str4 As String = ""

Dim strings() As String = _
{ _
    str1, _
    str2, _
    str3, _
    str4, _
    "0" _
}

Using fw As New System.IO.StreamWriter("testfile.txt")
    fw.WriteLine( _
        String.Join( _
            ",", _
            strings.Select(Function (s) """" & s & """")))
End Using

You still use the "" to indicate an inline quote, but you only need to do it twice. If your list of strings gets larger you only need to add them to the array (or it could be a list or any other enumerable).


text:
Q: Multi-line form submit button in rails Is there a way for me to get the
<%= f.submit "Save Draft", :class => "button" %>

Button text onto two lines?
I'd like it to say
Save Draft -> big text
and finish later -> this line smaller sized

A: No.
You can not apply two different font sizes to the same button, you could however supply a mouse hover event for the form class that represents the button in css to change the colour or you could use jQuery to hange the text and colour
.button:hover {
    border: 1px solid #f00;
    background: #eef;
}

Not sure what the jQuery code would look like though but more info can be found here on the mouseover event
http://api.jquery.com/mouseover/


text:
Q: Java Curve Fitting with Starting and Ending Points I am trying to fit a curve onto a set of points in Java, but am also trying to keep the starting and ending points consistent. I have tried to use polynomial regression (with varying degrees and stopping the line short near the starting and ending points), which usually produces a fairly accurate line, but often times the line travels above or below the starting or ending points.
Is there a way to have the regression function create a curve that smooths out the path of the points (by not exactly following every point) but still goes through the starting and ending points (possibly as defined by the user)?

Any help would be appreciated


text: Q: Angular mat-tab, set labels apart from each other I'm trying to create vertical mat-tab in Angular. I need to have 4 labels aligned to the top of the page, and 2 labels aligned to the bottom of the page. How to do that


text:
Q: Why is my string comparison failing when checking against class names? I'm working on a portion of an application which creates a user object on a server via HTTP POST. I'm having a really frustrating issue with matching the name of the callback class against a string constant.
Context:
Since this application makes about 8-10 different server requests, I've tried to encapsulate the actual connection process into one class, HTTPConnection. Every activity which needs to connect to the server passes its own instance of AndroidHttpClient, HttpRequest, and HTTPConnectionListener, which is an interface which every calling activity implements which allows the server response to be sent directly back to the activity.
This has been working great until I had to implement a portion of the app which required a response header to be returned. Until this point, I've only had to deal with response bodies, so  HTTPConnection only returned the body. To solve this, I rewrote HTTPConnection to check the name of the callback class, then return the header or body depending on which class was requesting the data.
What seemed like an easy solution has now used a good portion of my morning, so I realized I needed more eyes to see what I'm doing wrong.
The Problem:
In the constructor of HTTPConnection, I store the callbackListener (which is really anything that implements HTTPConnectionListener). In this case, my calling activity EditAccountActivity is the callback. I save this in a field early in doInBackground() to check against later.
    String callbackName = callbackListener.getClass().toString(); // Get the full name of the callback class and store it here.
    Log.v(TAG, "** Callback listener is set to " + callbackName);

Then, after I have finished the connection, I want to check against a constant (eventually a list of constants) to determine whether or not I return the body or the header of the response.
// The constant I am trying to match
final protected String EDIT_ACCOUNT = "com.example.appname.EditAccountActivity";

The logic of returning the body or response is below.
// Determine which section of response to return
if (callbackName.equals(EDIT_ACCOUNT)) {
    Header responseHeader = response.getFirstHeader("Location");
    return responseHeader.getValue();
} else {
return serverResponse;
}

As you can tell by the ridiculous amount of Log statements, I've been debugging with no success. My logcat output looks like this.
07-10 12:44:54.932: INFO/com.example.appname.ServerFetcher(21650): Entity set: HTTP.CONTENT_TYPE - application/json
07-10 12:44:54.932: VERBOSE/com.example.appname.ServerFetcher(21650): Sending user json:     {"last_name":"tester ","first_name":"tester       ","username":"test@testing11.com","password":"oflndveledmenkddjevhhlkh","email":"test@testing.com","profession":"tester "}
07-10 12:44:54.952: VERBOSE/com.example.appname.HTTPConnection(21650): ** Callback listener is set to class com.example.appname.EditAccountActivity
07-10 12:44:54.952: INFO/com.example.appname.HTTPConnection(21650): Executing the HTTP POST request to <url>
07-10 12:44:55.713: INFO/com.example.appname.HTTPConnection(21650): ** HTTP Response returned: 201 - CREATED
07-10 12:44:55.713: INFO/com.example.appname.HTTPConnection(21650): ** 201 - CREATED
07-10 12:44:55.713: INFO/com.example.appname.HTTPConnection(21650): Response body:
07-10 12:44:55.713: VERBOSE/com.example.appname.HTTPConnection(21650): Callback name is class com.example.appname.EditAccountActivity
07-10 12:44:55.713: VERBOSE/com.example.appname.HTTPConnection(21650): Listener is class com.example.appname.EditAccountActivity
07-10 12:44:55.713: VERBOSE/com.example.appname.HTTPConnection(21650): Are they equal? true
07-10 12:44:55.713: VERBOSE/com.example.appname.HTTPConnection(21650): EDIT_ACCOUNT constant is com.example.appname.EditAccountActivity
07-10 12:44:55.713: VERBOSE/com.example.appname.HTTPConnection(21650): Is callbackName equal to EDIT_ACCOUNT? false
07-10 12:44:55.713: VERBOSE/com.example.appname.HTTPConnection(21650): Is callbackListener.getClass().toString() equal to EDIT_ACCOUNT? false
07-10 12:44:55.723: VERBOSE/com.example.appname.EditAccountActivity(21650): onConnectionFinish called.
07-10 12:44:55.743: VERBOSE/com.example.appname.EditAccountActivity(21650): Response returned from user creation is

For some reason, whenever I check the class name of the listener with EDIT_ACCOUNT, it's not equal. But when I check the output, they all look equal to me. I'm not comparing anything with ==, everything is checked using .equals(). As a result, the body of the if statement is never executed, which means I output an empty string (as there is no response body in this particular connection).
Any advice on how to proceed would help keep hair on my head. Here's the whole class if needed.
HTTPConnection.java
package com.example.appname;

public class HTTPConnection extends AsyncTask<Void, Integer, String> {

final protected String TAG = HTTPConnection.class.getName();
protected AndroidHttpClient httpClient;
protected HttpRequestBase httpRequest;
protected HTTPConnectionListener callbackListener;

// Callback Class Name Constants
final protected String EDIT_ACCOUNT = "com.example.appname.EditAccountActivity";

public HTTPConnection(AndroidHttpClient httpClient, HttpRequestBase httpRequest, HTTPConnectionListener listener) {
    this.httpClient = httpClient;
    this.httpRequest = httpRequest;
    this.callbackListener = listener;
}

@Override
protected String doInBackground(Void.. voids) {
    String serverResponse = null;
    String callbackName = callbackListener.getClass().toString(); // Get the full name of the callback class and store it here.
    Log.v(TAG, "** Callback listener is set to " + callbackName);

    try {
        Log.i(TAG, "Executing the HTTP " + httpRequest.getMethod() + " request to " + httpRequest.getURI().toString());
        HttpResponse response;
        response = httpClient.execute(httpRequest);

        // Grab the returned string as it is returned and make it a String to save memory.
        StringBuilder stringBuilderResponse = inputStreamToString(response.getEntity().getContent());
        serverResponse = stringBuilderResponse.toString();

        // Log the response.
        Log.i(TAG, "** HTTP Response returned: " + response.getStatusLine().getStatusCode() + " - " + response.getStatusLine().getReasonPhrase());
        Log.i(TAG, "** Response Code: " + response.getStatusLine().getStatusCode() + " Reason Code: " + response.getStatusLine().getReasonPhrase());
        Log.i(TAG, "Response body: " + serverResponse);

        // ** Debug string equality **
        Log.v(TAG, "Callback name is " + callbackName);
        Log.v(TAG, "Listener is " + callbackListener.getClass().toString());
        boolean equality1 = callbackName.equals(callbackListener.getClass().toString());
        Log.v(TAG, "Are they equal? " + equality1);
        Log.v(TAG, "EDIT_ACCOUNT constant is " + EDIT_ACCOUNT);
        boolean equality2 = callbackName.equals(EDIT_ACCOUNT);
        Log.v(TAG, "Is callbackName equal to EDIT_ACCOUNT? " + equality2);
        boolean equality3 = callbackListener.getClass().toString().equals(EDIT_ACCOUNT);
        Log.v(TAG, "Is callbackListener.getClass().toString() equal to EDIT_ACCOUNT? " + equality3);

        // Determine which section of response to return
        if (callbackName.equals(EDIT_ACCOUNT)) {
            Header responseHeader = response.getFirstHeader("Location");
            return responseHeader.getValue();
        } else {
        return serverResponse;
        }

    } catch (IOException e) {
        Log.e(TAG, "Error when executing HTTP " + httpRequest.getMethod() + " request!");
        e.printStackTrace();
        return serverResponse;
    }
}

@Override
protected void onPostExecute(String result) {
    httpClient.close();
    callbackListener.onConnectionFinish(result);
}
}

}

A: Callback name is class com.example.appname.EditAccountActivity
EDIT_ACCOUNT constant is com.example.appname.EditAccountActivity
To fix this, instead of using callbackListener.getClass().toString() use callbackListener.getClass().getName(). – kabuko


text:
Q: Shipping timer condition for Magento 2 I want to create a restriction on a shipping method that it can only be used 1 hour after the most recent use by a customer.

A: You could do this by hooking into the class
Magento\Shipping\Model\Shipping class's collectRates() function
Just store in a database somewhere or something when a customer uses it, then compare that (plus one hour) to the current timestamp.
If the current timestamp is bigger, then show the method.


text:
Q: Graphviz does not show graph/pdf image in Spyder I'm trying to show BFS and UCS graphs using Graphviz with Spyder. My output is correct, however, no graph/pdf is shown when run. A snippet of my code related to Graphviz is below:
import graphviz
from graph import graph
from graph import graph_weights
import os
os.environ["PATH"] += os.pathsep + 'C:/location/of/files/'
f = graphviz.Digraph('G', filename='bfs.gv')
for i in Path:  # For each node in Path
    f.node(i)   # Add node to graphviz object
# For each node in Path except the last one
for i in range(len(Path)-1):
    # Add edge between the node and the next node
    f.edge(Path[i], Path[i+1])
f.view()    # View the graphviz object
print('Path from {} to {} is: {}'.format(
    start, end, Path))  # Print message

I've tried both f.view() and f.render() and nothing is shown. I'm not sure how to proceed.
Thank you.


text:
Q: chrome.runtime.sendMessage not working as expected I am writing a Chrome plugin with a content script and a background script, and I am trying to make the two communicate.
In my content script, I am doing
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
      console.log(response.farewell);
});

and in my background script, I am doing
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(sender.tab ?
          "from a content script:" + sender.tab.url :
          "from the extension");
        if (request.greeting == "hello")
            sendResponse({farewell: "goodbye"});
    }
);

My manifest looks like this:
{
    "manifest_version": 2,
    "name": "Tesing Phase",
    "version": "1.0",
    "background": {
        "persistent": false,
        "scripts": ["bgscript.js"]
    },
    "content_scripts": [{
        "js": ["contentscript.js"],
        "all_frames": true,
        "run_at" : "document_start",
        "matches": ["*://*/*"]
    }],
    "web_accessible_resources": ["script.js"]
}

When I run my plugin, I get the following error:
Uncaught TypeError: Object #<Object> has no method 'sendMessage'

I tried logging chrome.runtime, and there was no method sendMessage. I am using version 25.0 of Chromium on Ubuntu. I tried using sendRequest as well, but it said it's depreciated and sendMessage should be used.
Can anyone point me out what I am missing here? Are there any permissions needed for this to work?

A: chrome.runtime.sendMessage / onMessage (and other related events/methods such as connect) were introduced in Chrome 26.
If you want to write an extension which is compatible with Chrome 20 - 25, use chrome.extension.sendMessage.
A way to achieve optimal compatibility is to define the chrome.runtime methods yourself. For example, run the following code before the rest of your code (background/content script):
if (!chrome.runtime) {
    // Chrome 20-21
    chrome.runtime = chrome.extension;
} else if(!chrome.runtime.onMessage) {
    // Chrome 22-25
    chrome.runtime.onMessage = chrome.extension.onMessage;
    chrome.runtime.sendMessage = chrome.extension.sendMessage;
    chrome.runtime.onConnect = chrome.extension.onConnect;
    chrome.runtime.connect = chrome.extension.connect;
}

Then you can just use the latest API format:
// Bind event:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    // Do something
});

// Send message:
chrome.runtime.sendMessage({greeting: 'hello'});

If you feel uncomfortable with modifying methods on the chrome.runtime object, you can use the following approach instead:
var runtimeOrExtension = chrome.runtime && chrome.runtime.sendMessage ?
                         'runtime' : 'extension';

// Bind event:
chrome[runtimeOrExtension].onMessage.addListener(
  function(message, sender, sendResponse) {
    // Do something
});

// Send message:
chrome[runtimeOrExtension].sendMessage({greeting: 'hello'});


text:
Q: How can I make the zoning colours more distinct? I have installed Cities Skylines on my HP Envy m6 laptop with Ubuntu 14 installed. I also have the laptop plugged into a 27 inch monitor.
The game appears to run without any issues, except for an exception when closing down. However, when I try to mark any of the first zones the zone colours are incredibly faint. So much so, that when I first tried to zone an area I kept clicking and dragging thinking that nothing was happening.
It took some time before I realised the zones were in fact being marked, it's just hard to see.
Is there a way to increase the visibility of the zone colours?
Perhaps a mod that does this?

A: This probably isn't the case for you (and isn't for me), but it wouldn't surprise me if people with red/green colour blindness couldn't distinguish the colour used for residential zones from the colour for industrial zones, and those with blue/yellow colour blindness having difficulty distinguishing commercial zones from residential zones.  Unfortunately, there doesn't seem to be any options for colour blind people, but one thing you can try is forcing the colour palette to one of the climates (Temperate, Boreal, or Tropical) in the options.

A: Honestly, I find Cities Skylines' colors to be more vibrant than the average (3D) game.
I'd look into your monitor's settings, as I would expect this to be a direct display issue.
That being said, the green zoning for residential zones might sometimes be hard to see if you're building on grassy land. Especially if your monitor doesn't have a very wide range of colors, since the shades of green are already close to one another.


text:
Q: Event Viewer from Recovery Command Prompt I've got a 2008 Server machine that's doing a rolling reboot, even from safe mode. I can get into the recovery console prompt. From there can I somehow view what's in the event viewer?

A: I would boot off of a BARTPE CD and then open the event viewer files (in %SystemRoot%\System32\Config) from its event viewer.

A: Not sure how to comment on an existing post, but the post about BARTPE CD is either not possible with Windows 7 or not a very easy thing to do. http://www.911cd.net/forums//index.php?showtopic=23931 has some instructions on this