text:
Q: Error Occurs in implementing the Navigation drawer I have one Login Activity if user click on login button than automatically its go to Navigation Drawer but i got an error. Please Help me out from this error.
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener {

    private Toolbar toolbar;
    private DrawerLayout drawer;
    public String emailRegistration;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        //toolbar.setTitle("toolbar");
        setSupportActionBar(toolbar);

        //Set adapter to AutoCompleteTextView

      //  FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

//        if (!emailRegistration.matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+")) {
//
//            email.setError("Invalid Email Address");
//
//        }

//        fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Snackbar.make(v, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//            }
//        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
       DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
        setTitle("Home");
           Intent i = new Intent(MainActivity.this, HomeFragment.class);
            startActivity(i);
        } else if (id == R.id.nav_gallery) {
            setTitle("Edit Profile");
            EditFragment editFragment = new EditFragment();
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.fragment,editFragment).commit();

        } else if (id == R.id.nav_slideshow) {
            setTitle("Business");
            BusinessFragment businessFragment = new BusinessFragment();
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.fragment,businessFragment).commit();

        } else if (id == R.id.nav_manage) {
            setTitle("Message");
            MessageFragment messageFragment = new MessageFragment();
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.fragment,messageFragment).commit();

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        // TODO Auto-generated method stub
        //Log.d("AutocompleteContacts", "onItemSelected() position " + position);

    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {
        InputMethodManager imm = (InputMethodManager) getSystemService(
                INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        // TODO Auto-generated method stub

        // Show Alert
        Toast.makeText(getBaseContext(), "Position:"+i+" Country:"+adapterView.getItemAtPosition(i),
                Toast.LENGTH_LONG).show();

        Log.d("AutocompleteContacts", "Position:"+i+" Country:"+adapterView.getItemAtPosition(i));

    }
}

LoginActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends AppCompatActivity {
    public EditText email, password;
    public TextView textView;
    public Button login;

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

        email = (EditText) findViewById(R.id.email);
//        if( email.getText().toString().length() == 0 )
//            email.setError("Email is required!" );
        password = (EditText) findViewById(R.id.text_input_password_toggle);
//        if( password.getText().toString().length() == 0 )
//            password.setError("Password is required!" );
        textView = (TextView) findViewById(R.id.text2);
        login = (Button) findViewById(R.id.login);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(LoginActivity.this,signupactivity.class);
                startActivity(i);
            }
        });
    }

    }

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

Error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.addDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference

SignupActivity. java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;

public class signupactivity extends AppCompatActivity {
    public EditText firstname, lastname, email;
    private AutoCompleteTextView actv;
    public Button signup;
    String[] languages={"Indore","Ujjain","Bhopal","Delhi","Bangalore","Chennai"};
    List<CharSequence> list = new ArrayList<CharSequence>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        for (int i=0;i<20;i++){
            list.add("test " + i);  // Add the item in the list
        }
        firstname = (EditText)findViewById(R.id.firstname);
        lastname = (EditText)findViewById(R.id.lastname);
        actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
        email = (EditText) findViewById(R.id.email);
        signup = (Button)findViewById(R.id.signup);
        ArrayAdapter adapter = new
                ArrayAdapter(this,android.R.layout.simple_list_item_1,languages);
        actv.setAdapter(adapter);
        actv.setThreshold(1);

        signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(signupactivity.this, LoginActivity.class);
                startActivity(i);
            }
        });
    }

}

Image I want the blank fragment when i click on the home, edit profile but its show everywhere signup activity because my content_main framelayout id is fragment and its call in mainactivity and its my signup page too  (fragmentManager.beginTransaction().replace(R.id.fragment,editFragment).commit();) So how to solve this problem

A: In your MainActivity.java you are using
setContentView(R.layout.fragment_business);

But your drawer is in activity_main.xml
So your drawer is a null and you cannot add a listener to a null object.
Change the setContentView to
setContentView(R.layout.activity_main);


text:
Q: How does the try catch structure in Java compare to try except in Python? I am used to the following in Java:
try {
    // something bad happens here
} catch (SomeException se) {
   se.printStackTrace(); // let's me print the stack trace
   System.out.println(se); // let's me print and inspect the exception
   throw se; // I can re-throw it or wrap it and throw it
}

I am having a really hard time linking this to Pythons
try:
    pass # do something
except ExceptionClass1:
    print("OK I know I caught an ExceptionClass1 type exception")
    # but how do I get to the stack trace
    # how do I get to the object of the exception

A: You will need the traceback library:
try:
    # Do something
except ExceptionClass1 as error:
    traceback.print_exc()  # Prints the exception

    # Raise alone will re-raise the same exception
    raise

    # Or, raise a new exception
    raise RuntimeError("bad things") from error

redpajama_set_name: RedPajamaStackExchange


text:
Q: weak claw-free graphs The complete bipartite graph $K_{1,3}$ is known as a claw-graph. A graph $G$ is said to be claw-free it doesn't have an induced subgraph isomorphic to the claw-graph.
We define a graph to be weak claw-free if it doesn't have a subgraph isomorphic to the claw graph. It is immediate that the maximum degree of any vertex in this graph will be equal to two.
I am interested in the question, what more can be said about the structure of such simple graphs and any references regarding this notion will also very helpful.
Kindly share your thoughts.
Thank you.


text:
Q: drupal issues on page A customer has asked me if can help on their drupal site as they got errors/warnings on it and can't see the site, I have never used drupal but looking at the errors/warnings, I am wondering if the path is incorrect but can't see where to change the path, I found the settings.php but most of the code is commented out, I thought there may be some sort of config file that has the path in it
The errors/warnings on the site are below
Warning: include(/var/webroot/drupal7-master/base_url_generator.php): failed to open stream: No such file or directory in include() (line 551 of /home4/adyley/amlcomputersltd.co.uk/sites/default/settings.php).

Warning: include(/var/webroot/drupal7-master/base_url_generator.php): failed to open stream: No such file or directory in include() (line 551 of /home4/adyley/amlcomputersltd.co.uk/sites/default/settings.php).

Warning: include(): Failed opening '/var/webroot/drupal7-master/base_url_generator.php' for inclusion (include_path='.:/opt/php70/lib/php') in include() (line 551 of /home4/adyley/amlcomputersltd.co.uk/sites/default/settings.php).

PDOException: SQLSTATE[28000] [1045] Access denied for user 'username'@'localhost' (using password: YES) in lock_may_be_available() (line 167 of /home4/adyley/amlcomputersltd.co.uk/includes/lock.inc).

Can anyone help in where or how to solve these errors please

A: In setting.php there is a variable $base_url
This variable pointing your domain as wrong location
like in settings.php you said you domain name is drupal7-master
So Drupal is trying to include files from /var/webroot/drupal7-master/base_url_generator.php
But you actual root directory location is /home4/adyley/amlcomputersltd.co.uk/sites/default/settings.php
And also trying to find SQL connection credentials in /var/webroot/drupal7-master/sites/default/settings.php
So simply comment this $base_url variable or assign correct value to this variable
In my thoughts some one download live site and trying to run at local server without changing $base_ur value or comment this line
That's why he/she got these errors


text:
Q: How can I know if my iPhone had been erased? My iPhone was lost 3 months ago and I have decided to erase my iPhone since then but until now I don't know if it erased or not. I'm still afraid that the thief may have access to my private stuff.
How can I know that my iPhone have been erased or can I track at least if it was already erase?
I tried to check my email and apple account and yet there is no mail.

A: When the device is erased, you should receive an email notification informing you that the device has successfully been erased. This is regardless of whether the device was online or offline when you clicked Erase, since the next time the device is online the device will be erased and an email will be sent.

*

*If your device is online, the remote erase begins. A confirmation email is sent to your Apple ID email address.

*If your device is offline, the remote erase begins the next time it's online.

Source: http://support.apple.com/kb/PH2701
You will be unable to track the device through Find My iPhone if you erase it.

Note: If you erase your iPhone, you won't be able to use Find My iPhone to locate or protect it, but your Apple ID and password will be required to reactivate it.

Source: http://support.apple.com/kb/TI79

A: Assuming your iPhone is connected to Find iPhone, on erasing you should receive an email stating it has been erased. If its offline( assuming its still connected with your apple account), it will erase as soon as it comes online next.
Login to your iCloud account, and go to Find my iPhone. click on the All Devices dropdown, It should show you the status of your phone. If it has been erased, it will not show in the list( Again, assuming it was the find my iPhone setting was enabled by you and wasn't disabled by the thief).

A: I dont think an erased iPhone can be compromised.


text:
Q: Passing list variable to Subprocess.call function I am trying to pass the variable line inside a for loop that is calling a subprocess.call to calculate the unix command cksum.
with open('./my_filelist', 'r') as f:
    for line in f.readlines():
        print "Printing Checksum --->"
        print ""
        subprocess.call(["cksum",line])

Should print the cksum of all the files in ./my_filelist.

A: The lines returned by the file.readlines method all end with a newline character (except the last line if the file does not end with a trailing newline). You should strip the line of the trailing newline character; otherwise the newline character would be treated as part of the file name when passed to cksum as an argument:
subprocess.call(["cksum", line.rstrip()])


text:
Q: I can not log in to SQL Server database after deployment I have an asp.net site that stores information from textboxes to a database. It works fine when I run it from visual studio, but once I deploy it to IIS I get the following error message

[SqlException (0x80131904): Login failed for user 'LORENZNT\TLC08$'.]

This is my connection string.
Data Source=tlc08;Initial Catalog=SingableSolutions.com;Integrated Security=true

I have been through dozens of forums and tried everything I can think of. If anyone could help me out, I would greatly appreciate it. Thanks.

A: When you run under IIS, if the application pool is set to use "Application Identity" then it will the IIS computer's account to try to log into SQL Server. If you have not created a User in SQL Server corresponding to that computer account, then access will be denied.
You can either create a User in SQL Server for that account, or you can change your IIS Application Pool so it runs using a domain user account, or you can change your connectionstring to use a SQL account instead of Integrated Security.


text:
Q: using document.elementFromPoint on documentFragment When applying document.elementFromPoint on point(x,y) which points to an element somewhere inside a documentFragment, it returns the container element.
For example:

          something

Expected Result:
If (x,y) are pointing to #my_documentfragment, document.elementFromPoint(x,y) it should return #my_documentfragment.
Actual Result:
returns #container. the container of the document fragment

*

*What's the alternative to document.elementFromPoint(x,y) when some parts of the page are documentFragments?

*What's the alternative to jquery.parents() on an element that is part of a documentFragment


text:
Q: Custom jersey class member injection exception i have created a custom injectable provider, i've tried 2 approaches:
1)
@Provider
public static final class PrincipleInjectableProvider extends PerRequestTypeInjectableProvider<Context, Principal>
{
    public PrincipleInjectableProvider()
    {
        super(Principal.class);
    }

