text:
Q: How to limit the textview text height with 10 lines and then remaining text to scroll in Swift3 Here I have designed textview which will move up with keyboard and adjust its height depend on the text, in the textview there is no scrolling for textview, now I need textview  should limit with 10 lines then want scrolling.
Below is my code:
import UIKit

class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate{

    @IBOutlet weak var msgTextViewheightConstraint: NSLayoutConstraint!
    @IBOutlet weak var msgTextView: UITextView!
    @IBOutlet weak var textViewBottomLayoutContraint: NSLayoutConstraint!

    var activeTextView: UITextView?

    override func viewDidLoad() {
        super.viewDidLoad()

        msgTextView.layer.cornerRadius = 5
        msgTextView.layer.borderColor = UIColor.gray.withAlphaComponent(0.5).cgColor
        msgTextView.layer.borderWidth = 0.5
        msgTextView.clipsToBounds = true
        self.setupTextView()
        self.registerForKeyboardNotifications()
    }

    func registerForKeyboardNotifications(){
        //Adding notifies on keyboard appearing
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    func deregisterFromKeyboardNotifications(){
        //Removing notifies on keyboard appearing
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            self.textViewBottomLayoutContraint.constant = keyboardSize.size.height + 10

        }
    }

    func keyboardWillHide(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            self.textViewBottomLayoutContraint.constant = 10

        }
    }

    func textViewDidBeginEditing(_ textView: UITextView) {

        activeTextView = textView

    }
    func textViewDidEndEditing(_ textView: UITextView) {
        activeTextView = nil

    }
    private func textViewShouldReturn(_ textView: UITextView) -> Bool {
        textView.resignFirstResponder()
        return true
    }

    func setupTextView() {
        if let txtView = msgTextView {

            txtView.scrollsToTop = true
            txtView.isScrollEnabled = true

            txtView.addObserver(self, forKeyPath: "contentSize", options:[ NSKeyValueObservingOptions.old , NSKeyValueObservingOptions.new], context: nil)
        }
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        if let changeDict = change, let constraint = msgTextViewheightConstraint, let view = self.msgTextView {
            if object as? NSObject == self.msgTextView && keyPath == "contentSize" {
                if let oldContentSize = (changeDict[NSKeyValueChangeKey.oldKey] as AnyObject).cgSizeValue,
                    let newContentSize = (changeDict[NSKeyValueChangeKey.newKey] as AnyObject).cgSizeValue {

                    let dy = newContentSize.height - oldContentSize.height
                    constraint.constant = constraint.constant + dy;
                    self.view.layoutIfNeeded()
                    let contentOffsetToShowLastLine = CGPoint(x: 0.0, y: view.contentSize.height - view.bounds.height)
                    view.contentOffset = contentOffsetToShowLastLine
                }
            }
        }
    }

    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        return true
    }

}

Please help me in this concept.

A: You can get the number of lines of text by dividing the hight of the textView's content by the textView's font's line hight:
let numberOfLines = textView.contentSize.height/(textView.font?.lineHeight)!

You can then get the size of each line by dividing the textView.contentSize by the number of lines it contains:
let lineHeight = textView.contentSize.height / numberOfLines

Then, in your viewDidAppear method, you can set the height constraint for the textView to the lineHeight times 10:
NSLayoutConstraint.activate([
    textView.heightAnchor.constraint(lessThanOrEqualToConstant: lineHeight * 10)
])

Make sure that you are not setting a height constraint in your storyboard  if you do this.


text:
Q: Sendp function in Scapy I'm using sendp() function in Scapy module to send packet. And it's really works, but I get report:

Sent 1 packet

How can I hide this report? I don't want, that sendp() write something.

A: You can set the verbosity to 0 before you send the packet:
from scapy.all import conf

conf.verb = 0

# Start sending packets here...

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to align a column to other column with blank spaces in Google sheets I'm trying a spreadsheet wherein you input days, workouts and how many times. And it automatically logged your time in and out.
I made it like if the day is input the time start is logged and when new time day is input on another cell(same column) time ends is logged. My problem is that when my activities stack in the distance between my time start and end becomes large. Is there a way to just put them near each other?
Like time start is in A1 and time ends will be in B1 rather than it is to B3 or so?
I put my code in a7 and b7 for the auto time logging. Hope you understand what I'm saying xD. Thanks in advance
Here is the link.


text:
Q: How to get all the clients connected to MongoDB Is there any command which will display list of all IP addresses currently connected to MongoDB?
I tried db.serverStatus().connections but it only returns total number of connections, but does not give any information about connected clients.
Thanks in advance for your help.

A: db.currentOp(true) will give you that.


text:
Q: Executing Shell Script via Automator via Terminal/Totalterminal or iTerm, this script works very well:
cd ~/go/to/dir/ && R -e "shiny::runApp("/go/to/dir", launch.browser=TRUE)"
but as/in a App via Automator, the second Part wont work.
In Automator: run Shell-Script.
Where is the difference of "normal" Terminal and the Terminal used by Automator.
In both /bin/bash

A: Is r on the path in Automator? If not, replace r with the full path like /usr/local/bin/r (shown by which r).


text:
Q: Setting textfield of an fragment I have two activity named School.java and SchoolDetails.java.Under SchoolDetails activity i have used fragments by implementing swipeable tabs.I passed a value from Schools.java to SchoolDetails.java using intent.Now i want to set this value received from Schools.java to a textField which is inside a fragment of SchoolDetails.java activity.I got Following error.
 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference

This is all what I did inside Schools.java i passed the name of school to SchoolDetails
School.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.user.educationhunt.adapter.CustomListAdapter;
import com.example.user.educationhunt.fragment.About;
import com.example.user.educationhunt.pojos.AppController;
import com.example.user.educationhunt.pojos.OurSchool;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class School extends AppCompatActivity{

    // Log tag
    private static final String TAG = School.class.getSimpleName();

    // Billionaires json url
    private static final String url = "http://myeducationhunt.com/public/schools";

    private ProgressDialog pDialog;
    private List<OurSchool> ourSchoolsListItems = new ArrayList<OurSchool>();
    private ListView listView;
    private CustomListAdapter adapter;

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

        ActionBar actionBar=getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("Schools");

        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomListAdapter(this, ourSchoolsListItems);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                OurSchool ourSchool=new OurSchool();
                Intent i=new Intent(School.this,SchoolDetails.class);

                i.putExtra("id", ourSchoolsListItems.get(position).schoolId);
                i.putExtra("name", ourSchoolsListItems.get(position).schoolName);
                i.putExtra("location", ourSchoolsListItems.get(position).schoolLocation);
                i.putExtra("logo", ourSchoolsListItems.get(position).schoolLogo);
                i.putExtra("email", ourSchoolsListItems.get(position).schoolEmail);
                i.putExtra("website", ourSchoolsListItems.get(position).schoolEmail);
                i.putExtra("created_at", ourSchoolsListItems.get(position).createdAt);
                i.putExtra("updated_at", ourSchoolsListItems.get(position).updatedAt);

                startActivity(i);

            }
        });

        pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
        pDialog.setMessage("Loading…");
        pDialog.show();

// Creating volley request obj
        JsonArrayRequest billionaireReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                OurSchool ourSchool = new OurSchool();

                                ourSchool.schoolId=obj.getInt("id");
                                ourSchool.schoolName=obj.getString("name");
                                ourSchool.schoolLocation=obj.getString("location");
                                ourSchool.schoolLogo=obj.getString("logo");
                                ourSchool.schoolEmail=obj.getString("email");
                                ourSchool.schoolWebsite=obj.getString("website");
                                ourSchool.createdAt=obj.getString("created_at");
                                ourSchool.updatedAt=obj.getString("updated_at");

                            // adding schools to ourSchool list
                                ourSchoolsListItems.add(ourSchool);

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

                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();
            }
        });

     // Adding request to request queue
        AppController.getInstance().addToRequestQueue(billionaireReq);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            case R.id.schoolSearch:
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.search, menu);
        return true;
    }
}

SchoolDetails.java
  package com.example.user.educationhunt;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

import com.example.user.educationhunt.fragment.About;
import com.example.user.educationhunt.fragment.Admission;
import com.example.user.educationhunt.fragment.FeeStructure;
import com.example.user.educationhunt.fragment.Majors;
import com.example.user.educationhunt.pojos.OurSchool;

import org.junit.runner.Describable;

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

public class SchoolDetails extends AppCompatActivity{

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

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

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

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        About aboutFragment= (About) getSupportFragmentManager().findFragmentById(R.id.aboutFragment);
        aboutFragment.aboutSchoolName.setText("name:"+ getIntent().getStringExtra("name"));

    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new About(), "ABOUT US");
        adapter.addFragment(new Admission(), "ADMISSION");
//        adapter.addFragment(new Majors(), "MAJORS");
        adapter.addFragment(new FeeStructure(), "FEE");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

And finally this is my About Fragment
package com.example.user.educationhunt.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.user.educationhunt.R;
import com.example.user.educationhunt.School;
import com.example.user.educationhunt.SchoolDetails;
import com.example.user.educationhunt.pojos.OurSchool;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import org.junit.runner.Describable;

import java.io.Serializable;

/**
 * A simple {@link Fragment} subclass.
 */
public class About extends Fragment implements OnMapReadyCallback{

    MapView mapView;
    GoogleMap map;
    public TextView aboutSchoolName,aboutSchoolLocation,aboutSchoolNumber,aboutSchoolEmail,aboutSchoolWebsite,aboutSchoolCategory;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_about, container, false);

        aboutSchoolName= (TextView) v.findViewById(R.id.about_school_name);
        aboutSchoolLocation= (TextView) v.findViewById(R.id.about_school_location);
        aboutSchoolNumber= (TextView) v.findViewById(R.id.about_school_number);
        aboutSchoolCategory= (TextView) v.findViewById(R.id.about_school_category);
        aboutSchoolEmail= (TextView) v.findViewById(R.id.about_school_email);
        aboutSchoolWebsite= (TextView) v.findViewById(R.id.about_school_website);

//        School school=new School();
//        aboutSchoolName.setText("name:"+ school.getIntent().getStringExtra("name"));

        // Gets the MapView from the XML layout and creates it
        mapView = (MapView) v.findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);

        // Gets to GoogleMap from the MapView and does initialization stuff
        map = mapView.getMap();
        map.getUiSettings().setMyLocationButtonEnabled(false);
        map.setMyLocationEnabled(true);

        // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
        MapsInitializer.initialize(this.getActivity());

        // Updates the location and zoom of the MapView
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(27.6933, 85.3211), 15);
        map.animateCamera(cameraUpdate);
        onMapReady(map);

        return v;
    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

    @Override
    public void onMapReady(GoogleMap map) {
        map.addMarker(new MarkerOptions()
                .position(new LatLng(27.6933, 85.3211))
                .title("St. Xavier's College"));
    }
}

