text:
Q: Is There any Possible to Achieve Use SlideMenu With TabView In Android Studio Actually i'm designing one app now.
Slide menu control, this menu have 5 categories like 5 fragments.
Each fragment have different different datas.I implemented slide menu also working perfectly.
Here first fragment is home fragment,In that i need to use tab swipe view control i mean two tabs will be there like tab names recent and all tabs.
So when i press recent tab needs to show something and when  i press all tab needs to show something.
But here i don't know how to use i researched for lot but i didn't get those.
What i exactly need is in slide menu home fragment i need tab based fragment
For your reference this screen shot
I need those codes please.And let me know is it possible or not.
Thanks in advance
this is my home fragment
public class HomeFragment extends Fragment {
  View view;
  private TabLayout tabLayout;
  private ViewPager viewPager;

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

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

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

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new
    ViewPagerAdapter(getFragmentManager());
    adapter.addFragment(new MoviesFragment(), "ONE");
    adapter.addFragment(new PhotosFragment(), "TWO");
    adapter.addFragment(new SettingsFragment(), "THREE");
    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);
    }
}

These Fragments are for tab
adapter.addFragment(new MoviesFragment(), "ONE");
adapter.addFragment(new PhotosFragment(), "TWO");
adapter.addFragment(new SettingsFragment(), "THREE");

all are just empty fragments..thanks in advance
this is my main activity
  public class MainActivity extends AppCompatActivity {

private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private ImageView imgNavHeaderBg, imgProfile;
private TextView txtName, txtWebsite;
private Toolbar toolbar;
private FloatingActionButton fab;

// urls to load navigation header background image
// and profile image
private static final String urlNavHeaderBg = "http://api.androidhive.info/images/nav-menu-header-bg.jpg";
private static final String urlProfileImg = "https://lh3.googleusercontent.com/eCtE_G34M9ygdkmOpYvCag1vBARCmZwnVS6rS5t4JLzJ6QgQSBquM0nuTsCpLhYbKljoyS-txg";

// index to identify current nav menu item
public static int navItemIndex = 0;

// tags used to attach the fragments
private static final String TAG_HOME = "home";
private static final String TAG_PHOTOS = "photos";
private static final String TAG_MOVIES = "movies";
private static final String TAG_NOTIFICATIONS = "notifications";
private static final String TAG_SETTINGS = "settings";
public static String CURRENT_TAG = TAG_HOME;

// toolbar titles respected to selected nav menu item
private String[] activityTitles;

// flag to load home fragment when user presses back key
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mHandler = new Handler();

    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    navigationView = (NavigationView) findViewById(R.id.nav_view);
    fab = (FloatingActionButton) findViewById(R.id.fab);

    // Navigation view header
    navHeader = navigationView.getHeaderView(0);
    txtName = (TextView) navHeader.findViewById(R.id.name);
    txtWebsite = (TextView) navHeader.findViewById(R.id.website);
    imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
    imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);

    // load toolbar titles from string resources
    activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);

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

    // load nav menu header data
    loadNavHeader();

    // initializing navigation menu
    setUpNavigationView();

    if (savedInstanceState == null) {
        navItemIndex = 0;
        CURRENT_TAG = TAG_HOME;
        loadHomeFragment();
    }
}

/***
 * Load navigation menu header information
 * like background image, profile image
 * name, website, notifications action view (dot)
 */
private void loadNavHeader() {
    // name, website
    txtName.setText("Ravi Tamada");
    txtWebsite.setText("www.androidhive.info");

    // loading header background image
    Glide.with(this).load(urlNavHeaderBg)
            .crossFade()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .into(imgNavHeaderBg);

    // Loading profile image
    Glide.with(this).load(urlProfileImg)
            .crossFade()
            .thumbnail(0.5f)
            .bitmapTransform(new CircleTransform(this))
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .into(imgProfile);

    // showing dot next to notifications label
    navigationView.getMenu().getItem(3).setActionView(R.layout.menu_dot);
}

/***
 * Returns respected fragment that user
 * selected from navigation menu
 */
private void loadHomeFragment() {
    // selecting appropriate nav menu item
    selectNavMenu();

    // set toolbar title
    setToolbarTitle();

    // if user select the current navigation menu again, don't do anything
    // just close the navigation drawer
    if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
        drawer.closeDrawers();

        // show or hide the fab button
        toggleFab();
        return;
    }

    // Sometimes, when fragment has huge data, screen seems hanging
    // when switching between navigation menus
    // So using runnable, the fragment is loaded with cross fade effect
    // This effect can be seen in GMail app
    Runnable mPendingRunnable = new Runnable() {
        @Override
        public void run() {
            // update the main content by replacing fragments
            Fragment fragment = getHomeFragment();
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
                    android.R.anim.fade_out);
            fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
            fragmentTransaction.commitAllowingStateLoss();
        }
    };

    // If mPendingRunnable is not null, then add to the message queue
    if (mPendingRunnable != null) {
        mHandler.post(mPendingRunnable);
    }

    // show or hide the fab button
    toggleFab();

    //Closing drawer on item click
    drawer.closeDrawers();

    // refresh toolbar menu
    invalidateOptionsMenu();
}

private Fragment getHomeFragment() {
    switch (navItemIndex) {
        case 0:
            // home
            HomeFragment homeFragment = new HomeFragment();
            return homeFragment;
        case 1:
            // photos
            PhotosFragment photosFragment = new PhotosFragment();
            return photosFragment;
        case 2:
            // movies fragment
            MoviesFragment moviesFragment = new MoviesFragment();
            return moviesFragment;
        case 3:
            // notifications fragment
            NotificationsFragment notificationsFragment = new NotificationsFragment();
            return notificationsFragment;

        case 4:
            // settings fragment
            SettingsFragment settingsFragment = new SettingsFragment();
            return settingsFragment;
        default:
            return new HomeFragment();
    }
}

private void setToolbarTitle() {
    getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}

private void selectNavMenu() {
    navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}

private void setUpNavigationView() {
    //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        // This method will trigger on item Click of navigation menu
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            //Check to see which item was being clicked and perform appropriate action
            switch (menuItem.getItemId()) {
                //Replacing the main content with ContentFragment Which is our Inbox View;
                case R.id.home:
                    navItemIndex = 0;
                    CURRENT_TAG = TAG_HOME;
                    break;
                case R.id.nav_photos:
                    navItemIndex = 1;
                    CURRENT_TAG = TAG_PHOTOS;
                    break;
                case R.id.nav_movies:
                    navItemIndex = 2;
                    CURRENT_TAG = TAG_MOVIES;
                    break;
                case R.id.nav_notifications:
                    navItemIndex = 3;
                    CURRENT_TAG = TAG_NOTIFICATIONS;
                    break;
                case R.id.nav_settings:
                    navItemIndex = 4;
                    CURRENT_TAG = TAG_SETTINGS;
                    break;
                case R.id.nav_about_us:
                    // launch new intent instead of loading fragment
                    startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
                    drawer.closeDrawers();
                    return true;
                case R.id.nav_privacy_policy:
                    // launch new intent instead of loading fragment
                    startActivity(new Intent(MainActivity.this, PrivacyPolicyActivity.class));
                    drawer.closeDrawers();
                    return true;
                default:
                    navItemIndex = 0;
            }

            //Checking if the item is in checked state or not, if not make it in checked state
            if (menuItem.isChecked()) {
                menuItem.setChecked(false);
            } else {
                menuItem.setChecked(true);
            }
            menuItem.setChecked(true);

            loadHomeFragment();

            return true;
        }
    });

    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {

        @Override
        public void onDrawerClosed(View drawerView) {
            // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
            super.onDrawerClosed(drawerView);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
            super.onDrawerOpened(drawerView);
        }
    };

    //Setting the actionbarToggle to drawer layout
    drawer.setDrawerListener(actionBarDrawerToggle);

    //calling sync state is necessary or else your hamburger icon wont show up
    actionBarDrawerToggle.syncState();
}

@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawers();
        return;
    }

    // This code loads home fragment when back key is pressed
    // when user is in other fragment than home
    if (shouldLoadHomeFragOnBackPress) {
        // checking if user is on other navigation menu
        // rather than home
        if (navItemIndex != 0) {
            navItemIndex = 0;
            CURRENT_TAG = TAG_HOME;
            loadHomeFragment();
            return;
        }
    }

    super.onBackPressed();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.

    // show menu only when home fragment is selected
    if (navItemIndex == 0) {
        getMenuInflater().inflate(R.menu.main, menu);
    }

    // when fragment is notifications, load the menu created for notifications
    if (navItemIndex == 3) {
        getMenuInflater().inflate(R.menu.notifications, menu);
    }
    return true;
}

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

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_logout) {
        Toast.makeText(getApplicationContext(), "Logout user!", Toast.LENGTH_LONG).show();
        return true;
    }

    // user is in notifications fragment
    // and selected 'Mark all as Read'
    if (id == R.id.action_mark_all_read) {
        Toast.makeText(getApplicationContext(), "All notifications marked as read!", Toast.LENGTH_LONG).show();
    }

    // user is in notifications fragment
    // and selected 'Clear All'
    if (id == R.id.action_clear_notifications) {
        Toast.makeText(getApplicationContext(), "Clear all notifications!", Toast.LENGTH_LONG).show();
    }

    return super.onOptionsItemSelected(item);
}

// show or hide the fab
private void toggleFab() {
    if (navItemIndex == 0)
        fab.show();
    else
        fab.hide();
}

}


text:
Q: Is $\mathbb{R}^2$ a convex set without extreme points? My reasoning is, the vector space being a 'flat plane', a straight line joining any two points on it will always be contained in $\mathbb{R}^2$. And it has no points in it which cannot be on the straight line connecting two other points in the set (since the plane is infinite)
I am new to convex analysis and optimization techniques, so my line of thinking is very informal. Please let me know whether or not my approach is correct.

A: For any point $E \in \mathbb{R}^2$, because $\mathbb{R}^2$ is closed under addition and scalar multiplication, there exist two points (vectors) $x,y \in \mathbb{R}^2$ and an $\alpha \in (0,1)$ such that $E = \alpha x + (1-\alpha)y \in \mathbb{R}^2$.  Thus, the space does not contain any extreme points.