    @Override
    public Injectable<Principal> getInjectable(final ComponentContext ic, final Context a)
    {
        return new AbstractHttpContextInjectable<Principal>() {

            @Override
            public Principal getValue(final HttpContext c)
            {
                return c.getRequest().getUserPrincipal();
            }
        };
    }

}

2)
@Provider
public static final class PrincipleInjectableProvider extends AbstractHttpContextInjectable<Principal>
    implements InjectableProvider<Context, Type>, Injectable<Principal>
{

    @Override
    public ComponentScope getScope()
    {
        return ComponentScope.PerRequest;
    }

    @Override
    public Injectable<Principal> getInjectable(final ComponentContext ic, final Context a, final Type c)
    {
        return this;
    }

    @Override
    public Principal getValue(final HttpContext c)
    {
        return c.getRequest().getUserPrincipal();
    }
}

i made sure to add this class to my resource config:
final ResourceConfig resourceConfig = new DefaultResourceConfig(PrincipleInjectableProvider.class);

and in my REST resource i try to inject the class like this:
@Context
private Principal _principal;

I was originally planning on using a separate annotation called @Principal, but i would settle right now on making this work.
When i was trying to inject this as a method param, it was successful (with some changes to the injectable class, to implement
InjectableProvider<Context, Parameter>

instead)
but i just can't seem to inject it as a class member..
This is the exception message i'm getting:
Missing dependency for field: private com.....principal.Principal com.....net.TestResource._principal

I went through all the other posts that are relevant, but couldn't find a solution there. Most were fixed by changing from
InjectableProvider<Context, Parameter>

to
InjectableProvider<Context, Type>

Please help me find what I've done wrong here,
I tried with jersey 1.12 and 1.18.

A: In the end i found out my problem was that our resources are singletons, so these per-request injectable providers can't work.
Instead i implemented a signleton injectable provider that works similarly to how @Context works, with proxies and thread local.


text:
Q: Using nested query twice within one query - for FROM and WHERE I am trying to figure out why the following Microsoft SQL code does not work. I simplified the query as it is quite complex. Basically the part that is not working is the second nested subquery (line FROM a) - I get an error: Invalid object name 'a'.
I would appreciate any advice on why it is not working and how I could make it work. Some background sources on why is it not working would also be helpful, as I struggle to find any information on limitations of nested queries beyond some basics.
SELECT *
FROM (
SELECT ... FROM ...
) a

WHERE x IN(
SELECT x
FROM a
WHERE v1=v2)

A: I managed to solve my problem thanks to the suggestion in the comments to use CTE.
So I transformed it into:
WITH CTE_1
AS
 (
SELECT ... FROM ...
)
SELECT * FROM CTE_1
WHERE x IN(
SELECT x
FROM CTE_1
WHERE v1=v2)


text:
Q: Use PHP class in AJAX call without extra handlers At the moment I use two php files for my AJAX requests. One file holds the functions, the other file contains a switch function that determines which funtion should be fired. This works fine but recently I looked into a project that used php classes. The most interesting part I found was the fact that within the ajax calls, the url was set directly to the class and function.
The code is as follow:
class Score extends CI_Controller {
 const INDIVIDUAL_SCORE_RANGE_SIZE = 7;

 function __construct()
 {
   parent::__construct();
   $this->load->model('benchmarkscore','',TRUE);
   $this->load->model('aiinst','',TRUE);

   $this->load->helper('score');
   $this->load->helper('info');
 }

 function index()
 {
    show_404('score', false);
 }

 function accountingratio() {
    if($this->session->userdata('logged_in'))
    {
        $session_data = $this->session->userdata('logged_in');

        $ratio = strtolower($this->input->post('ratio'));
        $filter = strtolower($this->input->post('filter'));

        if(in_array($ratio, array('roi', 'rr', 'qr', 'cr', 'sr', 'vr'))) {
            $ai_inst = $this->aiinst->findById($session_data['ICIOM1ID']);

            $myScore = $this->benchmarkscore->getMyScoreByAccountingRatio($ratio, $session_data['ICIOM1ID']);
            $avgScore = $this->benchmarkscore->getAverageScoreOfOthersByAccountingRatio($ratio, $session_data['ICIOM1ID'], $filter, $ai_inst);
            $allScores = $this->benchmarkscore->getAllScoresByAccountingRatio($ratio, $session_data['ICIOM1ID'], $filter, $ai_inst);

            // We should only show 20 scores so we have to filter
            // some data.
            $filterDescription = getFilterDescription(count($allScores), $filter, $ai_inst);

            $filteredScores = filterRelatedScores($allScores, $ai_inst['ICIOM1ID'], Score::INDIVIDUAL_SCORE_RANGE_SIZE);

            $deviation = getBenchmarkDeviation($myScore['myscore'], $avgScore['avgscore']);
            $deviation = $deviation == -1 ? 'N/A' : $deviation.'%';

            $result = createResultArray($myScore['myscore'], $avgScore['avgscore'], $filteredScores,
                "Uw score: ".number_format($myScore['myscore'], 2, ',', '.')."\nBenchmark afwijking: ".$deviation,
                wrapText("Benchmark score: ".number_format($avgScore['avgscore'], 2, ',', '.')."\n\n" .
                "test".$filterDescription,35),
                $filterDescription);

            $this->output->set_content_type('application/json');
            $this->output->set_output(json_encode($result));
        }
    }
 }
}

The ajax call:
function getAccountingRatioData(type, filter, callback) {
    showLoader();

    setTimeout(function() {
        var jqxhr = $.ajax({
            type: 'POST',
            url: '/score/accountingratio',
            data: {
                ratio: type,
                filter: filter
            },
            dataType: 'json'
        }).done(function(data) {
            hideLoader();
            if(data == null) {
                bootbox.alert("error");
            } else {
                setTopChartDataProvider(data.benchmark);
                setBottomChartDataProvider(data.allscores, "test");
                setFilterInfo(data);
            }
            if(callback)
                callback.call();
        })
        .fail(function() { hideLoader();bootbox.alert("error"); });
    }, 500);
}

I was wondering how this is working because I learned that classes it self don't actually do anything, they just hold things and you should alwas create an object in order to "fire" the class..
Any thoughts?


text:
Q: Cakephp integration test how I will post request after login? I am trying to make a post request in cakephp IntegrationTest, Where post request, I have to send after login into admin prefix directory.
My database table name is admin_users
I have created an AdminUsersFixture, and Fixture has 3 records
Where 1st record is :
$this->records = [
  [
      'id' => 1,
      'name' => 'jone_due',
      'email' => 'jondue@test.com',
      'password' => 'password',
      'status' => 1,
      'modified' => date('Y-m-d H:i:s'),
      'created' => date('Y-m-d H:i:s'),
  ],
]

I have written AdminUsersTestController.php
<?php

class AdminUsersTest extends TestCase{
    use IntegrationTestTrait;

    public $fixtures = [
        'app.AdminUsers'
    ];

    public function testAddAuthenticated(): void
    {
          $query = $this->AdminUsers->find()->all();
          $this->assertEquals(3, $query->count());
    }
}

After run test script I have got response ok
OK (1 test, 1 assertion)

Then tried to login by post request and below changes I have written in action testAddAuthenticated()
public function testAddAuthenticated(): void
{
        $query = $this->AdminUsers->find()->all();
        $this->assertEquals(3, $query->count());

        $user = [
            'email' => 'jondue@test.com',
            'password' => 'password'
        ];
        $this->post('/admin?type=admin',$user);
        debug($this->_response);

        $this->get('/admin/adminUsers/add');
        $this->assertResponseOk();

}

In debug I always getting email and password is wrong message. Below this my login from html
<form method="post" accept-charset="utf-8" action="/admin?type=admin">
    <input type="hidden" name="_method" value="POST">
    <input type="email" name="email">
    <input type="password" name="password">

    <button name="redirect" type="submit">ログイン</button>
</form>

This is the output that I am getting in PHP unit result
There was 1 failure:

1) App\Test\TestCase\Controller\Admin\AdminUsersTest::testAddAuthenticated
Failed asserting that 302 is between 200 and 204.

In fixers has there any hash password issue ? Am I in right way ? How can I access link after login post request ?

A: Your fixture must contain the hashed password, as the data will be inserted into the database as-is, it will not go the way trough the ORM where your entity and its password hashing mechanism would be triggered.
Also note that you cannot just make two consecutive requests like that, as there is no actual state handling in integration tests. The second request would have an empty session, meaning you would not be authenticated.
Usually it's enough to simply check that your login request returns the expected response, that is for example a valid session cookie (assertCookie()), the expected session data (assertSession()), and a location header (assertRedirect()).
It doesn't make too much sense to test the login flow further in the very same method, as it will rely on you populating the session data for the next request manually anyways, meaning if the response session data is valid, then a request with that session data should work fine.
You would have tests for your other non-login endpoints accordingly anyways, where you'd manually populate the session with the expected data required for a valid authenticated state.
See also

*

*Cookbook > Testing > Setting up the Request

*Cookbook > Testing > Testing Actions That Require Authentication

*Cookbook > Testing > Testing Actions Protected by CsrfComponent or SecurityComponent

*Cookbook > Testing > Assertion methods


