text:
Q: as3 RollOver movieclip menu I'm trying to do a bottom menu like in www.zara.com.
My code have a transparent movieclip that shows the menu when mouse rolls over it, and hide when mouse rolls out.
The menu appears over that transparent movieclip, so I can use the roll over and out actions to maipulate the menu with the transparent MC.
The problem here is when mouse Roll Over my menu MC and it behaves as rolling out the transparent movieclip.
How can I make mouse rolls over a movieclip over another movieclip without roll out the first one?
Is it to confuse?
Thanx!

A: When a MovieClip B appears on top of another MovieClip A, MovieClip A will fire the MouseEvent.ROLL_OUT event. This is because MovieClip B is preventing MovieClip A from receiving any MouseEvents (since it is on top).
If you do not need to receive any MouseEvents from MovieClip B, you can set its mouseEnabled property to false, then MovieClip A underneath it will receive MouseEvents.
Also, depending on whether it makes sense in your particular case or not, you can make MovieClip B a child of MovieClip A, so that when MovieClip B obscures MovieClip A, the ROLL_OUT event will not be fired.
I hope this helps answer your question.

A: Here is a quick and dirty trick originaly from javascript technique
1.) build extra logic into the clipA rollout which waits a small period of time and then checks if the mouse is on the menu or not before closing it.
// define a boolean value for the moust beeing on the menu
public var menuOver:Boolean = false;

public function onMenuOver( event:MouseEvent ):void
{
    menuOver = true;
    // other menu code here
}

public function onMenuOut( event:MouseEvent ):void
{
    menuOver = false;
    // other menu code here
}

public function onMainClipOver( event:MouseEvent ):void
{
     // show menu code here
}

public function onMainClipOut( event:MouseEvent ):void
{
    setTimeout(execMainClipOut,100);
}

/**
 * close the menu only if the mouse is not over the menu
 */
public function execMainClipOut()
{
    if(!menuOver){
        // close the menu
    }
}

A: Ooh! I just remembered something interesting that might solve your problem.
When a MouseEvent.ROLL_OUT event is fired, the listener function is called with a MouseEvent object that has the relatedObject property. This is a reference to the object that is gaining mouse focus (getting rolled over) -- in your case, you could ignore the event if this property is set to your other MovieClip object, then fire the event manually when your other MovieClip object rolls out (so that it rolls out both of them).

A: as mentioned above, relatedObject works PERFECTLY
so for example if you have MovieClip A and then have Movieclip B on top.
You want Movieclip B to show on rolling over MovieClip A and hiding when rolling out of Movieclip A,
what generally happens is that Movieclip B will show but then when you hover over B, Moveclip B will dissappear, as B lies on top of A, rollout event takes place
so on Movieclip A rollout even just use
if((event.relatedObject == MoveClipB)
{
//if its rolling over B, which is a related object, dont do anything
}
else
{
//Hide B
}
Events for B still work when this is used


text:
Q: Good solution for virtualized chat view in Vue.js I currently have to develop a new chat interface for our web app. I tried using vue-virtual-scroller to virtualize the list of messages and attachments but I have some issues regarding updating the list and scrolling to the bottom.
Did anyone ever had to do the same via this package and had success with scrolling programmatically while also adding new items at the end of the list?
Hope someone can help me with this! Would like to push something to production today! :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I extract data using xpath and the rvest function html_nodes()? I'm web-scraping using the R package rvest. I don't get an error, but instead, my code captures an empty character in the environment.
My code:
amore_tomato_page <- "https://thrivemarket.com/p/amore-tomato-paste"
amore_tomato <- read_html(amore_tomato_page)
amore_tomato_body <- amore_tomato %>%
  html_node("body") %>%
  html_children()

allergens <- amore_tomato %>%
  html_nodes(xpath = '/html/body/div[1]/div[2]/div[4]/div[6]/div/div[1]/section/div/div/div/div/div[2]/div[2]/p[2]') %>%
  html_attr()

ingredients <- amore_tomato %>%
  html_nodes(xpath = '/html/body/div[1]/div[2]/div[4]/div[6]/div/div[1]/section/div/div/div/div/div[2]/div[1]/p') %>%
  html_attr()

I'm trying to extract allergen information and ingredients for the product (and hundreds of products).
Thank you in advance for your help troubleshooting this!
Best,
~Mayra

A: That data is loaded dynamically from a script tag containing a JSON string. You can extract that and deserialize into a JSON object with jsonlite and parse out the info of interest:
library(tidyverse)
library(rvest)
library(jsonlite)

amore_tomato_page <- "https://thrivemarket.com/p/amore-tomato-paste"
amore_tomato <- read_html(amore_tomato_page)
data <- amore_tomato %>% html_element('#__NEXT_DATA__') %>% html_text() %>% jsonlite::parse_json(simplifyVector = T)
allergy_info <- filter(data$props$pageProps$product$nutrition_info, friendly_label == 'Warning / Allergen Information')$value
ingredients <- data$props$pageProps$product$ingredients


text:
Q: Autodesk Forge File Conversion how to download files in manifest? Following the Model Derivative "Prepare a File for the Viewer" after I have successfully uploaded and converted file I call the manifest url
how do I then download the converted files in the manifest. If I only know the refrence urn?
(i.e.) How would I get the coverted svf          "urn:adsk.viewing:fs.file:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6bW9kZWxkZXJpdmF0aXZlL0E1LnppcA/output/1/A5.svf"
or the thumbnail
"urn:adsk.viewing:fs.file:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6bW9kZWxkZXJpdmF0aXZlL0E1LnppcA/output/1/A5.svf.png01_thumb_200x200.png"
Is there a api call that can be used to return the actual location?
Edit: The end result is I want to create something like the [extractor] (http://extract.autodesk.io/) does. With all the files I need to run the viewer locally
Edit2:The Manifest I get back from call after fileUploda
Result{
  "type": "manifest",
  "hasThumbnail": "true",
  "status": "success",
  "progress": "complete",
  "region": "US",
  "urn": "dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6Z3JlZ2JpbWJ1Y2tldC9yYWNfYmFzaWNfc2FtcGxlX3Byb2plY3RfdGVzdC5ydnQ",
  "derivatives": [
    {
      "name": "rac_basic_sample_project_test.rvt",
      "hasThumbnail": "true",
      "status": "success",
      "progress": "complete",
      "outputType": "svf",
      "children": [
        {
          "name": "{3D}",
          "hasThumbnail": "true",
          "role": "3d",
          "status": "success",
          "type": "geometry",
          "progress": "complete",
          "children": [
            {
              "name": "{3D}",
              "role": "3d",
              "camera": [
             ...
              ],
              "status": "success",
              "type": "view",
              "progress": "complete"
            },
            {
              "type": "resource",
              "urn": "urn:adsk.viewing:fs.file:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6Z3JlZ2JpbWJ1Y2tldC9yYWNfYmFzaWNfc2FtcGxlX3Byb2plY3RfdGVzdC5ydnQ/output/Resource/3D_View/_3D_/_3D_.svf",
              "role": "graphics",
              "mime": "application/autodesk-svf"
            },
            {
              "type": "resource",
              "role": "thumbnail",
              "urn": "urn:adsk.viewing:fs.file:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6Z3JlZ2JpbWJ1Y2tldC9yYWNfYmFzaWNfc2FtcGxlX3Byb2plY3RfdGVzdC5ydnQ/output/Resource/3D_View/_3D_/_3D_1.png",
              "resolution": [
                100,
                100
              ],
              "mime": "image/png",
              "status": "success"
            },

The Request I try to send but get a 404
https://developer.api.autodesk.com/modelderivative/v2/designdata/dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6Z3JlZ2JpbWJ1Y2tldC9yYWNfYmFzaWNfc2FtcGxlX3Byb2plY3RfdGVzdC5ydnQ/manifest/urn:adsk.viewing:fs.file:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6Z3JlZ2JpbWJ1Y2tldC9yYWNfYmFzaWNfc2FtcGxlX3Byb2plY3RfdGVzdC5ydnQ/output/Resource/3D_View/_3D_/_3D_1.png

Is there anything wrong with that call to modelderivative?

A: Cyrille Fauvel implemented this, so it is in his GitHub repo:
https://github.com/cyrillef/extract.autodesk.io
https://github.com/cyrillef/extract-php-view.and.data.api

A: You can also take a look at the implementation of the NPM View & Data Package for the time being. It is still using the v1 API endpoints but we are currently working on providing wrappers for multiple programming languages on the v2 endpoints

A: Using the derivativeurn GET worked
I also had to make sure the derivativeUrn was encoded
(JAVA)     derivativeUrn = URLEncoder.encode(derivativeUrn, "UTF-8");


text:
Q: animated border not connecting at corner I had this working the other day, but I've rewritten the code a few times to get all my animations working and styles displaying, and now for some reason, these animated borders aren't connecting at three of the corners. Can someone please tell me what has gotten lost in translation?

.desktopNav {
  list-style: none;
  position: fixed;
  display: block;
  top: 60px;
  margin: 0 auto;
}

.desktopNav li {
  display: inline;
  position: relative;
  margin: 0 1.7em;
}

.desktopNav a {
  text-decoration: none;
  color: #222323;
  font-family: 'Raleway';
  font-size: 2em;
  font-weight: 200;
  padding: 10px 15px;
  position: relative;
}

.hoverbox::before,
.hoverbox::after {
  content: '';
  position: absolute;
  transition: transform .5s ease;
}

.hoverbox::before,
.hoverbox::after {
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  border-style: solid;
  border-color: #f7941e;
}

.hoverbox::before {
  border-width: 2px 0 2px 0;
  transform: scaleX(0);
}

.hoverbox::after {
  border-width: 0 2px 0 2px;
  transform: scaleY(0);
}

.hoverbox:hover::before,
.hoverbox:hover::after {
  transform: scale(1, 1);
}

home

about

services

work

process

contact

A: use box-sizing.
.hoverbox::before,
    .hoverbox::after {
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      border-style: solid;
      border-color: #f7941e;
      box-sizing: border-box;
    }

.desktopNav {
  list-style: none;
  position: fixed;
  display: block;
  top: 60px;
  margin: 0 auto;
}

.desktopNav li {
  display: inline;
  position: relative;
  margin: 0 1.7em;
}

.desktopNav a {
  text-decoration: none;
  color: #222323;
  font-family: 'Raleway';
  font-size: 2em;
  font-weight: 200;
  padding: 10px 15px;
  position: relative;
}

.hoverbox::before,
.hoverbox::after {
  content: '';
  position: absolute;
  transition: transform .5s ease;
}

.hoverbox::before,
.hoverbox::after {
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  border-style: solid;
  border-color: #f7941e;
  box-sizing: border-box;
}

.hoverbox::before {
  border-width: 2px 0 2px 0;
  transform: scaleX(0);
}

.hoverbox::after {
  border-width: 0 2px 0 2px;
  transform: scaleY(0);
}

.hoverbox:hover::before,
.hoverbox:hover::after {
  transform: scale(1, 1);
}

home

about

services

work

process

contact

A: Here's one way to fix it:
A working fiddle:  http://jsfiddle.net/gratiafide/p4cv3cez/
.hoverbox::before, .hoverbox::after {
    content:'';
    position: absolute;
    transition: transform .5s ease;
}
.hoverbox::before, .hoverbox::after {
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    border-style: solid;
    border-color: #f7941e;
}
.hoverbox::before {
    border-width: 0 0 0 0;
    transform: scaleX(0);
}
.hoverbox::after {
    border-width: 2px 2px 2px 2px;
    transform: scaleY(0);
}
.hoverbox:hover::before, .hoverbox:hover::after {
    transform: scale(1, 1);
}


text:
Q: How do I reshape this data frame with R? I'm new to R and needed some help with reshaping a data frame that is similar to the one below:

company_name
year
profit_usd
profit_eur
profit_gbp

A
2017
1237
1006
871

B
2017
1337
1096
949

A
2018
1143
937
811

B
2018
1288
1056
914

I want to reshape this table such that I have only one column which shows profit and another column which shows the currency name. Something like this:

company_name
year
currency
profit

A
2017
usd
1237

A
2017
eur
1006

A
2017
gbp
871

B
2017
usd
1337

B
2017
eur
1096

B
2017
gbp
949

A
2018
usd
1143

A
2018
eur
937

A
2018
gbp
811

B
2018
usd
1288

B
2018
eur
1056

B
2018
gbp
914

Any help with this would be greatly appreciated, thank you!

A: Assuming your data is stored in an object df:
library(tidyverse)

df %>%
  pivot_longer(cols      = starts_with("profit"),
               names_sep = "_",
               names_to  = c("delete", "currency"),
               values_to = "profit") %>%
  select(-delete)

A: In addition to the answer of deschen.
library(tidyr)

#long format
df <- pivot_longer(df, cols = c("profit_usd", "profit_eur", "profit_gbp"), names_to = "currency", values_to = "profit")

#removes profit_ from your currency column
df$currency <- gsub("profit_", "", df$currency)

I have a personal preference not to use pipe functions. Especially when starting out, the use of pipe functions can create long lines of code which are harder to debug in comparison with multiple lines. Advantage of pipe functions is shorter code ofcourse.


text:
Q: Inline-block not working with images inside li I've images in each li tag. I am trying to show only one image at the start. So I am trying to hide the remaining by giving overflow: hidden to the parent.
But the inline-block is not working for li element.
HTML

CSS
body {
  background: #3bc;
}
.container {
  overflow: hidden;
}
.carousel {
  width: 300px;
  overflow: hidden;
}
ul li {
  display: inline-block;
  float: left;
  vertical-align: top;
  white-space: normal;
}

Codepen

A: You cannot have inline-block as well as float: left. The display is right. All you need to do is, add white-space: nowrap and get rid of the float:

body {
  background: #3bc;
}
.container {
  overflow: hidden;
}
.carousel {
  width: 300px;
  overflow: hidden;
  white-space: nowrap;     /* Add this and remove float. */
}
ul li {
  display: inline-block;
  vertical-align: top;
  white-space: normal;
}

I am not using Flexbox for the reason of lack of support and new technology.

A: The float:left takes the li elements out of the document flow. In the code below I removed the float and am using a flexbox instead.

body {
  background: #3bc;
}

.container {
  overflow: hidden;
}

.carousel {
  width: 300px;
  overflow: hidden;
}

ul {
  display: flex;
  list-style: none;
}


text:
Q: How to handle dropdownbox for listview flutter I have a listView with dropdownbox attached each item. They are being populated with items. I have two issues now. First when I select from each item, the selected value does not appear on the checkbox. Also, I need to handle them independently such that they could be selected individually. What happens now is that on launch of the app, there is no value at default till I select. Also, when I select it sets all others on the list.
Here's my code guys.
                                      ListView.builder(
                          physics: NeverScrollableScrollPhysics(),
                          itemCount: mainBloc.orders.length,
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                              decoration: BoxDecoration(
                                  border: Border.all(
                                      color: HexColor("#240C44"),
                                      width: 0.5),
                                  color: HexColor("#180332"),
                                  borderRadius:
                                  BorderRadius.all(Radius.circular(4))),
                              margin: EdgeInsets.only(
                                  top: 10, bottom: 10, left: 0, right: 0),
                              child: ListTile(
                                title: Row(
                                  children: <Widget>[
                                    new Image.asset(
                                      "assets/images/order_list_image.png",
                                      width: 40,
                                      height: 40,
                                    ),
                                    Spacer(),
                                    Container(
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(15.0),
                                        color: mainBloc.orders[index].status=="enroute"?
                                        HexColor("#FF9F1C"):
                                        mainBloc.orders[index].status=="delivered"?
                                        HexColor("#71F79F"):
                                        Colors.white.withOpacity(0.6),
                                        border: Border.all(
                                            color: HexColor("#FF9F1C"),
                                            style: BorderStyle.solid,
                                            width: 0.80),
                                      ),
                                      child: new DropdownButton<String>(
                                        items: <String>['Delivered', 'Enroute', 'Processed'
                                        ].map((String value) {
                                          return new DropdownMenuItem<String>(
                                            value: value,
                                            child: new Text(
                                              value,
                                              style: TextStyle(
                                                color: primaryColor,
                                                fontSize: 14,
                                                fontFamily: 'CircularStd',
                                                fontWeight: FontWeight.w500,
                                              ),
                                            ),
                                          );
                                        }).toList(),
                                        onChanged: (_) {

                                        },
                                      ),
                                    ),
                                    SizedBox(
                                      width: 20,
                                    ),
                                    IconButton(
                                      icon: Image.asset(
                                        "assets/images/edit.png",
                                        width: 15,
                                        height: 15,
                                        color: Colors.white,
                                      ), onPressed: () {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(builder: (context) =>
                                           EditOrderPage(index:index)),
                                      );
                                    },
                                    ),
                                  ],
                                ),
                              ),
                            );
                          }),

A: To manage the state of each of your dropdownbutton you need to wrap your list item inside a StatefulWidget.
Here is my implementation of your example :
Code Sample
class ListItem extends StatefulWidget {
  final String label;
  final String defaultStatus;

  ListItem({this.label, this.defaultStatus = 'Enroute'});

  @override
  createState() => _ListItemState();
}

class _ListItemState extends State<ListItem> {
  String _status;

  @override
  void initState() {
    super.initState();
    _status = widget.defaultStatus;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15.0),
        color: _status == null || _status.toLowerCase() == 'processed'
            ? Colors.white.withOpacity(0.6)
            : _status.toLowerCase() == "enroute"
                ? Color(0xFFFF9F1C)
                : Color(0xFF71F79F),
        border: Border.all(
            color: Color(0xFFFF9F1C), style: BorderStyle.solid, width: 0.80),
      ),
      child: Row(children: <Widget>[
        if (widget.label != null && widget.label.isNotEmpty)
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 16),
          child: Text(widget.label),
        ),
        DropdownButton<String>(
          value: _status,
          items:
              <String>['Delivered', 'Enroute', 'Processed'].map((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Text(
                value,
                style: TextStyle(
                  color: Theme.of(context).primaryColor,
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                ),
              ),
            );
          }).toList(),
          onChanged: (val) => setState(() => _status = val),
        ),
      ]),
    );
  }
}