A: You're right that it is convex. Taking any $\vec x,\vec y\in\Bbb R^2,$ we have for all $\alpha\in(0,1)$ that $\alpha\vec x,(1-\alpha)\vec y\in\Bbb R^2$ by closure under scalar multiplication, and so $\alpha\vec x+(1-\alpha)\vec y\in\Bbb R^2$ by closure under addition.
As for extreme points, note that if $\vec x\ne\vec 0,$ then $\vec x$ lies on the open line segment between $\frac12\vec x$ and $\frac32\vec x,$ so cannot be extreme. I will leave it to you to show (by example) that $\vec 0$ cannot be an extreme point, either.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is a quasicompact quasiseparated morphism separated? If a morphism between schemes $f : X \to Y$ is both quasicompact and quasiseparated, could we prove that $f : X \to Y$ is a separated morphism?
In other words, if $f : X \to Y$ is quasicompact and $\Delta : X \to X \times_Y X$ is quasicompact, could we prove that $\Delta : X \to X \times_Y X$ is a closed immersion?

A: The affine line over a field with doubled origin already provides a counterexample. This scheme is noetherian, hence every subset is quasi-compact, hence any morphism out of it is qcqs.


text:
Q: Number type in mongoose schema always get saved as string I have this simple schema, with contact as Number data type. Strangely, the input data(contact) always gets saved as string in mongodb. I have no idea, as to what is happening in the background, or am I missing something.
var mongoose = require('mongoose');
var memberSchema = new mongoose.Schema({
.
. Other fields are not shown/ necessary
.
contact: {
   type: Number,
   required: true,
   }
});

module.exports = mongoose.model('Member',memberSchema);