Can somebody please help me out?

A: Try to get the extras from an Intent in an Activity and then pass any extra data to fragments by instantiating them with arguments.
Follow this, Where/How to getIntent().getExtras() in an Android Fragment?

A: From Activity to Fragment
    About about = new About();
    Bundle args = new Bundle();
    args.putString("key", value);
    about.setArguments(args);

In Fragment
Bundle args = getArguments();
String value = args.getInt("key");


text:
Q: C++ Function Overload / With objects I made a class Valjak (Roller), and gave it variables h (height) and r (radius) and made functions for area (Oplosje) and volume (Volumen).
I created 2 objects and now I need to overload operator +  in such way that result of adding two objects from class Valjak (roller) creates a new third object that has as height equal to the height of first object plus the height of second object, and radius that is the radius of first object plus radius of third object.
This is my code so far:
#include <iostream>
#include <math.h>
using namespace std;

class Valjak{
private: float r, h;
public:
    Valjak(){
        r = 1;
        h = 1;
    }
    Valjak(float rr, float hh){
        r = rr;
        h = hh;
    }
    void Oplosje(){
        cout << "Oplosje valjka je: " << 2 * (pow(r, 2)*3.14) + 2 * r*h << endl;
    }
    void Volumen(){
        cout << "Volumen je: " << (pow(r, 2)*3.14) * h << endl;
    }
};

int main(){

    Valjak V1;
    Valjak V2(5, 10);
    cout << "Vrijednosti prvog objekta!" << endl;
    V1.Oplosje();
    V1.Volumen();
    cout << "Vrijednosti drugog objekta" << endl;
    V2.Oplosje();
    V2.Volumen();

    system("PAUSE");
    return 0;
}

A: First, you must write getters for r and h, let's name them get_r and get_h:
class Valjak {
// ...
public:
    float get_r() { return r; }
    float get_h() { return h; }
// ...
}

Then overload operator + for two objects of Valjak class:
Valjak operator+(const Valjak & a, const Valjak & b)
{
    return Valjak(a.get_r() + b.get_r(), a.get_h() + b.get_h());
}


text:
Q: Oracle load spikes couple hours after startup We use oracle as the back-end database for our product. I have been running series of stress tests on our system and I have started noticing that oracle is much faster right after the database was restarted. Over time (a couple hours or so) the database seems to get slower and slower and I will see the database machine under more stress.
Running the test right after an oracle restart, i will see a 1 min load average of 5 or so and average CPU around 10-15%. After a few hours, I see the load average at 13 and CPU at 40-70%. (This is red hat linux 2x Quad core xeon, Raid 10 10k rpm sas drives).
My first thought was wouldn't database transactions get faster because those queries are getting cached?
I can't seem to figure out the problem.
EDIT:
Turns out this was a problem on the connecting software side due to bad design. Every action on the system created a new insert, delete, and select. With all these unique queries being generated, what was cached was constantly changing. The spike I am talking about is when the query cache filled up.

A: What version of oracle are you running? Do you have statspack or AWR setup? if you do, check those to show you what the database is doing over time.

A: I've noticed that with Oracle 10g, Oracle schedules a job to automatically compute statistics each day. You might want to look at your active sessions when the database is busy and see if a background session is busy calculating statistics on your tables.

A: Are you sure the stress test is releasing the sessions that it uses?  The accumulation of sessions, then subsequent time out of those sessions could produce this kind of behavior.
Moved this query from the comments to the body of my answer per request...
select
  username,
  osuser,
  lockwait,
  status,
  sql_text
from
  v$session,
  v$sqltext
where
  username is not null
and
  username not in ('SYSMAN','DBSNMP')
and
  hash_value = sql_hash_value
order by
  username,
  hash_value,
  piece;

A: It could be a problem with the database SGA swapping to disk. Check the size of the SGA and the PGA, compared to the RAM size.
You need to provide more information about the version of Oracle and Red Hat (for example,
I have experienced performance problems with Oracle 9i and Red Hat Enterprise Linux 3.x, with RAM sizes of 4 Gbytes or greater, that have disappeared when upgrading to Red Hat 4.x and Oracle 10g)

A: So after you do the reboot and the performance improves again, do you drop the data or do you keep it? You need to run statspack/AWR/ADDM/OEM to get more information about what's happening.
As you haven't posted any detailed diagnostic info I take it you need to start learning the ABCs first. See Oracle 10.2 Performance Tuning Guide

A: Add to the list of information needed the following:
Are you using archive logs?
How many redo log groups do you have? How many redo logs are in each group?
How big are the redo logs?
How are you restarting Oracle? Are you just doing a shutdown immediate followed by a startup? Are you rebooting the server?
If your log files are too small you might be getting into a state where you're waiting for the redo logs to be written to the archive logs before being able to continue, you can help remedy this by increasing the size of the redo logs.
Shutting down and restarting oracle would result in the redo logs all being written to the archive logs and being fresh and ready to go after you start back up.  Then as they fill with redo information you hit a bottleneck when it comes time to archive them.
An AWR report would really be the most useful thing if you're running Oracle 10g.  If you're running 9i then statspack equvalent.
Running a AWR Report
Login to sqlplus
sqlplus <sys or system user>/<password>@<SID>

Create a 'before' statistics snapshot
SQL> execute dbms_workload_repository.create_snapshot

Run your specific performance/load tests
Create an 'after' statistics snapshot
SQL> execute dbms_workload_repository.create_snapshot

Create a workload repository report
SQL> start awrrpt

Using the AWR report you should be able to determine where your bottleneck is.

A: A perfect example for a RAC Analyst like me who has downed RAC multiple times but never knew what made it down. Now, I am using the suggested method. Really, Oracle has many hidden functionality or I am less trained hheee or i need to explore more on these


text:
Q: Remove elements from a Linked List Why doesn't my solution work on this freecodecamp question? The tests that fail are:

*

*Your remove method should decrease the length of the linked list by one for every node removed.

*Your remove method should not change the linked list if the element does not exist in the linked list.

this.remove = function(element){
    // Only change code below this line
    if (head.element === element){
      head = head.next;
      length--;
      return;
    }
    let p = head;
    while(p){
      p = p.next;
      if (p.next.element === element)
      {
        p.next = p.next.next;
        length--;
        return;
      }
    }
    return;
    // Only change code above this line
  };

A: Let's assume the structure of the code is as in the original question on freecodecamp.
Your mistake: the loop should start with p and not p.next

function LinkedList() {
  var length = 0;
  var head = null;

  var Node = function(element) {
    this.element = element;
    this.next = null;
  };

  this.size = function() {
    return length;
  };

  this.head = function() {
    return head;
  };

  this.add = function(element) {
    var node = new Node(element);
    if (head === null) {
      head = node;
    } else {
      var currentNode = head;

      while (currentNode.next) {
        currentNode = currentNode.next;
      }

      currentNode.next = node;
    }

    length++;
  };

  this.remove = function(element) {
    // Only change code below this line
    if (head.element === element) {
      head = head.next;
      length--;
      return;
    }
    let p = head;
    while (p) {
      if (p.next && p.next.element === element) {
        p.next = p.next.next;
        length--;
        return;
      } else {
        p = p.next;
      }

    }
    return;
    // Only change code above this line
  };
}

console.assert(
  (function() {
    var test = new LinkedList();
    return typeof test.remove === 'function';
  })()
);

console.assert(
  (function() {
    var test = new LinkedList();
    test.add('cat');
    test.add('dog');
    test.remove('cat');
    return test.head().element === 'dog';
  })()
);

console.assert(
  (function() {
    var test = new LinkedList();
    test.add('cat');
    test.add('dog');
    test.add('hamster');
    test.remove('cat');
    test.remove('fish');
    return test.size() === 2;
  })()
);

console.assert(
  (function() {
    var test = new LinkedList();
    test.add('cat');
    test.add('dog');
    test.add('snake');
    test.add('kitten');
    test.remove('snake');
    return test.head().next.next.element === 'kitten';
  })()
);

console.assert(
  (function() {
    var test = new LinkedList();
    test.add('cat');
    test.add('dog');
    test.add('kitten');
    test.remove('elephant');
    return (
      JSON.stringify(test.head()) ===
      '{"element":"cat","next":{"element":"dog","next":{"element":"kitten","next":null}}}'
    );
  })()
);

console.log("all assertions passed");


text:
Q: window.location.href on ajax success not working I've been trying to solve this for a while now, but I can't get itworking. When a user clicks a link he's asked to confirm that he wants to take this action. Then a ajax call is made. The script that's called works fine and returns a string where to redirect to.
I've seen several posts here on problems with window.location, buth none of them could solve mine.
My code:
function confirm(a,b,c){
        var r=confirm("Are you sure to do this?");
        if(r==true){
            $.ajax({
                type: "POST",
                url: "/process-action.php",
                async: false,
                data: {a:a,b:b,c:c},
                success: function(data){
                    window.location.href = data;
                }
            });
        } else {
            return false;
        }
    }

If I do alert(data) instead of window.location.href = data I can see that the correct data is passed. For instance /user/homepage. Yet, the redirection is not taking place.
If tried to replace the relative path with the entire url, but that didn't work either.

A: Try using assign() instead:
window.location.assign(data);

window.location.href is a property, not a method.

A: Location assign() Method
The assign() method is supported in all major browsers.

A: You can use this
<form action="submit.php" onsubmit="return false;" method="post">
and your same script will be work.

A: You can also use window.location = "someurl";


text:
Q: Using tensorflow, how can you average parameter gradient values over a number of batches and update using that average? Like many people developing deep learning models, I am hindered by my hardware resources, namely GPU memory. I have an audio classification problem for which I am trying out a number of RNNs. The data is very large and I am only able to use small batch sizes and must limit the lstm size also. I understand that many people use spectrograms or other methods to provide more condensed data to the network but I would specifically like to know how to do this with raw data.
This is what I am doing currently on a batch size of around 4:
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=label_op))

optimisation_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss_op)

I would ideally like to calculate the gradients for each parameter for a batch on the GPU, then move those to RAM whilst calculating the gradients for the next batch. After some number of batches, I would then like to average the gradients for each parameter and use them to update the network.
I got this idea from the inception github page, which describes something similar to parallelise over multiple GPUs: https://github.com/tensorflow/models/tree/master/research/inception