Try it on DartPad
Screenshot


text:
Q: Drawer on right side of screen? I'm new to Android development and wanted to know something. I'm using the navigation drawer for my application, but its on the left side. I want to know if there's a way to get it on the right side and how.
activity_home.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<!-- The main content view -->

<FrameLayout
    android:id="@+id/content_frame"

    android:layout_width="match_parent"
    android:layout_height="match_parent" />
<!-- The navigation drawer -->

<ListView

    android:id="@+id/drawer_list"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="#111"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp" />

drawer_list_item.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"

android:textColor="#fff"
android:background="?android:attr/activatedBackgroundIndicator"
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>

fragment_layout.xml
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<WebView
    android:id="@+id/webView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

My Home.java
package com.colourity.snatsh;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class Home extends Activity {

// Within which the entire activity is enclosed
private DrawerLayout mDrawerLayout;

// ListView represents Navigation Drawer
private ListView mDrawerList;

// Title of the action bar
private String mTitle = "";

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    mTitle = "JAVATECHIG.COM";
    getActionBar().setTitle(mTitle);

    // Getting reference to the DrawerLayout
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    mDrawerList = (ListView) findViewById(R.id.drawer_list);

    // Creating an ArrayAdapter to add items to the listview mDrawerList
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(),
            R.layout.drawer_list_item, getResources().getStringArray(R.array.menus));

    // Setting the adapter on mDrawerList
    mDrawerList.setAdapter(adapter);

    // Enabling Home button
    getActionBar().setHomeButtonEnabled(true);

    // Enabling Up navigation
    getActionBar().setDisplayHomeAsUpEnabled(true);

    // Setting item click listener for the listview mDrawerList
    mDrawerList.setOnItemClickListener(new OnItemClickListener() {

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

            // Getting an array of rivers
            String[] menuItems = getResources().getStringArray(R.array.menus);

            // Currently selected river
            mTitle = menuItems[position];

            // Creating a fragment object
            WebViewFragment rFragment = new WebViewFragment();

            // Passing selected item information to fragment
            Bundle data = new Bundle();
            data.putInt("position", position);
            data.putString("url", getUrl(position));
            rFragment.setArguments(data);

            // Getting reference to the FragmentManager
            FragmentManager fragmentManager = getFragmentManager();

            // Creating a fragment transaction
            FragmentTransaction ft = fragmentManager.beginTransaction();

            // Adding a fragment to the fragment transaction
            ft.replace(R.id.content_frame, rFragment);

            // Committing the transaction
            ft.commit();

            // Closing the drawer
            mDrawerLayout.closeDrawer(mDrawerList);

        }
    });
}

protected String getUrl(int position) {
    switch (position) {
    case 0:
        return "http://javatechig.com";
    case 1:
        return "http://javatechig.com/category/android/";
    case 2:
        return "http://javatechig.com/category/blackberry/";
    case 3:
        return "http://javatechig.com/category/j2me/";
    case 4:
        return "http://javatechig.com/category/sencha-touch/";
    case 5:
        return "http://javatechig.com/category/phonegap/";
    case 6:
        return "http://javatechig.com/category/java/";
    default:
        return "http://javatechig.com";
    }
}