In my routes file, I send user data for adding into DB like this
exports.post = function(req,res,next){
    if(!req.body.name || !req.body.email || !req.body.contact)
        return res.render('index', {error: 'Fill Name, Email and Contact'});
    //req.body.contact = parseInt(req.body.contact);
    var member = {
        name: req.body.name,
        email: req.body.email,
        contact: req.body.contact
}

As you can see req.body.contact is whatever user has entered in a form and I pass it that way.
The problem is, either I am not understanding the actual concept or there must me something more to it.
Note: I am not using any express or mongoose validator middlewares.
Any help would be highly appreciated.

A: You could test the contact value against a regular expression. The following example shows a custom validator using a regular expression to validates against a 10 digit number. Custom validation is declared by passing a validation function:
var memberSchema = new Schema({
    contact: {
        type: Number,
        validate: {
            validator: function(v) {
                return /d{10}/.test(v);
            },
            message: '{VALUE} is not a valid 10 digit number!'
        }
    }
});

var Member = mongoose.model('Member', memberSchema);

var m = new Member();

m.contact = '123456789';
// Prints "ValidationError: 123456789 is not a valid 10 digit number!"
console.log(m.validateSync().toString());

m.contact = 0123456789;
// Prints undefined - validation succeeded!
console.log(m.validateSync());


text:
Q: I want to know the speed of the wheel when wheel is rotating I am rotating the wheel using tweenlite, below is the piece of code
TweenLite.to(wheel, 12, {rotation:720, immediateRender:true, useFrames:false, onUpdate:onTweenUpdate});
When wheel is spinning i want to know the wheel speed for some stuffs. Can i know the speed of the wheel when it is rotating?

A: Based on @DodgerThud's comment..
to avoid manual calculation you could put your numbers in int variables like so
num_rotation : int = 720;
num_time     : int = 12;
num_speed    : int = 0; //updates later

Then your tween code could look like..
TweenLite.to(wheel, num_time, {rotation:num_rotation, immediateRender:true, useFrames:false, onUpdate:onTweenUpdate});

Then like @BotMaster's comment said, inside your onTweenUpdate you could have..
num_speed = num_rotation / num_time; //update speed calculation


text:
Q: Radio Button Handler not firing properly I have a set of 6 radio buttons : All , Time, Suppression, Address , Session and Tags.
I have a handler associated with each button that fires an event on it being clicked. The handler will fire a grid filtering event and load only certain portions of a grid depending on what radio is selected.
Example of a radio button code.
{

    boxLabel: 'Source',
    name: 'source',
    inputValue: 4,
    handler: function () {
        gridstore.clearFilter();
        gridstore.filter('id', '2');
        gridstore.load();
    }
}

The first time I click the radio, the handler loads and works properly displaying the right part of the grid for each of the 6 radios but if I try to fire it again (come back to an already clicked radio and click on it again), it doesn't work. I am sure I need to send some parameters to the handler. Can someone help me with what they should be?
EDIT: This is my entire code for that section
var radioGroup = {
    xtype: 'fieldset',
    // title: 'Radio Groups',
    layout: 'anchor',
    height: 250,
    border: false,
    defaults: {
        anchor: '100%',
        labelStyle: 'padding-left:4px;',
        border: false
    },
    collapsible: false,
    items: [{
        xtype: 'radiogroup',
        // fieldLabel: 'Single Column',
        columns: 1,
        border: false,

        items: [{
            boxLabel: 'All',
            name: 'all',
            inputValue: 1,
            border: false,
            checked: true,
            id: 'All',
            handler: function () {
                var all = Ext.getCmp('All');
                if (all.getValue()) {
                    gridstore.clearFilter();

                    gridstore.load();
                }
            }
        }, {
            boxLabel: 'Time',
            name: 'time',
            inputValue: 2,
            id: 'Time',

            handler: function () {
                var time = Ext.getCmp('Time');
                if (time.getValue()) {
                    gridstore.clearFilter();
                    gridstore.filter('id', '3');
                    gridstore.load();
                }
            },

        }, {
            boxLabel: 'Assignment',
            name: 'assignment',
            inputValue: 3,
            id: 'Assignment',
            handler: function () {
                var assignment = Ext.getCmp('Assignment');
                if (assignment.getValue()) {
                    gridstore.clearFilter();
                    gridstore.filter('id', '5');
                    gridstore.load();
                }
            }
        }, {
            boxLabel: 'Source',
            name: 'source',
            inputValue: 4,
            id: 'Source',
            handler: function () {
                var source = Ext.getCmp('Source');
                if (source.getValue()) {
                    gridstore.clearFilter();
                    gridstore.filter('id', '2');
                    gridstore.load();
                }
            }
        }, {
            boxLabel: 'Address',
            name: 'address',
            inputValue: 5,
            id: 'Address',
            handler: function () {
                var address = Ext.getCmp('Address');
                if (address.getValue()) {
                    gridstore.clearFilter();
                    gridstore.filter('id', '5');
                    gridstore.load();
                }
            }
        }, {
            boxLabel: 'Supression',
            name: 'supression',
            id: 'Supression',
            inputValue: 6,
            handler: function () {
                var supression = Ext.getCmp('Supression');
                if (supression.getValue()) {
                    gridstore.clearFilter();
                    gridstore.filter('id', '6');
                    gridstore.load();
                }
            }
        }, {
            boxLabel: 'Tags',
            name: 'tags',
            id: 'tags',
            inputValue: 7,
            handler: function () {
                var tags = Ext.getCmp('tags');
                if (tags.getValue()) {
                    gridstore.clearFilter();
                    gridstore.filter('id', '7');
                    gridstore.load();
                }
            }
        }]
    }]
};

Updated Code 2:
var radioGroup = Ext.create('Ext.form.Panel', {

    //defaultType: 'radiofield',
    // title: 'Radio Groups',
    layout: 'anchor',
    height: 250,
    border: false,
    defaults: {
        anchor: '100%',
        labelStyle: 'padding-left:4px;',
        border: false
    },
    collapsible: false,
    items: [{
        xtype: 'radiogroup',
        // fieldLabel: 'Single Column',
        columns: 1,
        border: false,
        listeners: {
            change: function (name, newValue, oldValue) {
                alert('new value is ', newValue);
            },

        },

        items: [{
            boxLabel: 'All',
            name: 'all',
            inputValue: 'all',
            border: false,
            checked: true,
            id: 'All',

        }, {
            boxLabel: 'Time',
            name: 'time',
            inputValue: 'time',
            id: 'Time',

        }

A: You need to combine them into one radio group, so only one of them will be selected. Then your event handlers will be fired again and again.
Update: first of all change all your handler to be like this:
handler: function(radio, checked) {
   if (checked) {
      // Do filtering
   }
}

Don't do getCmp and don't create additional and not used variables. Everything you need is already sent to the handler. Also you might want to add console.log(radio) before if (checked) to see if the handler is in fact being called second time.
And remove
name: xxx
id: xxx
border: xxx

from each radio button definition.
Update2: Try to add listener to RadioGroup itself:
listeners: {
   change: function(el, newValue, oldValue) { console.log('new value is ', newValue); }
   scope: me
}

Update3: Make something like this (see example http://docs.sencha.com/ext-js/4-0/#!/api/Ext.form.RadioGroup)
Panel
  -- RadioGroup
  --- listeners {}
  --- items: [
  ----- Radiobutton
  ----- Radiobutton
  ----- Radiobutton
      ]

A: The handler event looks at the change event. If you click an already checked radio it will not fire because nothing changes. There is no click event. Something that I am missing very much.


text:
Q: Home LAN ping problems I've following home LAN structure:

I'm trying to ping PC2 (192.168.1.2) from PC1 (192.168.0.11) but without success. What should i do to be able to ping it? Should i configure the routing table on PC1?

A: On PC1 you have to configure an static route. On Windows 7 for example it will be:

*

*Open the command prompt with Administrative rights going to the Start button, then type cmd on the search combo box. Right click on the cmd icon and click, Run as administrator

*Issue the command route add <destination subnet> mask <destination subnet mask> <gateway>, in this case:
route add 192.168.1.0 mask 255.255.255.0 192.168.0.10
It's a temporary route, to make it permanent you have to use route add -p.

A: This is correct, nothing is wrong.
With a typical SoHo NAT router setup, machines on the WAN side of the device cannot ping machines on the LAN side of the device. So machines on the Internet can't ping PC1 because they're on the WAN side of the modem (which is also a router) and PC1 is on the LAN side.
That's how small NAT routers work (like both your router and your modem).
So, similarly, PC1 is on the WAN side of the router because the modem is connected to the router's WAN port. PC2 is on the LAN side of the router. So PC1 should not be able to ping PC2.
If this was not what you wanted, you should not have set your network up this way. If you did this by mistake, change it around. Don't use the router's WAN port, don't set up two LANs, don't set up two DHCP servers, and just make on big happy LAN.


text:
Q: Newton's Method in perl Okay so for my math class we were asked to write a program that performs and prints Newton's method until the values converge and we have a root for the function. At first I thought it would be easy. It was until I just couldn't get the values derived from the first time to be used the second time. My knowledge of the language is basic. Really basic, so what you're about to see might not be pretty.
#!usr/bin/perl

use PDL;

print "First guess? (this is x0)\n";
$xorig = <>;

do {
  &fx;
} until ($fex == 0);

sub fx {

  if ($xn == 0) {
    $x = $xorig;
  }
  else {
    $x = $xn;
  }

  print "What is the coefficient (for each factor) of your function?\n";
  $fcx = <STDIN>;
  push @coefficient_of_x, $fcx;

  print "... times x to the (enter exponent, if no exponent, enter 1. if no x, enter 0)?\n";
  $fex = <STDIN>;
  push @exponent_x, $fex;

  chomp ($fcx, $fex, $x, $xorig);

  $factor = $fcx * ($x ** $fex);
  push @fx, $factor;
}

my $fx = 0;
foreach my $variable (@fx) {
  $fx = $variable + $fx #THIS PROVIDES A VALUE FOR THE GIVEN F(X) WITH A GIVEN X VALUE
}
print "f($x)=$fx\n";

do {
  &fprimex;
} until ($fprimeex == 0);

sub fprimex {

  if ($xn == 0) {
    $x = $xorig;
  }
  else {
    $x = $xn;
  }

  print "What is the coefficient (for each factor) of your derivative function?\n";
  $fprimecx = <STDIN>;
  push @coefficient_of_fpx, $fprimecx;

  print "... times x to the (enter exponent, if no exponent, enter 1. if no x, enter 0)?\n";
  $fprimeex = <STDIN>;
  push @exponent_fpx, $fprimeex;

  chomp ($fprimecx, $fprimeex, $x, $xorig);

  $factorprime = $fprimecx * ($x ** $fprimeex);
  push @fprimex, $factorprime;
}

$fprimex = 0;
foreach my $variableprime (@fprimex) {
  $fprimex = $variableprime + $fprimex #THIS PROVIDES A VALUE FOR THE GIVEN F'(X) WITH THAT SAME X VALUE
}
print "f'($x)=$fprimex\n";

sub x0 {
  $xn = $xorig - $fx / $fprimex; #THIS IS NEWTON'S METHOD EQUATION FOR THE FIRST TIME
  push @newxn, $xn;
  print "xn ia $xn\n";
}

&x0;

foreach $value (@exponent_x) {
  $exponent_x = $xn ** $value;
  push @part1, $exponent_x;
  $part1 = @part1;
}

foreach $value2 (@coefficient_of_x) {
  $part2 = $value2 * @part1;
  push @final1, $part2;
}

print "@part1\n";
print "@final1\n";

Essentially what it is is I first ask for the first guess. I use this value to define the coefficients and the exponents of f(x) to get a value for f(x) in terms of the given x. I do it again for f'(x). Then I perform newton's method the first time and get the new value xn. But I'm having a hard time to get values for f(xn) and f'(xn), meaning I can't get x(n+1) and can't continue newton's method. I need help.

A: Welcome to Perl.
I would strongly recommend the following changes to your code:

*

*Always include use strict; and use warnings; in EVERY Perl script.

*Always chomp your input from STDIN as your taking it:
chomp( my $input = <STDIN> );

*Don't needlessly create subroutines, especially for one-off scripts such as this.

*Instead of using the statement modifier form of do, I would recommend using an infinite while with loop control statements to exit:
while (1) {

    last if COND;
}

*Finally, since the coefficients of your polynomial are all associated with an exponent for X, I would recommend using a %hash for conveniently saving those values.
As demonstrated:
#!usr/bin/env perl
use strict;
use warnings;

print "Build your Polynomial:\n";

my %coefficients;

# Request each Coefficient and Exponent of the Polynomial
while (1) {
    print "What is the coefficient (for each factor) of your function? (use a bare return when done)\n";
    chomp( my $coef = <STDIN> );

    last if $coef eq '';

    print "... times x to the (enter exponent, if no exponent, enter 1. if no x, enter 0)?\n";
    chomp( my $exp = <STDIN> );

    $coefficients{$exp} = $coef;
}

print "\nFirst guess? (this is x0)\n";
chomp( my $x = <> );

# Newton's Method Iteration
while (1) {
    my $fx  = 0;
    my $fpx = 0;

    while ( my ( $exp, $coef ) = each %coefficients ) {
        $fx += $coef * $x**$exp;
        $fpx += $coef * $exp * $x**( $exp - 1 ) if $exp != 0;
    }

    print "   f(x) = $fx\n";
    print "   f'(x) = $fpx\n";

    die "Slope of 0 found at $x\n" if $fpx == 0;

    my $new_x = $x - $fx / $fpx;

    print "Newton's Method gives new value for x at $new_x\n";

    if ( abs($x - $new_x) < .0001 ) {
        print "Accuracy reached\n";
        last;
    }

    $x = $new_x;
}

A: I am having trouble working out what you intended with your code. The main problem seems to be that don't have it clear in your head what each of your subroutines do, as fx and fprimex ask for the data as well as evaluating the function (except for summing the terms which, oddly, is done outside the subroutine). That isn't what you want at all, as the exponents and coefficients remain constant throughout a program that has to evaluate those functions many times, and you really don't want to ask for the values again each time.
Here are some pointers to getting Perl code working in general

*

*Write your program in tiny chunks -- a line or two at a time -- and check after each addition that the program compiles and runs and produces the expected results. Writing an entire program before you even try to run it is a recipe for disaster

*Always use strict and use warnings, and declare every variable with my as close as possible to the point where it is first used. You have many undeclared variables which are therefore global, and passing information between sections of code using global variables is a good way to lose yourself in your own code. It is a good rule for a subroutine to use only parameters passed to it or variables declared within it

*chomp variables as soon as they are read, either from a file or from the terminal. A useful idiom to trim input strings at source is
chomp(my $input = <>)

which will ensure that there are no stray newlines anywhere in your data
That at least should get you started.
I'm in two minds about showing this. I hope it will help you, but I really don't want to drag you into parts of Perl that you're not familiar with.
It's a program that uses the Newton–Raphson method to find the root of polynomials. I've skipped the terminal input for now, and hard-coded the data. As it stands it finds the square root of 3,000 by finding the positive root of x2 - 3000.
Note that @f and @f_prime hold the coefficients of the function and its derivative backwards from the usual order, so @f is (-3000, 0, 1). The program also calculates the coefficients of the derivative function, as it is a simple thing to do and far preferable to asking the user for another set of values.
There is just one subroutine polynomial, which takes a value for x and a list of coefficients. This is used to calculate the value of both the function and its derivative for a given value of x.
The algorithm step is in the line
my $new_x = $x - polynomial($x, @f) / polynomial($x, @f_prime);

which calculates x - f(x) / f'(x) and assigns it to $new_x. Each successive estimate is printed to STDOUT until the loop exits.
Comparing floating-point values for equality is a bad idea. The precision of computer floating-point values is, obviously, limited, and a sequence will probably never converge to the point where the last two values of the sequence are equal. The best that can be done is to check whether the absolute value of the difference between the last two values is below a reasonable delta. An accuracy of 10E12 is reasonable for 32-bit floating-point numbers. I have found that the series converges to within 10E14 quite reliably, but if you find that your program hangs in an endless loop then you should increase the margin.
use strict;
use warnings;

my @f       = reverse (1, 0, -3000);
my @f_prime = map { $f[$_] * $_ } 1 .. $#f;

my $x = 0.5;
print $x, "\n";

while () {
  my $new_x = $x - polynomial($x, @f) / polynomial($x, @f_prime);
  last if abs($new_x - $x) < $x / 1e14;
  $x = $new_x;
  print $x, "\n";
}

sub polynomial {
  my ($x, @coeffs) = @_;

  my $total = 0;
  my $x_pow = 1;

  for my $coeff (@coeffs) {
    $total += $x_pow * $coeff;
    $x_pow *= $x;
  }

  $total;
}

output
0.5
3000.25
1500.62495833681
751.312062703027
377.652538627869
192.798174296885
104.179243809523
66.4878834504349
55.8044433107163
54.7818016853582
54.7722565822241
54.7722557505166


text:
Q: Group and concatenate many rows to one I want to "concatenate" all the "Text"-rows into one single row and get one row as a result. Is this even possible? I use MSSQL Server 2005.

A: I believe you're looking for something like this:
DECLARE @string nvarchar(max)
SET @string = N''

SELECT @string = @string + [Text] + N' ' FROM [YourTable]

SELECT @string

This will concatenate all of the values for the [Text] column into a single variable. You can then select the variable to retrieve all of the values in a single row.

A: Use FOR XML PATH:
SELECT [Text]+' ' AS 'text()' FROM _table FOR XML PATH('')

Another option - use string concatenation:
DECLARE @s nvarchar(max)
SELECT @s = ISNULL(@s, '') + t + ' '  FROM _table OPTION (MAXDOP 1)
SELECT @s

Please note that the latter one isn't guaranteed to work, afaik, officially the behaviour of "@s = @s + ..." for multi-row resultset is undefined.
MAXDOP 1 hint is used here to prevent the optimizer from creating a parralel execution plan, as this will yield an incorrect result for sure.

A: Something like:
DECLARE @result varchar(max)

SELECT @result = COALESCE(@result + ' ','') +[Text] FROM [Table]
SELECT @result


text:
Q: Height of a falling ball I'm confused about this formula $H = \frac {g}{2}\cdot t^2$
Imagine the following situation. A ball falls from a wall of $125$m and the fall lasts $5$s.
At the height of $80$m the time is $4$s, at the height of $45m$ the time is $3$s, since $80+45 = 125$, the time required to fall from a height of $125m$ is $4+3=7$, but by the formula the time would be $5$ and not $7$, I'm confused about this.

A: The formula you have given $$H=\frac{gt^2}{2}$$ is correct in the case where the initial velocity is $0$. This means that the time you have calculated is longer, as for the second part you used this equation which incorrectly assumes that at that point the initial speed would be $0$. The full equation should be $$H=ut+\frac{gt^2}{2}$$Hope this helps :)

A: In the case that throughout the question the initial velocity is zero (i.e. the object is dropped from a height $H$ ):
As the equation requires the time to be squared, the addition of the two times would have to be done like this:
$$t_1^2+t_2^2=t_{total}^2$$
So
$$4^2+3^2=25=5^2$$


text:
Q: How to invoke PHP script from JavaScript? I have a nagging feeling this has been asked, but I'm not sure how to phrase it correctly, so I'll ask here anyway.
I'm writing a simple calculator script (for learning, I'm newbie), and I split it up into two parts - front end form validation with JS and calculation with PHP.
To be more specific, here are the three parts:
HTML (index.php)
<form action = "calculator.php" method = "post">

First number: Input field here
Operator: Drop down
Second number: Input field here
Submit button
</form>

JavaScript (validate.js)
validate() - regex checks that first and second number are all digits
PHP (calculator.php)
Extract first and second number, calculate result, and display on page
Here's my question - I would like to make it such that when the submit button is pressed, the page is passed on to the server ONLY if all regex tests are passed.
Something like:
validate() {
    // testing code
    ...
    if first_num_valid == true && second_num_valid == true
        redirect to calculator.php
}

How do I do this in Javascript?
Or, if this isn't possible, can you suggest an alternative to this?
Thanks!
EDIT 1: Tried @joe's solution but not sure how to make it work?
$("#calculator").onsubmit(function() {
    if (first_valid && second_valid)
        return true;
    else
        return false;
});

I assume @joe was trying to say that the form only submit only if the return value is true, but I tried this, but the form submitted whether or not the values were true?
EDIT 2: For clarification
index.php
<form id = "calculator" action = "./calculation.php" method = "post" >

    First number
    <input type = "text" name = "first_num" id = "first_num"/>

    Operator

    <select name = "operator">
        <option value = "+" name = "add">+</option>
        <option value = "-" name = "minus">-</option>
        <option value = "*" name = "multiply">*</option>
        <option value = "/" name = "divide">/</option>
    </select>

    Second number
    <input type = "text" name = "second_num" id = "second_num" />

    <input type = "submit" name = "submit" id = "submit" onclick = "validate()"/>

</form>

validate.js
function validate() {
    var first_num = $("#first_num").val();
    var second_num = $("#second_num").val();

    var regex = new RegExp("^[\\d]+$");

    var first_valid = regex.test(first_num);
    var second_valid = regex.test(second_num);

    var alert_string = "";

    if (!first_valid && second_valid)
        alert_string += "First number invalid!
";
    else if (first_valid && !second_valid)
        alert_string += "Second number invalid!";
    else if (!first_valid && !second_valid)
        alert_string += "Both numbers invalid!";

    if (!first_valid || !second_valid)
        alert(alert_string);

    $("#calculator").onsubmit(function() {
        if (first_valid && second_valid)
            return true;
        else
            return false;
    });
}

EDIT 3: Put all code in handler, didn't work?
$("#calculator").on('submit', function() {
    var first_num = $("#first_num").val();
    var second_num = $("#second_num").val();

    var regex = new RegExp("^[\\d]+$");

    var first_valid = regex.test(first_num);
    var second_valid = regex.test(second_num);

    var alert_string = "";

    if (!first_valid && second_valid)
        alert_string += "First number invalid!";
    else if (first_valid && !second_valid)
        alert_string += "Second number invalid!";
    else if (!first_valid && !second_valid)
        alert_string += "Both numbers invalid!";

    if (!first_valid || !second_valid)
        alert(alert_string);

    if (first_valid && second_valid)
        return true;
    else
        return false;
});

A: Here's an answer for your form validation question.
First, give your form an id so that you can identify it.
<form id="calculator_form" action="calculator.php" method="post">

Then, attach a submit handler for that form. If the submit handler fails, the form will not submit.
document.getElementById('calculator_form').onsubmit = function() {
  if (!first_num_valid) {
    return false;
  }
  if (!second_num_valid) {
    return false;
  }
  return true;
}

OK now your question edit has jquery. That changes my answer here.
$("#calculator").on('submit', function() {
    if (first_valid && second_valid) {
        return true;
    }
    return false;
});

A: AJAX! (a basic AJAX call in jQuery)
function validate() {
    // testing code
        if (yourRegexTest == true) {
        $.ajax({
        url: "calculator.php?data1=" + jsVar1 + "&data2=" + jsVar2; // ...etc
        type: 'GET',
        dataType: 'json',
        success: function(data) {

           // data[0] now carries the php variable $newVar1 (below)
           // data[1] now carries $newVar2 (below)
           // do stuff with data[0] and data[1];
           return false; // do not submit the form. The ajax call does what you want pressing the submit button to effectively do.
        }

        });
        } else {  alert('regex check failed');
                  return false; // do not submit the form. regex check failed.
                  }
}

calculator.php
<?php
$var1 = $_GET['data1']; $var2 = $_GET['data2'];
$newVar1 = dostuffto($var1);
$newVar2 = dostuffto($var2);
echo json_encode(array($var1,$var2));
?>

Also -- "Here's my question - I would like to make it such that when the submit button is pressed, the page is passed on to the server ONLY if all regex tests are passed."
On the submit button use <input type="submit" id="myID" value="sumbit" onclick="return validate();"/>
When you return a JS function on an onclick event for a submit button as above, the form will not be submitted unless that function returns true. In my example the form never gets "submitted", but rather, the AJAX call is run only if the regex check passes.

A: AJAX is what you would want to look at to send things asynchronously to PHP.  Here is jQuery's API on the subject.  Gather your form info, submit it with AJAX, and put in your callback functions to capture what PHP kicks out (which you will use to display to the user on screen).
One side note I would like to offer though is that you do some validation on the server side.  It certainly isn't a bad thing to do any validation with JS on the client side, but malicious users can circumvent your validation.  My suggestion for validation is to do some basics with JS, but make sure PHP is sanitizing/validating the input properly.
EDIT

I have a version of this you can take a look at that uses native JS (as your question originally started as).  You appear to need AJAX, but looking at your question it looks like you wish to simply submit the form.  I say this because there seems to be no immediate place in your code where a return value would be delivered.
Anyhow, the basic idea is to get both of your values from your number fields, check them as number, and then submit.  Give this a try:
<form id = "calculator" action = "./calculation.php" method = "post" onsubmit="return validate()" >

    First number
    <input type = "text" name = "first_num" id = "first_num"/>

    Operator

    <select name = "operator">
        <option value = "+" name = "add">+</option>
        <option value = "-" name = "minus">-</option>
        <option value = "*" name = "multiply">*</option>
        <option value = "/" name = "divide">/</option>
    </select>

    Second number
    <input type = "text" name = "second_num" id = "second_num" />

    <input type = "submit" name = "submit" id = "submit" />

</form>

Hope that helps.  I still can stress enough that in a real-life application you should really rely on server side validation of data.


text:
Q: Simple download link for an ios app without itunes I want to supply a simple link for testing purpose to download an ios app? To which file has the link to point to.
I tried that one without success:

click this link to install

Any idea?

A: Please try to provide full plist url.
Example :
Install

For iOS 8, after you click the hyperlink, you must press the "Home" button manually to see your app installing.

A: From iOS 7.1 Apple forces you to use HTTPS, not HTTP. That means if you are going to use a host you have, or localhost, you must have an SSL Certificate. Or else, the download will not work.


text:
Q: Nestjs Mongoose, How to delete array member by its _id? The schema is like this. it's a shopping cart with items:
export interface Cart extends mongoose.Document {
  userId: string;
  total: number;
  count: number;
  status: string;
  items: [
    {
      itemId: string;
      itemName: string;
      count: number;
      price: number;
      itemTotal: number;
    },
  ];
}

if you look at the mondodb data, there is an _id to each of the members in items array.
I have this _id, and i want to remove an item by that _id.
The problem is, it's typescript, and _id is not part of the schema.
Here is the code i use to delete an item:
const cart = await this.cartModel.findOneAndUpdate(
   { _id: dto.cartId },
   { $pull: { items: { _id: '1234567890' } } },
   { new: true },
);

Which means, in that specific cart, find the item with _id equals to 1234567890, and delete it.
BUT the _id has red squiggly, as it is not part of my schema.
How can I solve this?

A: It shoulds be id not _id. Because _id is an object. But our query cannot send object to params. So, it should be a hexString.
You can change your entity _id to id by:
 @ObjectIdColumn()
 @Transform(id => id.toString())
 id: string;

So that, you can use id as hexString anywhere. Hope it helps

A: For lack of better solution, i have bypassed this issue by adding a text field called timeStamp. when an item is added to the cart, i push the current time (in ms) to that field, and that is unique enough to distinguish between entries in a shopping cart. In case you wonder, itemId is not good enough, as people can have the same item in 2 or more lines, with different details. I have added of course the new field to my schema, so typescript is not complaining ;)


text:
Q: API to monitor iphone app store reviews I'm trying to develop a review monitoring system for several iPhone apps I've developed, for instance to email me with the contents of a review when one comes in.  (Right now, without an iPhone, I can't even view reviews.) I was hoping there was some online browser for the app store (like cyrket for android), but I am unsure if this exists (I can't find any definitive answer via searching).
Is there any online browser that can be scraped? Or is there at least some API I can use to view app reviews?  Or will it come down to sniffing packets and reverse engineering the app store protocol?

A: Unfortunately, none of the answers here did the trick, and  I didn't get the feedback I needed.
However, I found an answer.
One can just go to the rss feed from Apple feedback (in the itunes connect site and replace the word xml with json (for those [like me] who prefer to work with json objects). However note, that XML has 2 extra fields, that are missing in JSON : <updated>(very useful) and <content type="html">.
https://itunes.apple.com/HERE-YOU-PUT-THE-CONTRY-CODE/rss/customerreviews/id=PUT-APP-ID-HERE/sortBy=mostRecent/json
APP ID - you cant get your app id from itunsconnect in the view details tab.
country codes - like il for israel, it for italy and etc.
For example, in my case the link was -
https://itunes.apple.com/il/rss/customerreviews/id=567630281/sortBy=mostRecent/xml
I hope this helps.

A: We had the same issues, and since we have 7 apps in the App Store, visiting the store pages wasn't really an option. So we built a tool that we recently released that you might find useful: https://launchkit.io/reviews/
It emails you all new reviews and posts them to your teams Slack channel.

A: This post outlines building such a "scraper" using curl.  It also gathers international reviews, which is difficult to do just using iTunes:
http://blogs.oreilly.com/iphone/2008/08/scraping-appstore-reviews.html

A: I know this question is probably out of date, but I found an EXCELLENT resource http://blog.manbolo.com/2012/09/10/useful-itunes-web-services outlining the various APIs that are available for querying iTunes data, INCLUDING a mechanism for querying app reviews, e.g.
https://itunes.apple.com/rss/customerreviews/id=400274934/xml


text:
Q: Memory leak for CComBSTR I have read that the following code causes memory leak. But did not understand why.
CComBSTR str;
pFoo->get_Bar(&str);
pFoo->get_Baf(&str);

How does it cause a leak when we are not allocating anything?

A: This Microsoft page is probably the where you read about it:
http://msdn.microsoft.com/en-us/library/bdyd6xz6.aspx

Memory Leak Issues
Passing the address of an initialized CComBSTR to a function as an [out] parameter causes a memory leak.

The CComBSTR object is allocating memory internally.  Evidently there are cases where it doesn't release it.

A: It leaks because get_Bar() and get_Baf() don't know that you're using a CComBSTR.
When you take the address of a CComBSTR what you're actually passing to the underlying object is a pointer to the CComBSTR's BSTR member.
Breaking down the sequence:
CComBSTR str;

This initializes the internal BSTR to NULL.
pFoo->get_Bar(&str);

get_Bar() sees a BSTR* and fills it with actual data.  Like this:
HRESULT get_Bar(BSTR* arg) { *arg = SysAllocString(L"My String"); }

Now the internal BSTR of str is a real BSTR.  When CComBSTR goes out of scope it will delete the str member.
Now if you call get_Baf() on &str the problem is that the CComBSTR doesn't know that you are changing the string.  So you call get_Baf() like this:
HRESULT get_Baf(BSTR* arg) { *arg = SysAllocString(L"My String"); }

Now get_Baf() has overwritten the original value of str's internal BSTR without anyone freeing the data that was allocated by get_Bar().
Ta da - Memory leak.


text:
Q: What does the '+' sign mean in a coffee script anonymous function do? I came across this coffee script.
y = ... // assume something that would work in the context
d3.svg.line().x((d)-> x(new Date(d.epoch * 1000))).y((d)-> y(+d[info]))

I want to know what is the + sign mean in that anonymous function at the tail. I tried to find coffee script ref. But I never learned this script, and I have know idea what should I look for.
I use JavaScript, and I want to convert this script into JS.

A: It is the unary + (plus) and works just as it does in JavaScript; it coerces the operand to a number.

The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already .. It can convert string representations of integers and floats, as well as the non-string values true, false, and null .. If it cannot parse a particular value, it will evaluate to NaN.

For Objects, such as Dates, +obj is the same as calling obj.valueOf().
It has nothing to do with functions.


text:
Q: Installing Java3D on Eclipse I'm trying to use Java3D in my project.  This is the error I receive:
29-Dec-2010 1:01:29 AM javax.media.j3d.NativePipeline getSupportedOglVendor
SEVERE: java.lang.UnsatisfiedLinkError: no j3dcore-ogl-chk in java.library.path
Exception in thread "main" java.lang.UnsatisfiedLinkError: no j3dcore-d3d in java.library.path
 at java.lang.ClassLoader.loadLibrary(Unknown Source)
 at java.lang.Runtime.loadLibrary0(Unknown Source)
 at java.lang.System.loadLibrary(Unknown Source)
 at javax.media.j3d.NativePipeline$1.run(NativePipeline.java:189)
 at java.security.AccessController.doPrivileged(Native Method)
 at javax.media.j3d.NativePipeline.loadLibrary(NativePipeline.java:180)
 at javax.media.j3d.NativePipeline.loadLibraries(NativePipeline.java:137)
 at javax.media.j3d.MasterControl.loadLibraries(MasterControl.java:948)
 at javax.media.j3d.VirtualUniverse.<clinit>(VirtualUniverse.java:280)
 at World.<init>(World.java:10)
 at Start.main(Start.java:12)

I have copied the .jar files into my project's lib folder and linked them in Project -> Properties -> Add Jar File.  There was also a .dll file in the Java3D download that I haven't touched or included in any way.  What am I missing?

A: On Windows you must add the directory containing the DLL's (e.g. …\j3d-1_5_2-windows-i586\bin) to the PATH environment variable. The "Unzip Instructions" incorrectly says that the nonexistent "…\lib\i386" should be added (version 1.5.2).
Not able to test it on Linux, but probably you must add the directory with the SO files to the LD_LIBRARY_PATH environment variable.
More details in the README-unzip.html file in j3d-1_5_2-windows-i586.zip or j3d-1_5_2-linux-i586.zip (same for other systems).

A: For me, the answer was "project/properties/java build path/source tab/expand and select native library location / navigate to i386 folder." by telman shahbazov (problems with java3D lib configuration). Thought I'd put this here for anyone else googling with this problem.

A: when you install the java3d, in the created folder, there are bin and ext folders, do the next:
Copy the .dll file from:

.../Program Files/Java/Java3D/1.5.1/bin

to

.../Program Files/Java/jre7/bin

Copy all .jar files from:

.../Program Files/Java/Java3D/1.5.1/lib/ext

to

.../Program Files/Java/jre7/lib/ext

A: Include the .dll file in your system's classpath, and then restart eclipse.


text:
Q: Symbol cannot be resolved when entered as a parameter in constructor I'm working on a coding task as part of one of my labs for a University paper and stuck on setting up my constructor and a couple of booleans that are to pull an age variable from the constructor without using another data field (age), in the class. Can anyone shed any light on why I can't resolve these symbols (age) in my booleans, even though age is a parameter in the constructor?
UML Diagram:

*

*name: string

*child: boolean

*student: boolean

*

*Customer(nameIn:String, age:int, studentIn:boolean)

*getName(): String

*isChild(): boolean

*isStudent(): boolean

and here is my code so far:
public class Customer {
    /**Data Field declarations */
    String name;
    boolean child;
    boolean student;
    boolean booked;

    /** Contstructor for the customer
    * @param nameIn, age and is student
    */
    public Customer (String nameIn, int age, boolean studentIn) {

        this.name = nameIn;
        this.student = studentIn;
    } //end method

    /**Accessor method to get name of customer */
    public String getName(){
        return name;
    }//end method

    /**Boolean test method to check if child */
    private boolean isChild() {
        if (age <= 5 && age >= 17)
            return child;
    }//end method

    /**Boolean test method to check if student */
    private boolean isStudent() {
        if (age <= 16 && age >= 18)
            return student;
    }//end method
}

Please help! Been stuck on this for a few hours now!

A: Do the Testing for wether the Customer with the given age is a child within the constructor. If it is the set child to true, otherwise to false. So the same for student.
Then you can rewrite the isChild() and isStudent() function so that it returns the attribute value of the class.

A: In your isChild() and isStudent() methods, you don't pass any age parameter. You should pass an int age parameter in both of those methods, and set the values of the booleans to child = isChild(age) and student = isStudent(age). It should in the end look like the hastebin here: https://hastebin.com/nowopokuyu.java . Hope this helps!!

A: The reason you can't resolve the age variable in your Boolean methods is that age is only accessible within the constructor.
Why not move your conditional logic and set the values of child and student within the constructor and provide simple getters as you've done with name?
There's also an issue with your conditions - you've mixed up your <= and >= in such a way that those conditions can never evaluate to true.

A: In the following code:
private boolean isChild() {
    if (age <= 5 && age >= 17)
        return child;
}

Not all paths return a value. You must set the variables for child and student in the constructor. I would change it to be like so in this hastebin, so long as you can use isChild as an accessor: https://hastebin.com/oqiqobayuw.java
edit: also the >= and <= are flipped for each of the comparisons.

A: You have to set your booleans in the constructor (i.e with a method to evaluate age) and then use public method to access those attributes.
Customer:
public class Customer {
    private String name;
    private boolean child, student;

    public Customer(String nameIn, int age, boolean studentIn) {

        this.name = nameIn;
        this.student = studentIn;
        this.child = isChild(age);
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    private boolean isChild(int age) {
        return (age >= 5 && age <= 16);
    }

    public boolean isStudent() {
        return student;
    }

    public boolean isChild() {
        return child;
    }

    @Override
    public String toString() {
        return "Customer [name=" + name + ", child=" + child + ", student=" + student + "]";
    }

}

MainP:
public class MainP {

    public static void main(String[] args) {
        Customer c1 = new Customer("c1", 5, true);

        System.out.println(c1.getName() + " " + c1.isChild() + " " + c1.isStudent());

        Customer c2 = new Customer("c2", 50, false);

        System.out.println(c2.getName() + " " + c2.isChild() + " " + c2.isStudent());

    }

}

Output:
c1 true true
c2 false false


text:
Q: Add multiple Elements to Set in a Dictionary I am trying to achieve the following structure.
{0: set([1]), 1: set([2]), 2: set([0,3]), 3: set([3])}

Following is my code :
class Graph(object):
    """ This is the graph class which will store the information regarding
        the graph like vertices and edges.
    """

    def __init__(self,num_vertices):
        self.vertices = num_vertices
        self.edges = []
        self.indi_edges = ()

    def enter_edges(self,source,dest):
        self.indi_edges = (source, dest)
        self.edges.append(self.indi_edges)

    def form_graph_structure(self):
        temp_dict = {}
        for idx,value in enumerate(self.edges):
            if value[0] in temp_dict:
                print "here"
                temp_dict[value[0]].update(value[1])
            print "there"
            temp_dict[value[0]] = set()
            temp_dict[value[0]].add(value[1])
        print temp_dict

    def display(self):
        print self.edges

g = Graph(4)
g.enter_edges(2,0)
g.enter_edges(2,3)
g.enter_edges(0,1)
g.enter_edges(1,2)
g.enter_edges(3,3)
g.form_graph_structure()

I am getting the following error
  File "DFS.py", line 20, in form_graph_structure
    temp_dict[value[0]].update(value[1])
TypeError: 'int' object is not iterable

Can anyone help?

A: set.update() expects an iterable of values. Use set.add() to add one value:
if value[0] in temp_dict:
    temp_dict[value[0]].add(value[1])

Rather than test for value[0] each time, use dict.setdefault() to set an empty set if the key is missing:
def form_graph_structure(self):
    temp_dict = {}
    for source, dest in self.edges:
        temp_dict.setdefault(source, set()).add(dest)
    return temp_dict

A: You can use defaultdict using set as its default value.
from collections import defaultdict

class Graph(object):
    """ This is the graph class which will store the information regarding
        the graph like vertices and edges.
    """

    def __init__(self, num_vertices):
        self.vertices = num_vertices
        self.edges = []

    def enter_edges(self, source, dest):
        self.edges.extend([(source, dest)])

    def form_graph_structure(self):
        temp_dict = defaultdict(set)
        for pair in self.edges:
            source, dest = pair
            temp_dict[source].add(dest)
        print temp_dict

    def display(self):
        print dict(self.edges)

g = Graph(4)
g.enter_edges(2,0)
g.enter_edges(2,3)
g.enter_edges(0,1)
g.enter_edges(1,2)
g.enter_edges(3,3)

>>> g.form_graph_structure()
{0: set([1]), 1: set([2]), 2: set([0, 3]), 3: set([3])}

You could also update the graph structure after entering each pair of edges:
class Graph(object):
    """ This is the graph class which will store the information regarding
        the graph like vertices and edges.
    """

    def __init__(self):
        self.graph = defaultdict(set)

    def enter_edges(self, source, dest):
        self.graph[source].add(dest)

    def display(self):
        print dict(self.graph)

g = Graph()
edges = [(2, 0), (2, 3), (0, 1), (1, 2), (3, 3)]
for pair in edges:
    g.enter_edges(*pair)
g.display()
{0: set([1]), 1: set([2]), 2: set([0, 3]), 3: set([3])}


text:
Q: WPF ComboBox resets selected item when item-source changes Consider the following XAML:
<ComboBox Name="CompanyComboBox"
    HorizontalAlignment="Stretch"
    ItemsSource="{Binding Path=GlobalData.Companies}"
    SelectedValuePath="Id"
    SelectedValue="{Binding Customer.CompanyId, ValidatesOnDataErrors=True}"
    DisplayMemberPath="Name" />

GlobalData.Companies is a collection (IEnumerable<Company>) of companies; this collection can be reloaded on background (it is downloaded from a webservice). When this happens, ComboBox correctly reloads items via binding. However as a side-effect, it also resets the selected item!
I have used Reflector to inspect combo-box sources and apparently this is intended behavior.
Is there any "nice" way how to get around this? What I want to achieve, is that if the user selects "Company A" and reloads list of companies afterwards, then "Company A" stays selected (assuming it is in the new list).

A: Maybe you can use ObservableCollection<Company> instead of your IEnumerable<Company>? Then, on background change you would only Add / Remove items that are new / absent in the new list, selected item should stay, unless it was removed by the change.
You can update your observable collection in a separate thread with a small hack-around.

A: Please try with the following code.
Enable the following property to the combo box
IsSynchronizedWithCurrentItem="True"

A: hmm, I don't know if it is a "nice" way, but if you can access the selected item before the reload occurs, you can save it (or its key or something), and select it programatically again after the reload is done.
quick mockup:
var selectedItem = myCombo.SelectedItem;
DoReload();
myCombo.SelectedItem = selectedItem;

But I assume you mean another way than this manual work around?
Hope this helps anyway...
UPDATE
Ok I see, from a background thread.
Are you using an ICollectionView to bind your combobox too? If so, you can use the CurrentItem property to keep a reference. I made a quick mockup, and this is working on my setup. this assumes you have a reference to your UI:
XAML
<Grid VerticalAlignment="Top">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <ComboBox ItemsSource="{Binding Items}" IsSynchronizedWithCurrentItem="True" Grid.Column="0" Grid.Row="0" DisplayMemberPath="Name"/>
    <Button Command="{Binding UpdateCommand}" Grid.Column="1" Grid.Row="0">Update</Button>
</Grid>

View/ViewModel
public partial class Window1 : Window {
   public Window1() {
        InitializeComponent();
        this.DataContext = new ViewModel(this);
   }
}

public class ViewModel
{
    private readonly Window1 window;
    private ObservableCollection<Item> items;
    private ICollectionView view;

    public ViewModel(Window1 window) {
        this.window = window;
        items = new ObservableCollection<Item>
            {
                new Item("qwerty"),
                new Item("hello"),
                new Item("world"),
            };

        view = CollectionViewSource.GetDefaultView(items);
    }

    public ObservableCollection<Item> Items { get { return items; } }

    public ICommand UpdateCommand {
        get { return new RelayCommand(DoUpdate); }
    }

    public Item SelectedItem { get; set; }

    private void DoUpdate(object obj) {
        var act = new Func<List<Item>>(DoUpdateAsync);
        act.BeginInvoke(CallBack, act);
    }

    private List<Item> DoUpdateAsync() {
        return new List<Item> {
                new Item("hello"),
                new Item("world"),
                new Item("qwerty"),
            };
    }

    private void CallBack(IAsyncResult result) {
        try {
            var act = (Func<List<Item>>)result.AsyncState;
            var list = act.EndInvoke(result);

            window.Dispatcher.Invoke(new Action<List<Item>>(delegate(List<Item> lst) {
                                                                    var current = lst.Single(i => i.Name == ((Item)view.CurrentItem).Name);
                                                                    Items.Clear();
                                                                    lst.ForEach(Items.Add);
                                                                    view.MoveCurrentTo(current);
                                                                }), list);

        } catch(Exception exc){ Debug.WriteLine(exc); }
    }
}

public class Item {
    public Item(string name) {
        Name = name;
    }
    public string Name { get; set; }
}

You will need to do some handling in case the selected item is no longer in the list.
The IsSynchronizedWithCurrentItem property is important here, else it won't work!
Also, the way the reference to the main window is made should be by a DI-framework.

A: As Yacoder pointed out this has to do with object equality. As long as you bind SelectedValue instead of SelectedItem you can define the ItemsSource as an anonymous type collection. Then this problem will not occur (and it is also faster if you need to read the values from a database).


text:
Q: Deploying MongoDB & Express based back-end API to Heroku dosen't work I wrote a small front-end project with Vue.js, and Express was adopted in the back-end. The front-end and back-end were in two different directories respectively. The API works in my local environment but when I deploy my back-end api to Heroku, and tried GET request by Postman, it doesn't work.
In my index.js:
This is the listening port:
const port = process.env.PORT || 5000;
I am using mongoose to connect mLab:
const db = require("./config/keys").mongoURI;
mongoose.connect(db)
And my package.jsonis here:
{
    "name": "backend-api",
    "version": "1.0.0",
    "description": "",
    "main": "server.js",
    "scripts": {
        "start": "node index.js",
        "server": "nodemon index.js"
    },
    "author": "Yeoman_Li",
    "license": "ISC",
    "devDependencies": {
        "body-parser": "^1.18.3",
        "express": "^4.16.4",
        "mongoose": "^5.4.0"
    }
}

My index.js is here:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");

const app = express();

// CORS
app.all("*", (req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
    res.header(
        "Access-Control-Allow-Headers",
        "Content-type, Accept, X-Access-Token, X-Key"
    );
    if ("OPTIONS" == req.method) res.status(200).end();
    else next();
});

const mediaReq = require("./routes/api/mediaReq");

//  DB
const db = require("./config/keys").mongoURI;

// body-parser
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//  connect to DB
mongoose
    .connect(db)
    .then(() => console.log("MonogoDB Connected"))
    .catch(err => console.log(err));

//  router
app.use("/api/mediaReq", mediaReq);

// port
const port = process.env.PORT || 5000;

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

And here is my api router:
const express = require("express");
const router = express.Router();

const mediaController = require("../../controllers/media");

//  test
router.get("/test", (req, res) => {
  res.json({ msg: "test works" });
});

// $route GET api/mediaReq/medias || /medias/:id
router.get("/medias", mediaController.allMedia);
router.get("/medias/:id", mediaController.byId);
router.post("/medias", mediaController.create);
router.delete("/medias/:id", mediaController.remove);

module.exports = router;

I used postman to send a simple GET request and it works:
http://localhost:5000/api/mediaReq/medias
But when I tried to send a GET request to my heroku backend-api, it doesn't work:
https://fast-reaches-23458.herokuapp.com/api/mediaReq/medias


text:
Q: Not able to get Instagram App Approval - Reviewer Http-Request Problems? we are having a problem going through the review process of meta instagram review - our question is: Is there any settings in the reviewers browser or company network that prohibits sending data via XMLHttpRequest in our javascript code on our onboarding website (www.sensai-bot.de/fb-login)?
More detailed:
We have a problem with the instagram review. when the reviewer performs the outlined steps at the bottom (reviewer sticks to the video explanation as expected) we send from our website (www.sensai-bot.de) the newly generated page access token for the linked page to our secured bot server.
This is done with the below outlined code "send_to_bot()".
We are receiving logs for all steps, including the click on the "activate bot" button and of the javascript code entering the function send_to_bot (as visible in the appended screenshot).
However after this there are no further logs, our endpoint doesn't get triggered i.e. we do not receive the page access token from the reviewers page and thus cannot activate our app for the linked page. Therefore we get denied everytime.
This procedure works on multiple of our machines without fail.
steps:

*

*reviewer is directed to our onboarding website frontend

*reviewer clicks on Log In

*a new browser window opens to link their page

*reviewer chooses linked page for review purposes

*reviewer clicks ok and proceed

*reviewer clicks the button "activate bot" (see below screenshot 07:53:36.544 31.199s)

*send_to_bot code gets triggered (see below screenshot 07:53:36.552 31.207s)

*we expect our endpoint to receive the new page access token, however we don't receive a request at our endpoint
consequently the onreadystatechange handler will not be triggered and we don't receive any further logs.

Logging Screenshot
function send_to_bot(page_access_token, user_id, app_id) {
Rollbar.info("send_to_bot start of function");
url = activation_url + "/onboard_page" + "?application_id=" + app_id + "&user_id=" + user_id + "&pat=" + page_access_token;
const Http = new XMLHttpRequest();
Http.open("GET", url);
Http.send();
Rollbar.info("send_to_bot: XMLHTTPRequest sent" + url);
Http.onreadystatechange = (e) => {
  dom_log_status(Http.responseText);
}

};
Below is my video screencast showing everything working perfectly:
https://www.youtube.com/watch?v=nQc6OyEOCbk&t=2s


text:
Q: How to transfer files from external storage device to Nextcloud Snap? I recently set up the Nextcloud Snap package through an Ubuntu Server 22.04 VM, and most things are working. However, I'm having trouble migrating my data over from an external 2TB drive to the server's internal 8TB drive. I tried moving the data from the drive to /var/snap/nextcloud/common/nextcloud/data/constancies/files as root, but the files don't appear in the web interface, and deleting folders here also does nothing. I found a guide online that seemed like it would help with this (https://help.nextcloud.com/t/tutorial-how-to-migrate-mass-data-to-a-new-nextcloud-server/9418), but it says to run the command sudo -u www-data php console.php files:scan --all to force scan the filesystem. However, trying to run this just gives me this error: sudo: php: command not found.
I'm pretty sure this is because the guide uses the Docker installation of Nextcloud, so then, what about the Snap version?
Thanks.

A: If you just move files into the nextcloud dir they won't appear in the Webinterface. You'll also have to index them with the occ files:scan command
https://help.nextcloud.com/t/using-occ-on-snap-nextcloud-installation/107129


text:
Q: qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found I'm getting
 qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.

after a fresh installation of qt creator in Debian 9. Unfortunately, the solutions here tell me to do ldd /usr/lib/qt/plugins/platforms/libqxcb.so but /usr/lib/qt/ doesn't even exist.

A: sudo apt-get install --reinstall libxcb-xinerama0

A: Follow this two steps, it work for me with wireshark
$ sudo -s
# sudo apt-get install libcap2-bin

and reboot for more ...


text:
Q: Implement global listener to pause code execution I have this code which is used to pause execution of Selenium code:
Boolean waitruntil = new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[@class='ngx-loading-text center-center' and starts-with(., 'Loading')]")));
I have every test running into JUnit code. Do you know how I can implement a global listener which pauses code execution if loading bar is shown(detect using Xpath locator)

A: There is a WebDriverEventListener that can accomplish what you want. You could implement this listener such that before each command executed by selenium, the listener checks for the visibilityOfElementLocated(By.xpath("//div[@class='ngx-loading-text center-center' and starts-with(., 'Loading')]")));, and if so execute your WebDriverWait. Without seeing your code I'm not sure exactly how you'd implement this, but here's a resource with some good examples.
http://toolsqa.com/selenium-webdriver/event-listener/

A: One solution which is a bit more complex than using a listener would be to wrap your element with a proxy and perform the check whenever you hit the proxy.
Let the listeners listen to events and not change the test's flow,
First of all we need to create a class that will perform the check whenever you call the element:
public class ElementProxy implements InvocationHandler {

    private final WebElement element;

    public ElementProxy(WebElement element) {
        this.element = element;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        this.waitForPageLoad();
        return method.invoke(element, args);
    }

    private void waitForPageLoad() {
        WebDriver driver = ((WrapsDriver) element).getWrappedDriver();
        WebElement loadingBar = driver.findElement(By.xpath("//div[@class='ngx-loading-text center-center' and starts-with(., 'Loading')]"));
        new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOfElement(loadingBar))
    }

    public static WebElement proxy(WebElement element) {
        ElementProxy proxy = new ElementProxy(element);
        WebElement wrappdElement = (WebElement) Proxy.newProxyInstance(ElementProxy.class.getClassLoader(),
                                                                       new Class[] { WebElement.class },
                                                                       proxy);
        return wrappdElement;
    }

}

Then you can call ElementProxy.proxy(element) which will return a new proxied element, similar to the behavior of PageFactory under the hood.
Last thing is to wrap it under your own PageFactory so you can control the behavior of the elements:
public class MyPageFactory {

    public static <T> void initElements(WebDriver driver, T pageObject) {
        PageFactory.initElements(driver, pageObject);

        for (Field field : pageObject.getClass().getDeclaredFields()) {
            if (field.getType().equals(WebElement.class)) {
                boolean accessible = field.isAccessible();
                field.setAccessible(true);

                field.set(pageobject, ElementProxy.proxy((WebElement) field.get(pageObject)));
                field.setAccessible(accessible);
            }
        }

    }

}

Now if you are in a web-page where the loading-bar is present, use your new MyPageFactory, which will perform the check automatically.
If you do not need to perform the check, use the regular PageFactory.
Reference: https://www.vinsguru.com/selenium-webdriver-how-to-handle-annoying-random-popup-alerts/


text:
Q: Java Bytecode invokeinterface instruction Looking at this Java Bytecode (from the Eclipse ClassFile viewer), I noticed something strange with the invokeinterface instruction: It has a nargs (number of arguments) 'attribute' that occupies 2 bytes:
35  aload_2 [map]
36  ldc <String "a"> [15]
38  invokeinterface java.util.Map.get(java.lang.Object) : java.lang.Object [33] [nargs: 2]
43  checkcast java.lang.String [35]
46  invokevirtual java.io.PrintStream.println(java.lang.Object) : void [47]
49  getstatic java.lang.System.out : java.io.PrintStream [41]

Why does this exist? What is the difference between invokeinterface and invokevirtual? Shouldn't the JVM be able to infer the number of arguments (thus the number of values to pop from the stack) from the given method signature?

A: You're right that the number of arguments can be inferred from the signature. The JVM spec has this to say about that:
"The count operand of the invokeinterface instruction records a measure of the number of argument values, where an argument value of type long or type double contributes two units to the count value and an argument of any other type contributes one unit. This information can also be derived from the descriptor of the selected method. The redundancy is historical."


text:
Q: How to loop through all but the last item of a list? I would like to loop through a list checking each item against the one following it.
Is there a way I can loop through all but the last item using for x in y? I would prefer to do it without using indexes if I can.
Note
freespace answered my actual question, which is why I accepted the answer, but SilentGhost answered the question I should have asked.
Apologies for the confusion.

A: if you meant comparing nth item with n+1 th item in the list you could also do with
>>> for i in range(len(list[:-1])):
...     print list[i]>list[i+1]

note there is no hard coding going on there. This should be ok unless you feel otherwise.

A: the easiest way to compare the sequence item with the following:
for i, j in zip(a, a[1:]):
     # compare i (the current) to j (the following)

A: for x in y[:-1]

If y is a generator, then the above will not work.

A: If you want to get all the elements in the sequence pair wise, use this approach (the pairwise function is from the examples in the itertools module).
from itertools import tee, izip, chain

def pairwise(seq):
    a,b = tee(seq)
    b.next()
    return izip(a,b)

for current_item, next_item in pairwise(y):
    if compare(current_item, next_item):
        # do what you have to do

If you need to compare the last value to some special value, chain that value to the end
for current, next_item in pairwise(chain(y, [None])):

A: To compare each item with the next one in an iterator without instantiating a list:
import itertools
it = (x for x in range(10))
data1, data2 = itertools.tee(it)
data2.next()
for a, b in itertools.izip(data1, data2):
  print a, b

A: This answers what the OP should have asked, i.e. traverse a list comparing consecutive elements (excellent SilentGhost answer), yet generalized for any group (n-gram): 2, 3, ... n:
zip(*(l[start:] for start in range(0, n)))
Examples:
l = range(0, 4)  # [0, 1, 2, 3]

list(zip(*(l[start:] for start in range(0, 2)))) # == [(0, 1), (1, 2), (2, 3)]
list(zip(*(l[start:] for start in range(0, 3)))) # == [(0, 1, 2), (1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 4)))) # == [(0, 1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 5)))) # == []

Explanations:

*

*l[start:] generates a a list/generator starting from index start

**list or *generator: passes all elements to the enclosing function zip as if it was written zip(elem1, elem2, ...)
Note:
AFAIK, this code is as lazy as it can be. Not tested.


text:
Q: Random walk with limited number of steps and 'refuel' nodes Here is a process to which an analogy in a different setting is of interest.
Let $G = (V, E)$ be a graph with $F \subset V$.  Let $G$ represent, for example, a road network, and $F$ are refueling stations. A random walk (random drive) on this network is limited to $k$ steps without refueling. After refueling (visiting a node in $F$), the driver can take another $k$ steps.
Apart from road networks, are there any other analogies for such a process? Maybe for example, in social networks rumor/gossip spreading, disease spreading? It seems like there should be one since "realistic" random walks should not be infinite in practice.
A lot of theoretical properties can be proved about this process and I am looking for any literature that has anything remotely connected.


text:
Q: docker run throws "invalid reference format: repository name must be lowercase" using $(pwd) in volume flag docker run throws an "invalid reference format: repository name must be lowercase" error when using $(pwd) in the volume flag (-v). This is the command that is currently causing the issue:
docker run --rm -v $(pwd)/app/polymer:/home/polymer/app jefferyb/polymer-cli polymer build

A: For my own circumstance, the output of pwd contained a directory with a space (i.e. /something/Problematic Directory/something-else). This was resolved by wrapping $(pwd) in quotation marks to explicitly identify it as a string:
docker run --rm -v "$(pwd)/app/polymer":/home/polymer/app jefferyb/polymer-cli polymer build

The documentation I read didn't use quotation marks, however this might be better practise when using variable interpolation in shell to avoid these kind of issues.


text:
Q: How do I garbage collect a Guix System generation? Running sudo guix gc --list-roots on my Guix System I see a lot of system generations lying around, going all the way back to when I first installed the system.
$ sudo guix gc --list-roots
...
/var/guix/profiles/system-22-link
/var/guix/profiles/system-1-link
/var/guix/profiles/system-10-link
/var/guix/profiles/system-11-link
/var/guix/profiles/system-12-link
/var/guix/profiles/system-13-link
/var/guix/profiles/system-14-link
/var/guix/profiles/system-15-link
...

These are not garbage collected when I run sudo guix gc --delete-generations=30d as I would expect. Why is this and how do I GC the system roots?

A: As I observed guix gc does not not touch any of the system gc-roots. There is a separate command guix system delete-generations for managing these. Running guix system delete-generations 1m followed by guix gc did remove system gc-roots older than one month and clean up the store in /gnu/store of the old state. On my machine this was a neat 34GiB.


text:
Q: Android : Dependant textboxes triggering each others change events leading to endless loop Basically I am trying to implement the Google converter kind of thing here. Two EditText controls, and two dropdowns with units for conversion. The user can enter value in any one of the textbox and the conversion takes place (based on the appropriate units selected for each text box). Basically, there is no fixed, to and from text box. Now what happens is (obviously), the change in either of the textbox, triggers the change in the other text box
i.e. Enter value in Textbox1 --> triggers a conversion and the output is displayed in Textbox2 --> triggering the change event for Textbox2. Now when the calculation for Textbox2 is triggered, I assume no change to take place for the value of Textbox1 and the sequence should stop.... But sadly, for some reason, the sequence does not terminate and the Change events for both textboxes keep getting triggered,until my code crashes due to this endless loop.
Below is what the change event for both EditText controls looks like. (Only the name of the triggering control is different.)

fromValue.addTextChangedListener(new TextWatcher() {
             public void afterTextChanged(Editable s)
             {

             }

             public void beforeTextChanged(CharSequence s, int start, int count, int after) {

             }

             public void onTextChanged(CharSequence s, int start, int before, int count)
             {
                 //we need to trigger the calculation here
                calculate();
             }
         }
        );

When I comment out the Change event of any one EditText control, the conversions take place correctly...So the issue is definitely due to the controls triggering each others change events.
I was able to get this done in Obj C and Html using the respective OnChange events for the controls, but Android doesn't seem to agree with this approach. Any insight/help/support on this would be really helpful.

A: I thinks it's so simple and you are drunk :P
just use a boolean(true value for init) in your activity class and in beginning of onTextChanged just check if the boolean is false just toggle it and exit else set it to false and  change the text.
onTextChanged(...) {
 if(boolean==false)
    return;
 //reset the flag
 boolean=true;
 //do your stuff
 return;
 }


text:
Q: How to copy a database table from one database to another I am looking to perform some database operations programatically inside a Django application, namely, I want to:

*

*Copy Table A in Database A over to Table A (table name preserved) in Database B, then clean-up and remove Table A.

Therefore, I have a number of possible options to try and utilise:

*

*I could try and call "pgdump" from the application, using some sort of system call.

*I could potentially utilise the psycopg package.

*I have a preference to use Django's built in with connection.cursor() as cursor
Assumptions:

*

*"Table A" exists in Database A but "Table A" (both schema and data) does not exist in Database B.

*Database A and Database B exist on different "HOSTs"

What would be the some potential methods to achieve this? I need something like this but to talk between the two databases, source and target...
CREATE TABLE [Table to copy To]
AS [Table to copy From]
WITH NO DATA;

A: 1) you can do it using dblink:
# connect to pg
# psql -U user_here etc...
-- create a few db
create database first;
create database second;

-- connect to first db and create a table with a few records
\c first;

create table users
(
    id serial not null
        constraint users_pk
            primary key,
    name varchar(20) not null
);

INSERT INTO public.users (id, name) VALUES (1, 'first');
INSERT INTO public.users (id, name) VALUES (2, 'sec');
INSERT INTO public.users (id, name) VALUES (3, 'one_more');
INSERT INTO public.users (id, name) VALUES (4, 'etc');

-- connect to second db and copy table with data
\c second;
-- dblink -- executes a query in a remote database
create extension dblink;

-- set your creds...
CREATE TABLE users AS SELECT * FROM dblink('dbname=first user=root password=root', 'select id, name from users') as tbl(id int, name varchar(20));

-- check data:
SELECT * FROM users;

2) you can do it using pg_dump:
# generate dump with data of users table from first db
pg_dump -U root -d first --table=users --inserts > /tmp/users.dump
# run dump script on second db
psql -U root -d second < /tmp/users.dump;

3) you can do it using pandas:
import pandas as pd
from sqlalchemy import create_engine

for df in pd.read_sql(
    'SELECT * FROM users',
    con=create_engine('postgres+psycopg2://root:root@localhost:5432/first', echo=True),
    chunksize=1000
):
    df.to_sql(
        con=create_engine('postgres+psycopg2://root:root@localhost:5432/second', echo=True),
        name='users',
        index=False,
        if_exists='append'
    )


text:
Q: CoffeeScript jQuery plugin and trying to call to external jQuery plugin I have the following (simple) CoffeeScript jQuery Plugin:
$ = jQuery

$.fn.extend
    schoolSelect: (options) ->
        settings =
            apiUrl: '/api/v1'
            debug: false

        settings = $.extend settings, options

        log  = (msg) ->
            console?.log msg if settings.debug

        return @each ->
            @.dropkick
                change: (val, label) ->
                    log val
                    log label

And I call it in another CoffeeScript file like so:
$('.school_select').schoolSelect
        debug: true

But for some reason I keep getting the following error:
Uncaught TypeError: Object #<HTMLSelectElement> has no method 'dropkick'
I am using the DropKickjQuery plugin for my HTML selects: http://jamielottering.github.com/DropKick/
How can I access the DropKick plugin within my CoffeeScript jQuery plugin?

A: This line:
    return @each ->
        @.dropkick

Needs to be
    return @each ->
        $(@).dropkick

In the context of a jQuery callback for each, this gives you back a raw DOM element (hence the warning about HTMLSelectElement), not a jQuery object.
If your plugin is calling another plugin, you need to ensure the setup for the DropKick plugin is done before you extend jQuery.


text:
Q: unity DI error - Make sure that the controller has a parameterless public constructor I have followed the below sample and it works fine until I have replaced the ProductsContext class by my own LDAPConnector class that need to get data from AD and since it's not working and get the Parameterless error.
http://www.asp.net/web-api/overview/advanced/dependency-injection
What I should add in the webAPIConfig.cs in order to register this new class ?
I have try this but it's not working:
container.RegisterType<ILDAPConnector, LDAPConnector>(new HierarchicalLifetimeManager());

I have also tried to add parameterless construction in both Controller and in the LDAPConnector class but still get the same issue.
The controller
    public class ADAccountController : ApiController
{
    IADAccountRepository _repository;

    public ADAccountController() : base()
    {
    }

    public ADAccountController(IADAccountRepository repository)
    {
        _repository = repository;
    }

    public IHttpActionResult GetByID(string id)
    {
        try
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                AccountAD contact = _repository.GetByID(id);

                if (contact == null)
                {
                    return NotFound();
                }
                return Ok(contact);

the Repository where I get the error on the LDAPConnector connector = new LDAPConnector();
public class ADAccountRepository : IADAccountRepository
{
    static ConcurrentDictionary<string, AccountAD> _todos = new ConcurrentDictionary<string, AccountAD>();

    private LDAPConnector connector = new LDAPConnector();

    public ADAccountRepository()
    {
        Add(new AccountAD { Name = "Item1" });
    }

    public AccountAD GetByID(string id)
    {
        return connector.GetAccountDetails(id);

        //AccountAD item;
        //_todos.TryGetValue(id, out item);
        //return item;
    }

The ADConnector
   public class LDAPConnector : ILDAPConnector
{

    public LDAPConnector ()
    {

    }

    public AccountAD GetAccountDetails(string id)
    {
        AccountAD _AccountDetails = new AccountAD();

        List<SearchResult> searchResult = new List<SearchResult>();

finally the webapiconfig
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var container = new UnityContainer();
        container.RegisterType<IADAccountRepository, ADAccountRepository>(new HierarchicalLifetimeManager());
        container.RegisterType<ILDAPConnector, LDAPConnector>(new HierarchicalLifetimeManager());
        //container.RegisterType<LDAPConnector>(new InjectionFactory(c => new LDAPConnector()));
        config.DependencyResolver = new UnityResolver(container);

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
    }
}

error reported:
{"Message":"An error has occurred.","ExceptionMessage":"An error occurred when trying to create a controller of type 'ADAccountController'. Make sure that the controller has a parameterless public constructor.","ExceptionType":"System.InvalidOperationException","StackTrace":"   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Type 'ADConnector.Controllers.ADAccountController' does not have a default constructor","ExceptionType":"System.ArgumentException","StackTrace":"   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"}}

A: Unity tries to pick the constructor with the most arguments, I think in this case the exception is misleading.
Not got IDE to hand, but does this work?
container.RegisterType<ILDAPConnector>(new HierarchicalLifetimeManager(),
    new InjectionFactory(c => new LDAPConnector()));


text:
Q: Font Customization in bot framework web chat v4 I am using web chat v4, I have created one dropdown there user can select font size/font weight for her/his convenience. I can't achieve two things.

*

*Can't change font size/font weight/font family for adaptive card/hero card/other attachments

*Can't change font family
I am currently using jquery to perform button click change  using id "webchat".Code is below. Similarly for font-weight, Help me achieve the two thing I mentioned.
function font_size() {
    var e = document.getElementById("sizeselect");
    var value = e.options[e.selectedIndex].value;
    document.getElementById("webchat").style.fontSize = value;
}

A: To make changes to Adaptive Cards, you will actually need to edit and provide your own Host Config with your styling adjustments. You can take a look at the Host Config editor on AdaptiveCards.io to see the kinds of changes you are able to make.
Web Chat has its own adaptiveCardHostConfig in use. You can use this page as an example on how to implement your own host config and use it in your version of Web Chat when you build your Composer.


text:
Q: Fedora 34: Pasting multiple commands into a bash terminal behavior change I use Mediawiki to store all the commands I need to do to rebuild my system from scratch when a Fedora upgrade is available.
Until now, I would simply copy/paste a huge set of commands into a terminal window and let it run free.
I am trying to upgrade my Fedora 32 to 34 and this no longer works.  When anything in my script enters a CLI - like mysql or even a new bash shell, execution stops until I type 'exit'.  Then, the SQL commands or whatever are executed in bash and makes an ugly display.
Here is the most simplified example of this that I could create.  This works fine in Fedora 32 but gets stuck in Fedora 34:
echo 'AAA'
echo 'AAA'
echo 'AAA'
bash
echo 'BBB'
echo 'BBB'
echo 'BBB'

I am guessing something changed within Fedora, I just do not know what.  I have searched and can't seem to find an answer.
My question is - what do I need to change so that I can get the old (F32) behavior back?

A: I can confirm this in Fedora 34 / GNU bash, version 5.1.0(1)-release (x86_64-redhat-linux-gnu.
This is a new feature in the underlying readline library and the feature is enabled by default. Currently, the only way to turn it off is to edit your ~/.inputrc and add the line:
set enable-bracketed-paste off

Then, after logging out and in again, you should have the old behavior.