A: Use tf.Variable objects to store the gradients. Place those on the CPU.


text:
Q: Location management using android phone and dot net server I want to implement a location based service ,In that service the mobile users will send their location co-ordinates to db in 10 seconds 6 hours per day (around 25 devices for a client,we have multiple clients). We have a windows dedicated server we are planning to build our web-service in SOA architecture ,We have giving dedicated db for each client,What is the best approach for this scenario.

A: Create a  WCF service that Sends and recieve JSON data, I had a similar requirement to yours. and i built one using this link http://www.codeproject.com/Articles/167159/How-to-create-a-JSON-WCF-RESTful-Service-in-sec. and it works well. though we did not send location every 10s. insteaad the location was stored locally and then dumped to server at regular intervals say an hour and the local db was cleared
Edit: how to receive json data can be found here How to accept JSON in a WCF DataService?

A: Not sure which aspect of a solution you are asking about but i can share our experience from similar project.
We have android/iphone applications that observe users gps locations and then report them to web app we did through ASP Web Api.
Web Api is, of course, connected to db which aside from storing locations is also used for users management. In our case db is not partitioned to be single tenant but its a multi tenant instead. In your case, you should handle finding out correct db for given user in your web app.
Bear in mind that heavy gps sensor usage will drain your battery. Useful read on that topic is here:
http://developer.android.com/guide/topics/location/strategies.html

A: Just another case study for your consideration. I have implemented similar scenario using Heroku in combination with golang and PostgreSQL. I have collected location in 2 category one is single pinpoint location and other one is in path mode. As you have said you are planning to use multiple db which can avoided by introducing userId of something to identify source/client.
Edit: 2
Collection of coordinates was to keep track on how device moved and where it was at particular time.


text:
Q: Type of object to cast to when parsing DataGrid.SelectedItems (bound to a MySql DataTable) I have a simple C# / WPF application that reads a MySql database into a DataGrid.
<DataGrid  Height="470" Width="800" AutoGenerateColumns="True" CanUserResizeColumns="True" CanUserReorderColumns="True" x:Name="DgrReadWrite" ItemsSource="{Binding ''}"  HorizontalAlignment="Center" VerticalAlignment="Center" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible" />

I load the Sql data into it like this:
string connStr = Service.getConnectionString();

string sql = "SELECT * FROM adat";
try
{
    MySqlConnection connection = new MySqlConnection(connStr);
    MySqlCommand cmdSel = new MySqlCommand(sql, connection);

    MySqlDataAdapter da2 = new MySqlDataAdapter(cmdSel);
    da2.Fill(this.dt2);
    DgrReadWrite.DataContext = dt2;
}
catch (Exception ex)
{
    MessageBox.Show("MySQL kapcsolódási hiba!", "Hiba!", MessageBoxButton.OK, MessageBoxImage.Error);
}

When I press the delete button, this would happen:
for (int i = 0; i < this.dt2.Rows.Count; i++)
{

    // looping through DgrReadWrite.SelectedItems.Cast<SomethingReadable??>
    if (somethingReadable[0] == this.dt2.Rows[i][0].ToString())
    {
        dt2.Rows[i].Delete();
        DgrReadWrite.Items.Refresh();
    }
}

My question: what type should I cast the selected items so I can make sense of them in the method? Thank you in advance.

A: It is easy to parse the data with DataRowView.
 foreach (DataRowView drRow in DgrReadWrite.SelectedItems)
            {
                listOfRowsToDelete.Add(drRow.Row);
                // put index numbers into a string for MySQL query
                ids = ids + drRow["index"] + ",";
            }