/** Called whenever we call invalidateOptionsMenu() */

public boolean onPrepareOptionsMenu(Menu menu) {
    // If the drawer is open, hide action items related to the content view
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);

    menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.home, menu);
    return true;
}
}

A: Well as the documentation states:
http://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html

Drawer positioning and layout is controlled using the android:layout_gravity attribute on child views corresponding to which side of the view you want the drawer to emerge from: left or right. (Or start/end on platform versions that support layout direction.)

So yes you can put it no the right side as well using the android:layout_gravity property : )


text:
Q: C++ Variadic template - Unable to figure out the compilation error Given below is the code(CPP part of it) that I am trying to compile
template<typename... T>
void SelectOperation::fetchNextRow(tuple<T...>& row) const
{
    fetchColumn<0, decltype(row), T...>(row, nullptr);
}

template<int index, typename T, typename U>
void SelectOperation::fetchColumn(T& row) const
{
    cout << typeid(row).name();
    std::get<index>(row) = this->get<U>(index + 1);
}

template<int index, typename T, typename U, typename... V>
void SelectOperation::fetchColumn(T& row, void*) const
{
    fetchColumn<index, T, U>(row);
    fetchColumn<index + 1, T, V...>(row, nullptr); //Error at this statement
}

The errors I am getting are as follows:
D:\workspaces\Calzone_Mayank\modules\Figgy\include\common/db/core/SelectOperation.h(149):
error C2783: 'void figgy::SelectOperation::fetchColumn(T &,void *) const': could not deduce
template argument for 'U'
D:\workspaces\Calzone_Mayank\modules\Figgy\include\common/db/core/SelectOperation.h(58):
note: see declaration of 'figgy::SelectOperation::fetchColumn'
D:\workspaces\Calzone_Mayank\modules\Figgy\include\common/db/core/SelectOperation.h(149):
error C2780: 'void figgy::SelectOperation::fetchColumn(T &) const': expects 1 arguments
- 2 provided

I am unable to understand why argument for 'U' couldn't be deduced. Why is the compiler unable to determine which overloaded function it should look for?
Edit
The fetchNextRow is called as shown below:
template<typename... T>
void SelectOperation::fetchAllRows(vector<tuple<T...>>& rows) const
{
    while (next())
    {
        tuple<T...> row;
        fetchNextRow<T...>(row);
        rows.push_back(row);
    }
}

AND
vector<tuple<string, string, int>> rows;
SelectOperation o("users", {"name", "employee_id", "age"});
o.fetchAllRows<string, string, int>(rows);

A: Consider this:
template<int index, typename T, typename U, typename... V>
void SelectOperation::fetchColumn(T& row, void*) const {
    fetchColumn<index, T, U>(row);
    fetchColumn<index + 1, T, V...>(row, nullptr); //Error at this statement
}

When V... is an empty parameters pack, it won't work.
You invoked fetchColumn with two parameters (row and nullptr), so the mentioned function is called recursively.
Each time you consume a type from your parameters pack (that is U).
Sooner or later, V... will be an empty parameters pack, so you won't have any U and the compiler is saying that it is neither able to find it nor to deduce it.
You should rather provide two functions, the recursive case and the final one.
As an example:
template<int index, typename T, typename U, typename... V>
void SelectOperation::fetchColumn(T& row, void*) const {
    fetchColumn<index, T, U>(row);
    fetchColumn<index + 1, T, V...>(row, nullptr); //Error at this statement
}

template<int index, typename T>
void SelectOperation::fetchColumn(T& row, void*) const {
    // Do whatever you want with your last type...
}

A: Ok, I'll try to give you a scheme, how you should declare variadic templates.
Except the case of a forwarder, when you can simply define just one variadic-template version, which will redirect to another variadic-template function, you will always have two versions, let's call them closed and open.
The open version is a version with variadic template. This shall do some "continuation" on next arguments. The closed version has a fixed number of arguments. The most important thing is that these versions be distinguishable by the compiler basing on the rules of function overloading resolution (similar it's with the class templates and partial specialization, you'll figure it out easily once you get the scheme for the functions). Another important thing of course is that the open version must contain at least one fixed argument because this is the only way how to split the argument pack into an argument and the "rest".
In general, you have two possibilities:

*

*Closed version operates with argument, Open version does iteration. Example:

template <class T>
size_t Size(T arg) { return 1; }

template <class T1, class T2, class... Args>
size_t Size(T1 t1, T2 t2, Args... args) { return Size(t1) + Size(t2, args...); }

In this case the version are distinguished by the compiler because the closed version uses one argument and the open version uses two at least arguments. The open version cannot use just T1 and Args because this way it could be called with exactly one argument (Args... is potentially unlimited number of arguments including empty list).

*Closed version does nothing (just terminates the iteration), Open version does the job and the iteration. Example:

size_t Size() { return 0; }

template <class T1, class... Args>
size_t Size(T1 t1, Args... args)
{ return 1 + Size(args...); }

In this case the call: Size(args...) will potentially resolve into either this function itself, with the difference that it will skip the first argument, or into Size(), if the args... list at some iteration happens to be already empty.
I have a feeling that in your code you haven't exactly decided, which scheme you want to follow, and which of the versions is going to make an operation on the data, and which should continue iteration. The exact problem in your code is that this call:

fetchColumn<index + 1, T, V...>(row, nullptr);
May need to sometimes resolve into such a declaration (because V... resolves to nothing and the effective list of template arguments is index+1, T):

template<int index, typename T>
void SelectOperation::fetchColumn(T& row, void*) const
and you haven't declared it.


text:
Q: How to sort Python's PrettyTable integer column correctly We have a problem sorting a Population column. The issue is that
PrettyTable reads all data from a CSV file as strings and sorts the integer values as strings. How to fix this?
#!/usr/bin/python3

from prettytable import from_csv

with open("data.csv", "r") as fp:

    x = from_csv(fp)

x.sortby = "Population"
print(x)

data.csv
"City name", "Area", "Population", "Annual Rainfall"
"Adelaide", 1295,1158259, 600.5
"Brisbane", 5905,1857594, 1146.4
"Darwin", 11200000,120900, 1714.7
"Hobart", 1357,205556, 619.5
"Sydney", 2058,4336374, 1214.8
"Melbourne", 1566,3806092, 646.9
"Perth", 5386,1554769, 869.4

A: You can do it with sort_key argument where custom key function is passed to:
#!/usr/bin/python3

from prettytable import from_csv

with open("data.csv", "r") as fp:
    x = from_csv(fp)

print(x.get_string(sortby='Population', sort_key=lambda row: int(row[0])))

Output:
+-----------+----------+------------+-----------------+
| City name |   Area   | Population | Annual Rainfall |
+-----------+----------+------------+-----------------+
|   Darwin  | 11200000 |   120900   |      1714.7     |
|   Hobart  |   1357   |   205556   |      619.5      |
|  Adelaide |   1295   |  1158259   |      600.5      |
|   Perth   |   5386   |  1554769   |      869.4      |
|  Brisbane |   5905   |  1857594   |      1146.4     |
| Melbourne |   1566   |  3806092   |      646.9      |
|   Sydney  |   2058   |  4336374   |      1214.8     |
+-----------+----------+------------+-----------------+


text:
Q: Get OAuth2 authorize code with no user interaction but by passing username and password through parameters I am new to azure and trying to retrieve authorization code after hitting the below API without UI interaction.

I don't want to interact with the Microsoft sign-in page. Is there any way to resolve this issue?

A: Authorization code can be retrieved using OAuth 2.0 authorization code grant flow which require User Interaction .
This flow is mainly used for single page applications, web applications and native application where user interaction is required to get the access token.
The authorization code is a temporary code that the client will exchange for an access token and can be generated in the the address bar along with reply URL after user's sign in.
Refer https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
If you looking to get access token for the service application where no user interaction is required, then client-credential flow can be used to get the access token which can be used further to call Microsoft Graph API or any customized product API.


text:
Q: Ubuntu 13.04 on Gateway NV57H44u turns monitor idle even when told not to The screen is shutting off when power settings are NOT set to make it turn off.
I am running Ubuntu 13.04 on an Gateway NV57H44u. For some reason my screen keeps going to sleep (going blank) after 10 minutes of being idle, but I have the screen saver turned off and I have the power settings set to NEVER turn off or dim the monitor.
I also checked to make sure that there wasn't a setting in the BIOS that could be doing this and there are no power saving settings in my BIOS.
Thankz.

A: Could you please share both screenshots for "Brightness & Lock" and "Power" from the System Configuration options.
Also, did you look into the /var/log/syslog to check if there is anything that could lead you to the root cause of your screen being powered off ?
Two more things:
Is there any script running on the crontab that could turn off the screen ?
Is there any application that could turn off the screen?
Regards.


text:
Q: how multi images appear in the Picture box with the file name in the datagridview I want to appear multi or a single image in the picturebox with the file name in the datagridview when clicked on datagridview.
for information I use visual studio 2010
Imports System.Data.OleDb

Public Class Form1
  Dim Path As String = "C:\Users\Administrator\Desktop\DBF"
    Dim Pathimage As String = "C:\Users\Administrator\Desktop\CATALOG"
    Dim cn = "provider=Microsoft.Jet.OLEDB.4.0; data source=" & Path & "; Extended Properties=dBase IV"
    Private Sub PopulateDataGridView()
        Try
            Dim dt = New DataTable()
            Dim query = "select ITM,ITC,QOH,PRS,FILENAME1,FILENAME2,FILENAME3,FILENAME4 FROM ITEM"

            Using adapter As New OleDbDataAdapter(query, cn.ToString)
                adapter.Fill(dt)
            End Using

            Me.DataGridView1.DataSource = dt
        Catch myerror As OleDbException
            MessageBox.Show("Error: " & myerror.Message)
        Finally
        End Try
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        PopulateDataGridView()
    End Sub
End Class

A: Add a FlowLayoutPanel to your form, and paste this handler for DataGridView1 SelectionChanged
Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView1.SelectionChanged
    Dim row = DirectCast(DataGridView1.CurrentRow.DataBoundItem, DataRowView)
    Dim pbAdder =
        Sub(name As String)
            If row(name) IsNot Nothing AndAlso Not String.IsNullOrEmpty(row(name).ToString()) Then
                FlowLayoutPanel1.Controls.Add(New PictureBox With {.Name = name, .ImageLocation = row(name).ToString()})
            End If
        End Sub
    FlowLayoutPanel1.Controls.Clear()
    pbAdder("FILENAME1")
    pbAdder("FILENAME2")
    pbAdder("FILENAME3")
    pbAdder("FILENAME4")