text:
Q: How to block scrolling to the top of the page after clicking on a link in the hamburger menu- React Bootstrap I have a little problem with the hamburger menu in Bootstrap React. When I click on the link (originally it moves the home page down using scrollIntoView) the page goes down to the designated place, and then immediately scrolls up automatically. Can it be turned off?
const handleClickAboutus = () => {
  const aboutus = document.getElementById("aboutus_main");
  if (aboutus) {
    aboutus.scrollIntoView({ behavior: "smooth" });
  }
};

<Navbar.Toggle
  onClick={() => setExpanded(expanded ? false : "expanded")}
  aria-controls={`offcanvasNavbar-expand-${expand}`}
/>
<Navbar.Offcanvas
  id={`offcanvasNavbar-expand-${expand}`}
  aria-labelledby={`offcanvasNavbarLabel-expand-${expand}`}
  placement="end"
  className="offcanvas"
>
  <Offcanvas.Header closeButton>
    <Offcanvas.Title id={`offcanvasNavbarLabel-expand-${expand}`}>
      Menu
    </Offcanvas.Title>
  </Offcanvas.Header>
  <Offcanvas.Body>
    <Navbar.Collapse id="basic-navbar-nav">
      <Nav className="me-auto justify-content-end flex-grow-1 pe-3">
        <Nav.Link onClick={() => setExpanded(false)}>
          <Link to="/">Home</Link>
        </Nav.Link>
        <Nav.Link onClick={() => setExpanded(false)}>
          <Link to="/" onClick={handleClickAboutus}>About us</Link>
        </Nav.Link>

I've tried to find anything but can't. The page cannot scroll to the top, because it breaks the entire tabs.


text:
Q: How to send byte[] and strings to a restful webservice and retrieve this information in the web method implementation I am trying to send a byte[] as one of the parameters from my android client and receive this information in my restful web service that i have implemented in netbeans.
this is my Android client code:
@Override
protected String doInBackground(String... params) {

    String param1 = params[0];
    String param2 = params[1];
    String param3 = params[2];
    String param4 = params[3];
    String param5 = params[4];
    String param6 = params[5];

   //param6 is a Base64 encoded byte array to string

    String url = "http://ipAdress:port/example/api/booking/Booking?";

    String parameters = "param1=" + param1 + "&param2=" +param2+ "&param3="+param3+"&param4="+param4+"&param5="+param5+"&param6="+ URLEncoder.encode( new String(param6),"UTF-8"));
    try {
        URL Url = new URL(url);

        HttpURLConnection con = (HttpURLConnection)
        Url.openConnection();

        con.setInstanceFollowRedirects( false );
        con.setRequestMethod( "POST" );

        con.setDoOutput( true );
        DataOutputStream wr = new DataOutputStream(connect2Rest.getOutputStream());
        wr.writeBytes(parameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();

        BufferedReader is = new BufferedReader(new InputStreamReader(connect2Rest.getInputStream()));
        String inString;
        StringBuilder sb = new StringBuilder();
        while ((inString = is.readLine()) != null) {
            sb.append(inString + "\n");
        }

        is.close();
        String xml = sb.toString();

        System.out.print(responseCode);

        return xml;

    } catch (MalformedURLException e) {
        System.out.println("MalformedURLException: " + e);
    } catch (IOException e) {
        System.out.println("IOException: " + e);
    }
    return null;
}

and this is my web service implementation code for this method
@POST
@Path("createBooking")
@Consumes({MediaType.APPLICATION_XML})
public Bookings createBooking(@QueryParam("param1") String param1, @QueryParam("param2") String param2, @QueryParam("param3") String param3, @QueryParam("param4") String param4, @QueryParam("param5") String param5, @QueryParam("param6") byte[] param6 ){

    // needs implementation
    return null;
}

i have currently tried puttin the encoded byte[] into the url but it cannot hold all of the byte[] information, i have looked at using the httpurlconnection POST method but i dont quite understand how to use it in my situation.
How would i go about doing this?
thanks