text:
Q: How to fix : Executing lambda expression using pthread in c++ I have a main.cpp file where I have the following code
paral(start, end, [&](int i){
    C1[i] = A1[i] + B[i];
}, numThreads);`

I have paral definition in otherfile.cpp, where I have the following code
void paral(int start, int end, T &&lambda, int nT){
    pthread_t thread1;
    int status = pthread_create(&thread1, NULL,lambda ,1);//Should execute lambda(1)
    lambda(2);//Executed by main thread
    //Code for join and so on
}

It says:

can't covert lambda to (void*)(*)(void *).

I tried to cast and pass the lambda function to pthread but it wasn't helpful.
I want to invoke the lambda function from the created thread as well which I'm unable to do.

A: First of all you must understand that Lambda is an object, that implements operator()(args...) member function. In your specific case it is operator()(int i).
In order to execute this lambda two parameters must be passed to the operator()(int):

*

*Lambda pointer (this)

*integer

Address of the lambda is an address to object (i.e. data) rather than address of code.
Thread start function instead is a function that accepts void* and returns void*. Address of function is an address to machine code.
Therefore, to execute your lambda you should define void* (void*) function and pass its address as start_routine parameter. The address of lambda you pass as arg parameter:
template<typename Lambda>
void paral(int start, int end, Lambda&& lambda, int nT){

    struct Args
    {
        int Start;
        int End;
        Lambda& Func;
    };

    // create captureless lambda
    auto threadStart = +[](void* voidArgs) -> void*
    {
        auto& args = *static_cast<Args*>(voidArgs);

        for(int i = args.Start; i < args.End; ++i)
            args.Func(i);

        return nullptr;
    };

    // I create one thread here. You will create more.
    auto args = Args{start, end, lambda};
    pthread_t handle;
    int rc = pthread_create(&handle, NULL, threadStart, &args);

    if(rc)
        throw std::system_error(
            std::error_code(rc, std::generic_category()),
            "pthread_create");

    pthread_join(handle, nullptr);
}

However in this specific case, you better to use std::thread instead of pthread library. In such case you code may look like following:
#include <iostream>

#include <atomic>
#include <thread>
#include <vector>

template<typename Func>
void paral(int start,
           int end,
           Func &&func,
           int threads_count = std::thread::hardware_concurrency())
{
    std::atomic_int counter {start};
    std::vector<std::thread> workers;
    workers.reserve(threads_count);

    for(int i = 0; i < threads_count; ++i) {
        workers.emplace_back([end, &counter, &func] {
            for(int val = counter++; val < end; val = counter++)
                func(val);
        });
    }

    for(int i = 0; i < threads_count; ++i)
        workers[i].join();
}

int main() {
    int C1[10];
    int A[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int B[10] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 110};
    paral(0, 10, [&](int i){ C1[i] = A[i] + B[i]; });

    for(auto&& v: C1)
        std::cout << v << "\n";
    std::cout << "Done. Bye!" << std::endl;
}

There is important note though. Your code may may work not as fast as you may expect. It will experience the false sharing problem as several threads modify the memory of the same cache line, which will force CPU cores to update their L1 caches every time when memory is updated by another CPU core.
See also:

*

*Passing C++ captureless lambda as function pointer to C API


text:
Q: How to get dynamic values from product flavor into a properties file I'm developing a Flutter application with different product flavors for Android and want to be able to define a value for each flavor, and select the value based on which flavor I'm building, and interpolate it into a properties file in order to dynamically configure a third party library.  I would also be open to having multiple duplicate properties files, each with their flavor-specific values, and then selecting the right one at build time.
My research suggests I'm likely taking the wrong approach.  After reading the Android documentation, I tried using BuildConfig to generate the values and then reference them in the properties file.  I do see that the BuildConfig.java is built with the right values, but they are not being interpolated in my properties file.  I'm not sure what approach I should be taking here, so any suggestions would be great!
thirdPartyLibrary.properties
customProperty=${BuildConfig.CUSTOM_PROPERTY}

build.gradle
...

flavorDimensions "app"

    productFlavors {
        dev {
            dimension "app"
            buildConfigField "String", "CUSTOM_PROPERTY", "\"my custom property for dev\""
        }
        qa {
            dimension "app"
            buildConfigField "String", "CUSTOM_PROPERTY", "\"my custom property for qa\""
        }
    }

    ...

A: I managed to get this working by following the steps outlined here:
https://stackoverflow.com/a/47992042/4215892
So I removed the values from my properties file, and instead added this code to the gradle file:
...

def thirdPartyLibraryProperties = new Properties()
File thirdPartyConfig = file("src/main/assets/thirdPartyLibrary.properties")

flavorDimensions "app"

    productFlavors {
        dev {
            dimension "app"
            thirdPartyLibraryProperties.load(thirdPartyConfig.newDataInputStream())
            thirdPartyLibraryProperties.setProperty("customProperty", "my custom property for dev")
            thirdPartyLibraryProperties.store(thirdPartyConfig.newWriter(), null)
        }
        qa {
            dimension "app"
            thirdPartyLibraryProperties.load(thirdPartyConfig.newDataInputStream())
            thirdPartyLibraryProperties.setProperty("customProperty", "my custom property for qa")
            thirdPartyLibraryProperties.store(thirdPartyConfig.newWriter(), null)
        }
    }

    ...

However this feels like I'm repeating myself unnecessarily and like there is probably a cleaner solution.  It is also modifying a file that is in source and not the build destination, which is generally bad practice.

A: The correct thing to do here was to simply create duplicate configuration files for each flavor and place the flavor-specific properties files in the correct folder for the flavor, so that it is copied to the correct "build/app/intermediates/merged_assets" folder.  So instead of having a single "src/main/assets/thirdPartyLibrary.properties" file, I now have two files, one for dev and one for QA:
"src/dev/assets/thirdPartyLibrary.properties"
"src/qa/assets/thirdPartyLibrary.properties"
This is so painfully obvious once you understand how Android's build system works, but was initially opaque to me as a new Flutter developer.
This is the thread that pointed me at the right answer: Reference different assets based on build flavor


text:
Q: Is the following function Riemann integrable? Consider $f:\mathbb{R^2}\to\mathbb{R}$ defined by:
$$f(x,y):=\arctan\frac{1}{x-y}\quad\forall x\neq y$$
$$f(x,x):=0$$
Is the function Riemann integrable in the square $[0,1]\times[0,1]$?
I just have no clue how to attack this, surely basic, exercise.

A: Well,  this function has an uncountable number of discontinuities, so it should not be Riemann Integrable (assuming that same result holds for functions from $\mathbb R ^2$ as well as it does for $\mathbb R$
It is discontinuous on the entire diagonal of $[0,1]^2$,  since as you approach the diagonal when $x<y$,  you get the $\arctan (-\infty)=-\pi /2$,   whereas when you approach it when $x>y$,  you get $\arctan(\infty )=\pi /2 $,  neither of which is 0., and for a function to be Riemann integrable you must have at most a countable number of discontinuties.


text:
Q: $p$-adic closures of infinite sets Let $S\subsetneq\mathbb{Z}$ be an infinite set.  Does there always exist a prime $p$ such that the closure of $S$ in the $p$-adic integers, $\mathbb{Z}_p$, contains a rational integer $n\notin S$?
Or, in elementary language, does there always exist a prime $p$ and $n\in \mathbb{Z}\setminus S$ such that for all $k$ there is an $s\in S$ such that $p^k\mid n-s$.

A: How about $S = \{ 0 \} \cup \{ n! : n \in \mathbb{N} \}$?


text:
Q: JavaScript: Append object properties as child elements I have an array of object and I'm trying to create HTML elements for each object and for each object's property, but got stuck, when I try to loop through containerDiv and appending object's properties as children elements.

*

*I want to create a div for each object with the class name of
containerDiv;

*I want to loop through containerDiv;

*I want to create an element for each object property and append them
as children elements to containerDiv;

My code sample looks like this:
var parent = document.getElementById('parent');

function createHTMLElements() {
    for(var i = 0; i < arrayOfObjects.length; i++) {
        var containerDiv = document.createElement('div');
        containerDiv.className = 'container';
        parent.appendChild(containerDiv);

        // Loop through containerDiv and append object properties as child elements
    }
}

var arrayOfObjects = [
    {
        name: 'John',
        surname: 'Doe'
    },
    {
        name: 'David',
        surname: 'Mills'
    }
]

A: You can create the child element using same document.cretateElement . Also you need to call the function

var arrayOfObjects = [{
    name: 'John',
    surname: 'Doe'
  },
  {
    name: 'David',
    surname: 'Mills'
  }
]
var parent = document.getElementById('parent');

function createHTMLElements() {
  for (var i = 0; i < arrayOfObjects.length; i++) {
    var containerDiv = document.createElement('div');
    containerDiv.className = 'container';
    var nameDiv = document.createElement('div');
    var surnameDiv = document.createElement('div');
    nameDiv .innerHTML = arrayOfObjects[i].name;
    surnameDiv .innerHTML = arrayOfObjects[i].surname;
    containerDiv.append(nameDiv );
    containerDiv.append(surnameDiv);
    parent.appendChild(containerDiv);

  }
}
createHTMLElements()

A: All you need is a loop over the current object in the array.
for (var p in arrayOfObjects[i]) {
  containerDiv.appendChild(document.createElement("p"))
    .textContent = p + ": " + arrayOfObjects[i][p];
}

DEMO:

var parent = document.getElementById('parent');

var arrayOfObjects = [{
    name: 'John',
    surname: 'Doe'
  },
  {
    name: 'David',
    surname: 'Mills'
  }
];

createHTMLElements();

function createHTMLElements() {
  for (var i = 0; i < arrayOfObjects.length; i++) {
    var containerDiv = document.createElement('div');
    containerDiv.className = 'container';
    parent.appendChild(containerDiv);

    for (var p in arrayOfObjects[i]) {
      containerDiv.appendChild(document.createElement("p"))
        .textContent = p + ": " + arrayOfObjects[i][p];
    }
  }
}
.container {
  border: 2px dashed #333;
  margin: 4px;
}

.container>p {
  margin: 10px;
  padding: 5px;
  background: #DDD;
}

Here's a demo that doesn't use a loop but uses a helper function to make cleaner code.

var parent = document.getElementById('parent');

var arrayOfObjects = [{
    name: 'John',
    surname: 'Doe'
  },
  {
    name: 'David',
    surname: 'Mills'
  }
];

createHTMLElements();

function createHTMLElements() {
  for (var i = 0; i < arrayOfObjects.length; i++) {
    var containerDiv = create('div', {className: "container"}, parent);

    var obj = arrayOfObjects[i];
    create("p", {textContent: "name: " + obj.name}, containerDiv);
    create("p", {textContent: "surname: " + obj.surname}, containerDiv);
  }
}

function create(type, props, parent) {
  var el = document.createElement(type);
  for (var p in props) {
    el[p] = props[p];
  }
  if (parent) {
    parent.appendChild(el);
  }
  return el;
}
.container {
  border: 2px dashed #333;
  margin: 4px;
}

.container>p {
  margin: 10px;
  padding: 5px;
  background: #DDD;
}

A: This is a more generic and structured approach. Refactoring becomes more easy for it provides methods for each special "create and append" task. Making use of reduce as list iterator method comes with the advantage of staying more flexible with e.g. what kind of "container" to choose by providing kind of a configuration to each "container" creating process.

var objectList = [{
  name: 'John',
  surname: 'Doe'
}, {
  name: 'David',
  surname: 'Mills'
}];

var elmContainer = document.createElement('li');
elmContainer.className = 'container';

function createAndAppendContainerChild(itemKey, itemValue, parentNode) {
  var elmChild = document.createElement('span');
  elmChild.className = itemKey;
  elmChild.appendChild(document.createTextNode(itemValue));
  parentNode.appendChild(elmChild);
}
function createAndAppendContainer(config, item) {
  var elmContainer = config.blueprintNode.cloneNode();
  Object.keys(item).forEach(function (key) {
    createAndAppendContainerChild(key, item[key], elmContainer);
  });
  config.parentNode.appendChild(elmContainer);
  return config;
}

objectList.reduce(createAndAppendContainer, {
  parentNode   : document.querySelector('#container-parent'),
  blueprintNode: elmContainer
});
.surname:before {
  content: ' '
}


text:
Q: Qual ferramenta utilizar para o envio de SMS em laravel Bom pessoal eu tenho uma aplicação PHP laravel e preciso enviar um SMS para algum clientes porém não sei como implementar esta função , como posso fazer?

A: De uma olhada no Twilio.
Tem um monte de recursos visando telefonia móvel, como mensagens automáticas, verificações por sms, chamada de voz automática etc...
Ele é compatível com Phyton, Java, C#, Ruby, PHP e javascript, algumas empresas famosas como Coca Cola e Netflix a utilizam.

A: Colega, você terá que encontrar alguma empresa de mensageria SMS (nexmo, zenvia, etc) e contratar o serviço deles. Para fazer a integração com o seu sistema haverá todo o suporte da empresa que vc contratou (parecido com o check-out de um e-commenrce). Pois cada API será implementada de uma forma diferente.


text:
Q: Puppet agent hans on Loading facts from Info
root@slx04c-8odu:/home/xiaojguan# which puppet
/usr/share/rvm/rubies/ruby-2.3.8/bin/puppet
root@slx04c-8odu:/home/xiaojguan# puppet -V
3.8.6
root@slx04c-8odu:/home/xiaojguan# facter -v
1.7.5
root@slx04c-8odu:/home/xiaojguan# ll /var/lib/puppet/lib/facter/
total 188
drwxr-xr-x 3 root root  4096 Feb 25  2021 ./
drwxr-xr-x 4 root root  4096 Nov 22  2020 ../
-rw-r--r-- 1 root root   430 Nov 22  2020 README.md
-rw-r--r-- 1 root root   916 Nov 22  2020 asset.rb
-rw-r--r-- 1 root root  3842 Nov 22  2020 bmc.rb
-rw-r--r-- 1 root root   620 Nov 22  2020 broadcast.rb
-rw-r--r-- 1 root root    66 Nov 22  2020 check_nsx_manager.rb
-rw-r--r-- 1 root root   627 Nov 22  2020 cidr.rb
-rw-r--r-- 1 root root  1683 Feb 25  2021 cloudnative.rb
-rw-r--r-- 1 root root   581 Nov 22  2020 core_count.rb
-rw-r--r-- 1 root root  1016 Nov 22  2020 default_gateway.rb
-rw-r--r-- 1 root root   294 Nov 22  2020 default_route.rb
-rw-r--r-- 1 root root  1250 Nov 22  2020 dhcp_server.rb
-rw-r--r-- 1 root root  4313 Nov 22  2020 disks.rb
-rw-r--r-- 1 root root   305 Nov 22  2020 efi.rb
-rw-r--r-- 1 root root  1116 Nov 22  2020 esx.rb
-rw-r--r-- 1 root root  4667 Nov 22  2020 facter_dot_d.rb
-rw-r--r-- 1 root root   236 Nov 22  2020 ip6tables_version.rb
-rw-r--r-- 1 root root   444 Nov 22  2020 iptables_persistent_version.rb
-rw-r--r-- 1 root root   234 Nov 22  2020 iptables_version.rb
-rw-r--r-- 1 root root  1792 Nov 22  2020 metadisks.rb
-rw-r--r-- 1 root root   374 Nov 22  2020 my-vars.rb
-rw-r--r-- 1 root root   183 Nov 22  2020 nameserver.rb
-rw-r--r-- 1 root root  6228 Nov 22  2020 nics.rb
-rw-r--r-- 1 root root   542 Nov 22  2020 nvidia_3d.rb
-rw-r--r-- 1 root root   114 Nov 22  2020 nvidia_product_id.rb
-rw-r--r-- 1 root root   564 Nov 22  2020 ovs_client_cert.rb
-rw-r--r-- 1 root root  1172 Nov 22  2020 pe_version.rb
-rw-r--r-- 1 root root   184 Nov 22  2020 proc_mounts.rb
-rw-r--r-- 1 root root   620 Nov 22  2020 processor_frequency.rb
-rw-r--r-- 1 root root   937 Nov 22  2020 puppet_vardir.rb
-rw-r--r-- 1 root root 20125 Nov 22  2020 raid.rb
-rw-r--r-- 1 root root   875 Nov 22  2020 root_home.rb
-rw-r--r-- 1 root root   213 Nov 22  2020 service_daemon_helper.rb
-rw-r--r-- 1 root root   618 Nov 22  2020 staging_http_get.rb
-rw-r--r-- 1 root root   251 Nov 22  2020 staging_windir.rb
-rw-r--r-- 1 root root   149 Nov 22  2020 swap_file_exists.rb
-rw-r--r-- 1 root root   790 Nov 22  2020 swapon_size.rb
drwxr-xr-x 2 root root  4096 Nov 22  2020 util/
-rw-r--r-- 1 root root   146 Nov 22  2020 var_mb.rb

problem description:
When i run puppet agent -t --debug --verbose on ubuntu 20.04 it just hans on below stage.
Debug: Loading facts from /var/lib/puppet/lib/facter/puppet_vardir.rb
Debug: Loading facts from /var/lib/puppet/lib/facter/esx.rb
Debug: Loading facts from /var/lib/puppet/lib/facter/asset.rb
Debug: Loading facts from /var/lib/puppet/lib/facter/nvidia_product_id.rb
Debug: Loading facts from /var/lib/puppet/lib/facter/core_count.rb
Debug: Loading facts from /var/lib/puppet/lib/facter/efi.rb
Debug: Loading facts from /var/lib/puppet/lib/facter/nvidia_3d.rb
Debug: Loading facts from /var/lib/puppet/lib/facter/disks.rb
Debug: Loading facts from /var/lib/puppet/lib/facter/swapon_size.rb
Debug: Loading facts from /var/lib/puppet/lib/facter/nics.rb
Debug: Loading facts from /var/lib/puppet/lib/facter/service_daemon_helper.rb
Debug: Loading facts from /var/lib/puppet/lib/facter/cidr.rb

I use strace to trace the process and got below stuff
root@slx04c-7tgb:/var/lib/puppet/lib# strace -p $(ps aux | grep applying | grep -v grep | awk '{ print $2}')
strace: Process 13250 attached
select(10, [9], [], NULL, NULL

Things i tried

*

*change the directory var/lib/puppet/lib/facter and rerun the puppet agent with below commands

mv /var/lib/puppet/lib/facter /var/lib/puppet/lib/facter-bak
puppet agent -t --debug --verbose

Expectation

*

*how to know which snippet code stuck

*how to make the puppet agent ok to run

Thanks in advance.


text:
Q: multiply a column by a number in pandas skip or make it zeros if the column does not exists So I have table whuich I created a pivot from
After the pivot I made the index, columns and used one of the column values as columns from which the expected counts are represented. I'd like to multiply each column(values turn columns) to a figure, but because some of the values were not created at that point in time, the column with the specified name did not appear; making the multiplication process run into errors, is there a way I could skip that error or make the the column be Created but show zeros after the multiplication, in cases where the values are not in the converted column
df
**Name Fruit**
Jane Apple
Celi Banana
Pete Mango
Fred grape

pivot
Name Apple Banana   Mango   grape
Jane  1      0        0      0
Celi  0      1        0      0
Pete  0      0        1      0
Fred  0      0        0      1

pivot['total']=(pivot['Apple '].multiply(14)+
                pivot['Banana ].multiply(110)+
                 pivot['Mango'].multiply(18)+
                 pivot['grape].multiply(10)+
                 pivot['peach].multiply(140))

Expected this:
Name Apple Banana   Mango   grape  total
Jane  1      0        0       0      14
Celi  0      1        0       0      110
Pete  0      0        1       0      18
Fred  0      0        0       1      10

But getting errors due to peach not being in the values. is there a way I could skip that error or make the the column be Created but show zeros after the multiplication, in cases where the values are not in the converted column . Any help on this would be appreciated

A: Use DataFrame.dot with mapping columns names:
d = {'Apple':14,'Banana':110,'Mango':18,'grape':10,'peach':140}

df1 = pivot.select_dtypes(np.number)
pivot['total'] = df1.dot(df1.columns.map(d).fillna(0))
#alternative solution
#pivot['total'] = df1.mul(df1.columns.map(d).fillna(0)).sum(axis=1)
print (pivot)
   Name  Apple  Banana  Mango  grape  total
0  Jane      1       0      0      0     14
1  Celi      0       1      0      0    110
2  Pete      0       0      1      0     18
3  Fred      0       0      0      1     10

Or with Series.map for helper column and then use DataFrame.pivot_table:
d = {'Apple':14,'Banana':110,'Mango':18,'grape':10,'peach':140}
pivot = (df.assign(new = df['Fruit'].map(d))
           .pivot_table(index='Name', columns='Fruit', values='new', aggfunc='sum'))


text:
Q: Flex only for two out of three elements I have 3 seperate elements all in one container/wrapper.
I have flex applied so the image and Text are side by side. However i want the "Scroll Down" div to be placed underneath the other two elements while still using Flex.
Is there any flex property to somehow only apply Flex on the two first elements?
Image:
https://gyazo.com/a391508e26aff2486103579134c051e1

Centuries Gaming

Roleplay on a different level

From the aspirations and dreams of others, we stand tall, proud, and loyal
                        to our visions and project. We provide the best and most immersive...

                            Apply

                            Read More

                <button>
                    Scroll Down

                </button>

/* Home Section */

.home-section {
  height: 100vh;
  display: flex;
  align-items: center;
}

.home-column {
  display: flex;
}

.home-row h1 {
  font-size: 60px;
  color: white;
  font-weight: 700;
  margin-bottom: 7x;
}

.home-row h2 {
  font-weight: 500;
  color: #ffffff80;
  margin-bottom: 20px;
}

.home-row p {
  color: #ffffff80;
  font-size: 14px;
  max-width:600px;
}

.home-row .home-buttons {
  display: flex;
  margin-top: 50px;
}

A: If you add flex-direction: column; to .home-section then the parent element will display its children vertically. And the scroll element will be below the order elements.

A: You can use flex-direction:column
.home-section {
    height: 100vh;
    display: flex;
    align-items: center;
    flex-direction: column;
}

The default is row, but you can change that property to stack the elements vertically. https://developer.mozilla.org/en-US/docs/Web/CSS/flex-direction


text:
Q: Sequelize.js,How to insert a model with one to many to many relationship I'am use sequlize.js creat a model with one to many,it can work,but I want to create a model with one to many to many,I don't konw  where to start
Now I have defined three model,below is they relationship

*

*Projects

Projects.associate = () => {
    Projects.Colors = Projects.hasMany(ProjectColors, { foreignKey: 'project_id', sourceKey: 'id' });
  };

*ProjectColors

ProjectColors.associate = () => {
    Projects.Sizes = ProjectColors.hasMany(ProjectSizes, { foreignKey: 'project_color_id', sourceKey: 'id' });
  };

*ProjectSizes

There is a object,I want to create through Project Model
const project = {
  name: 'xxproject',
  colors:[
    {
      color: 'red',
      sizes:[
        {size: 'L'}
      ]
    },
    {
      color: 'bule',
      sizes:[
        {size: 'L'},
        {size: 'M'}
      ]
    },
  ]
}

I try one to many like Office Document, it can work well as follow
await Projects.create(project, {
  include: [ Projects.Colors ],
});

if I change the code,it work error
await Projects.create(project, {
      include: [{
        model: Projects.Colors,
      }],
    });

It's the error stack
2019-04-04 10:57:10,074 ERROR 60510 [-/127.0.0.1/-/20ms POST /api/v1/projects] nodejs.TypeError: self._expandAttributes is not a function
    at Function._conformOptions (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/model.js:198:12)
    at Function._conformInclude (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/model.js:264:12)
    at options.include.options.include.map.include (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/model.js:213:59)
    at Array.map (<anonymous>)
    at Function._conformOptions (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/model.js:213:39)
    at new Model (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/model.js:3070:24)
    at new projects (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/sequelize.js:340:19)
    at Function.build (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/model.js:1966:12)
    at Function.create (/Users/jaytam/school/garment-production-backend/node_modules/sequelize/lib/model.js:2017:17)
    at ProjectController.create (/Users/jaytam/school/garment-production-backend/app/controller/projects.js:42:20)
    at Object.callFn (/Users/jaytam/school/garment-production-backend/node_modules/egg-core/lib/utils/index.js:44:21)
    at Object.classControllerMiddleware (/Users/jaytam/school/garment-production-backend/node_modules/egg-core/lib/loader/mixin/controller.js:87:20)
    at Object.callFn (/Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/lib/utils.js:12:21)
    at wrappedController (/Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/lib/egg_router.js:322:18)
    at dispatch (/Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/node_modules/koa-compose/index.js:44:32)
    at next (/Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/node_modules/koa-compose/index.js:45:18)
    at /Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/lib/router.js:190:18
    at dispatch (/Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/node_modules/koa-compose/index.js:44:32)
    at /Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/node_modules/koa-compose/index.js:36:12
    at dispatch (/Users/jaytam/school/garment-production-backend/node_modules/@eggjs/router/lib/router.js:195:33)
    at dispatch (/Users/jaytam/school/garment-production-backend/node_modules/koa-compose/index.js:42:32)
    at /Users/jaytam/school/garment-production-backend/app/middleware/handleGetInt.js:22:11

In fact,I want to code like this,but above code dont work
await Projects.create(project, {
      include: [{
        model: Projects.Colors,
        include: [{
          model: Projects.Sizes,
        }],
      }],
    });

after Travis Haby suggest, I retry
I imitate Sequlize.js Document,change thire relationship define
Projects.Colors = app.model.ProjectColors.belongsTo(Projects, { foreignKey: 'project_id', targetKey: 'id' });
app.model.ProjectColors.Sizes = app.model.ProjectColors.hasMany(app.model.ProjectSizes, { foreignKey: 'project_color_id', sourceKey: 'id' });

the create code
await Projects.create(project, {
      association: Projects.Colors,
      include: [ ProjectColors.Sizes ],
});

or
    await Projects.create(project, {
      include: [{
        association: Projects.Colors,
        include: [{
          association: ProjectColors.Sizes,
        }],
      }],
    })

the tow ways only create project, and each way both color and size not created
[2019-04-04 14:22:15.564] [cfork:master:60831] worker:60969 exit (code: 0, exitedAfterDisconnect: true, state: dead, isDead: true, isExpected: true, worker.disableRefork: false)
{ name: 'sadqw',
  cycle: 230,
  fund: 1230123,
  manage_by: 'dsa',
  project_colors: [ { color: 'asd', imageUrl: '', project_sizes: [Array] } ],
  status: '0' }
2019-04-04 14:26:24,276 INFO 60980 [egg-sequelize](1ms) Executed (default): INSERT INTO `projects` (`id`,`name`,`cycle`,`fund`,`manage_by`,`created_at`,`updated_at`,`status`) VALUES (DEFAULT,'sadqw',230,1230123,'dsa','2019-04-04 06:26:24','2019-04-04 06:26:24','0');

A: According to this part of the sequelize docs you should be able to nest as follows (depending on which version of sequelize you're using):
return Projects.create(project, {
  include: [{
    association: Projects.Colors,
    include: [ Colors.Sizes ]
  }]
});

At first glance it looks like you have Projects.Colors and then Projects.Sizes, but I think it should be Colors.Sizes instead because thats the many to many relationship.
Hope that helps!

A: First, try changing projectColors association to this (assuming you receive models as an argument):
ProjectColors.associate = () => {
    ProjectColors.Sizes = ProjectColors.hasMany(models.project_size, { foreignKey: 'project_color_id', sourceKey: 'id' });
    ProjectColors.Projects = ProjectColors.belongsTo(models.project)
};

Second, try adding to ProjectSizes:
ProjectSizes.associate = () => {
    ProjectSizes.Colors = ProjectSizes.belongsTo(models.project_color, { foreignKey: 'project_color_id'});
};

NOTE: the model name (that you use after models.) is the name as defined in the model definition (Sequelize.define([modelname]).
Let me know if it helped.
The create should look like this I believe:
await Projects.create(project, {
      include: [{
        association: Projects.Colors,
        include: [ ProjectColors.Sizes ]
      }]
    });

A: I try and try again, it work well. thanks @Sagi Rika & @Travis Haby
In fact, it's so simple
Projects.associate = () => {
    Projects.Colors = Projects.hasMany(ProjectColors, { foreignKey: 'project_id', sourceKey: 'id' });
  };

ProjectColors.associate = () => {
    Projects.Sizes = ProjectColors.hasMany(ProjectSizes, { foreignKey: 'project_color_id', sourceKey: 'id' });
  };

And call create method as follow
    Projects.create(project, {
      include: [{
        association: Projects.Colors,
        include: [{
          association: Projects.Sizes,
        }],
      }],
    })


text:
Q: How to compute the Hausdorff dimension of a "semi" self-similar shape? The essence of self-similar fractals is that rescaling the original shape and gluing together a number of identical copies will produce the same overall shape. The quadratic type 2 curve is an example of such a fractal. You scale down the original shape by a factor of $1/4$ and piece together $8$ copies to get the same fractal:

This results in a fractal with dimension $\log_{4}{8} = 1.5$:

What I'm interested in, and what I mean by "semi" self-similar, is fractals where there are differently scaled copies of the shape building up the entire image. For example, if the vertical "middle" of the quadratic type 2 curve is treated as one iteration, rather than two, then the copy of the curve making up this piece is only scaled by $1/2$, while all of the other pieces are scaled by the original $1/4$. This ends up producing quite a different-looking fractal:
Basic Structure:

Limit Fractal:

Another example would be a "shark fin" fractal, similar to the Koch snowflake, but where the "middle third" has a right triangle with height $1/3$, and hypotenuse $\sqrt{2}/3$:
Basic Structure:

Limit Fractal:

Any ideas about how to calculate the Hausdorff dimensions of such shapes would be greatly appreciated!

A: The similarity dimension of $\log_4 8$ comes from solving $8\left(\frac{1}{4}\right)^s = 1$.  Your modified fractal's dimension is the solution of $6\left(\frac{1}{4}\right)^s + \left(\frac{1}{2}\right)^s   = 1$, which Wolfram Alpha tells me is $s = \log_2 3$.  In general there may not be  a nice closed-form solution, and indeed your "shark fin" fractal requires solving $3\left(\frac{1}{3}\right)^s + \left(\frac{\sqrt{2}}{3}\right)^s = 1$, which Wolfram Alpha gives numerically as $s \approx 1.393\ldots$.
I'm not sure what is necessary to prove that this similarity dimension is equal to the Hausdorff dimension, probably it involves showing that the shape satisfies an "open set condition" (essentially, that it doesn't self-overlap too much).


text:
Q: ASP MVC Twitter Authorization I am attempting to create an application that will allow a user to log in and join a group.  On joining a group and successfully logging in the user will be presented with a list of items specific to that group.
Currently I am trying to use Twitter as a means of authorization and I'm having problems.  I have been looking at Twitterizer and TweetSharp all day without having any luck, the problem seems to be finding some examples which relate to the architecture I am using: ASP .NET MVC2, I can't seem to figure out how I would implement this authorization functionality using controllers etc.
Thanks, total newbie at this.
Kev.

A: I've implemented this with Twitterizer in ASP.NET MVC.
First, you'd have a Login action that takes a username and password on a controller that authorizes the user and saves the tokens:
[HttpPost]
public ActionResult Login(string username, string password) {
    OAuthTokenResponse tokens;
    var consumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"];
    var consumerSecretKey = ConfigurationManager.AppSettings["TwitterConsumerSecret"];
    try {

        tokens = XAuthUtility.GetAccessTokens(consumerKey, consumerSecretKey, username, password);
        Session["AccessToken"] = tokens.Token;
        Session["AccessTokenSecret"] = tokens.TokenSecret;
     }
     catch (ArgumentNullException) {
        ViewData["message"] = "Username or password incorrect";
        return View();
     }
     ViewData["message"] = "You are logged in to twitter as " + tokens.ScreenName;
     return View();
}

Then you have a PostMessage action that takes the message content and posts to twitter:
[HttpPost]
public ActionResult PostMessage(string message ) {
     // you should check to make sure the user is actually logged in by checking the session vars first

     var tokens = new OAuthTokens
                      {
                          AccessToken = Session["AccessToken"],
                          AccessTokenSecret =  Session["AccessTokenSecret"],
                          ConsumerKey = consumerKey,
                          ConsumerSecret = consumerSecretKey
                      };

     var tweetResponse = TwitterStatus.Update(tokens, data.Message);
     if (tweetResponse.Result == RequestResult.Success) {
        ViewData["message"] = "Message posted!";
     } else {
        ViewData["message"] = "Error posting to twitter.";
     }
     return View();
}

This code wasn't tested and more error checking should be added, but it should get you started...

A: You'll want to create a custom MembershipProvider.  Here's a good tutorial on how to do that:
http://www.asp.net/general/videos/how-do-i-create-a-custom-membership-provider
There's more detail than you need in the tutorial, but basically what you need to do is create a new class that inherits from System.Web.Security.MembershipProvider and override the ValidateUser method.  In that method, you'll call the twitter login code from my previous answer and return true or false on success.  You'll also need to modify the <membership/> section of the web.config to tell ASP.NET to use your custom membership provider when doing authorization.


text:
Q: How can I have the middle column go on top on small screens with Bootstrap 3? The following code shows "1 2 3":

        1

        2

        3

How can I have the main contents on top on smaller screens (phones); "2 1 3"?

A: You could do this..

        2

        1

        3

Demo: http://bootply.com/91812


text:
Q: My page displays if there is an image only This is the weirdest problem I've never met on PHP (I use it since 10 years) and that's why I'm writing this message. PHP version is 7.2.
I think it's not important but i use CodeIgniter, my problem is before, in the first index.php. All works in local, but when I put my code on a server (which is a shared server unfortunately), the behavior is :

*

*if, in the beginning of index.php, there is an image using data:image with base64, the page displays

*if not, i have a blank page

I just can't understand. I noticed this when i added a phpinfo at the beginning, suddenly my page displayed because the logo of phpinfo uses this kind of picture.
I made many many many tests, and the only way to make it work is using a data:image base64 before (and by the way, just before I use "" to put it in display none and it still works...). Using a link for the image doesn't work.
I have no error, nowhere.
I just want to know if someone has an idea about what is happening here ?
Thank you so much ! (Sorry I'm not an english native person)

A: I think you are using windows machine for local development. And your server is Linux based...
Linux server is fully case sensitive. Please check folder,files name is correct or not..
If a folder is ../View/123.jpg
Then.  The src="../VIEW/123.JPG"  will work on windows machime. But error in linux server..


text:
Q: How can I have C# code run after a jquery script that is running on page load? I have a webpage that loads and runs jquery once the page is ready, like this:
$(document).ready(function () {
        navigator.geolocation.getCurrentPosition(showPosition, positionError);

        function showPosition(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            document.getElementById('div_latitude').innerHTML = latitude;
            document.getElementById('div_longitude').innerHTML = longitude;
        }

        function positionError(position) {
            alert("Error: " + position.code);
        }
    });

After I have assigned the div_latitude and div_longitude their values, I want to run code that will use this information automatically.  How can I make sure this second piece of code will run after the jquery?

A: You will have to make an AJAX call up to the server.

A: You might like to check status in jquery as "complete" and you can make an AJAX call to C# codes you want to execute.

A: You will have to make an ajax call to communicate to the server side code so that you can pass the vales you needed after jQuery is loaded.
Code is as follows.
$(document).ready(function () {
        navigator.geolocation.getCurrentPosition(showPosition, positionError);
    function showPosition(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        document.getElementById('div_latitude').innerHTML = latitude;
        document.getElementById('div_longitude').innerHTML = longitude;
    }

    function positionError(position) {
        alert("Error: " + position.code);
    }
     makeAjaxCall();

});
  function makeAjaxCall()
   {
     $.ajax({
          type: "POST",
          url: "PageName.aspx/MethodName",
          data: "{}",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function(msg) {
          // Ajax Call Successfull.
           }
       });
    }


text:
Q: Error; cannot find symbol; Symbol: variable super I am working on 3 programs that contain the classes CarRental.java, LuxuryCarRental.java, and UseCarRental.java, On my LuxuryCarRental.java, I keep getting the error, Error; cannot find symbol; Symbol: variable super for the class, here is my program, I'm relatively new to Java, so please be detailed! Thanks in advance!
import java.text.DecimalFormat;

public class LuxuryCarRental extends CarRental{

private boolean chauffeur;
private double dailyChauffeurFee;

public LuxuryCarRental(String renterName, int renterZip, String sizeOfCar,int rentalDays, boolean chauffeur) {
    super(renterName, renterZip, sizeOfCar, rentalDays);
    this.chauffeur = chauffeur;
}

public void display(){

    super.dailyRentalFee = 79.99;

    this.dailyChauffeurFee = 0;
    if(chauffeur){
        this.dailyChauffeurFee = 200;
    }

    super.totalRentalFee = super.dailyRentalFee * super.getRentalDays() + this.dailyChauffeurFee * super.getRentalDays();

    DecimalFormat df = new DecimalFormat("0.00");

    System.out.println("Car Rental - Renter Name : " + super.getRenterName() + ", Renter Zip: " + super.getRenterZip() +
            ", Rental Days : " + super.getRentalDays() +
            ", Daily Rental Fee: " + dailyRentalFee + ", Daily Chauffer Fee: " + dailyChauffeurFee +
            ", Total Rental Fee: " + df.format(totalRentalFee));
}

}

And here are all the classes from all three of my programs that correspond to each other.
  public class CarRental {

private String renterName;
private int renterZip;
private String sizeOfCar;
private int rentalDays;
protected double dailyRentalFee;
protected double totalRentalFee;

public class UseCarRental

public class LuxuryCarRental extends CarRental {

private boolean chauffeur;

private double dailyChauffeurFee;

public CarRental(String renterName, int renterZip, String sizeOfCar, int rentalDays)
{
    renterName = renterName;
    renterZip = renterZip;
    sizeOfCar = sizeOfCar;
    rentalDays = rentalDays;

And my altered code:
public class CarRental
{

public static void main(String[] args)
{

private String renterName;
private int renterZip;
private String sizeOfCar;
private int rentalDays;
protected double dailyRentalFee;
protected double totalRentalFee;
}

public CarRental(String renterName, int renterZip, String sizeOfCar, int rentalDays)
{
    renterName = renterName;
    renterZip = renterZip;
    sizeOfCar = sizeOfCar;
    rentalDays = rentalDays;
}

 public void setDailyRentalFee(double dailyRentalFee)

 {

 this.dailyRentalFee = dailyRentalFee;

 }

public double getDailyRentalFee()

 {

 return dailyRentalFee;

 }

public void display(){

    if(sizeOfCar.equalsIgnoreCase("economy"))
  {
        dailyRentalFee = 29.99;
    }

  else if(sizeOfCar.equalsIgnoreCase("midsize"))
  {
        dailyRentalFee = 38.99;
    } else {
        dailyRentalFee = 43.50;
    }

    //calculates total rental fee
    this.totalRentalFee = this.dailyRentalFee * rentalDays;

    DecimalFormat df = new DecimalFormat("0.00");

    //displays output
    System.out.println("Car Rental - Renter Name : " + renterName + ", Renter Zip: " + renterZip +
            ", Size of car: " + sizeOfCar + ", Rental Days : " + rentalDays +
            ", Daily Rental Fee: " + dailyRentalFee + ", Total Rental Fee: " + df.format(totalRentalFee));
}

public String getRenterName()
{
    return renterName;
}

public int getRenterZip()
{
    return renterZip;
}

public int getRentalDays()
{
    return rentalDays;
}

}

A: super.dailyRentalFee = 79.99;

This doesn't work. The same goes for every other place you've used it.
I assume your class has a private field dailyRentalFee?
Make it protected instead. Or use public/protected getters and setters.
You're in a subclass which you should really view as an extension of the superclass. Everything that is available in the superclass is available in the subclass, provided you don't use private access but rather protected (available in current class and subclass) or public (available everywhere that has access to the current class).
Example:
class SuperClass {
   protected int someValue = 5;
   private int anotherValue = 10;
}

class SubClass extends SuperClass {
   public void doSomething() {
      someValue = 6; // I can access it because it's protected instead of private
      anotherValue = 1; // I can't access it because it's private and only accessible in the SuperClass
   }
}

To summarize:

*

*Drop the super.X, super() is used to call the constructor of the superclass

*Use protected or public access identifiers instead of private

A: First thing, super doesn't work the way you have used it.
when you extend a class, CarRental in your case, you inherite all public and protected members of that class. so to use a variable of your super class, you dont have to prefix super, you can just use the variable as if the child class holds it. so instead of
super.dailyRentalFee = 79.99;

use
dailyRentalFee = 79.99;  // since dailyRentalFee is protected in class CarRental
                         // this will work

similarly,
super.totalRentalFee = super.dailyRentalFee * super.getRentalDays() + this.dailyChauffeurFee * super.getRentalDays();

should be written as
totalRentalFee = dailyRentalFee * getRentalDays() + this.dailyChauffeurFee * getRentalDays();

provided, the method getRentalDays is public in the CarRental class.
and about the error you mentioned in @Jeroen's answers' comments,
make sure LuxuryCarRental and CarRental are in the same package. To be simple,
make sure both files are in the same folder.
EDIT:
Your code doesn't contain a main method, that is why that error is produced. You should have a main method in your program for it to execute. That is the starting point of all java applications. so define a class with a main method inside and then create a LuxuryCarRental object and perform your computations there. for example,
class Sample {
  public static void main(String[] args) { //this is how all main methods would look

    LuxuryCarRental luxuryCar = new LuxuryCarRental("A",62020,"SUV",10,true);
    //call the LuxuryCarRental methods as per your coding requirements

  }
}

see, its simpe,
class CarRental {
  //CarRental code
}

class LuxuryCarRental {
  //LuxuryCarRental code
}

class Test {
  public static void main(String[] args) {
    LuxuryCarRental luxuryCar = new LuxuryCarRental("A",62020,"SUV",10,true);
    luxuryCar.display();
  }
}


text: Q: ffmpeg Limit File Size I am converting MPGs into GIF files using ffmpeg.  I need to limit the output to 2MB max as this is the maximum GIF size supported on the server.  I have tried the -fs switch, however this chops off the video to fit the size.  I would rather have the GIF scaled and the quality adjusted.  The source videos are limited to 5 seconds, so I'm not trying to fit a video with particularly long duration into a small GIF file size.  Some solutions I have seen include checking the file size after conversion, deleting if too large and trying again with modified properties until the desired file size is reached.  Is there a more automated approach I could take with ffmpeg?


text:
Q: UNO classes to VB .NET I've found some samples of OpenOffice UNO dll to try out with VB.NET, but I'm still having issues with it:

*

*It doesn't want to compile with any version of .NET Framework over 2.0 (Which is at least 7 years old!)

*Sample is very poor in functionalities, just insert some plain text without formating.
Are there any specs or documentation available for UNO for .NET? C# or VB?

*Has anyone had a good experience with OpenOffice Automation and .NET?

A: I have successfully used OpenOffice UNO SDK in my projects.
I posted hello world example in answer to this question "Hello World" using OpenOffice 3 sample code


text:
Q: What are the style parameters for nested lists? I am working in memoir class and would like to customize some nested lists. But I do not know all the style parameters, in particular, the lengths. How can I list them? This is a generic question, but I provide the following example. To what length does \leftmargin refer outside the lists, within the outer list, and within the inner list?
\documentclass[12pt]{memoir}
\begin{document}
$\backslash$leftmargin = \the\leftmargin
\begin{description}
  \item{Outer 1} $\backslash$leftmargin = \the\leftmargin
  \begin{description}
    \item{Inner 1} $\backslash$leftmargin = \the\leftmargin
    \item{Inner 2} $\backslash$leftmargin = \the\leftmargin
  \end{description}
\item{Outer 2} $\backslash$leftmargin = \the\leftmargin
\end{description}
$\backslash$leftmargin = \the\leftmargin
\end{document}

Output
\leftmargin = 29.3747pt
 Outer 1 \leftmargin = 29.3747pt
 Inner 1 \leftmargin = 25.84969pt
 Inner 2 \leftmargin = 25.84969pt
 Outer 2 \leftmargin = 29.3747pt
\leftmargin = 29.3747pt

A: The relevant code in memoir.cls is from line 4572 to line 4607:
\def\@listi{\leftmargin\leftmargini
  \parsep\parsepi
  \topsep\topsepi
  \itemsep\itemsepi}
\let\@listI\@listi
\defaultlists
\@listi

\def\@listii{\leftmargin\leftmarginii
             \labelwidth\leftmarginii
             \advance\labelwidth-\labelsep
             \topsep\topsepii
             \parsep\parsepii
             \itemsep\parsepii}

\def\@listiii{\leftmargin\leftmarginiii
              \labelwidth\leftmarginiii
              \advance\labelwidth-\labelsep
              \topsep\topsepiii
              \parsep\z@
%%%              \itemsep\topsep
%%%              \partopsep \p@ \@plus\z@ \@minus\p@
              \itemsep\itemsepiii
              \partopsep\partopsepiii}

\def\@listiv{\leftmargin\leftmarginiv
             \labelwidth\leftmarginiv
             \advance\labelwidth-\labelsep}

\def\@listv{\leftmargin\leftmarginv
            \labelwidth\leftmarginv
            \advance\labelwidth-\labelsep}

\def\@listvi{\leftmargin\leftmarginvi
             \labelwidth\leftmarginvi
             \advance\labelwidth-\labelsep}

where we see that the lists are defined in terms of \leftmarginX, where X stands for the (lowercase) Roman numeral denoting the list nesting level.
In mem12.clo we find
\renewcommand{\normalsize}{%
   \@setfontsize\normalsize\@xiipt{14.5}%
   \abovedisplayskip 12\p@ \@plus3\p@ \@minus7\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6.5\p@ \@plus3.5\p@ \@minus3\p@
   \belowdisplayskip \abovedisplayskip
   \let\@listi\@listI}
\normalsize
\newcommand{\small}{%
   \@setfontsize\small\@xipt{13.6}%
   \abovedisplayskip 11\p@ \@plus3\p@ \@minus6\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6.5\p@ \@plus3.5\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 9\p@ \@plus3\p@ \@minus5\p@
               \parsep 4.5\p@ \@plus2\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
   \belowdisplayskip \abovedisplayskip
}
\newcommand{\footnotesize}{%
   \@setfontsize\footnotesize\@xpt\@xiipt
   \abovedisplayskip 10\p@ \@plus2\p@ \@minus5\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6\p@ \@plus3\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 6\p@ \@plus2\p@ \@minus2\p@
               \parsep 3\p@ \@plus2\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
   \belowdisplayskip \abovedisplayskip
}

where we see that first level lists are redefined in the sizes \small and \footnotesize, the only ones where a list should be typeset in.
The values of the parameters is established in lines 4406 to 4421 of memoir.cls
\if@twocolumn
  \setlength{\leftmargini}{2em}
\else
  \setlength{\leftmargini}{2.5em}
\fi
\leftmargin \leftmargini
\setlength{\leftmarginii}{2.2em}
\setlength{\leftmarginiii}{1.87em}
\setlength{\leftmarginiv}{1.7em}
\if@twocolumn
  \setlength{\leftmarginv}{.5em}
  \setlength{\leftmarginvi}{.5em}
\else
  \setlength{\leftmarginv}{1em}
  \setlength{\leftmarginvi}{1em}
\fi

This part of the code is processed after memYY.clo has been read in, so after \normalsize has been issued and, as a consequence, the value of em is taken from the main font at that point, which is Computer Modern.
If you want to modify them, you're free to do it; if you plan to use em units, then do the changes using \AtBeginDocument after the font package you like has been loaded.
As you see, there are several parameters: \topsepX, \parsepX, \partopsepX (for X equal to i, ii oriii`).
The memoir class sets them using \defaultlists, but there are also \firmlists and \tightlists, see the manual.