End Sub


text:
Q: MySQL query not working when added date comparison The query works fine if the date the last condition from the WHERE clause is removed (settlement_Date)
I have also tried LIKE operator, BETWEEN Condition but none of them prosuced the result
The SETTLEMENT_DATE Column is of datetime type with format 'yyyy-mm-dd hh:mm:ss'
I have also tried
SETTLEMENT_DATE BETWEEN "2010-04-01 00:00:00" AND "2010-04-01 23:59:59"

And I want the query to shows the results of a particular date
SELECT date_format(SETTLEMENT_DATE,"%H:%i") AS "TIME",
SUM(CASE WHEN CORPORATE_ID=1328727040 THEN 1 ELSE 0 END ) AS "TOTAL",
SUM(CASE WHEN CORPORATE_ID=1328727040 AND ( QUOTA_CODE=0 OR QUOTA_CODE =1) THEN 1 ELSE 0 END) AS "Non-Tatkal",
SUM(CASE WHEN CORPORATE_ID=1328727040 AND QUOTA_CODE=2 THEN 1 ELSE 0 END) AS "Tatkal"
FROM ticket
WHERE PNR_NUMBER!="0"
AND CURRENT_RES_STATUS NOT IN (9,10,11,16)
AND date(SETTLEMENT_DATE) = str_to_date('01-04-2014', '%Y-%m-%d')
GROUP BY date_format(SETTLEMENT_DATE,"%H:%i")

Any Help is appreciated

A: The issue is here:
str_to_date('01-04-2014', '%Y-%m-%d')

when you run it like:
SELECT STR_TO_DATE('01-04-2014', '%Y-%m-%d');

It gives:
'2001-04-20'

But your dates are in the range: "2010-04-01 00:00:00" AND "2010-04-01 23:59:59"

A: applying a date() function to your column can not utilize a possible index.  I have typically found the following type of condition works well with dates...
SETTLEMENT_DATE >= '2010-04-01'
AND SETTLEMENT_DATE < '2010-04-02'

This way, you leave the date-based field alone, and the >= starting date is obvious, but the second being LESS than the following day at midnight is the same as your 2010-04-01 at 11:59:59pm but does not include 2010-04-02.


text:
Q: Why is my project identifying way more files and folders than there actually are? I am working on an HTML website. If I go into my project, highlight everything, and check the properties I see the following:

*

*Size: 16.2 MB

*Size on disk: 16.4 MB

*120 files

*19 folders

If I right click the folder containing all of these files I get the following:

*

*Size: 120 MB

*Size on disk: 121 MB

*576 files

*246 folders

If I download my project from GitHub, I see the smaller (and actual) size of my project. I've tried refreshing the folder and my desktop, as well as restarting my computer. Is this an issue and should I be worried?