A: So basically, with my POST methods, i changed the parameters in my webservice to @formparams and made it that it consumses application/x-www-form-urlencoded. i also changed the variable to a string so that the webservice recieves the base64 strings and then decoded the string with base64.geturldecoder.decode()
eg:
@POST
@Path("createBooking")
@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
@Produces({MediaType.TEXT_PLAIN})
public String createBooking(@FormParam("param1") String param1){@FormParam("param1") String param1, @FormParam("param2") String param2, @FormParam("param3") String param3, @FormParam("param4") String param4, @FormParam("param5") String param5, @FormParam("param6") String param6 ){

and in the android client i my post function:
 con.setRequestMethod( "POST" );
        con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        con.setRequestProperty( "charset", "utf-8");
        con.setRequestProperty( "Content-Length", Integer.toString( postData.length ));

        con.setDoOutput( true );

        con.setUseCaches( false );
        DataOutputStream wr = new DataOutputStream(connect2Rest.getOutputStream());
        wr.write(postData);
        wr.flush();
        wr.close();

where the byte array was encoded to string with
Base64.encodeToString(byte[],  Base64.NO_WRAP + Base64.URL_SAFE);

it didnt work before because the byte array encoded string was too long as a url parameter, hence the only way to do it was to put it in the body of the method and send it that way.


text:
Q: Output for scraped data with Text value in CSV file I am new to web scraping using Python and need help on extracting Sub category name (Title) and the Page Title (Main Category Header) with the URLs that is being scraped with my Python code. I tried .text with beautifulsoup but I think there could be better option to do this task as I am getting error and no output once used.
Help would be appreciated. Please take a look at the code and help with Output stored in csv file with URL \t Sub category title \t Main Category header.
Example: Subcategory URL
Required:
http://www.medicalexpo.com/medical-manufacturer/neonatal-incubator-2963.html        Neonatal incubators        Pediatrics
http://www.medicalexpo.com/medical-manufacturer/infant-radiant-warmer-13522.html
Infant radiant warmers      Pediatrics
http://www.medicalexpo.com/medical-manufacturer/infant-phototherapy-lamp-44327.html        Infant phototherapy lamps        Pediatrics

Something like this
Code:
from bs4 import BeautifulSoup
import requests
import unicodecsv
import time
import random

def get_soup(url):
    return BeautifulSoup(requests.get(url).content, "lxml")

url = 'http://www.medicalexpo.com/'
soup = get_soup(url)
raw_categories = soup.select('div.univers-main li.category-group-item a')
print(raw_categories)
category_links = {}

for cat in (raw_categories):
    t0 = time.time()
    response_delay = time.time() - t0
    time.sleep(10*response_delay)
    time.sleep(random.randint(2,5))
    soup = get_soup(cat['href'])
    links = soup.select('#category-group li a')

    category_links[cat.links] = [link['href'] for link in links]
    print(category_links)


text:
Q: STM with fclabels I built a small game engine to manage a board of squares (currently used for playing a Conway's game of life). All the data is accessed throught lenses from fclabels and State. The engine couples user input and graphic rendering (usual game loop).
The computations between frames can sometimes be slow and long to execute. So I would like to use concurrency to manage the squares, using STM's TVar.
My data is currently represented like this:
data World = World {
    … -- window configuration, not important
    , _squares :: TVar [Square]
}

mkLabels [''World] -- creates labels, similar to mkLenses

My functions run in the Game Monad, which is defined as follow:
type Game a = StateT World IO a

Using the monadic versions of labels. I use Getters & Setters inside my monad.
I would like to know if there is a way to somehow write new labels that behave like these:
gets :: MonadState f m => Lens (->) f o -> m o
…
puts :: MonadState f m => Lens (->) f o -> o -> m ()

But that takes care of STM (gets would involve readTVar, puts would involve writeTvar, etc.).

A: If I understand you correctly, you want to define a lens tlens s.t.:
gets tlens

is the same as:
do tvar <- gets squares
   sqs <- liftIO $ atomically $ readTVar tvar
   return sqs

and where puts tlens sqs is the same as:
do tvar <- gets squares
   liftIO $ atomically $ writeTVar tvar sqs

I think this can be answered by looking at the type of gets:
gets :: MonadState f m => Lens (->) f o -> m o

The lens parameter is pure and not monadic. To get at the contents of the TVar you'll need to run code in the IO-monad.
Moreover, the definition of gets in Data.Label.Monadic is (link) is:
gets lens = State.gets (Total.get lens)

where State is Control.Monad.State and Total is Data.Label.Total.
But State.gets takes a pure function, so again you're not going to be able to create a lens which will work with gets.


text:
Q: NSEvent addGlobalMonitorForEventsMatchingMask: Hotkey Intercepting I wanna intercept hotkeys that begin with Control+Shift and ends with a character (mandatory).
I have the following code:
[NSEvent addGlobalMonitorForEventsMatchingMask:NSFlagsChangedMask handler: ^(NSEvent *event) {
    NSUInteger flags = [event modifierFlags] & NSDeviceIndependentModifierFlagsMask;
    if(flags == NSControlKeyMask + NSShiftKeyMask){
        NSLog(@"pressed!");
    }
}];

What do i need to add to my code to check if the user pressed ControlShift+character, and what character the user pressed?
The code NSLog(@"pressed!"); will be executed only if what i said above is true.
This is my pseudo-code for what i'm looking for:
[NSEvent addGlobalMonitorForEventsMatchingMask:NSFlagsChangedMask handler: ^(NSEvent *event) {
    NSUInteger flags = [event modifierFlags] & NSDeviceIndependentModifierFlagsMask;
    if((flags == NSControlKeyMask + NSShiftKeyMask) && [event containsCharacter]){
       NSLog(@"%@", [event character];
    }
}];

So if the user presses Control+Shift+1 i'll do one thing, if Control+Shift+2 other thing, and so on...

A: You need to compare bitwise:
- (void)keyDown:(NSEvent *)theEvent {
    if ([theEvent modifierFlags] & (NSControlKeyMask | NSShiftKeyMask)) {
        if (theEvent.keyCode == 1/* add the right key code */) {
            NSLog(@"Do something");
        }
    } else {
        [super keyDown:theEvent];
    }
}

A: Try this:
 [NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *event) {
    NSUInteger key = 8; // 8 is "C"
    NSUInteger modifier = NSControlKeyMask + NSShiftKeyMask;
    if ([event keyCode] == key && [NSEvent modifierFlags] == modifier)

NSLog(@"pressed!");

}];


text:
Q: Jenkins get sha256 for an artifact I would like to download an artifact from a Jenkins job. While this is straight-forward, I also, in advance, need a sha256 of the artifact but could not find a way yet, to retrieve it.
So question is - is there any way to get the hash or at least a way to upload the sha256, so it directly gets exposed by the REST API?

Caveat - I have artifacts above 1GB, as such I do not want to manually generate the sha256 in the Job, but have it processed "offline" somewhere not impacting Job time.


text:
Q: python - calculation inside arguments Can "cur_range + range_nmbr" inside the arguments cause problems?
   my_thread = threading.Thread(target=check,args=(cur_range, cur_range + range_nmbr))
        my_thread .start()
        thread_counter += 1
        cur_range += range_nmbr

A: No, it won't cause any problems in your code. Python will first add this two values and then process the rest of the code


text:
Q: Batch file renaming: How to preserve the order of filename? I have 1000 images that I want to rename them from 1 to 1000. I found this solution (the most voted answer):
dirData = dir('*.png');         %# Get the selected file data
fileNames = {dirData.name};     %# Create a cell array of file names
for iFile = 1:numel(fileNames)  %# Loop over the file names
newName = sprintf('%04d.png',iFile);  %# Make the new name
movefile(fileNames{iFile},newName);        %# Rename the file
end

But it falls short when the number of digits from the original file name changes. Specifically:

*

*After renaming 10 images, the tenth image becomes the number one.

*Applying the code on 101 images, 101th image becomes the first, 100th becomes the second and the tenth becomes the third.

This affects my dataset because their position is important.
The aim is renaming the images from 1,2,3,.... to N. Any way to fix this problem?

My original file names are in the form of 90_AAA_AA_CC and the first number of the above form, varies from 1 to N for N images.
From "dirData.name", the orders for 100 images are as follows:
100,10,11,12, ...
19,1,20,21, ...
29,2,30,31, ...
39,3,40,41, ...
49,4,50,51, ...
59,5,60,61, ...
69,6,70,71, ...
79,7,80,81, ...
89,8,90,91, ... 99,9

A: The following does what you want. The problem is that the files are currently in lexicographic order, which does not take the whole number into account, but only the separate digits.
By using a regular expression to get the digits from the filename, and then converting this to a number using str2double, you can keep the correct numbering.
dirData = dir('*.png');         % Get the selected file data
fileNames = {dirData.name};     % Create a cell array of file names
for iFile = 1:numel(fileNames)  % Loop over the file names
    fileName = fileNames{iFile};
    imgNum = str2double(regexp(fileName,'\d*','Match')); % get the img number from the filename
    newName = sprintf('%04d.png',imgNum);  % Make the new name
    movefile(fileName,newName);        % Rename the file
end


text:
Q: Is Swift able to read an input which consists of several lines? So, the input looks like this:
1 2
3 4
5 6
7 8

And I need to store each line as an array, like this:
[1, 2]
[3, 4]
[5, 6]
[7, 8]

I guess I can do this with .componentsSeparatedByString(" ") and then converting each element to an integer.
The problem is, I've tried using readLine(), but it only stores the first line, 1 2. I've thought about doing a while loop, but my input can contain more than 50 lines, and entering every single line would be pretty inconvenient.
Is there a way to store several lines as a string at once? It would also be good if I could replace the line breaks with ;, but I have no idea how, since it only stores the first line. Any help would be appreciated.
Thanks in advance!

A: You can use componentsSeparatedByCharactersInSet to break up your lines, then map each line breaking up your elements and finally map them to Int:
let strInput = "1 2\n3 4\n5 6\n7 8"

let numbers = strInput.componentsSeparatedByCharactersInSet(.newlineCharacterSet())
                      .map{$0.componentsSeparatedByString(" ")
                      .map{Int($0) ?? 0}}

print(numbers)  // [[1, 2], [3, 4], [5, 6], [7, 8]]


text:
Q: Updating output file The program should then access/create a report file (called output.txt) where the result of this calculation will be saved.
Notice that if the "output.txt" file already exists then the program should just append the existing data by adding the result of this calculation.
while(choice==1){
int choice1;
        menu();
        cin>>choice1;
        cout<<endl;

        if (choice1==2){
            int num, counter=0;
            int node=0;
            cout<<"Please give the node you are looking for: ";
            cin>>node;

            for (num=0;num<arcs;num=num+2){
                if (node==tail[num]) {
                    counter++;

                }
            }
                cout<<"There are "<<counter<<" arcs leaving node "<<node;
            cout<<endl;
            outfile.open("output.txt");
            if(outfile.is_open()){
                outfile<<"There are "<<counter<<" arcs leaving node "<<node<<endl;

            }
outfile.close();//when I choose option 2 again it replaces the previous one
cout<<"Report stored in file: output.txt."<<endl<<endl;

when I choose option 2 a second time the previous output is replaced by the new one.

A: This should add text to the end of your file.
#include <iostream>
#include <fstream>

using namespace std;

int main() {

 fstream addtext;

addtext.open ("testdoc.txt", fstream::in | fstream::out | fstream::app);

addtext<<"testTestTest"<<endl;

addtext.close();
            return 0;
        }


text:
Q: Callback with reference to itself vs. standalone subclass Maybe stupid question, but I can't understand...
Is there a difference between the following ways?
I mean waste memory or something?
class A implements Handler.Callback {
    // is it OK to pass the loopback reference into the Handler in this case?
    Handler mHandler = new Handler(this);
    public boolean handleMessage(Message msg) {
         ...
    }
}

class B {
    Handler mHandler = new Handler() {
         @Override
         public void handleMessage(Message msg) {
             ...
         }
    };
}

Thank you!

A: I would say it depends on your desired usage. If you have just one button and need to handle its click, I would use an anonymous class (like in your class B). But if a view contains lots of buttons or other things, you want to handle click events for, I would use the first method with one single handler for all controls. This saves you creating an extra object for each control (coding and memory overheap), too!
I am using this way in a project currently, having my activity handling every click and then doing the further work:
public class MyActivity extends Activity implements View.OnClickListener {

...

@Override
public void onClick(View view) {
    switch (view.getId()) {
    case R.id.button1:
        // handle button 1
        break;
    case R.id.button2:
        // handle button 2
        break;
        // ...
    }
}
...
}


text:
Q: TableViewCell delete is not animated on alertViewController action I am adding a "delete" button inside a tableview cell, which presents an alertController in alert mode. On the "destroyAction" I delete the data and fire delete the row from table.
let destroyAction = UIAlertAction(title: "Delete", style: .destructive) { (action) in
let indexPath = tableView.indexPath(for: cell!)

   self.numbers.remove(at: (indexPath?.row)!)
   tableView.deleteRows(at: [indexPath!], with: .right)
    }
}

Problem is that the row is deleted without animation.
But when I wrap it inside with DispatchQueue.main.async {} then the animation will work.
let destroyAction = UIAlertAction(title: "Delete", style: .destructive) { (action) in
let indexPath = tableView.indexPath(for: cell!)

   DispatchQueue.main.async {
   self.numbers.remove(at: (indexPath?.row)!)
   tableView.deleteRows(at: [indexPath!], with: .right)
    }
}

Can someone explain why this made animation to work and if there is a simpler way to achieve this.


text:
Q: Using Option and strings instead of Some in code I've seen a lot of times code like this:
...
val aString: String = someFunctionDataReturnsAString()
...
if (someCondition) Some(aString)
else
...

Is it right to create a new Option using Some(aString)?
What if for some reason turns out the value of aString is null?
Wouldn't be good replacing the if sentence with:
if (someCondition) Option(aString)

Because:
val a = Some("hello")
val b: String = null
val c = Some(b)
val d = Option(b)
println(a)
println(c)
println(d)

Will print in the console:
Some(hello)
Some(null)
None

Looks like a better idea to use Option when passing a string as parameter, so in case the string is null the value of the Option will be None.
I've seen code to be reviewed and I think with cases like this a comment should be added asking for replacing Some(aString) with Option(aString).

A: You are right. Assuming your string can be null, it's recommended to use Option(aString):

def apply[A](x: A): Option[A]
An Option factory which creates Some(x)
if the argument is not null, and None if it is null.
x - the value
returns - Some(value) if value != null, None if value == null

Class Option mentions that both have their use case, so the programmer has the last say which one is better suited for his particular need:

Interacting with code that can occasionally return null can be safely
wrapped in scala.Option to become None and scala.Some otherwise.

On a personal note, since strings are immutable and you can't really have uninitialized strings (because Scala always requires you to initialize them - unless you use var variables, which is not the recommended way to program in Scala anyway), you'll rarely actually encounter null strings in your code.
That being said, one can still decide to go for Option(aString) every time, and it's perfectly fine.

A: Normally it's ok to replace Some.apply with Option.apply (and safer).
But, although normally this is not a big deal (and let's avoid premature optimizations), there can be minor runtime overhead for Option.apply, since we add another branching instead of just wrapping.
Generally, you could split your project into pure FP part (it's ok to assume that your strings are not null there and use Some.apply, also Some.apply is canonical monadic pure for Option) and part where you interact with the outer world, with Java libraries etc. (it's more safely to use Option.apply there).
But we should keep in mind that Some.apply returns Some[A] while Option.apply returns its supertype Option[A]. Normally it's ok but sometimes in type-level calculations this can be too rough if you need to know precise type at compile time. See for example Shapeless and annotations , how to use shapeless to detect field type annotation


text:
Q: Magento 2 sitemap wrong paths in sitemap index when running on cron I am using Magento 2.2.2.
Please see below the current settings of the sitemap.

It works correctly when we create sitemap by hitting generate button in admin. But when it gets generated automatically using cron it shows /public_html/ in sitemap index for sub-sitemaps, please see below image, its sitemap.xml

Thank you

A: Fixed it.
Its not recommended but you can try it as temporary fix. Override below file.
Magento_Root/vendor/magento/module-sitemap/model/sitemap.php
comment line 705
// return realpath($this->_request->getServer('DOCUMENT_ROOT'));
And add your own domain directly.
return 'https://www.example.com';
Working for now.


text:
Q: How to correctly implement dynamic prototype cells in a UITableView I, previously, had an issue where my UITextView was incapable of functioning, entirely. Since then, another user has taken a lot of time to help me solve this issue. I can say that it was successfully resolved. However, I now have an additional issue. When attempting to utilize properties of a prototype cell, which I've already made a UITextViewCell custom class for, as well as linked all the appropriate items, I run into an issue where the properties of the cell are being ignored. Only one property every shows, the dimensions are incorrect and the property that shows doesn't have correct formatting. If you have time, can someone do a step by step, possibly with images, detailing EXACTLY what to do to make a custom table view cell that initializes correctly? You can assume that the table view and accompanying arrays etc. are already correctly initialized. Thank you.

A: Make sure you set both values...
With the Table View selected - note the Value for Row Height:

With the Cell selected - note the Value for Row Height:


text:
Q: How can I get prioritize output of a query based on where condition I have a query which is shown below
SELECT * FROM vehicle_type_master order by standard_volume asc

which yields following result
Vehicle_Type_ID    standard_volume
 TATA ACE            20
  407                30
 20 FT               40

So there may arise the following condition, the query looks like
1st Instance:
SELECT * FROM vehicle_type_master where Vehicle_Type_ID    = '407'

So for this query the desired result should come like
Vehicle_Type_ID    standard_volume
  407                30
TATA ACE             20
 20 FT               40

2nd Instance:
SELECT * FROM vehicle_type_master where Vehicle_Type_ID    = '20 FT'

So for this query the desired result should come like
Vehicle_Type_ID    standard_volume
  20 FT                 40
TATA ACE                20
  407                   30

So whichever the condition is present in where the condition that should come first and other rows should be displayed as per standard_volume asc.
Any help appreciated

A: You can use CASE WHEN with multiple ORDER BY
SELECT *
FROM vehicle_type_master
ORDER BY (CASE WHEN Vehicle_Type_ID  = '407' then 0 else 1 end) ,
standard_volume asc

SQLfiddle:http://sqlfiddle.com/#!9/1b3907/10
most simple way you can use IF and ORDER BY
SELECT *
FROM vehicle_type_master
ORDER BY IF(Vehicle_Type_ID ='20 FT',0,1),standard_volume asc

sqlfiddle:http://sqlfiddle.com/#!9/1b3907/9


text:
Q: How to avoid redundant code in designing inheritance in C++ Say I have a Base class called Car and it has 3 derived  classes say Ford, Honda and  Audi.
The issue is, all three derived classes have exactly same code but minor difference in calling member functions of  their respective engines (these engines have separate class).
For example, Ford class calls code which is exactly same as other two  classes  but do call something like ford_engine-> start(),  ford_engine->clean() etc.
//ly  honda  calls   honda_engine->start()   honda_engine->clean();

//ly  Audi calls audi_engine->start()  audi->clean();

Now here the issue is, it has redundant code in all three places with minute difference. How can I have code at one place, most  probably in base class and all derived classes use same code?

A: First of all, Ford, Honda and Audi probably should not be classes derived from Car. Derivation should reflect differences in behavior on an abstract level.
In this case, it probably makes more sense to simply have a Car object with a field identifying the manufacturer. The Car owns an engine--but in a typical case, you don't need a different class for each brand of engine either; at an abstract level, the brand is generally irrelevant.
As such, you can have something like:
class Car {
    class Engine {
        enum { diesel, piston, rotor, electric, hybrid } type;

        int HP;
        int torque;
        int max_rpm;

        bool running;

        void start() { running = true; }
        void stop() { running = false; }
        // ...
    } engine;

    std::string brand;
    std::string model;
};

In a few cases you honestly need to model an engine at a level of detail where things like firing order really matter, and you'll need much more detail than this. It should still be at a behavioral level though. If you had a Ford_motor vs. Honda_motor the brand should still really be a short-hand for behavioral differences. You really want to maintain the most abstract view you can though, so you usually want to model an engine (car, etc.) in terms of behavior. The difference between a Ford and a Honda motor should be things like one has higher torque and the other higher red-line than the other; these differences can be modeled quite easily by supplying suitable parameters when instantiating the object. If Ford and Honda were to produce engines with identical characteristics (not just power, but power curves, etc.) then the difference in brand is irrelevant to your modeling.
Oh, and no you should not have a getEngine as a member of a Car. A car is a car. It has an engine. If you provide a getEngine at all, it should be a member of AutoPartsStore or something on that order (but unless you're dealing with buying and selling engines, you probably shouldn't have such a thing at all).
When a person starts their car, the don't get the engine and start the engine. They start the car and after they do so (successfully), the car is running. Forcing a client to use a getEngine and start the engine is both crappy from a coding viewpoint and from a modeling viewpoint--starting my car does more than just start the engine. It also controls things like some of the lights, the radio, heating/air conditioning, and so on. One of the basic points of object-oriented programming is to protect client code from dealing with all these internal details, not to force them to deal with the details and use crappy getXxx() syntax to do it!

A: The idea is to add a read only protected member variable (i.e. a protected property) engine to your superclass. Then, redefine the accessor in the subclasses to return the proper engine instance. Your code become this->getEngine()->start() and so on.


text:
Q: Doubling measure is absolutely continuous with respect to Lebesgue Let $\mu$ be a fixed finite measure on $\mathbb R$. We say that $\mu$ is doubling if there exists a constant $C>0$, such that for any two adjacent intervals $I=[x−h,x]$ and $J=[x,x+h]$, $$C^{−1}\mu(I)≤\mu(J)≤C\mu(I).$$
Assuming that $\mu$ is doubling, show that there exist positive constants $B$ and $a$, such that for every interval $I$, $$\mu(I)≤B[length(I)]^a$$
By Radon-Nikodim, I solved but I use the fact that $\mu$ is absolutely continous with respect to Lebesgue measure, but I don't know to prove this last part, i.e., that $\mu$ is absolutely continuous with respect to Lebesgue.


text:
Q: Pandas - group by to return first occurence and there on every third occurence of a value I am trying to filter records from a Dataframe based on their occurence. I am trying to filter out the first occurence and then on every third occurence based on emp_id. Given below is how my Dataframe is.
emp_id,date,value
101,2018-12-01,10001
101,2018-12-03,10002
101,2018-12-05,10003
101,2018-12-13,10004

In the above sample, expected output is :
emp_id,date,value
101,2018-12-01,10001
101,2018-12-13,10004

Given below is the code I have built this far:
df['emp_id'] = df.groupby('emp_id').cumcount()+1
df['emp_id'] = np.where((df['emp_id']%3)==0,1,0)

This however returns back 2nd occurence and every third occurrence after that. How could I modify such that it returns back the first occurence and then on every third occurence based on emp_id

A: I think you need boolean indexing with check 0 or 1, assign to column is not necessary, is possible create helper Series s:
print (df)
   emp_id        date  value
0     101  2018-12-01  10001
1     101  2018-12-03  10002
2     101  2018-12-05  10003
3     101  2018-12-13  10004
4     101  2018-12-01  10005
5     101  2018-12-03  10006
6     101  2018-12-05  10007
7     101  2018-12-13  10008

s = df.groupby('emp_id').cumcount()
df['check'] = (s % 3) == 0

Alternative:
s = df.groupby('emp_id').cumcount()  + 1
df['check'] = (s % 3) == 1

print (df)
   emp_id        date  value  check
0     101  2018-12-01  10001   True
1     101  2018-12-03  10002  False
2     101  2018-12-05  10003  False
3     101  2018-12-13  10004   True
4     101  2018-12-01  10005  False
5     101  2018-12-03  10006  False
6     101  2018-12-05  10007   True
7     101  2018-12-13  10008  False


text:
Q: Stop HCE if sdk < Kitkat I have a weird question. I want to know if I can block the hce feature/service if the device sdk is smaller than the required Kitkat sdk?
At the moment I stop my HCe service at the startup of my app but I am not sure if thats the correct way
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT){
                //Disable Hce service if sdk < 19
                Intent intent = new Intent();
                intent.setComponent(new ComponentName("at.ventopay.mocca.hce_service", "at.ventopay.mocca.hce_service.MyHostApduService"));
                stopService(intent);
            }

It works like a charm but I m just not convinced that I should even do this.
My question now is:       Can I block the HCE feature if the device sdk is wrong or does my device need to be  >=Kitkat if I use HCE?

A: There is no reason to stop your HCE service on platform versions < 19. If your Android version does not support HCE/use your HCE service, it will not even generate an event that starts the service component in the first place.
Your service is registered with the system through a section like this in your manifest:
<service android:name="..." android:exported="true"
         android:permission="android.permission.BIND_NFC_SERVICE">
    <intent-filter>
        <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE" />
    </intent-filter>
    <meta-data android:name="android.nfc.cardemulation.host_apdu_service"
               android:resource="@xml/apduservice"/>
</service>

So the service can only be started by binding to it with the intent action android.nfc.cardemulation.action.HOST_APDU_SERVICE (or with an explcit intent for your service component). Moreover, only an application that holds the permission android.permission.BIND_NFC_SERVICE can do that.
As a platform prior to Kitkat neither knows about that intent nor about that permission, it will not cause your service to be started.


text:
Q: Data transfer from controller to view page When I set a "message" attribute in ModelMap, it does not get displayed in the JSP.  Instead of value of "message", string literal ${message} is getting displayed in browser
UserHandler.java

hello.jsp

spring-bean-config.xml

web.xml

Result page:  Here I expect to see welcome instead of ${message}

A: Your problem is not in the controller, but in your view hello.jsp. What is happening is the view interpret  ${message} as a literal text, not as the value of an attribute.
I've never work with jsp, but the following might do the trick for you.
In hello.jsp change the line: ${message} for something like : <c:out value="${message}" />

A: user1442922,
Do you have the root root declarations on top of your web.xml and spring-bean-config.xml and just leave them off in your post for brevity? If you don't have them in your .xmls, try adding them, the one for web.xml should look something like:
<web-app
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">


text:
Q: How to create custom assertions for collections in AssertJ There is an example on how to create custom assertions for custom classes in AssertJ:
http://joel-costigliola.github.io/assertj/assertj-core-custom-assertions.html
But what about collections of custom classes?
How to create assertions for them?

A: Two features exist for collection custom assertions :

*

*use a specific element comparator + standard assertions collections

*use a Condition to verify something on one or several collections elements
Hope it helps


text:
Q: how to get yesterday from whenever the QdateEdit pyqt I am using a PyQt5 GUI application and I need to get the value of yesterdays from any date in the QdateEdite I have inside the GUI application, for example I want to choose the day I use this code
date_n = str(self.dateEdit_2.text())

How can I get the ysterday of the day_n whenever the date_n it will be?

A: You have to get the QDate from QDateEdit, then subtract one day from it and then convert it to a string:
selected_dt = self.dateEdit_2.date()
last_dt = selected_dt.addDays(-1)
last_dt_str = last_dt.toString(self.dateEdit_2.displayFormat())
print(last_dt_str)


text:
Q: Combination C code for a random set of integers I have a random set S={3,12,15,24,33,40} and I need to generate subsets of size 3 from this set.Most of the examples and explanations regarding combination involved a set of increasing and ordered values like S1={1,2,3,4,...n}. Using the combination formula,I found that the number of possible combinations is 20 but can't figure out how to generate that list in C.
What if the set is random like S above and how do I get the possible list without duplicates in C?
Thanks.

A: Use the algorithms you have seen that have increasing, ordered values and simply replace those with the values in your list.
For example, the combinations (0-indexed) would be:
0, 1, 2
0, 1, 3
0, 1, 4
...
...

Then have an array with your numbers
int array[] = { ...values... };

and change the combinations to:
array[0], array[1], array[2]
array[0], array[1], array[3]
...
...

A: You can generate all combinations of n items recursively. Something like this should work:
void combos(int[] values, int[] used, int[] selected, int len, int needed, int next) {
    int i;
    if (needed > 0) {
        /* select each available item as the next item and recurse */
        for (i = 0; i < len; i++) {
            if (!used[i]) {
                used[i] = 1;
                selected[next] = values[i];
                combos(values, used, selected, len, needed-1, next+1);
                used[i] = 0;
            }
        }
    } else {
        /* selected[0] .. selected[next-1] contains a combination */
        reportCombination(selected, next);
    }
}

Call this with next=0 and needed=3 to get the ball rolling and it should generate 20 calls to reportCombination, each with a unique combination of 3 values. (If you need to collect an array of all combinations, then you don't need reportCombination, but you will need extra bookkeeping arguments or else some global variables.)

A: You are asking for a subset of the Power set of S, called by convention P(S) — namely all three-element sets in the Power set P(S).
You could modify the Power set function in this C code example to output sets of a certain cardinality (count).

A: Use the cartesian product of the same set again by removing the repeations,,
try this code,,
int array[6]={3,12,15,24,33,40};
int combinations[20][3];
int n=0;
for(i=0;i<4;i++)
{                      //loops for 1st num in combination
   for(j=i+1;j<5;j++)
   {                       //loops for 2nd num in combination
     for(k=j+1;k<6;k++)
     {                         //loops for 3rd num in combination
        combinations[n++]={array[i],array[j],array[k]};
     }
   }
}

At-last the combinations 2D array will have all the possible combinations of numbers without repeatition


text:
Q: POSIX: perror() - what does "MT-Safe race:stderr" mean? Please can someone help me to understand the POSIX safety concept, especially for perror(). The man page states that perror() is "MT-Safe race:stderr". As perror() outputs to standard error I would like understand what the given race condition means for the implementation.
Does this mean that output on stderr may be mixed, or are there other things someone must care about?

A: It means that perror writes into stderr and stderr is not thread-safe. The race condition means that you may get interleaved output if multiple threads write into stderr simultaneously.
POSIX requires most functions to be thread-safe:

All functions defined by this volume of POSIX.1-2017 shall be thread-safe, except that the following functions1 need not be thread-safe.

perror is not in that list.


text:
Q: Insert parent-child rows using Parallel programming I have a method that iterates the rows using for loop and inside that for loop call the DNN API that inserts a parent child row into the database. The maximum to insert the data is 1000 rows per execution. I tested it on my local machine the performance is very slow. I am thinking to use a Parallel Programming, but not sure on how to implement this since there is a dependency on data insertion because of parent child relationship. And I am not sure if this is a good approach to use Parallel programming. Any help please?
Sample code
        private void AddTab()
        {
           for (i = 0; i < 1000; i++) {
               TabController tabController = new TabController();
               var portalSettings = new
                  DotNetNuke.Entities.Portals.PortalSettings(info.PortalId);

                TabInfo tab = new TabInfo();
                tab.PortalID = info.PortalId;
                tab.TabName = info.TabName;
                tab.Title = info.Title;
                tab.Description = info.TabName;
                tab.KeyWords = info.TabName;
                tab.IsVisible = info.IsVisible;
                tab.DisableLink = info.IsDisabled;
                tab.ParentId = info.ParentId == null ? Null.NullInteger : info.ParentId.GetValueOrDefault();
                tab.IsDeleted = false;
                tab.Url = "";
                tab.SkinSrc = "[G]Skins/HRT.Portal.DNNThemes.Default/Home.ascx";
                tab.ContainerSrc = portalSettings.DefaultPortalContainer;
                tab.IsSuperTab = false;

                 var parentPage = tabController.GetTab(portalSettings.HomeTabId, info.PortalId);

            //clone parent page permissions
                 foreach (TabPermissionInfo permission in parentPage.TabPermissions.ToList())
                 {
                     tab.TabPermissions.Add(permission);
                 }

                int tabId = tabController.AddTab(tab, true);
        }
}


text:
Q: Fastest way to calculate minimum distance from a large set of locations to facilties in R/sf I have two CSV files containing the coordinates of locations (11 million rows with three columns : "lid", "lat", "lon") and facilities (50k rows columns "fid", "lat", "lon"). For each location, I need to calculate the minimum distance to the nearest facility.
I know how to do this using "st_distance" in R. However, "st_distance" is taking ages because it first calculates the full matrix of distances and the two files are pretty large. I have tried breaking the location files intro smaller groups and use "future_map" across 3 cores, it is taking a lot more time than I expected. Is there a way to speed up the process?

A: Have you thought about using st_buffer first? This would limit the amount of locations you would need to search to find the closest location. For example start with a radius of 10 miles and see if that captures all of the data. If that doesn't work maybe try the findNeighbors() function. See documentation https://www.rdocumentation.org/packages/fractal/versions/2.0-4/topics/findNeighbors
In the future it would also be good if you provided a sample of your data.

A: I am sure there must better ways of doing this but this is how I would do it. Hope it is helpful.
library(tidyverse)
library(furrr)

MILLION_1 <- 10^6
K_50 <- 10^4*5

# dummy data --------------------------------------------------------------------

d_1m <-
  tibble(
    lid_1m = 1:MILLION_1,
    long_1m = abs(rnorm(MILLION_1) * 100),
    lat_1m = abs(rnorm(MILLION_1)) * 100
  )

d_50k <-
  tibble(
    lid_50k= 1:K_50,
    long_50k = abs(rnorm(K_50) * 100),
    lat_50k = abs(rnorm(K_50) * 100)
  )

# distance calculation for each facility ------------------------------------------

future::plan(multiprocess)

d_distance <-
  # take one row of facility: long,lat and id as an input
  future_pmap_dfr(d_50k, function(...){
  d50_row <- tibble(...)
  # to calculate distance between one facility location and 1 million other locations
  d <- tidyr::crossing(d_1m, d50_row)

  d %>%
    mutate(
      #euclidean distance
      distance = sqrt((long_1m - long_50k)^2 + (lat_1m - lat_50k)^2)
      ) %>%
    # to get the location which is the closest to the facility
    filter(distance == min(distance))

})


text:
Q: App Engine backup never finishes only clue is failure in map reduce worker_callback Over the last few weeks we have repeatedly failed on doing a complete backup of the data store using the datastore admin tool.  We thought the issues had to do with quota errors we were running into so we switched our application from a free to a paid app and we still have problems.
Each time we are attempting to back up to the blobstore and what occurs is that the process never finishes.  We see the backup in our Pending Backups list but it never actually completes.  We only have a total of 43MB of data right now so we don't see it as a data transfer problem.  Looking at our default Task Queues it shows that we have two pending tasks one is a call to  /_ah/mapreduce/controller_callback and another is a call to  /_ah/mapreduce/worker_callback
The worker_callback racks up its retry count and the only error clue we have is on the Previous Run tab it shows the last http response code to be 500.  There is no error message, nothing shows up in our error logs, it just keeps trying over and over again.
We've been able to narrow the backup problems to a specific entity kind for a particular namespace but we can't figure out why that entity kind is failing whereas the others are not.  The major difference is the entity kind has a large number of embedded entities, but if the app engine is able to read / put those entities we can't understand why it seems to be having problems backing it up.  The particular namespace that the error occurs in has the largest data stored for that entity kind compared to the other namespaces we have setup.
We think if we can see what error is occurring in the worker_callback we may be able to figure out why the backup is failing, or what is wrong with our data that's preventing the backup. Is there something we need to setup / enable through settings / configuration files to give us more detailed information on the backup?  Or is there some other avenue we should explore to figure out how to investigate/fix this problem?
I should mention we are using the Java SDK as well as Objectify V3 to work with the data store.  We are also backing up data to the Blobstore.
Thank you.

A: Well with the app engine team's help we figured what the problem was and we worked around the issue.  I want to give details in case anyone else runs into this problem.
From issue 8363 the app engine team indicated that from their logs they could see that the map reduce failed because of the large number of properties that our entity kind had.  The specific entity kind that was causing the failure had a large number of variable properties that was generating errors when map reduce tried to write out a schema.  They indicated that the solution on their end was to ignore entities that were like this in the backup to make it so the backup worked successfully.
What we did to work around the issue and make the backup work was change how we told objectify to store out data.  The large number of properties were being created due to our use of the @embedded keyword on a HashMap() class member field.  Since the embedded keyword breaks down classes into individual components it was generating a large number of properties.  We switched the member field to be @serialized and then ran a conversion process to make it use the new serialized property.  This made the backup / restore work again.
You can read more about the differences between embedded and serialized on objectify's website

A: snielson, would you mind opening an issue on our Public issue tracker here. Remember to add your Application ID so we can further debug this specific scenario.
Thanks!


text:
Q: How do I get a Zenity feature in Yad? I have the following twenty-six files in a folder:
$ ls
a.txt  c.txt  e.txt  g.txt  i.txt  k.txt  m.txt  o.txt  q.txt  s.txt  u.txt  w.txt  y.txt
b.txt  d.txt  f.txt  h.txt  j.txt  l.txt  n.txt  p.txt  r.txt  t.txt  v.txt  x.txt  z.txt
$

I can use Zenity like this:
zenity --list --title=Test --width=275 --height=400 --column="File names" *.txt

and get this interface initially:

If I want to select a file lower down the list, say, r.txt, I press r and r.txt is selected.

However, if I use Yad instead of Zenity like this:
yad --list --title=Test --width=275 --height=400 --column="File names" *.txt

pressing r does nothing. I have to use the arrow keys to scroll through the list until I come to r.txt.
My understanding is that Yad has more features than Zenity. So is there some way to get Yad to do what Zenity does?
(Tested using the repository versions of Yad and Zenity found in 18.04 and 19.10.)

A: For learning yad I found this great reference: YAD - Smokey01.com
As mentioned in comments you want to use the option --search-column=N
Take the following code snippet as an example:
while true ; do
    local Selected INSTRUCTIONS
    INSTRUCTIONS="Click Icon to move and press Enter"
    Selected=$(yad --list --radiolist \
    --image="$ICON" --window-icon="$ICON" \
    --margins=10 --no-click  --search-column=4 \
    --title="$TITLE" "${GEOMETRY[@]}" \
    --text="<big><b>$TEXT</b></big> - $INSTRUCTIONS" \
    --column "Select" \
    --column "Order" \
    --column "Icon Type:HD" \
    --column "Icon name" \
    --column "Linkless name:HD" \
    --column "Modified date" \
    --column "Col Pos:NUM" \
    --column "Row Pos:NUM" \
    --button="_Alpha Sort:$ButnAlpha" \
    --button="_Linkless Sort:$ButnLinkless" \
    --button="_Oldest Date:$ButnOldest" \
    --button="_Newest Date:$ButnNewest" \
    --button="_Test:$ButnTest"  \
    --button="_Apply:$ButnApply" \
    --button="_Cancel:$ButnCancel" \
    "${IconsArr[@]}")

    Retn="$?"

Columns #3 and #5 are hidden but they are still counted. We want to search on Icon Name so it is column #4 as recorded here:
    --margins=10 --no-click  --search-column=4 \

The short .gif clip below shows what happens when we type:

*

*a, Backspace, b, Backspace, c, Backspace, e (then gif loops)


text:
Q: How many pairs of positive constants $a, b$ exist such that $P(a < X < b) = 0.95$, where $X$ has a chi-squared distribution? $X$ is a chi-squared distribution with $n$ degrees of freedom (sum of the squares of $n$ $N(0,1)$ variables). How many pairs of positive constants $a,b$ exist such that
$$ P(a < X < b) = 0.95 $$
I'm not really sure how to go about this - I know it can be done using the c.d.f of a chi-squared distribution but I don't think we're supposed to use this method, given that we haven't covered it yet.
Any hints would be appreciated :)

A: The CDF of the mentioned distribution is continuous and is monotonically increasing on $(0,\infty)$.
Consequently for every $a>0$ with $P(X\leq a)<0.05$ or equivalently $P(X>a)>0.95$ a unique $b>a>0$ exists such that $P(a<X<b)=0.95$.
Combining the mentioned properties of the CDF with $F_X(0)=0$ we find that the set $\{a\in(0,\infty)\mid P(X\leq a)<0.05\}$ is uncountably infinite.


text:
Q: Delphi MDI Application Next Window menu item How would I go about implementing the Ctrl+F6 Next Window action in the Windows menu for an MDI application in Delphi 7?

A: Use the Next and Previous methods of the MDI parent window. You can do this from a menu event, and assign a shortcut like any other menu item. In the code below, the MDI parent form is TFormMDIParent, and it assumes you've created two menu items captioned "Next Child" and "Previous Child", leaving their names set to the default generated by the IDE. It also assumes that you've set the main form up correctly to be the MDI parent (FormStyle = fsMDIForm).
procedure TFormMDIParent.NextChild1Click(Sender: TObject);
begin
  Self.Next;
end;

procedure TFormMDIParent.PreviousChild1Click(Sender: TObject);
begin
  Self.Previous;
end;

A: I don't think you need to do anything - it is implicit in MDI apps (created with the new MDI app wizard in Delphi 2006 anyway).
It also "just works" in an app the was originally created in Delphi 6 as well.

A: Send the main form a wm_SysCommand message. Use sc_NextWindow or sc_PrevWindow for the wParam parameter.


text:
Q: Tableau online how to integrate numerous views into one I am using Tableau public desktop - the free version.  I am trying to place multiple worksheets, and dashboards on one page and link it to my blog site.
Is there a way to customize views in this application? Something like this:
https://public.tableau.com/views/CountyGuide-Demographics_0/DemographicsAll?%3Aembed=y&%3Ahost_url=%2F%2Fpublic.tableausoftware.com%2F&%3AshowVizHome=no&%3Ascrolling=no&%3Atabs=no&%3Atoolbar=yes&%3Aanimate_transition=yes&%3Adisplay_static_image=yes&%3Adisplay_spinner=yes&%3Adisplay_overlay=yes&%3Adisplay_count=no&%3AloadOrderID=0#3
Or does it require a subscription to accomplish this feat? Is there a workaround for if not?
Thanks for any input.

A: All the cool stuff WRT layout/navigation in the sample link you posted are possible in Tableau Public.
You don't need subscription for creating dashboards and adding actions for navigation etc.
You can see Tableau Tutorials for details.


text:
Q: Redmine - Error calling Dispatcher.dispatch # I have for a few days now been attempting to install Redmine on my CentOS WHM/CPanel server and I have been able to get it to a point where is says it is running in CPanel but when I try to get to the application it never loads and I get the first below segment in my mongrel.log and the second segment in the production.log. Any ideas?
Ruby 1.8.7 (2011-02-18 patchlevel 334) [x86_64-linux]
Rails 2.3.14
<mongrel.log>
Mon May 07 20:26:30 -0400 2012: Error calling Dispatcher.dispatch #<NoMethodError: private method `split' called for nil:NilClass>
/usr/lib/ruby/gems/1.8/gems/actionpack-2.3.14/lib/action_controller/cgi_process.rb:52:in `dispatch_cgi'
/usr/lib/ruby/gems/1.8/gems/actionpack-2.3.14/lib/action_controller/dispatcher.rb:101:in `dispatch_cgi'
/usr/lib/ruby/gems/1.8/gems/actionpack-2.3.14/lib/action_controller/dispatcher.rb:27:in `dispatch'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/rails.rb:76:in `process'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/rails.rb:74:in `synchronize'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/rails.rb:74:in `process'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel.rb:159:in `process_client'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel.rb:158:in `each'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel.rb:158:in `process_client'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel.rb:285:in `run'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel.rb:285:in `initialize'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel.rb:285:in `new'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel.rb:285:in `run'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel.rb:268:in `initialize'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel.rb:268:in `new'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel.rb:268:in `run'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/configurator.rb:282:in `run'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/configurator.rb:281:in `each'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/configurator.rb:281:in `run'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:128:in `run'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/command.rb:212:in `run'
/usr/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:281
/usr/bin/mongrel_rails:23:in `load'
/usr/bin/mongrel_rails:23

<production.log>
Processing WelcomeController#index (for 24.52.2XX.XX at 2012-05-07 20:26:30) [GET]
  Parameters: {"action"=>"index", "controller"=>"welcome"}
Redirected to http://projects.mydomain.com/login?back_url=http%3A%2F%2Fprojects.mydomain.com%2F
Filter chain halted as [:check_if_login_required] rendered_or_redirected.
Completed in 38ms (DB: 35) | 302 Found [http://projects.mydomain.com/]

I have tried fixes adding the mongrel.rb patch in the initializers folder (http://www.redmine.org/issues/7688) and still no luck.
Here is the list of gems installed on my system.
actionmailer (2.3.14)
actionpack (2.3.14)
activerecord (2.3.14)
activeresource (2.3.14)
activesupport (2.3.14)
bundler (1.1.3)
cgi_multipart_eof_fix (2.5.0)
coderay (0.9.8)
daemon_controller (1.0.0)
daemons (1.1.8)
edavis10-object_daddy (0.4.3)
fastercsv (1.5.4)
fastthread (1.0.7)
gem_plugin (0.2.3)
hoe (3.0.4)
i18n (0.4.2)
json (1.7.1)
metaclass (0.0.1)
mocha (0.11.4)
mongrel (1.1.5)
mysql (2.8.1)
net-ldap (0.3.1)
passenger (3.0.12)
rack (1.1.1)
rails (2.3.14)
rake (0.8.3)
RedCloth (4.2.9)
ruby-openid (2.1.8)
rubygems-update (1.8.24)
rubytree (0.5.2)
sqlite3 (1.3.6)
tzinfo (0.3.33)

The projects subdomain .htaccess file is as follows.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^projects\.mydomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.projects\.mydomain\.com$
RewriteRule ^.*$ "http\:\/\/127\.0\.0\.1\:12001%{REQUEST_URI}" [P,QSA,L]

I'm sure it's just something I am somehow overlooking, please help. Thanks!
James

A: In the mongrel patch mentioned above, the system met all the conditions required to run the script, but in the end, after commenting out the first and last lines of mongrel.rb, the script was able to run and the site started working.
Strange, not sure what could cause it to not to pass the validation rules. Those rules are there for good reason. If anyone has any ideas, please let me know!
#if ['2.3.8', '2.3.9', '2.3.10', '2.3.11', '2.3.14'].include?(Rails.version) && Gem.available?('mongrel', '~>1.1.5') && self.class.const_defined?(:Mongrel)
....
#end

The specs of what was running was
Ruby 1.8.7 (2011-02-18 patchlevel 334) [x86_64-linux]
Rails 2.3.14
Gem: mongrel (1.1.5)

A: In this web you have one solution for your question,
http://borrowbits.com/2012/05/how-to-install-redmine-1-3-on-centos-server-with-whmcpanel/
I hope that you can install correctly Redmine
Regards,
Vicente

A: Your config/initializers/mongrel.rb might read
if ['2.3.8', '2.3.9', '2.3.10', '2.3.11','2.3.14'].include?(Rails.version) && Gem.available?('mongrel', '~>1.1.5') && self.class.const_defined?(:Mongrel)
If is that so, you can add 2.3.15 on the supported rails versions, like this:
if ['2.3.8', '2.3.9', '2.3.10', '2.3.11','2.3.14','2.3.15'].include?(Rails.version) && Gem.available?('mongrel', '~>1.1.5') && self.class.const_defined?(:Mongrel)


text:
Q: Can a nested for loop in C recursively increase in depth times a user given integer? I would like to avoid a nested for loop since it should recursively increase in depth by a user given integer.
So if the user input 3 it should be nested like the example below.. if the user input 6 there should be three more loops inside!?
#include <stdio.h>

int main(void)
{
    // int depth_lvl = 3
    char n[] = {'a','b','c'};
    int i,j,y;
    int x = sizeof(n);

    for(i = 0; i < x; i++)// <---- LEVEL 1
    {
        printf("%c\n",n[i]);
        for(j = 0; j < x; j++)// <---- LEVEL 2
        {
            printf("%c%c\n",n[i],n[j]);
            for(y = 0; y < x; y++) // <---- LEVEL 3
            {
                printf("%c%c%c\n",n[i],n[j],n[y]);
            }
        }
    }

}

A: Is it something like that what you are looking for?
The solution uses recursion together with an intermediate result string at each level, with which each state of the current level is carried over to the next deeper level.
#define MAX_DEPTH 6

void printRecursive(char n[], int x, int curDepth, char* result)
{
    // note: x is supposed to be sizeof(n).

    if (x > MAX_DEPTH)  // prohibit overflow of intermediateResult
        x = MAX_DEPTH;

    if (curDepth < x) {
        char intermediateResult[MAX_DEPTH+1];
        if (result)
            strcpy(intermediateResult,result);
        else
            strcpy(intermediateResult, "");

        for (int i=0;i<x;i++) {
            intermediateResult[curDepth] = n[i];
            intermediateResult[curDepth+1] = '\0';
            printRecursive(n,x,curDepth+1,intermediateResult);
        }
    }
    if (curDepth > 0)
        printf("%s\n", result);
}

int main(void)
{
    char n[] = {'a','b','c', 'd'};
    int x = sizeof(n);
    printRecursive(n, x, 0, NULL);
    return 0;
}


text:
Q: wordpress + cyrillic characters with SQL server 2008 r2 I have a blog running on a windows 2008 machine with SQL server 2008 r2. WP version 3.3.2
I have an English blog, but I would like to post some content in Russian.
When I try and post the content I get question marks where the Cyrillic characters should be. I see the same question marks stored in the DB.
I tried inserting the post manually in to the database and it works, i.e. the issue is not the sql server itself, since it can store Cyrillic characters.
I already tried disabling all plug-ins, and that did not help.
Is this a known issue? Is there any work around?


text:
Q: use python importlib causes lost autocomplete and lint First. Some context. I have a class that helps to import several modules, as this will be done dynamically it is important to use the importlib library, so far everything works fine. BUT ... autocomplete capability is completely lost and the lint is not responding (vs-code).
The question is: How do I recover the autocomplete and the lint?
Here is the example code:

# ----------- file foo.py
import typing, types, importlib

print("foo was imported!")

class foo () :
    def __init__ ( self ) : pass
    def foo_get_doble( self, number : int ) -> int : return number*2
    def foo_print_hello_word( self ) -> None : print("hello world")

# ----------- file __init__.py
import typing, sys, importlib

if __package__ :
    template_module = importlib.import_module( f"{__package__}.foo" )
else :
    print( "NO PKG" )
    sys.path.append( r"C:\working_folder" )
    foo_mod = importlib.import_module( "foo" )

importlib.reload( foo_mod )
# foo_class = foo_mod.  # NO HINTS NO LINT NO TYPE CHECK NOTHING (vs-code)
foo_class = foo_mod.foo() # but its there. works.

#output
# NO PKG
# foo was imported!
# foo was imported!

What I expect after the import :
enter image description here
What I get :
enter image description here
EDIT
after a long search. It seems that importlib does not return the custom module as such. But a TypeModule or something. Which is a kind of generic module class. When I get anything from the module, I get such a TypeAny. However, knowing this does not solve the problem. How I cast the type. or as a fill in the module so that the classes and methods are recognized?

A: In VS Code, Python's Linting function and auto-completion function are provided by the Python extension. Therefore, it is recommended that you reinstall the python extension and reload VS Code.
For the use of the python code analysis tool, take Pylint as an example, please install the module "pylint" in the python environment you are currently using, and then run it.

Update:
When I use "from de.foo import fo" to import the method fo() in the file "foo.py", "class_foo.f" shows the auto-completion option:

Since VS Code starts from the parent folder of the current file by default when searching for files, as an example to ensure the code runs, I added the code
import sys
sys.path.append("./")

, which adds the file path to the system path to help VS Code find it.
Reference: Linting in VS Code.

A: After a lot of research. It's impossible. Because the data is created in runtime. So... VSCode (or any editor) can get the information before hand. Is only possible after the creation, after the execution. The more near solution is use a Jupyter Notebook, but is no suitable for larges files.


text:
Q: 500 Internal Server Error - TS3 Module WHMCS I am running a WHMCS website, we are going to offer Teamspeak 3 servers soon, we are using CPanel to host the website. Our current version of WHMCS is 7.0, it is licensed.
We are using a Windows VPS with a firewall that is currently turned off to host the TeamSpeak 3 servers. We have an API (using node.js) that is working with the module,
Everything works fine except one thing, when I enter the clientarea and goes to my TeamSpeak control panel I see buttons that says "start, stop, ban, settings" and all that, I can basicly turn on or off the teamspeak server from the control panel, but when I click any of those buttons my website just keeps loading and loading, the only way to stop it is to clear cookies. I forgot to mention that when I click e.g "stop" the teamspeak server actually stops, but the website keeps loading and it wont be solved until I clear cookies.
Image on the Control Panel
I can't find anything in the logs. The API is running on "http://VPS-IP:3000"
And the port is open, I have no clue why this is happening. I also get this error if I wait for about 20 minutes after I've clicked on of these buttons.

Internal Server Error
The server encountered an internal error or misconfiguration and was
  unable to complete your request.
Please contact the server administrator at webmaster@mysite.com to
  inform them of the time this error occurred, and the actions you
  performed just before this error.
More information about this error may be available in the server error
  log.
Additionally, a 500 Internal Server Error error was encountered while
  trying to use an ErrorDocument to handle the request.

A: You really should look into your server error log file.
Check if it updated at all?
Take a look into /var/log directory and see if any general log activity exists?
This kind of problems always affects in the logs if not configured otherwise.
Regards.


text:
Q: Automatically setting properties in SQLAlchemy declarative models This is a contrived example of what I'm trying to do. I have child objects that could by one of two categories of related object (here 'home and 'work').
I was wondering if there's a sensible way of having the column that determines which category they are in (Address.type) automatically set when they are bound using their respective relationships.
Maybe there's a better way of handling this situation generally?
class Person(Base):
    __tablename__ = 'person'

    id = Column(Integer, primary_key=True)

    home_addresses = relationship('Address', primaryjoin="and_(Person.id==Address.person_id, Address.type == 'home')")
    work_addresses = relationship('Address', primaryjoin="and_(Person.id==Address.person_id, Address.type == 'work')")

class Address(Base):
    __tablename__ = 'address'

    id = Column(Integer, primary_key=True)
    person_id = Column(Integer, ForeignKey('person.id'))
    type = Column(String)

p = Person()
p.home_addresses.append(Address())  # automatically set type to 'home'
p.work_addresses.append(Address())  # automatically set type to 'work'

A: You can use orm events
from sqlalchemy import event
@event.listens_for(Person.home_addresses, 'append')
def receive_append(target, value, initiator):
    # set the address type to home
    value.type = 'home'
    return value


text:
Q: Why do images haven't smooth edges in Flutter? The quality of images in Flutter is really bad.
Example:
The edges of the circle are not smooth.
Here is a screenshot of the problem:

This is the code:
      Image.asset(
        "assets/images/circle.png",
        width: 100.0,
        height: 100.0,
      ),

I have the same problem with many other images, which have round edges despite the orginal images have a very good quality.
Can anybody help?
I looked for two hours on the internet, but maybe I didn't used the right terms to search...
Thanks in advance! :)

A: It's probably an 8-bit PNG file with no anti-aliasing. Try a 24-bit file with the alpha channel. You'd do this by configuring the save settings in your image editor.


text:
Q: NSwag: a clear steps and clean sample on how to use class extensions in NSwag studio There are not clear documentation on how to extend the auto-generated TS file using NSwag. I mean the extension methods with a protector access modifier
here a discussion with the NSwag's owner:
https://github.com/RicoSuter/NSwag/issues/1012
but there is some uncertainty among the steps followed. especially in the case when adding a static suffix and/or prefix to the controller's name.
Can someone provide a clear explanation of how can we extend the auto-generated methods?

A: Finally, the correct convention to extend the auto-generated classes with prefixes and/or suffixes is to follow the rule as below
  { prefixIfExists} + {classname} + {suffixIfExists} extends generated.{classnameOnly} {

}

Example:

class FilesApplicationsManagerService extends generated.FilesApplicationsManager {
}