text:
Q: Dexterity content type unavailable for editing with activated diazo theme? I am creating a new Plone 4.3 site with a Diazo theme, and my users will need to be able to choose between multiple page configurations (layouts). To make those available I have used Dexterity Content Types and set the class to "Item". With the theme deactivated the content shows on the necessary pages and can be edited with the visual editor, but with the Diazo theme active neither the content nor the visual editor appear in the content section when edit is clicked.
Is this not the intended use for what I am trying to achieve? Am I missing follow-up steps after I create the Dexterity Content Type?
I have already rerun buildout and restarted Zope. The secondary page option needs to be something the contributor can select as this is a large organization and individually controlling theme templates with diazo rules.xml would not be efficient.

A: In my usecases it also usually was some error in the rules file(s). I usually find it helpfull to look at the differences between the diazo styled site and the original (use ?diazo.off=1 after your url to see the unstyled version of your site).
Use the Firepath tab in your Firebug in Firefox to see of your CSS3 or XPath selectors actually select what you mean to select for use in your theme.
Then adjust your rules file(s) accordingly.


text:
Q: Modifying a query that had a left join and an inner join The query below sums up points from the MySQL table "comment" when the following conditions are met:

*

*The loginid when l.username = '$profile' is found.

*All the submissionids are found that have the loginid from #1 above.