text:
Q: Having trouble with paths returned by flowPath in raster R-package Paths returned by the flowPath function in the raster package consist of segments parallel to the x- and y-axes.
Starting with the Vector Field Plots example in the rasterVis documentation (https://oscarperpinan.github.io/rastervis/), I try to find the flow-path from a starting point on the surface, but the path output is incorrect.
library(raster)
library(rasterVis)
proj <- CRS('+proj=longlat +datum=WGS84')
df <- expand.grid(x = seq(-2, 2, .01), y = seq(-2, 2, .01))
df$z <- with(df, (3*x^2 + y)*exp(-x^2-y^2))
r <- rasterFromXYZ(df, crs=proj)

# Up to this point we follow the example in the rasterVis documentation
# Now attempt to find the path from a point on the surface

contour(r$z)
r.fd<-terrain(r,opt='flowdir')
r.c<-cellFromXY(r,cbind(-1,0))
r.p<-flowPath(r.fd,r.c)
p.xy<-xyFromCell(r.fd,r.p)
lines(p.xy,col='green')

Flow path from point (-1,0) depicting undesired behavior.
As you can see above, the flow path proceeds to the minimum at approximately (0,-.8) by moving towards +x and then -y.  I have been unable to construct a data set which does not exhibit this problem.  However:  the example included in the flowPath documentation (in the raster package, using the volcano data) produces output one might expect and does not exhibit this problem.
What am I doing incorrectly that I cannot extend the example in the rasterVis documentation?
Addendum:  My reason for questioning the output may be more a misunderstanding of what flowPath is supposed to return. I expected the kind of path a droplet might follow as it moves downhill.  Like this:
Expected flowPath
This was computed using a simple steepest-descent walk.  However, if (as stated by respondent Hijmans) flowPath is working as intended, then I may need to find another function which provides the path droplets would follow moving downhill.

A: Why is the path incorrect? It looks good to me. Illustrated by aggregating and labeling.
library(raster)
proj <- CRS('+proj=longlat +datum=WGS84')
df <- expand.grid(x = seq(-2, 2, .01), y = seq(-2, 2, .01))
df$z <- with(df, (3*x^2 + y)*exp(-x^2-y^2))
r <- rasterFromXYZ(df, crs=proj)
r <- aggregate(r, 25) * 10

r.fd <- terrain(r, opt='flowdir')
r.p <- flowPath(r.fd, cbind(-1,0))
p.xy <- xyFromCell(r.fd,r.p)

plot(r)
lines(p.xy,col='green', lwd=2)
text(r)

Add some noise to get a more wiggly path
set.seed(01234)
r <- rasterFromXYZ(df, crs=proj)
r <- aggregate(r, 10) * 10
r <- r + runif(ncell(r), 1, 2)
r.fd <- terrain(r, opt='flowdir')
r.p <- flowPath(r.fd, cbind(-1,0))
p.xy <- xyFromCell(r.fd,r.p)

plot(r)
lines(p.xy,col='green', lwd=2)


text:
Q: Enum Extension Method To Clear Inplace I have an enum, suppose it is called sports:
enum Sports
{
  Baseball = 1,
  Basketball = 2,
  Football = 4,
  Hockey = 8,
  Soccer = 16,
  Tennis = 32,
  etc...
}

I would basically like to add an extension method that clears a mask bit like this:
Sports Mask = Sports.Baseball | Sports.Football | Sports.Tennis; //37
Mask.Clear(Sports.Baseball);
// Mask = Football | Tennis

This is the extension method I've come up with, it doesn't work.  Clear doesn't affect Mask, the value remains 37. I'm not sure I can modify the this portion from within the extension method.  Is there some other way to accomplish this?
public static void Clear<T>(this Enum value, T remove)
{
  Type type = value.GetType();
  object result;

  if (type.Equals(typeof(ulong)))
  {
    result = Convert.ToUInt64(value) & ~Convert.ToUInt64((object)remove);
  }
  else
  {
    result = Convert.ToInt64(value) & ~Convert.ToInt64((object)remove);
  }

  value = (Enum)Enum.Parse(type, result.ToString());
}

A: Because enums are value types, so that you modified the parameter only. You can return the modified value and assign it to the original variable.
public static T Clear<T>(this Enum value, T remove) { ... }
mask = mask.Clear(Sports.Baseball);
//just like
//DateTime dt = DateTime.Now;
//dt = dt.AddHour(1);

And by the way, I don't think it worth an extension method here. Why not just simply use:
mask = mask & ~Sports.BaseBall;
mask = mask & ~anotherMask;

Your extension method is very inefficient because of (un)boxing.

A: Krzysztof Cwalina at MSDN Blogs explains how to clear Enum values using Flags attribute on enums at the below 2 links:
http://blogs.msdn.com/b/kcwalina/archive/2006/08/29/clearingflagenum.aspx
http://weblogs.asp.net/bhouse/archive/2006/08/29/Clearing-Enum-Flags.aspx
Sample:
[Flags]
public enum Foos {
    A = 1,
    B = 2,
    C = 4,
    D = 8,
    AB = A | B,
    CD = C | D,
    All = AB | CD
}

static class Program {
    static void Main() {
        Foos value = Foos.AB;
        Console.WriteLine(ClearFlag(value,Foos.A);
    }
    public static Foos ClearFlag(Foos value, Foos flag) {
       return value & ~flag;
    }
}

A: You're asking to pass the instance to the extension method by reference. But you can't do this in C#.


text:
Q: Pandas converting columns to rows I have a dataframe with columns like this -
Name Id 2019col1 2019col2 2019col3 2020col1 2020col2 2020col3 2021col1 2021Ccol2 2021Ccol3

That is, the columns are repeated for each year.
I want to take the year out and make it a column, so that the final dataframe looks like -
 Name Id Year col1 col2 col3

Is there a way in pandas to achieve something like this?

A: Use wide_to_long, but before change order years to end of columns names like 2019col1 to col12019 in list comprehension:
print (df)
  Name   Id  2019col1  2019col2  2019col3  2020col1  2020col2  2020col3  \
0    a  456         4         5         6         2         3         4

   2021col1  2021col2  2021col3
0         5         2         1

df.columns = [x[4:] + x[:4] if x[:4].isnumeric() else x for x in df.columns]

df = (pd.wide_to_long(df.reset_index(),
                      ['col1','col2', 'col3'],
                      i='index',
                      j='Year').reset_index(level=0, drop=True).reset_index())
print (df)

   Year   Id Name  col1  col2  col3
0  2019  456    a     4     5     6
1  2020  456    a     2     3     4
2  2021  456    a     5     2     1


text:
Q: AR GLTF animations with React Native Viro I am trying to place an animated 3D object, my problem is that although this object does have animation, I do not know the name of the animation. Is there a way to know the name?
My code is:
 <Viro3DObject
    source={require("./res/works.gltf")}
    scale={[0.1, 0.1, 0.1]}
    position={[0, 0, -20]}
    type="GLTF"
    animation={{
        name: "0",
        run: true,
        loop: true,
    }}
/>

I don't know the name of the animation, that's why it doesn't move. Others that I do know the name move.


text:
Q: How can I backup a SQL Server 2008 database and restore it again My PC is running slow. I want to format it but my asp project database is in SQL Server 2008, I know how to backup the database but a friend of mine told me it won't be restored if you format your system, backup only gets restored if you use same computer, SQL Server. I'm really confused, but I have to format my PC in any case. Can anyone tell me what I need to do to save my database?

A: *

*Right Click on your Database which you want to take as backup .Then Go to Task>Backup

*While doing backup select the drive which you are not going to Format and keep back there.

*For Restoring. Right Click on Databases{Top one} and select Restore option.

*Select From Device option.

*While Restoring Select the file which you created as backup by browsing. If you are not able to find that backup file, then make sure you have specified Files Type as All.

and yes your Friend is wrong :)


text:
Q: Finding the original positions of words in a sentence when the word occurs more than once I need to find the positions of words in a sentence the user inputs and if the word occurs more than once, only print the first time that word occurs
I have the code so far-
sentence=input("Enter a sentence: ")
sentence=sentence.lower()
words=sentence.split()
place=[]

for c,a in enumerate(words):
    if words.count(a)>2 :
        place.append(words.index(a+1))
    else:
        place.append(c+1)

print(sentence)
print(place)

But it prints the positions of the individual words in the sentence rather than repeating a original position of a word that occurs more than once
Can anyone help me with this???

A: If you are using python 2, then raw_input instead of input else it'll eval.  That isn't a problem, just an observation (you're probably using python 3 then, so I'll leave it that way).
You could create a dict to track word counts and positions found. This is basically a dict of lists.  The dict being a map of words to a list of positions.
sentence=input("Enter a sentence: ")
sentence=sentence.lower()
words=sentence.split()

place={}
for pos, word in enumerate(words):
    try:
        place[word].append(pos)
    except KeyError:
        place[word] = [pos]

print(sentence)
print(place)

Also, if you wanted to do something a little more advanced with your sentence parsing, you could do:
import re
words = re.split('\W+',sentence)

Basically uses all nonalphanumerics (commas, colons, etc) as a split.  Just note you can get a blank entry this way (probably at the end).

A: Your code needs some modifications to achieve what you are trying to do:

*

*if words.count(a)>2 : It should be if words.count(a)>1 since count would be more than 1 if the word is repeated.

*place.append(words.index(a+1)) : It should be place.append(words.index(a)+1) since you want to find the index of a and then add 1 to it.
The modified code based on the suggestions:
sentence=input("Enter a sentence: ")

sentence=sentence.lower()
words=sentence.split()
place=[]

for c,a in enumerate(words):
    if words.count(a)>1 :
        place.append(words.index(a)+1)
    else:
        place.append(c+1)

print(sentence)
print(place)

Output:

Enter a sentence: "hello world hello people hello everyone"
hello world hello people hello everyone
[1, 2, 1, 4, 1, 6]

A: Split the string
>>> s = '''and but far and so la ti but'''
>>> s = s.split()
>>> s
['and', 'but', 'far', 'and', 'so', 'la', 'ti', 'but']

use set to find the unique words and use the list.index method to find the first position of each unique word.
>>> map(s.index, set(s))
[0, 5, 2, 1, 4, 6]

zip the result of that with the unique words to associate the word with its position.
>>> zip(set(s),map(s.index, set(s)))
[('and', 0), ('la', 5), ('far', 2), ('but', 1), ('so', 4), ('ti', 6)]
>>>

I suppose a list comprehension might be easier to read;
>>> s = '''and but far and so la ti but'''
>>> s = s.split()
>>> result = [(word, s.index(word)) for word in set(s)]
>>> result
    [('and', 0), ('la', 5), ('far', 2), ('but', 1), ('so', 4), ('ti', 6)]
>>>

Sort on position
>>> import operator
>>> position = operator.itemgetter(1)
>>> result.sort(key = position)
>>> result
[('and', 0), ('but', 1), ('far', 2), ('so', 4), ('la', 5), ('ti', 6)]
>>>


text:
Q: concatenate the argument of date into one string my main program takes a time stamp having the format of the date as well as the time, separated by a comma, but it is still one string and one argument:
#source main.sh '2015-02-10 00:00:00'

Now, I want to give time stamp automatically to the program by running the following script.
My problem is that, I should keep the space between the date and time and the output of the first line or the value of TIMESTAMP is two arguments, one for the date and the other of the time, which contradicts the permitted number of arguments passed to the main.sh.
TIMESTAMP=$(date --date='40 days ago' '+%F %T')
TARGET=/opt/db_maintain/main.sh
COMMAND=${TARGET}" "${TIMESTAMP}
#source $COMMAND
echo $TIMESTAMP

the output is:
   2015-02-04 15:55:50

Is there any way to join the date and the time of TIMESTAMP as only one argument? plz be informed that I should maintain the space between the time and the date.

A: Update:
Please try the following snippet instead:
TIMESTAMP=$(date --date='40 days ago' '+%F %T')
TARGET=/opt/db_maintain/main.sh
source $TARGET "$TIMESTAMP"

To avoid quoting your TIMESTAMP argument why not using the iso8601 T delimiter?
Date and time can be one string: 2014-02-04T13:49:40
And you can use such format as date input:
$ date --date='2014-02-04T13:49:40'
Tue Feb  4 13:49:40 CET 2014

If your target script can only understand datetime with a space, store it this way:
TIMESTAMP="$(printf "%q" "$(date --date='40 days ago' '+%F %T')")"

The space will be escaped:
$ echo $TIMESTAMP
2015-02-04\ 14:04:51

Alternatively you can escape quotes like this:
COMMAND="$TARGET \"$TIMESTAMP\""


text:
Q: Converting SQL int to C# string I've been trying to load an INT from my SQL-Server DB into my C# application and convert it into string.
Basically, it's the ID/Primary key of the DB Table that I want to use as string.
This is what I do :
string Variable_ID;
Variable_ID = HandleDBNull(reader, "ID");

and I get a IndexOutOfRange exception.
Here is the HandleDBNullfunction :
    private string HandleDBNull(SqlDataReader r, string columnName)
    {
        if (!r.IsDBNull(r.GetOrdinal(columnName)))
            return r[columnName].ToString();
        else
            return String.Empty;
    }

It works for the string columns so there seems to be something wrong with the conversion. I've already tried Convert.ToString and got the same error.
Any ideas?

A: I would guess that your columnName and columnOrder are out of step with each-other. One is wrong. Since they express the same information, one is redundant. I would use instead:
// probably should be renamed, btw
private string isDBNull(SqlDataReader r, int columnOrder)
{
    if (!r.IsDBNull(columnOrder))
    {
        return r[columnOrder].ToString();
    }
    else return "";
}

obviously with:
Variable_ID = isDBNull(reader, 0);

although I'm not quite sure I'd want everything as strings.

A: You can try with - Because your condition is based on columnOrder
 ...
 return r[columnOrder].ToString();

Suggestion
private bool isDBNull(SqlDataReader r, string columnName, int columnOrder)
    {
        if (!r.IsDBNull(columnOrder))
        {
            return true;
        }
        return false;
    }

A: Simplify the code:
string Variable_ID;
Variable_ID = isDBNull(reader, "ID");

private string isDBNull(SqlDataReader r, string columnName)
{
    if (!r.IsDBNull(r.GetOrdinal(columnName)))
        return r[columnName].ToString();
    else
        return string.Empty;
}


text:
Q: Yii URLFormat Path will not work For some reason, since I've enabled the urlManager, domain.com/site/logout/ or domain.com/logout/ will not work.
Here's my .htaccess:
RewriteEngine on

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php
RewriteRule . index.php

... and here's my main.cfg
    'components'=>array(
       'assetManager' => array(
          'linkAssets' => true,
        ),
        'user'=>array(
           'allowAutoLogin'=>true,
         ),
         'request'=>array(
            'baseUrl' => "http://google.com"
         ),

         'urlManager'=>array(
                    'urlFormat'=>'path',
                    'showScriptName'=>false,
                    'rules'=>array(
                            'rules'=>array(
                                'post/<id:nd+>/<title:.*?>'=>'post/view',
                                'posts/<tag:.*?>'=>'post/index',
                                '<controller:nw+>/<action:nw+>'=>'<controller>/<action>',
                    ),
            ),

Any ideas? Thanks :/


text:
Q: How to access value of a jenkins groovy variable in shell script for loop When i am passing value of a variable declared in jenkins Groovy script its value is not retained in for loop which is running on a remote server. Strange thing is i am able to access the same value outside the for loop.
Here is the sample code i am trying to use
#!/usr/bin/env groovy

def config
def COMMANDS_TO_CHECK='curl grep hello awk tr mkdir bc'
pipeline {

    agent {
        label "master"
    }

    stages {
            stage ('Validation of commands') {
            steps {
                script {
                    sh """
                    #!/bin/bash
                    /usr/bin/sshpass -p passwrd ssh user@host << EOF
                    hostname

                      echo $COMMANDS_TO_CHECK ---> This is printed
                          for CURRENT_COMMAND in \$COMMANDS_TO_CHECK
                        do
                        echo ${CURRENT_COMMAND}  ---> Why This is not printed?
                        echo \${CURRENT_COMMAND} ----> Why This is not printed?
                        done
                        hostname
EOF
                        exit

"""

}
}
}
}
}

Output
[workspace@3] Running shell script
+ /usr/bin/sshpass -p passwrd ssh user@host
Pseudo-terminal will not be allocated because stdin is not a terminal.
illinsduck01
curl grep hello awk tr mkdir bc
illinsduck01
+ exit

A: You can wrap sh in """ ... """ as below
#!/usr/bin/env groovy

def config
pipeline {
agent {
    label "master"
}
stages {
    stage ('Validation of commands') {
        steps {
            script {
            sh """#!/bin/sh
            /usr/bin/sshpass -p password ssh username@hostname << EOF
            COMMANDS_TO_CHECK="curl grep hello awk tr mkdir bc"

            hostname

            echo \$COMMANDS_TO_CHECK

            for CURRENT_COMMAND in \$COMMANDS_TO_CHECK
            do
            echo \$CURRENT_COMMAND
            which \$CURRENT_COMMAND
            status=\$?

            if [ \${status} -eq 0 ]
            then
               echo  \${CURRENT_COMMAND} command is OK
            else
               echo "Failed to find the \${CURRENT_COMMAND} command"
            fi
            done
            hostname
            EOF

            exit
           """
           }
         }
       }
     }
  }


text:
Q: System of differential equations, phase portrait Consider the system of differential equations:
$$x'=-2x+y-x^3$$
$$y'=-y+x^2$$
a. Determine the fixed points.
(Am I correct in thinking that to determine the fixed points, I must set x' and y'=0? I'm not sure if I am doing this right...)
$y'=-y+x^2$
$0=-y+x^2$
$y=x^2$
$x'=-2x+y-x^3$
$0=-2x+y-x^3$
$0=-2x+x^2-x^3$
$0=-x(2-x+x^2)$
so I get $x=0$ and $x=\frac{1±\sqrt{7}i}{2}$
b. Determine the nullclines and the signs of $x'$ and $y'$ in the various regions of the plane.
So I know I have to determine the fixed points to do this, which I did above (not sure if I did that correctly though) and I also need to determine their stability, right?
For stability I have to compute eigenvalues and if the real parts of both are negative, it's stable, if the real parts of one is positive it's unstable, and if one of the real parts is 0, it is L-stable/marginally stable...is this right?
I guess I am not really sure how to compute the eigenvalues in this case, so far I am only really comfortable with computing the eigenvalues when the question is already in matrix form, as opposed to these equations...so I need some guidance...
c. Sketch a rough phase portrait.

A: $\qquad\qquad\qquad\qquad\qquad$
To prove the convergence to the unique fixed point $(0,0)$, apparent on the phase diagram above, note that $$4(x^2+y^2)'=-2(2x^2-y)^2-(4x-y)^2-5y^2\lt0,$$ for every $(x,y)\ne(0,0)$.
An interesting question about this dynamical system would be to determine an explicit equation for the curve $$x=u(y),$$ also apparent on the phase diagram above, which can be defined by the fact that the reversed dynamics $$\bar x'=2\bar x-\bar y+\bar x^3,\qquad\bar y'=\bar y-\bar x^2,$$ is such that $\bar x(t)\to-\infty$ when $t\to+\infty$ for every $(\bar x(0),\bar y(0))$ such that $\bar x(0)\lt u(\bar y(0))$, and such that $\bar x(t)\to+\infty$ when $t\to+\infty$ for every $(\bar x(0),\bar y(0))$ such that $\bar x(0)\gt u(\bar y(0))$. The function $u$ solves the differential equation $$(z-u^2(z))\cdot u'(z)=u^3(z)+2u(z)-z,$$ with initial condition $u(0)=0$.


text:
Q: Left and Right Ideal Generated by Two Matrices. Let $R= {\rm Mat}_2(\Bbb R)$ be the ring (with $1$) of $2\times2$-matrices with entries in $\Bbb R$. Let $$M = \left\{\begin{pmatrix}1&0 \\0&0\end{pmatrix},\begin{pmatrix}0&1\\0&0\end{pmatrix}\right\},$$ i.e. a set of two matrices. What are the left and right ideal generated by $M$ in $R$?

I tried to write my answer by it won't accept it. I don't know how to write Matrices (and their product) in the right format.
Is this correct:
For left ideal: $$\begin{pmatrix}a&b\\c&d\end{pmatrix}\begin{pmatrix}1&0\\0&0\end{pmatrix}=\begin{pmatrix}a&0\\c&0\end{pmatrix} \quad \text{ and } \quad \begin{pmatrix}a&b\\c&d\end{pmatrix}\begin{pmatrix}0&1\\0&0\end{pmatrix}=\begin{pmatrix}0&a\\0&c\end{pmatrix}$$
hence $L = \begin{pmatrix}a&a\\c&c\end{pmatrix}$.
For right ideal:
$$\begin{pmatrix}1&0\\0&0\end{pmatrix}\begin{pmatrix}a&b\\c&d\end{pmatrix}=\begin{pmatrix}a&b\\0&0\end{pmatrix} \quad \text{ and } \quad \begin{pmatrix}0&1\\0&0\end{pmatrix}\begin{pmatrix}a&b\\c&d\end{pmatrix}=\begin{pmatrix}c&d\\0&0\end{pmatrix}$$
hence $R = \begin{pmatrix}a+c&b+d\\0&0\end{pmatrix}$.

A: Sorry, there are some issues here caused by your choice of notation. By multiplying the same $a,b,c,d$ matrix with both generators, you've overlooked that there's nothing wrong with multiplying the generators with two different matrices and adding, which will produce many more possiblities.
In the left ideal generated by those two things, a general element will look like this:
$\begin{bmatrix}a&b\\c&d\end{bmatrix}\begin{bmatrix}1&0\\0&0\end{bmatrix}+\begin{bmatrix}e&f\\g&h\end{bmatrix}\begin{bmatrix}0&1\\0&0\end{bmatrix}=\begin{bmatrix}a&e\\c&g\end{bmatrix}$.
Notice how we didn't recycle the $a,b,c,d$ matrix for both generators. Since you can pick $a,e,c,g$ to be whatever you want, you can see that the left ideal generated by these two things is the entire matrix ring.
Try to apply similar reasoning to the right ideal generated by these two things. You will get a different answer than the left ideal, and the answer you gave is not incorrect. It's just that you can express what the right ideal looks like more simply.


text:
Q: Most common checked and unchecked Java Exceptions? As far as I understand, there is no way to find out which exceptions a method throws without looking up the API docs one-by-one.
Since that is no option, I'd like to reverse the research and ask you which are the most common Exceptions and RuntimeExceptions you've come across when dealing with:

*

*Casting

*Arrays

*Vector, ArrayList, HashMap, etc.

*IO (File class, streams, filters, ...)

*Object Serialization

*Threads (wait(), sleep(), etc.)

*or anything else that is considered "basic Java"

I realize that this might be subjective and boring but it is for a class test and I really don't know better.

A: java.lang:

*

*ArithmeticException

*ArrayIndexOutOfBoundsException

*ClassCastException

*ClassNotFoundException

*CloneNotSupportedException

*IllegalArgumentExcepion

*IllegalMonitorStateException

*IllegalThreadStateException

*IndexOutOfBoundsException

*InterruptedException

*NullPointerException

*NumberFormatedException

java.util:

*

*ConcurrentModificationException

java.io :

*

*EOFException

*FileNotFoundException

*IOException

*NotSerializableException

A: Unchecked Exception List
ArrayIndexOutOfBoundsException
ClassCastException
IllegalArgumentException
IllegalStateException
NullPointerException
NumberFormatException
AssertionError
ExceptionInInitializerError
StackOverflowError
NoClassDefFoundError
Checked Exception List
Exception
IOException
FileNotFoundException
ParseException
ClassNotFoundException
CloneNotSupportedException
InstantiationException
InterruptedException
NoSuchMethodException
NoSuchFieldException

A: Assume the below are java.lang unless I specify otherwise:

*

*Casting: ClassCastException

*Arrays: ArrayIndexOutOfBoundsException, NullPointerException

*Collections: NullPointerException, ClassCastException (if you're not using autoboxing and you screw it up)

*IO: java.io.IOException, java.io.FileNotFoundException, java.io.EOFException

*Serialization: java.io.ObjectStreamException (AND ITS SUBCLASSES, which I'm too lazy to enumerate)

*Threads: InterruptedException, SecurityException, IllegalThreadStateException

*Potentially common to all situations: NullPointerException, IllegalArgumentException

You would do well to look at Java site's Package Summary pages. Here's one: http://java.sun.com/j2se/1.4.2/docs/api/java/io/package-summary.html

A: As Bill K says. Checked exceptions are easy.  If your IDE/program editor doesn't give you an quick way to see method javadocs or signatures you need to throw it away.  Seriously.
Unchecked exceptions are a different kettle of fish.  But I think the best strategy with unchecked exceptions is to not try to catch them.  Instead, you write you code so that it avoids throwing them in the first place.  For example;
// ... not sure if 'obj' is null
if (obj != null) {
    obj.someMethod();
}
// ... not sure if 'obj' has the right type
if (obj instanceof Foo) {
    Foo foo = (Foo) obj;
}
// ... not sure if 'i' is in range
if (i >= 0 && i < array.length) {
    .... = array[i];
}

Here's why I recommend this:

*

*A guard test is orders of magnitude more efficient than throwing and catching an exception.

*A guard test is more readable ... less lines of code.

*If you catch an unchecked exception, you can never be sure that it happened for the reasons you think it did; for example:

    // obj might be null ...
    try {
        obj.doSomething();
    } catch (NullPointerException ex) {
        System.err.println("obj was null");  // WRONG!!!
        // the NPE could have happen inside doSomething()
    }

*

*If an unchecked exception is caused by a bug, you DO want a stacktrace and (depending on the application) you MAY NOT want to recover.

Obviously, you only include these "guard" checks where your understanding of the code tells you that they are necessary!  So, for example if you know that 'obj' ought to be non-null and 'i' ought to be in range, it is a good idea to leave the checks out.  If you leave out one test too many, you'll get an exception ... but that's good because you can then use the stacktrace to figure out why your understanding of the code was wrong, and maybe fix the underlying bug.

A: I would like to contribute a list that groups by situation, which is probably more meaningful than grouping by packages or fields of programming.
Unexpected exceptions
These are exceptions that should ideally never be thrown in production. You should fix them instead of catching them and stfu.
when you test newly written code (and sometimes unexpectedly seen by users)
They should never happen again once you see them.

*

*AssertionError

*

*congratulations, you are writing good code

*you should be happy that you made this error, because less (errors) is more (bugs)

*I hope you won't end up finding out that your code is correct and you accidentally inverted your assertion

*NullPointerException

*

*where are your @NotNulls?

*did you check before using the return value from Map.get()?

*ArrayIndexOutOfBoundsException

*

*do you check before using List.get()?

*I hope you know well enough that Java isn't JavaScript, arrays are fixed-sized and you can't just array[array.length] = newElement

*ClassCastException

*

*too much generics is bad for your brain cells; consider moving to golang!

*IllegalArgumentException

*

*this could sometimes mean "read the fishing docs"

And less likely to see,

*

*IllegalMonitorStateException

*

*yes, having to synchronized sucks, but it's like this in most languages

*CloneNotSupportedException

*

*hey, just don't use clone(). aren't copy constructors cool?

And then you get more NullPointerException.
And then... Still NullPointerException? That @NotNull annotation is rubbish!
when you test newly written code for the 100th time
Exceptions that happen due to race conditions or rare probability. You should buy a lottery if you see them the first 10 times you run your code.

*

*ConcurrentModificationException

*

*?your synchronized is where

*IllegalStateException

*StackOverflowError (not Exception)

*

*have you tried tail recursion?

during compilation, deployment, etc.
They usually happen when you messed up the dependencies, used wrong versions of libraries, etc.

*

*LinkageError

*NoClassDefFoundError

*java.lang.XxxNotFoundException, java.lang.NoSuchXxxException (classes, methods, etc.)

*

*not reflections please

when you are too lazy
and when you are using @lombok.SneakyThrows or equivalent

*

*RuntimeException

*? extends RuntimeException

Expected exceptions
If they are not caught, this probably means you are too lazy as well. You can't prevent them from throwing; you just have to catch them.
high likeliness
These exceptions have high likeliness to happen, and should always be handled specifically (i.e. you should actually handle them instead of just outputting the error)

*

*NumberFormatException

*

*I never understand why this exception extends RuntimeException.

medium likeliness
These exceptions sometimes happen due to invalid user input (but you should really validate them, so I classify these as "unexpected exceptions"), and sometimes happen due to system constraints that might not be reproducible when (non-stress) testing.

*

*IOException and other java.io.XxxException

*SecurityException

*StackOverflowException

*

*unfortunately, going to StackOverflow most likely won't fix your StackOverflowExceptions, because you will get more overflown stacks as you are looking for something to Ctrl-C and Ctrl-V

*StackUnderflowException

*

*no, StackOverflow is still not going to help a lot

*OutOfMemoryError

*

*I hope it's not a memory leak

A: NullPointerException

A: Checked exceptions are easy, your editor should display the javadocs when you hover/complete the method name.
Unchecked are generally actual errors and aren't even in the javadocs more often than not.  I guess the most common might be IllegalArgumentException, any method that has any possible combination of parameters that is invalid should throw it.

A: How about looking for subclasses of java.lang.exception, for example here
Personally I use 2 checked exceptions of my own TransientException for cases when a retry might work. And InvalidRequestException for validation errors.

A: NumberFormatException

A: *

*Casting - ClassCastException

*Arrays - ArrayIndexOutOfBoundsException

*Vector, ArrayList, HashMap, etc. - I rarely see exceptions when working with Java collections, but very occasionally ConcurrentModificationException

*IO (File class, streams, filters, …) - FileNotFoundException

*Object Serialization - ClassNotFoundException

*Threads (wait(), sleep(), etc.) - In my experience, usually threading problems manifest themselves in random ways that aren't exception specific.  Having to deal with InterruptedException occupies a lot of time, though I haven't seen the exception actually thrown much.

*or anything else that is considered "basic Java" - by far the most common exception in my experience is NullPointerException.


text:
Q: How can I change the way of handling exceptions in my java project in a better way? I have to refactor a Java program created with Eclipse RCP. My predecessor handed over a ViewPart Implementation through several calls down to the class I want to write Unit Tests for. The ViewPart is handed over for exception handling purposes. Every time an error occurs the error message will be written onto the ViewPart's StatusLineManager.
What I want to do now is to change this exception handling process, because it causes me a lot of problems when I want to make my Unit Tests.
Is there a way to pass these Exceptions to the ViewPart without handing it down over several method calls?
My initial ideas to create some kind of ExceptionMessenger class that will be initialized every time an exception occurs. But I didn't find a way to access the ViewPart then.
edit
code example:
class A {
    void func() {
         B.funcB(arg, arg1, arg2, ViewPart view):
    }
}

class B {
      void funcB(arg, arg1, arg2, ViewPart view) {
           C.funcC(arg, arg1, ViewPart view);
      }
}

class C {
    void funcC(arg, arg1, ViewPart view) {
        try{
             doSomeThing():
        catch(Exception e) {
            doSomeErrorMessages(e, view);
        }
     }

    void doSomeErrorMessages(e, ViewPart view) {
        SomeOtherClass.writeToStatusLine( StatusCategory.Processing, e.getMessage(), view);
    }
 }

class SomeOtherClass {
    void writeToStatusLine(final StatusCategory category, final String message, final ViewPart view) {
    IActionBars bars = view.getViewSite().getActionBars();
        IStatusLineManager statusLineManagerRef = bars.getStatusLineManager();
        statusLineManagerRef.setErrorMessage(null); // clear any error msg

        doWhatEver();
    }
 }

A: If I understood your task correctly, there are two parts where you are dealing with exceptions:

*

*Java's exception handling when some exceptional behaviour occurs. For this, you should stick to what Java offers you, as described, e.g., in Josh Bloch's Effective Java, Item 57 ( Use exceptions only for exceptional conditions).

*Visualisation of exceptions in your tool (by ViewPart). Since this is not part of exception handling to recover or otherwise cope with exceptional conditions, I would deliberately not use Java's exception handling for that, i.e. avoid misusing exception handling for control flow. Hence I think your predecessor's design to pass down the ViewPart to then pass the Exceptions as parameters to your ViewPart is good.

An alternative would be to let the exceptions get thrown upward and then at some sensible border of layer/framework do the visualisation. But

*

*be careful not to mix the two parts of dealing with exceptions listed above

*if you are dealing with checked exceptions and can handle them far down in your call hierarchy, this will make your code much uglier than passing down ViewPart (and definitely mix the two parts listed above).

What are your problems when unit testing?

*

*If the ViewPart is making trouble: mock it.

*If passing the ViewPart as parameter is annoying you: use some framework for your dependency injection, e.g. Spring or Guice.

*If an alternative visualisation/handling of the Exceptions is making trouble: might a (junit-)rule solve the problem?


text:
Q: Temporary Password Security - Storing as Plain Text How much of a security issue would it be to store temporary / machine generated passwords as clear text in a database?
I understand that passwords should be encrypted using a 1-way hash function with salt.  This is especially true for user supplied passwords as users typically re-use them over and over again.  If the database was stolen, a thief might be able to gain access to user user accounts on 3rd party websites such as: utility bills, social networks, even potential for online banking.
How much of an issue would it be to store temporary/machine generated "welcome" or "reset" passwords as clear text in a database?  The password would be emailed to users and must be changed upon login.  The passwords that they supply would then be hashed.
The reason for me asking is that there are a some nice properties to storing a temporary password as clear text.  For example, if a user does not get the "welcome" or "reset" email, an admin can quickly look-up their temporary password.
Because the temporary password would be machine generated, if the database was stolen, the thief would not be able to access any 3rd party websites that the users log into.  The thief would however be able to login to the application that generated the temporary passwords.
Assigning these passwords a small "expiration" would limit exposure, but overall I am just looking to see how dangerous this approach would be.

A: You should not store even machine generated passwords in plain text.
Let's see what an attacker can do, if he somehow gains only read access to your database with SQL-injection (i made a small demo how easy SQL-injection can be, just click the next-arrow to get a malicious input).
The attacker with read access, could demand a password reset for any e-mail address he likes. Because he can see the new generated token in the database, he could call the reset page with this token and therefore can change the password of this user. Unnecessary to say, that he can now impersonate the original user.
Handle the token just like every other password, even if it can not be used on other sites. The data accessible by the user-account could contain other data (like birthday, real name), that can be used to hack other sites.

A: You absolutely must not store passwords in a database at all, let alone in plain text. You should store hashes of them. See this answer for why. Then you need to build all your password-reset facilities around that fact. See also this answer about password reset features.


text:
Q: encryption and decryption that work for both c# and php Is there any encryption  and decryption  Algorithms that work for both php and c#? Please I need a sample codes

A: I think what you are looking for is DES3 encoding which can work fairly easily between C# and PHP.  Check out these two links for code examples.
C# Example:
http://www.csharper.net/blog/library_encrypt_and_decrypt_methods_using_tripledes_and_md5.aspx
PHP Example
http://us3.php.net/manual/en/mcrypt.examples.php


text:
Q: How to efficiently sample from a vector of numbers data <- data.frame(p1 = runif(10, 0, 1), p2 = runif(10, 0, 1), p3 = runif(10, 0, 1))

I want to sample from (1, 2, 3) based on probabilities (p1, p2, p3). Currently, I've written this in a loop
for(i in 1:nrow(data)){
  data$x <- sample(c(1, 2, 3), size = 1, replace = TRUE, prob = c(data$p1[i], data$p2[i], data$p3[i])
}

Is there a more efficient way to do this? This is quite slow as the number of rows in the data set increases.

A: We could use rowwise here
library(dplyr)
data %>%
   rowwise %>%
   mutate(x = sample(c(1, 2, 3), size = 1, replace = TRUE,
       prob = c_across(matches('^p\\d+$')))) %>%
   ungroup

-output
# A tibble: 10 x 4
      p1    p2     p3     x
   <dbl> <dbl>  <dbl> <dbl>
 1 0.297 0.602 0.852      2
 2 0.169 0.892 0.481      3
 3 0.589 0.777 0.384      2
 4 0.553 0.940 0.741      2
 5 0.910 0.414 0.0253     2
 6 0.756 0.131 0.963      1
 7 0.193 0.710 0.795      3
 8 0.424 0.807 0.926      3
 9 0.429 0.868 0.859      3
10 0.765 0.992 0.912      2

Or a more efficient approach would be with dapply from collapse
library(collapse)
data$x <- dapply(gvr(data, '^p\\d+$'), MARGIN = 1, FUN = function(x)
           sample(c(1, 2, 3), size = 1, replace = TRUE, prob = x))

A: You can use mapply in base R -
data <- transform(data, x = mapply(function(x, y, z)
                  sample(c(1, 2, 3), 1, prob = c(x, y, z)), p1, p2, p3))

#          p1        p2         p3 x
#1  0.4546779 0.1741450 0.03489881 3
#2  0.4398293 0.8059894 0.27687308 2
#3  0.6514023 0.2697283 0.84126810 3
#4  0.8332548 0.7092438 0.03198509 2
#5  0.1218922 0.9857776 0.86859004 3
#6  0.6887676 0.4206811 0.20454715 2
#7  0.5082115 0.5669147 0.68234409 1
#8  0.1382448 0.1015148 0.89351722 3
#9  0.2095876 0.1667515 0.99908780 2
#10 0.5600337 0.9912484 0.09108034 2


text:
Q: How to find out programmatically if port, input-ed by user is being used by a particular service? I want to install a Major upgrade of an application, the application uses particular services which listens at ports given as input by the user. The check for Port In Use is done programmatically before previous version of application is uninstalled and it's upgrade is installed.
I want my installer to allow its services listen at particular ports if the previous version of the application's services are listening at the same ports as input-ed by the user while doing major upgrade.

A: If you are serious about this approach, determine the PID of your running service and then look for it in the result of GetExtendedTcpTable with TCP_TABLE_OWNER_PID_ALL set.
However, I suppose you will have a much easier time forgetting about the actual listen sockets and just looking for the configuration information in the registry or config files, so maybe you should rethink your approach.


text:
Q: Are there a better approach then defining many classes in typescript for knockout viewmodels I have seperated out my viewmodels into classes using typescript.
Now in my Bootstraper i am importing them all like this:
import dl = module("DataLayer");
import vm1 = module("AppBarViewModel");
import vm2 = module("Nav2ViewModelCommander");
import vm3 = module("IdentityViewModel");

Are there not a way to collect them to one namespace?
I am using requirejs and my viewmodels look something like this when compiled to js.
define(["require", "exports"], function(require, exports) {
    var AppBarViewModel = (function () {
        function AppBarViewModel() {
            this.visible = ko.observable(true);
            this.buttons = ko.observableArray([]);
            this.enableContext = ko.observable(true);
            this.canClose = ko.computed(function () {
                var k = ko.utils.arrayFirst(this.buttons(), function (b) {
                    return b.blockHide && b.blockHide == true;
                });
                return k == null;
            });
        }
        AppBarViewModel.prototype.addButton = function (data) {
            this.buttons.push(data);
            this.visible(data.blockHide && data.blockHide == true);
        };
        AppBarViewModel.prototype.removeButton = function (data) {
            this.buttons.remove(data);
            this.visible(!this.canClose());
        };
        return AppBarViewModel;
    })();
    exports.AppBarViewModel = AppBarViewModel;
})

from
///<reference path="../knockout.d.ts" />
///<reference path="../require.d.ts" />

declare var ko: any;

    export class AppBarViewModel {

        visible = ko.observable(true);
        buttons = ko.observableArray([]);

        enableContext = ko.observable(true);
        addButton(data) {
            this.buttons.push(data);
            this.visible(data.blockHide && data.blockHide == true);
        }
        removeButton(data) {
            this.buttons.remove(data);
            this.visible(!this.canClose());
        }
        canClose = ko.computed(function () {
            //var buttons = self.buttons();
            //ko.utils.arrayForEach(self.buttons(), function () { return });

            var k = ko.utils.arrayFirst(this.buttons(), function (b) { return b.blockHide && b.blockHide == true });
            return k == null;
        });
        constructor() {

        }
    }

A: Yup. Put the viewmodels inside the same module and import that module.
You are currently creating a new module for each viewmodel/class.
Update not working see update 2 If you want to still have multiple files for modules you can merge them into one with the typescript compiler:
tsc AppBarViewModel.ts IdentityViewModel.ts

Then assuming that the files have the same module "ViewModels" inside of them you can import them with:
import vms = module("ViewModels");

Update 2 Merging external modules is currently not supported: https://typescript.codeplex.com/discussions/430782

Also, to your question about external modules in a single file.
  External modules assume that you're using a module loader.  In this
  case, you'd want your modules to be built into separate source files
  so that they can be loaded via the module loader.  Building all the
  modules into one .js file is counter to how these tools work.
I could see wanting to build external modules out of multiple source
  files, though we don't currently support this and might be a good
  feature request for the issue tracker, if it's not there already

Vote for this feature here : https://typescript.codeplex.com/workitem/759

A: What I did was to turn off AMD support in typescript and instead utilize WebEssentials JS bundle to create a single export for requireJS. To do this I have a "_prebundle.fragment.js" and a "_postbundle.fragment.js" and all the TS compiled code in between:
    <file>/js/_prebundle.fragment.js</file>

    <file>/js/file1.js</file>
    <file>/js/file2.js</file>
    <file>/js/file3.js</file>

    <file>/js/_postbundle.fragment.js</file>

This creates the following:
///#source 1 1 /js/_prebundle.fragment.js
// START _PREBUNDLE.FRAGMENT >>

(function(factory){
    // Support module loading scenarios
    if (typeof define === 'function' && define.amd){
        // AMD Anonymous Module
        define(['jquery', 'ga', 'knockout', 'sammy'], factory);
    } else {
        // No module loader (plain <script> tag) - put directly in global namespace
        var global = (window || this);

        global.ma = factory(bootstrap, jQuery, qa, ko, sammy);
    }
})(function($, ga, ko, sammy){
    if (!$) throw new Error('JQuery is a pre-requisite and must be loaded for this component.');
    if (!ga) throw new Error('Google Analytics is a pre-requisite and must be loaded for this component.');
    if (!ko) throw new Error('KnockoutJS is a pre-requisite and must be loaded for this component.');
    if (!sammy) throw new Error('SammyJS is a pre-requisite and must be loaded for this component.');

// END _PREBUNDLE.FRAGMENT
///#source 1 1 /js/File1.js
var ma;
(function (ma) {
    var File1 = (function() {
        function File1() {
            // blah
        }

        return File1;
    })();

    ma.File1 = File1;
})(ma || (ma = {}));
//# sourceMappingURL=file1.js.map

///#source 1 1 /js/_postbundle.fragment.js
// START _POSTBUNDLE.FRAGMENT >>

    return ma;
});

// END _POSTBUNDLE.FRAGMENT

This produces a single require element and also supports being used without RequireJS, which is nice for when I want to make it public. Additionally, I can bundle up multiple different flavors of my code for use on other pages. Not sure if there's a better way to do this, but this works for me...


text:
Q: Input equations into Matlab for Simulink Function I am currently working on an assignment where I need to create two different controllers in Matlab/Simulink for a robotic exoskeleton leg. The idea behind this is to compare both of them and see which controller is better at assisting a human wearing it. I am having a lot of trouble putting specific equations into a Matlab function block to then run in Simulink to get results for an AFO (adaptive frequency oscillator). The link has the equations I'm trying to put in and the following is the code I have so far:
    function [pos_AFO, vel_AFO, acc_AFO, offset, omega, phi, ampl, phi1] = LHip(theta, eps, nu, dt, AFO_on)
            t = 0;
            % syms j
            % M = 6;
            % j = sym('j', [1 M]);

            if t == 0
                omega = 3*pi/2;
                theta = 0;
                phi = pi/2;
                ampl = 0;
            else
                omega = omega*(t-1) + dt*(eps*offset*cos(phi1));
                theta = theta*(t-1) + dt*(nu*offset);
                phi = phi*(t-1) + dt*(omega + eps*offset*cos(phi*core(t-1)));
                phi1 = phi*(t-1) + dt*(omega + eps*offset*cos(phi*core(t-1)));
                ampl = ampl*(t-1) + dt*(nu*offset*sin(phi));
                offset = theta - theta*(t-1) - sym(ampl*sin(phi), [1 M]);
            end

            pos_AFO = (theta*(t-1) + symsum(ampl*(t-1)*sin(phi*        (t-1))))*AFO_on; %symsum needs input argument for index M and range
            vel_AFO = diff(pos_AFO)*AFO_on;
            acc_AFO = diff(vel_AFO)*AFO_on;
    end

https://www.pastepic.xyz/image/pg4mP
Essentially, I don't know how to do the subscripts, sigma, or the (t+1) function. Any help is appreciated as this is due next week

A: You are looking to find the result of an adaptive process therefore your algorithm needs to consider time as it progresses. There is no (t-1) operator as such. It is just a mathematical notation telling you that you need to reuse an old value to calculate a new value.
omega_old=0;
theta_old=0;
% initialize the rest of your variables

for [t=1:N]
   omega[t] = omega_old +  % here is the rest of your omega calculation
   theta[t] = theta_old +  % ...

   % more code .....

   % remember your old values for next iteration
   omega_old = omega[t];
   theta_old = theta[t];
end

I think you forgot to apply the modulo operation to phi judging by the original formula you linked. As a general rule, design your code in small pieces, make sure the output of each piece makes sense and then combine all pieces and make sure the overall result is correct.


text:
Q: how to combine two variables in jquery I have two variables like :
<script language="javascript" type="text/javascript">
    var count = 1;
    calc_my_project_ + count = Math.round( count * 268 / 100); // It shoud be calc_my_project_1 and next time it shoud be calc_my_project_2

    count += count + 1;
</script>

At now result is calc_my_project_ + count . how can I do this ?
EDIT : This is my main code :
<script language="javascript" type="text/javascript">
    var count = 1;
    var str = 'calc_my_project_';
    var str2 = 'my_pro_';
    var result = str + count;
    result = Math.round( @Html.DisplayFor(x => item.ProgressPercent) * 268 / 100);
    var secresult = str2 + count;
    secresult = "-" + result + "px 0";

    var jq3 = jQuery.noConflict();
    jq3(document).ready(function () {
        jq3("#bar-pro-@barcount1st").css({ "background-position": secresult });
        if (@Html.DisplayFor(x => item.ProgressPercent) == 100) {
            jq3("#bar-pro-@barcount1st").css({ "background-image": "none" });
            jq3("#bar-pro-@barcount2st").css({ "background-image": "none" });
        };
    });
    count++;
</script>

result and secresult return a fixed value I don't want to be like this .

A: You can do it like:
var myObj = {};
myObj['my_project_' + count] = 'some value';

count++;

A: try something like this
<script language="javascript" type="text/javascript">
    var count = 1;
    var str = 'calc_my_project_';

    var result = str + count = Math.round( count * 268 / 100);

    count += count + 1;
</script>

A: You could store your calc_my_project_ variable in an array an iterate through it each time
obj = new Array(calc_my_project_1, calc_my_project2, ...);
obj[0] = 1;
obj[1] = 2;
...

A: Use an array.
var myCount = new Array();
var count = 0;
$("#click").click(function() {
   myCount[count] = Math.round( count * 268 / 100);
    console.log(count + ' - ' + myCount[count]);
    count++;
});

Fiddle: http://jsfiddle.net/johnkoer/yyakv/1/

A: If you want to set "global" variables, you can use the global variable container window :
window["calc_my_project_"+ count ] = Math.round( count * 268 / 100);

alternatively you can use eval but there are more risk involved :
eval ("calc_my_project_"+ count +"= Math.round( count * 268 / 100)") ;

else, if you don't need, global variables, you can use the solution provided by Baszz


text:
Q: Does the LinkedIn API cover University pages? Title pretty much says it all. Is there any way to access the feed/ updates of a university page on LinkedIn?
The only mention of university on their developer site is their Alumni widget.

A: In one word: No.
With all the currently available endpoints of the API, there seems to be no endpoint for University pages. You can check all the available endpoints here.
I tried accessing the University page by using the Company page endpoint and some random University's id, and as expected, it does not work. You can test it on your own at the link mentioned above.
So, either the University page needs to be changed to a Company page or there is no scope from the available API to get the data.
Even if the page is a company page, you will need the admin permission to access it. You can check all the details related to company page here.


text:
Q: How can I copy data from one MongoDB collection to another using jenssegers I wanted to copy specific attributes from all documents in one MongoDB collection to another. I am using Lumen (v6.0.2) with jenssegers/mongodb(3.6.0). Is it possible to do it without looping through the documents?

A: Figured out. Assuming that I wanted to copy 2 attributes, ID and updated_at from sourcecollection to targetcollection
DB::collection('sourcecollection')->raw(function($collection) {
 return $collection->aggregate(array(
 array(
 '$project' => array(
  'ID' => 1,
  'updated_at' => 1
 )),
 array(
  '$out' => 'targetcollection'
 ),
 )
 );
}
 );