*All the commentids with the submissionids from #2 above are found, and the corresponding points are summed.
Now, how could I make a different query that returns an array of all of the comments in #3 above rather than summing the points?
Here are the MySQL tables involved:
login:
logind username created activated
submission:
submissionid loginid
comment:
commentid submissionid points comment
Query:
SELECT
    l.loginid,
    l.username,
    l.created,
    l.activated,
    COALESCE(scs.total, 0) AS commentsreceivedvalue

FROM login l

LEFT JOIN (
    SELECT S2.loginid, SUM(C2.points) AS total
FROM submission S2
INNER JOIN comment C2
ON S2.submissionid = C2.submissionid
GROUP BY S2.loginid
) scs ON scs.loginid = l.loginid

WHERE l.activated = 1
AND l.username = '$profile'

GROUP BY l.loginid
ORDER BY commentsreceivedvalue DESC

A: Isn't it as simple as:
SELECT l.loginid, l.username, l.created, l.activated, scs.commentid, scs.comment
  FROM login AS l
  LEFT JOIN (SELECT S2.loginid, c2.commentid, c2.comment
               FROM submission AS S2
               JOIN comment    AS C2 ON S2.submissionid = C2.submissionid
            ) AS scs ON scs.loginid = l.loginid
 WHERE l.activated = 1
   AND l.username = '$profile'
 ORDER BY scs.commentid DESC;

The outer GROUP BY in the original was not doing anything useful.  The ORDER BY in the original was replaced here by the ordering in reverse order of comment ID, which is an approximation to reverse chronological order (most recent first, in other words).


text:
Q: can´t get decimal value in my MVC controller I have a model with a decimal value that represents the price of an event, the property has some validations
[Required(ErrorMessage="Especifique precio evento")]
[Display(Name="Precio Evento")]
[DataType(DataType.Currency, ErrorMessage = "formato precio incorrecto")]
[RegularExpression(@"^\$?\d+(\.(\d{2}))?$", ErrorMessage = "formato precio incorrecto")]
[Range(0, 9999999999999999.99, ErrorMessage = "precio incorrecto")]

public decimal PrecioEvento { get; set; }

my problem is that when the user submits the model (form's data) to the controller, if the value specified for Precioevento property is a number without point (ex: 126) the controller gets the price without any problem ... but if the user enters 126.45 then I get the value 0 in the controller, could you help and tell me what is the problem ?


text:
Q: How to run different independent parallel job on different nodes using slurm using worker/master concept? I have a program that uses the master/salve concept for parallelization. There is a master directory and multiple worker directories. I should first run the executive file in the master directory, then go to the working directories and run the working executive in each directory. The master waits for the worker to finish their jobs and send the results to the master for further calculations. The jobs of working directories are independent of each other so they can be run on different machines (nodes). The master and workers communicate with each other using the TCP/IP communications protoco.
I'm working on a cluster with 16 nodes and each node has 28 cores with slurm job manager. I can run my jobs with 20 workers on 1 node totaly fine. currently my slurm script looks like this:
#!/bin/bash
#SBATCH -n 1               # total number of tasks requested
#SBATCH --cpus-per-task=18 # cpus to allocate per task
#SBATCH -p shortq            # queue (partition) -- defq, eduq, gpuq.
#SBATCH -t 12:00:00        # run time (hh:mm:ss) - 12.0 hours in this.

cd /To-master-directory
master.exe /h :4004 &
MASTER_PID=$!

cd /To-Parent
# This is the directory that contains all worker (wrk)directories

parallel -i bash -c "cd {} ; worker.exe /h 127.0.0.1:4004" --
wrk1 wrk2 wrk3 wrk4 wrk5 wrk6 wrk7 wrk8 wrk9 wrk10 wrk11 wrk12 wrk13 wrk14
wrk15 wrk16 wrk17 wrk18 wrk19 wrk20
kill ${MASTER_PID}

I was wondering how can I modify this script to divide jobs running on workers between multiple nodes. For example, jobs associated with the wrk1 to wrk5 run on node 1, jobs associated with the wrk6 to wrk10 run on node 2 etc?

A: First, you need to let Slurm allocate distinct nodes for your job, so you need to remove the --cpus-per-task option and rather ask for 18 tasks.
Second, you need to get the hostname where the master runs as 127.0.0.1 will no longer be valid in a multi-node setup.
Third, just add srun before the call the bash in parallel. With the --exclusive -n 1 -c 1, it will dispatch each instance of the worker spawned by parallel to each of the CPUs in the allocation. They might be on the same node or on other nodes.
So the following could work (untested)
#!/bin/bash
#SBATCH -n 18               # total number of tasks requested
#SBATCH -p shortq            # queue (partition) -- defq, eduq, gpuq.
#SBATCH -t 12:00:00        # run time (hh:mm:ss) - 12.0 hours in this.

cd /To-master-directory
master.exe /h :4004 &
MASTER_PID=$!
MASTER_HOSTNAME=$(hostname)

cd /To-Parent
# This is the directory that contains all worker (wrk)directories

parallel -i srun --exclusive -n 1 -c 1 bash -c "cd {} ; worker.exe /h $MASTER_HOSTNAME:4004" --
wrk1 wrk2 wrk3 wrk4 wrk5 wrk6 wrk7 wrk8 wrk9 wrk10 wrk11 wrk12 wrk13 wrk14
wrk15 wrk16 wrk17 wrk18 wrk19 wrk20
kill ${MASTER_PID}

Note that in your example with 18 tasks and 20 directories to process, the job will first run 18 workers and then the two additional ones will be 'micro-scheduled' whenever a previous task finishes.


text:
Q: Unable to access modified value of imported variable I am new to python and have some problem understanding the scope here.
I have a python module A with three global variables :
XYZ = "val1"
ABC = {"k1" : "v1", "k2" : "v2"}
PQR = 1

class Cls_A() :
    def sm_fn_A(self) :
        global XYZ
        global ABC
        global PQR

        XYZ = "val2"
        ABC["k1"] = "z1"
        ABC["k3"] = "v3"
        PQR += 1

And another module B :
from A import Cls_A, XYZ, ABC, PQR

class Cls_B():
    def sm_fn_B(self) :
        Cls_A().sm_fn_A()
        print XYZ
        print ABC
        print PQR

Cls_B().sm_fn_B()

This gives me the following output :
val1
{'k3': 'v3', 'k2': 'v2', 'k1': 'z1'}
1

Since these are all global variables, why do I not get updated values of all the global variables printed ?

A: Explanation
Three global variables are defined in module A, in this code:
XYZ = "val1"
ABC = {"k1" : "v1", "k2" : "v2"}
PQR = 1

Then new global variables XYZ, ABC, PQR are defined in module B, in this code:
from A import Cls_A, XYZ, ABC, PQR

This line of code creates new variables, just as if the following was written:
import A
XYZ = A.XYZ
ABC = A.ABC
PQR = A.PQR

It is important to understand that A.XYZ and B.XYZ are two variables which point to the same object. They are not the same variable.
Then a new object is assigned to A.XYZ:
    XYZ = "val2"

This modified A.XYZ, but did not modify B.XYZ. The two used to be two variables which pointed to the same object, but now A.XYZ points to a different object.
On the other hand, A.ABC is not assiciated with a different object. Instead, the object itself is modified. When the object is modified, both A.ABC and B.ABC still point to the same object:
    ABC["k1"] = "z1"
    ABC["k3"] = "v3"

The third case is also not a case of object modification, but rather reassignment:
    PQR += 1

The value was incremented. That created a new object and than thet new object was assigned to A.PQR. B.PQR is unchanged. This is equivalent to:
    PQR = PQR + 1

A thing which may not be obvious is that both strings and integers are immutable objects in Python (there is no way to change number to 2 to become 3 - one can only assign a different int object to a variable, not change the existing one). Because of that, there is actually no way to change A.XYZ in a way that affects B.XYZ.
The dictionary could behave the same way
The reason why with the dictionary it "worked" is that the object was modified. If a new dictioanry was assigned to A.ABC, that would not work. E.g.
    ABC = {'k3': 'v3', 'k2': 'v2', 'k1': 'z1'}

Now it would not affect B.ABC, because the object in A.ABC was not changed. Another object was assigned to A.ABC instead.
Not related to modules
The same behaviour can be seen without any modules:
A_XYZ = "val1"
A_ABC = {"k1" : "v1", "k2" : "v2"}
A_PQR = 1

B_XYZ = A_XYZ
B_ABC = A_ABC
B_PQR = A_PQR

A_XYZ = "val2"
A_ABC["k1"] = "z1"
A_ABC["k3"] = "v3"
A_PQR += 1

print B_XYZ
print B_ABC
print B_PQR

Prints:
val1
{'k3': 'v3', 'k2': 'v2', 'k1': 'z1'}
1

Solution
Well, don't keep reference to the temporary object. Use the variable which has the correct value.
For example, in module B:
import A

class Cls_B():
    def sm_fn_B(self) :
        A.Cls_A().sm_fn_A()
        print A.XYZ
        print A.ABC
        print A.PQR

Cls_B().sm_fn_B()

Now there is actually no B.XYZ variable, which could be wrong. A.XYZ is always used.


text:
Q: GNOME Boxes: proper network configuration? I've got a problem with GNOME Boxes:
I've 2 machines, cloned 1 from other, with CentOS. Both machines get same IP address on GNOME Boxes, so when I boot the 2nd, the 1st gets disconnected from network, and vice versa. This is not acceptable behaviour, and I've been struggling to find out why does this happen for quite some time.

A: What I've found out is that Gnome Boxes & Libvirt save mac-address for machines in config located here:
/home/$USER/.config/libvirt/qemu

So, to fix the issue, both machines must have different Mac-addresses, which can be fixed only by editing those files. Didn't find any relevant option in Gnome Boxes GUI.