text:
Q: LongClick to Delete List Item (Using Fragments in Master-Detail) I've created a Master-Detail Flow application, and I'm using all of the default files that Eclipse/Android creates. I created a project using the template, and haven't modified anything in it, except to add the methods discussed below for deleting the item.
I need to implement an onItemLongClickListener so that when I longpress an item in the list, that item is deleted. I don't want an alert or a confirmation or to select multiple items, I just want the one I longclick to go away.
I've found several tutorials on the subject, but my issue is that they aren't using fragments, so I'm getting a bit confused about what methods go where. (This is the one I'm mostly working with: AndroidForBeginners)
If I'm understanding correctly, I should only be using the ItemListActivity and ItemListFragment. I understand that methods in the Fragment will be called in the Activity (such as the default onItemSelected that comes with the template). I understand that the removeItemFromList method (from the linked tutorial) removes the item from the array and notifies the adapter to update the list. My problem is, I don't know where the array and adapter are within the Master-Detail fragments and activities. There's an ArrayList in the DummyContent, so I thought maybe if I call removeItem in the fragment, then send it to the Activity, then call it from the DummyContent class it would work. But it doesn't, and I'm stuck.
Any advice would be much appreciated!
As requested, here is the code I'm currently using. As I said, just the default android template.
ItemListActivity.java
package Andrea.deletelistitem;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

/**
 * An activity representing a list of Items. This activity
 * has different presentations for handset and tablet-size devices. On
 * handsets, the activity presents a list of items, which when touched,
 * lead to a {@link ItemDetailActivity} representing
 * item details. On tablets, the activity presents the list of items and
 * item details side-by-side using two vertical panes.
 *

 * The activity makes heavy use of fragments. The list of items is a
 * {@link ItemListFragment} and the item details
 * (if present) is a {@link ItemDetailFragment}.
 *

 * This activity also implements the required
 * {@link ItemListFragment.Callbacks} interface
 * to listen for item selections.
 */
public class ItemListActivity extends FragmentActivity
        implements ItemListFragment.Callbacks {

    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet
     * device.
     */
    private boolean mTwoPane;

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

        if (findViewById(R.id.item_detail_container) != null) {
            // The detail container view will be present only in the
            // large-screen layouts (res/values-large and
            // res/values-sw600dp). If this view is present, then the
            // activity should be in two-pane mode.
            mTwoPane = true;

            // In two-pane mode, list items should be given the
            // 'activated' state when touched.
            ((ItemListFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.item_list))
                    .setActivateOnItemClick(true);
        }

        // TODO: If exposing deep links into your app, handle intents here.
    }

    /**
     * Callback method from {@link ItemListFragment.Callbacks}
     * indicating that the item with the given ID was selected.
     */
    @Override
    public void onItemSelected(String id) {
        if (mTwoPane) {
            // In two-pane mode, show the detail view in this activity by
            // adding or replacing the detail fragment using a
            // fragment transaction.
            Bundle arguments = new Bundle();
            arguments.putString(ItemDetailFragment.ARG_ITEM_ID, id);
            ItemDetailFragment fragment = new ItemDetailFragment();
            fragment.setArguments(arguments);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.item_detail_container, fragment)
                    .commit();

        } else {
            // In single-pane mode, simply start the detail activity
            // for the selected item ID.
            Intent detailIntent = new Intent(this, ItemDetailActivity.class);
            detailIntent.putExtra(ItemDetailFragment.ARG_ITEM_ID, id);
            startActivity(detailIntent);
        }
    }
}

ItemListFragment.java
package Andrea.deletelistitem;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import Andrea.deletelistitem.dummy.DummyContent;

/**
 * A list fragment representing a list of Items. This fragment
 * also supports tablet devices by allowing list items to be given an
 * 'activated' state upon selection. This helps indicate which item is
 * currently being viewed in a {@link ItemDetailFragment}.
 *

 * Activities containing this fragment MUST implement the {@link Callbacks}
 * interface.
 */
public class ItemListFragment extends ListFragment {

    /**
     * The serialization (saved instance state) Bundle key representing the
     * activated item position. Only used on tablets.
     */
    private static final String STATE_ACTIVATED_POSITION = "activated_position";

    /**
     * The fragment's current callback object, which is notified of list item
     * clicks.
     */
    private Callbacks mCallbacks = sDummyCallbacks;

    /**
     * The current activated item position. Only used on tablets.
     */
    private int mActivatedPosition = ListView.INVALID_POSITION;

    /**
     * A callback interface that all activities containing this fragment must
     * implement. This mechanism allows activities to be notified of item
     * selections.
     */
    public interface Callbacks {
        /**
         * Callback for when an item has been selected.
         */
        public void onItemSelected(String id);
    }

    /**
     * A dummy implementation of the {@link Callbacks} interface that does
     * nothing. Used only when this fragment is not attached to an activity.
     */
    private static Callbacks sDummyCallbacks = new Callbacks() {
        @Override
        public void onItemSelected(String id) {
        }
    };

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public ItemListFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // TODO: replace with a real list adapter.
        setListAdapter(new ArrayAdapter<DummyContent.DummyItem>(
                getActivity(),
                android.R.layout.simple_list_item_activated_1,
                android.R.id.text1,
                DummyContent.ITEMS));
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // Restore the previously serialized activated item position.
        if (savedInstanceState != null
                && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
            setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // Activities containing this fragment must implement its callbacks.
        if (!(activity instanceof Callbacks)) {
            throw new IllegalStateException("Activity must implement fragment's callbacks.");
        }

        mCallbacks = (Callbacks) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();

        // Reset the active callbacks interface to the dummy implementation.
        mCallbacks = sDummyCallbacks;
    }

    @Override
    public void onListItemClick(ListView listView, View view, int position, long id) {
        super.onListItemClick(listView, view, position, id);

        // Notify the active callbacks interface (the activity, if the
        // fragment is attached to one) that an item has been selected.
        mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mActivatedPosition != ListView.INVALID_POSITION) {
            // Serialize and persist the activated item position.
            outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
        }
    }

    /**
     * Turns on activate-on-click mode. When this mode is on, list items will be
     * given the 'activated' state when touched.
     */
    public void setActivateOnItemClick(boolean activateOnItemClick) {
        // When setting CHOICE_MODE_SINGLE, ListView will automatically
        // give items the 'activated' state when touched.
        getListView().setChoiceMode(activateOnItemClick
                ? ListView.CHOICE_MODE_SINGLE
                : ListView.CHOICE_MODE_NONE);
    }

    private void setActivatedPosition(int position) {
        if (position == ListView.INVALID_POSITION) {
            getListView().setItemChecked(mActivatedPosition, false);
        } else {
            getListView().setItemChecked(position, true);
        }

        mActivatedPosition = position;
    }
}

DummyContent.java
package Andrea.deletelistitem.dummy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Helper class for providing sample content for user interfaces created by
 * Android template wizards.
 *

 * TODO: Replace all uses of this class before publishing your app.
 */
public class DummyContent {

    /**
     * An array of sample (dummy) items.
     */
    public static List<DummyItem> ITEMS = new ArrayList<DummyItem>();

    /**
     * A map of sample (dummy) items, by ID.
     */
    public static Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();

    static {
        // Add 3 sample items.
        addItem(new DummyItem("1", "Item 1"));
        addItem(new DummyItem("2", "Item 2"));
        addItem(new DummyItem("3", "Item 3"));
    }

    private static void addItem(DummyItem item) {
        ITEMS.add(item);
        ITEM_MAP.put(item.id, item);
    }

    /**
     * A dummy item representing a piece of content.
     */
    public static class DummyItem {
        public String id;
        public String content;

        public DummyItem(String id, String content) {
            this.id = id;
            this.content = content;
        }

        @Override
        public String toString() {
            return content;
        }
    }
}

This is the method from the tutorial:
protected void removeItemFromList(int position) {
final int deletePosition = position;

AlertDialog.Builder alert = new AlertDialog.Builder(
        MainActivity.this);

alert.setTitle("Delete");
alert.setMessage("Do you want delete this item?");
alert.setPositiveButton("YES", new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TOD O Auto-generated method stub

            // main code on after clicking yes
            arr.remove(deletePosition);
            adapter.notifyDataSetChanged();
            adapter.notifyDataSetInvalidated();
    }
});
alert.setNegativeButton("CANCEL", new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
        dialog.dismiss();
    }
});

alert.show();
}

This is the method with my modifications, to remove the confirmation alert:
protected void removeItemFromList(int position) {
    arr.remove(position);
    adapter.notifyDataSetChanged();
    adapter.notifyDataSetInvalidated();
}

In this method, I think ITEMS from the DummyContent would replace the arr array, because it's an ArrayList. I'm not sure about the adapter, though.

A: There's a method on any Fragment called onActivityCreated You want to @Override that method.
Then, inside it, using getListView() you can attach an onLongItemClickListener().
Like so:
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
          @Override
          public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //Here you implement your code. Basically delete an item from
                // the underlying data structure of your adapter, and then...
                setListAdapter(.....); //re-set the list adapter.
                return false;

          }
});


text:
Q: Rasterization tools for vector datasets with styles I have hundreds of Personal Geodatabases and I want to create one georeferenced TIFF for each one. Each PGDB has the same feature classes ('CotourLines', 'Hidrography', etc) for what I have some layers with the styles. The style (or symbol) for each feature could depend on many fields. And the final TIFF files must have a fixed pixel size.
I was searching for tools I can use. From ArcToolBox there are some tools like 'Feature to Raster' but doesn't fit to my requirements.
Maybe should I make an automation?
Having an MXD containing the layers with the styles, loading the feature classes of each PGDB, and using 'Export Map' to create the TIFF file?
This is the only solution I have in mind.
I think there should be an straightforward solution I could use, maybe with an ArcGis extension. I could export the PGDB to ShapeFiles (or a PostGIS database) and have the styles in SLD files.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dictionary mutability issue while adding new key and value to the dictionary in python I'm trying to find the longest increasing subsequence from the python list i'm passing. The final dictionary structure should look something like this:
Expected structure
subsequence_dict={ 0:[15], 1:[15,27], 2:[14],3:[15,27,38],4:[14,26],5:[15,27,38,55],6:[15,27,38,46],7:[15, 27, 38, 55, 65, 85]}

Output:
{0: [15, 27, 38, 55, 65, 85], 1: [15, 27, 38, 55, 65, 85], 2: [14, 26, 46], 3: [15, 27, 38, 55, 65, 85], 4: [14, 26, 46], 5: [15, 27, 38, 55, 65, 85], 6: [14, 26, 46], 7: [15, 27, 38, 55, 65, 85], 8: [15, 27, 38, 55, 65, 85]}

As looking at the key 0 in my output it looks there is some mutability issue.
For every value of i in the main function there should be a new key in the dict which has value as list coming from longest_subsequence function.
from copy import deepcopy
def longest_subsequence(dict_elent,subsequence_dict):
    """

    :param dict_elent: Dictionary element to which the longest list last element to be compared
    :param subsequence_dict:
    :return:  List
    """
    x=subsequence_dict.values()
    sorted_list = sorted(x, reverse=True)
    flag=False
    for sublist in sorted_list:
        if sublist[-1]<dict_elent:
            sublist.append(dict_elent)
            flag=True
            break
    if flag==True:
        return  sublist
    else:
        return [dict_elent]

def main(d,subsequence_dict):
    for i in range(len(d)):
        if i==0 :
            subsequence_dict[i]=[d[i]]
        else:
            subsequence_dict.update({i: longest_subsequence(d[i],subsequence_dict)})

if __name__ == '__main__':
    d=[15,27,14,38,26,55,46,65,85]
    subsequence_dict={}
    main(d,subsequence_dict)
    print(subsequence_dict)


text:
Q: how can I make my interstitial adMob ad show overtime a button is clicked Right now it only shows the full page ad one time. When I go back and press the button again it does not show. I would like it to show overtime my button is clicked. I have my AdMob hooked up to my Firebase project.
class FirstViewController: UIViewController, UIAlertViewDelegate {

var interstitial: GADInterstitial!

@IBAction func loadAd(_ sender: Any) {

    if (interstitial.isReady){
        interstitial.present(fromRootViewController: self)
    }
}

override func viewDidLoad() {

    interstitial = GADInterstitial(adUnitID: "ca-app-pub-11111111/9758796532")
    let request = GADRequest()
    interstitial.load(request)

    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

A: You need to create GAD request every time.

GADInterstitial is a one time use object. That means once an
  interstitial is shown, hasBeenUsed returns true and the interstitial
  can't be used to load another ad. To request another interstitial,
  you'll need to create a new GADInterstitial object. The best practice,
  as shown above, is to have a helper method to handle creating and
  loading an interstitial.

 @IBAction func loadAd(_ sender: Any) {
         interstitial = GADInterstitial(adUnitID: "ca-app-pub-11111111/9758796532")
        interstitial.delegate = self
        let request = GADRequest()
        interstitial.load(request)

    }

And while loaded successfully you need to present at delegate method
optional func interstitialDidReceiveAd(_ ad: GADInterstitial!){
    if (interstitial.isReady){
           interstitial.present(fromRootViewController: self)
         }
}

optional func interstitialWillDismissScreen(_ ad: GADInterstitial!){
      interstitial.delegate = nil
      interstitial = nil
 }

 optional func interstitialDidFail(toPresentScreen ad: GADInterstitial!){
   interstitial.delegate = nil
   interstitial = nil
  }

More : https://firebase.google.com/docs/admob/ios/interstitial

A: When dismissing the interstitial we have to create and make load request for next interstitial ads.
func interstitialDidDismissScreen(_ ad: GADInterstitial) {
  interstitial = createAndLoadInterstitial()
}

The best place to allocate another interstitial is in the interstitialDidDismissScreen: method on GADInterstitialDelegate so that the next interstitial starts loading as soon as the previous one is dismissed. You may even consider breaking out interstitial initialization into its own helper method:
Source: https://firebase.google.com/docs/admob/ios/interstitial


text: Q: Not able to use inline code editor for zip files in AWS Lambda I have been using the Alexa sdk and was able to edit the code using the online code editor since i loaded the boiler plate -  alexa skills kit sdk. But then  i suddenly needed to use the request module which i cannot directly npm install . So i created the folder structure and uploaded but the problem is i am NOT able to use the inline code editor , if i need to make any small change i ll have to edit the code and upload the whole zip again which is a tedious process if i need to test for small changes and is consuming a lot of time . Please help me find another way. Any help is appreciated . Thanks !


text:
Q: Why Google Map Api Key have 39 chars? Keys always starts from "AIzaSy" (maybe I wrong, but my it's). And next are 33 chars.
As I see they using alphabet, numbers and some special chars. It's about 64 variants per char place. And about 64^33 combinations (keys) ~ 401734511064747568885490523085290650630550748445698208825344 keys.
So why they chooses exactly 39 (6+33) chars?
Why not choose 20 chars or 63 chars?

A: I don't have specific knowledge about how Google Maps API keys are generated, but if you are wondering how this number of characters might make sense from a mathematical point of view, consider this:
Based on observation, a key starts with the 6-character string AIzaSY. If you look closer, you may also find that the 7th character is not completely random. In fact, it seems to often be an upper-case character from the beginning of the alphabet (A, B, C, D...). So this indicates that this character also has some special status, perhaps encoding some additional information. For our purpose, this is not important, but the point is that since this character is clearly not random, it cannot be part of a cryptographically generated key.
So, after this prefix of 7 characters, we have 39 - 7 = 32 characters left. Like you observed, these characters seem to be Base64 encoded. Now, in Base64, each character takes up 6 bits, so we have 32 * 6 = 192 bits (or 24 bytes), which is one of the common standards for the length of keys in cryptography, and provides better security than e.g. 128-bit keys (another standard).


text:
Q: Setting filepaths inside your .rb file when converted into an exe with ocra I've had a lot of trouble getting one my wxruby scripts to use an image file I included in the exe with ocra.  If I didn't have the original image file in the same directory as the exe, the exe wouldn't find the image.
shape = File.join('warning3.png' )

I wanted the script to find the image I included in the exe.

A: In the ocra documentation it mentions Dir.chdir File.dirname($0) but I didn't get what it meant when it was mentioned.
If you need to use say an image file in your script you can make sure it works merely by having this Dir.chdir(File.dirname($0)) line before you try to use any of your images.
For example in my app I'm using an image file and I couldn't get my exe to work if it wasn't in the same dir as the file but with the below it works anywhere so far.
Dir.chdir(File.dirname($0))
shape = File.join('warning3.png' )

I think this sets the script's current directory to the exe's directory inside it?  If I'm wrong please let me know!


text:
Q: Color overlapping in GLBarGraphItem PYQTgraph python I am trying to remove color overlaps that occur while drawing stacked 3d bars using GLBarGraphItem. Here below is my code:
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
import numpy as np
import pyqtgraph as pg
from itertools import groupby
#pg.setConfigOptions(antialias=False)

mainList = [['BM', 'Butterfly', 'E-shop', '1400'],
            ['BM', 'Butterfly', 'Fler', '2450'],
            ['BM', 'Butterfly', 'Holesovice', '2450'],
            ['Climbing presents', 'Ear-rings', 'Holesovice', '136'],
            ['Climbing presents', 'Other jewellery', 'E-shop', '160'],
            ['Climbing presents', 'Other jewellery', 'Other', '112'],
            ['PP', 'Skirts', 'Fler', '1380'],
            ['PP', 'Skirts', 'Holesovice', '1320'],
            ['PP', 'Skirts', 'Sashe', '450'],
            ['PP', 'Bags', 'E-shop', '2500'],
            ['PP', 'Skirts', 'E-shop', '5600'],
            ['PP', 'Dresses', 'Other', '6551'],
            ['Mar', 'Dresses', 'Holesovice', '1000'],
            ['Mar', 'Skirts', 'Holesovice', '3000'],
            ['Mar', 'Ear-rings', 'Holesovice', '2000']]

app = QtGui.QApplication([])
w = gl.GLViewWidget()
w.opts['distance'] = 50
w.showMaximized()
w.setWindowTitle('pyqtgraph example: GLViewWidget')

ax = gl.GLAxisItem()
ax.setSize(10,10,10)
w.addItem(ax)
labels = dict(zip(list(set([x[0] for x in mainList])), [2*i for i,j in enumerate(list(set([x[0] for x in mainList])))]))
shops = dict(zip(list(set([x[2] for x in mainList])), [2*i for i,j in enumerate(list(set([x[2] for x in mainList])))]))
items = dict(zip(list(set([x[1] for x in mainList])), [2*i for i,j in enumerate(list(set([x[1] for x in mainList])))]))

emptyL = []
for index, row in enumerate(mainList):
    label = labels.get(row[0])
    shop = shops.get(row[2])
    if index != 0 and mainList[index-1][0] == mainList[index][0] and mainList[index-1][2] == mainList[index][2]:
        emptyL.append([[label, shop, float(mainList[index-1][3])/1000]])
    else:
        emptyL.append([[label, shop, 0]])

colors = {}
for i in items.keys():
    a = round(5*np.random.rand()*np.random.rand(),2)
    b = round(5*np.random.rand()*np.random.rand(),2)
    c = round(5*np.random.rand()*np.random.rand(),2)
    d = round(5*np.random.rand()*np.random.rand(),2)
    colors[i] = (a,b,c,d)

for index, row in enumerate(emptyL):
    size = np.empty((1,1,3))
    size[...,0:2] = 1
    size[...,2] = float(mainList[index][3])/1000
    bg = gl.GLBarGraphItem(np.array([row]), size)
    bg.setColor(colors[mainList[index][1]])
    w.addItem(bg)

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

Here below is a picture demonstrating problem described above:

I am not sure how this color overlapping occurs. I tried to play around with antialiases without any success. Could anyone suggest where the potential problem could be?

A: In case someone experiences similar issue, it is most likely caused by incorrectly reckoned coordinates for drawing.
After amending the code as follows, it draws everything correctly:
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
import numpy as np
import pyqtgraph as pg

class NestedDict(dict):
    def __getitem__(self, item):
        if item not in self:
            self[item] = NestedDict()
        return super().__getitem__(item)

mainList = [['BM', 'Butterfly', 'E-shop', '1400'],
            ['BM', 'Butterfly', 'Fler', '2450'],
            ['BM', 'Butterfly', 'Holesovice', '2450'],
            ['Climbing presents', 'Ear-rings', 'Holesovice', '136'],
            ['Climbing presents', 'Other jewellery', 'E-shop', '160'],
            ['Climbing presents', 'Other jewellery', 'Other', '112'],
            ['PP', 'Skirts', 'Fler', '1380'],
            ['PP', 'Skirts', 'Holesovice', '1320'],
            ['PP', 'Skirts', 'Sashe', '450'],
            ['PP', 'Bags', 'E-shop', '2500'],
            ['PP', 'Skirts', 'E-shop', '5600'],
            ['PP', 'Dresses', 'Other', '6551'],
            ['Mar', 'Dresses', 'Holesovice', '1000'],
            ['Mar', 'Skirts', 'Holesovice', '3000'],
            ['Mar', 'Ear-rings', 'Holesovice', '2000']]

app = QtGui.QApplication([])
w = gl.GLViewWidget()
w.opts['distance'] = 50
w.showMaximized()
w.setWindowTitle('pyqtgraph example: GLViewWidget')

ax = gl.GLAxisItem()
ax.setSize(10,10,10)
w.addItem(ax)

labels = dict(zip(list(set([x[0] for x in mainList])), [2*i for i,j in enumerate(list(set([x[0] for x in mainList])))]))
shops = dict(zip(list(set([x[2] for x in mainList])), [2*i for i,j in enumerate(list(set([x[2] for x in mainList])))]))
items = dict(zip(list(set([x[1] for x in mainList])), [2*i for i,j in enumerate(list(set([x[1] for x in mainList])))]))

d = NestedDict()

for tag, item, source, qty in mainList:
    d[tag][source][item] = qty

for key, value in d.items():
    for nkey, nvalue in value.items():
        val = []
        for index, nvalue_ in enumerate(nvalue.values()):
            if index == 0:
                val.append(0)
            else:
                val.append(float(list(nvalue.values())[index-1])/1000)
            size = np.empty((1,1,3))
            size[...,0:2] = 1
            size[...,2] = float(list(nvalue.values())[index])/1000
            bg = gl.GLBarGraphItem(np.array([[[labels[key], shops[nkey], sum(val)]]]), size)
            bg.setColor((round(5*np.random.rand()*np.random.rand(),2),
                         round(5*np.random.rand()*np.random.rand(),2),
                         round(5*np.random.rand()*np.random.rand(),2),
                         round(5*np.random.rand()*np.random.rand(),2)))
            w.addItem(bg)

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()


text:
Q: Sorting by unique values of multiple fields in UNIX shell script I am new to unix and would like to be able to do the following but am unsure how.
Take a text file with lines like:
TR=P567;dir=o;day=su;TI=12:10;stn=westborough;Line=worcester
TR=P567;dir=o;day=su;TI=12:10;stn=westborough;Line=lowell
TR=P567;dir=o;day=su;TI=12:10;stn=westborough;Line=worcester
TR=P234;dir=o;day=su;TI=12:10;stn=westborough;Line=lowell
TR=P234;dir=o;day=su;TI=12:10;stn=westborough;Line=lowell
TR=P234;dir=o;day=su;TI=12:10;stn=westborough;Line=worcester

And output this:
TR=P567;dir=o;day=su;TI=12:10;stn=westborough;Line=worcester
TR=P567;dir=o;day=su;TI=12:10;stn=westborough;Line=lowell
TR=P234;dir=o;day=su;TI=12:10;stn=westborough;Line=lowell
TR=P234;dir=o;day=su;TI=12:10;stn=westborough;Line=worcester

I would like the script to be able to find all all the lines for each TR value that have a unique Line value.
Thanks

A: Since you are apparently O.K. with randomly choosing among the values for dir, day, TI, and stn, you can write:
sort -u -t ';' -k 1,1 -k 6,6 -s < input_file > output_file

Explanation:

*

*The sort utility, "sort lines of text files", lets you sort/compare/merge lines from files. (See the GNU Coreutils documentation.)

*The -u or --unique option, "output only the first of an equal run", tells sort that if two input-lines are equal, then you only want one of them.

*The -k POS[,POS2] or --key=POS1[,POS2] option, "start a key at POS1 (origin 1), end it at POS2 (default end of line)", tells sort where the "keys" are that we want to sort by. In our case, -k 1,1 means that one key consists of the first field (from field 1 through field 1), and -k 6,6 means that one key consists of the sixth field (from field 6 through field 6).

*The -t SEP or --field-separator=SEP option tells sort that we want to use SEP — in our case, ';' — to separate and count fields. (Otherwise, it would think that fields are separated by whitespace, and in our case, it would treat the entire line as a single field.)

*The -s or --stabilize option, "stabilize sort by disabling last-resort comparison", tells sort that we only want to compare lines in the way that we've specified; if two lines have the same above-defined "keys", then they're considered equivalent, even if they differ in other respects. Since we're using -u, that means that means that one of them will be discarded. (If we weren't using -u, it would just mean that sort wouldn't reorder them with respect to each other.)


text:
Q: How to run a PHP project on localhost I started learning Php and we have a php project (framework Codeigniter) running on Server. I want to run it locally and understand more the code how it works.
I installed WAMP server and copied the source code file under 'www'. I have created a database with the same name on phpmyadmin and imported the tables from .sql file.
I have changed the database.php to run locally
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'report';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

Then when I put on browser localhost/report,
I receive many errors like this

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: c
Filename: views/pool.php
Line Number: 13
Request method: GET
Request uri: /report/

Many variables are not defined in the views. Should i change something other yet so that the views will be working ? I am new to Php and i have been following many tutorials but i still can't make it work.
Another question please, do i need to install code Igniter too ? or enough wamp and the source code.
Any suggestions please ? Thank you.

A: A PHP Error was encountered
Severity: Notice
Message: Undefined variable: c
Filename: views/pool.php
Line Number: 13
Request method: GET
Request uri: /report/
This error is showing that variable "c" is not defined on line number 13 in views/pool.php, what else you wanted to know, just check that or you can turn the error reporting off to hide all these errors in index.php file in your projects root folder.   just change the ENVIRONMENT constant "production" or "testing"

A: The error is clearly in file views/pool.php, line number 13. That is what you should provide so that we can check what might be wrong.
You are using CodeIgniter, an MVC framework and the error is in one of your views. Bear in mind that views are templates. That means:

*

*You have to mark your variables somehow, to let the template engine know
that you want to output data from your application --same applies for control structures like if/else, for, etc.- In the case of CodeIgniter, it is done with PHP-style codes <? ?>.

*You have to tell your application which data the view will have access to.
If you don't pass that data to the view, it will fail even if you used the
correct syntax. You have to do this in your controller function:
$mydata = ['c' => 'cool!', 'user_id' => 123, ...];
$this->load->view('pool', $mydata);
Go to CodeIgniter's views documentation and you will find a detailed explanation.


text:
Q: Как исправить Message to delete not found? Подскажите, как исправить Message to delete not found, после нажатия на кнопку удалить, текст удаляется, но секунд через 30, появляется вот такая ошибка.

ERROR:asyncio:Task exception was never retrieved
future: <Task finished name='Task-9' coro=<Dispatcher._process_polling_updates() done, defined at F:\1samoe_nuzhnoe\Py__Python\Telegram\PyCharm\Tg_aiogram_ru\aiogram\dispatcher\dispatcher.py:407> exception=MessageToDeleteNotFound('Message to delete not found')>
Traceback (most recent call last):
  File "F:\1samoe_nuzhnoe\Py__Python\Telegram\PyCharm\Tg_aiogram_ru\aiogram\dispatcher\dispatcher.py", line 415, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "F:\1samoe_nuzhnoe\Py__Python\Telegram\PyCharm\Tg_aiogram_ru\aiogram\dispatcher\dispatcher.py", line 235, in process_updates
    return await asyncio.gather(*tasks)
  File "F:\1samoe_nuzhnoe\Py__Python\Telegram\PyCharm\Tg_aiogram_ru\aiogram\dispatcher\handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "F:\1samoe_nuzhnoe\Py__Python\Telegram\PyCharm\Tg_aiogram_ru\aiogram\dispatcher\dispatcher.py", line 256, in process_update
    return await self.message_handlers.notify(update.message)
  File "F:\1samoe_nuzhnoe\Py__Python\Telegram\PyCharm\Tg_aiogram_ru\aiogram\dispatcher\handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "F:/1samoe_nuzhnoe/Py__Python/Telegram/PyCharm/Tg_aiogram_ru/chat_ti1_t2.py", line 49, in handler_text
    await send.delete()
  File "F:\1samoe_nuzhnoe\Py__Python\Telegram\PyCharm\Tg_aiogram_ru\aiogram\types\message.py", line 2986, in delete
    return await self.bot.delete_message(self.chat.id, self.message_id)
  File "F:\1samoe_nuzhnoe\Py__Python\Telegram\PyCharm\Tg_aiogram_ru\aiogram\bot\bot.py", line 2823, in delete_message
    return await self.request(api.Methods.DELETE_MESSAGE, payload)
  File "F:\1samoe_nuzhnoe\Py__Python\Telegram\PyCharm\Tg_aiogram_ru\aiogram\bot\base.py", line 231, in request
    return await api.make_request(await self.get_session(), self.server, self.__token, method, data, files,
  File "F:\1samoe_nuzhnoe\Py__Python\Telegram\PyCharm\Tg_aiogram_ru\aiogram\bot\api.py", line 140, in make_request
    return check_result(method, response.content_type, response.status, await response.text())
  File "F:\1samoe_nuzhnoe\Py__Python\Telegram\PyCharm\Tg_aiogram_ru\aiogram\bot\api.py", line 115, in check_result
    exceptions.BadRequest.detect(description)
  File "F:\1samoe_nuzhnoe\Py__Python\Telegram\PyCharm\Tg_aiogram_ru\aiogram\utils\exceptions.py", line 140, in detect
    raise err(cls.text or description)
aiogram.utils.exceptions.MessageToDeleteNotFound: Message to delete not found

Весь код

#from time import time, gmtime, strftime, sleep
import aiogram
import logging
import math
import os
import time
import asyncio
import aiohttp
import random
from time import sleep
from time import time
from aiogram import Bot, Dispatcher, executor, types
from aiogram.types import CallbackQuery, ReplyKeyboardRemove, ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ChatMember
from aiogram.types import InlineQuery, \
    InputTextMessageContent, InlineQueryResultArticle
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from asyncio import sleep
from contextlib import suppress
from aiogram.utils.exceptions import (MessageToEditNotFound, MessageCantBeEdited, MessageCantBeDeleted, MessageToDeleteNotFound)
#from data import config

API_TOKEN = 'moi_token'
logging.basicConfig(level=logging.INFO)

bot = Bot(token=API_TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
dp.middleware.setup(LoggingMiddleware())

btn_send_delete = InlineKeyboardButton('Удалить', callback_data='message_delete')
btn_send_markup = InlineKeyboardMarkup().add(btn_send_delete)

@dp.callback_query_handler(lambda c: c.data == 'message_delete')
async def dell_callback(callback: types.CallbackQuery):
    await callback.answer('Удалено')
    await bot.delete_message(chat_id=callback.message.chat.id, message_id=callback.message.message_id)

@dp.message_handler(content_types=["text"])
async def handler_text(message):
    menu = types.InlineKeyboardMarkup(row_width=1)
    item2 = types.InlineKeyboardButton(" Прочитать", callback_data='exit_to_prochitat')
    menu.add(item2)
    for i in range(1):
        send = await message.reply("Здравствуйте, {0.first_name}. \n\nОбязательно нажмите кнопку <b>->Прочитать.</b>".format(message.from_user, bot.get_me()), disable_notification=True, disable_web_page_preview=True, parse_mode='html', reply_markup=menu)
        await asyncio.sleep(30)
        await send.delete()
        break

@dp.callback_query_handler(lambda call: True)
async def podpishis_callback(call: types.CallbackQuery):
    chat_id = call.message.chat.id
    message_id = call.message.message_id
    if call.message:
        if call.data == 'exit_to_prochitat':
            send = await bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="\n\nЗдесь весь текст".format(call.message.from_user, bot.get_me()), parse_mode='html', reply_markup=btn_send_markup)
            await asyncio.sleep(20)
            await send.delete()

if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)


text:
Q: Why am I not getting floating point numbers? I am writing a very simple practice script (I am a novice) that will take in values of a, b, c, and x and plug them in to a quadratic function.
For some reason I am not getting floating point numbers into my equation.  I have tried adding float() to more places than I feel I need to, and yet I'm still getting fixed point numbers.
Note: I ended up with this many float inputs after trying several ways; this is merely the last iteration.  Here is my code:
def quadratic(a, b, c, x):

    return float(a*x**2 + b*x + c)

print "Let's find the output value for the values in a quatratic function..."
print "Our formula is ax^2 + bx + c = ?"

a = float(raw_input("What value for 'a'?"))

b = float(raw_input("What value for 'b'?"))

c = float(raw_input("What value for 'c'?"))

x = float(raw_input("What value for 'x'?"))

solution = float(quadratic(a, b, c, x))

print "(%d)(%d)^2 + (%d)(%d) + %d = %d" % (a, x, b, x, c, solution)

and here is my output (after entering decimal values for a, b, c, x).
Let's find the output value for the values in a quatratic function...

Our formula is ax^2 + bx + c = ?

What value for 'a'?.75

What value for 'b'?.44

What value for 'c'?.3467

What value for 'x'?.77

(0)(0)^2 + (0)(0) + 0 = 1

Clearly this is user error on my part.  Can someone provide insight as to why I'm getting fixed point numbers?  Thanks!

A: As several other users commented, the issue is not with your calculation, but with the formatting of your output string. The %d formatting sequence tells Python to convert the relevant value to an integer before turning it into a string. Using a different code would make it work the way you expect.
The most obvious code to use would be %f, which indicates that you want a float value. You can add some extra characters if you want the float to round to a particular number of decimal places (rather than the default which may be very long). Using %.4f for instance would round at four decimal places, which might be a good choice since that's the maximum number of significant digits you used in your example inputs.
Another option would be to use %s, which means you want to convert the argument directly to a string using the builtin str function. This doesn't allow the nicer rounding options of %f, but it will work for almost any type (even non-numeric ones).
I'd actually go further and recommend that you use an alternative formatting method entirely. The str.format method allows you to do some more sophisticated formatting than the % operator does, which is a useful in this situation since you want to repeat the same x value twice. Using an appropriate format string with str.format lets you duplicate the value in the output without needing to repeat it in the arguments. Here's one way of doing it using keyword arguments to str.format:
print "({a:.4f})({x:.4f})^2 + ({b:.4f})({x:.4f}) + {c:.4f} = {solution:.4f}".format(
    a=a, b=b, c=c, solution=solution, x=x
)

If you were using Python 3.6+ (which I'd also recommend for a wide variety of other reasons), you could use what are known as "F-strings" to do the same formatting as the call above, but without needing to explicitly call format and pass in a bunch of variables as keyword arguments with their own names. When you prefix the first quotation mark with an f, Python will do the formatting for you based on the variables in your current namespace:
print(f"({a:.4f})({x:.4f})^2 + ({b:.4f})({x:.4f}) + {c:.4f} = {solution:.4f}")


text:
Q: Why is softKeys() deprecated in Guava 10? As of Guava 10, MapMaker.softKeys is deprecated, and the corresponding method doesn't exist in CacheBuilder.
Why was this change made? What do I need to do with existing code that use it?

A: Here is my attempt of explanation of the issue (a little more complete to Chris' response)
http://groups.google.com/group/guava-discuss/browse_thread/thread/764af1e627d6fa0e?pli=1

A: I wrote the question because, initially, I did genuinely wonder why (as I had existing code that used softKeys). However, the reason was obvious on reflection and I decided to post it here, in case someone else also uses softKeys and was wondering the same thing.
In short, the reason was that softKeys never made any sense in the first place. Thus, its initial inclusion was in itself a mistake, one which the Guava developers are rectifying via deprecation.
In general, you use soft references if you want the object to stick around for a little after all the strong references are gone; in contrast, with weak references, the object usually gets collected soon once there are no strong or soft references left. This is useful for cached values that you want to hold on to temporarily, so that a lookup using the corresponding key will "revive" a strong reference for the value.
However, this behaviour doesn't make any sense for keys:

*

*Since softKeys and weakKeys maps use an identity-based lookup, the only way to get at an entry of interest is to posess a strong reference to its key.† Thus, once there are no strong key references left, the entry is effectively dead (with no possibility of revival).

*The only practical difference between softKeys and weakKeys is how long an entry remains in the map after all the strong references to its key are gone. Since such entries are dead anyway, using softKeys instead of weakKeys only delays the entry's eviction, for no good reason.

Thus, most times when coming across code that uses softKeys, a much more suitable replacement is weakKeys.
† I am not considering the case of fetching the entry via iteration, or anything other than key-based lookup, since maps are primarily about key-based operations.


text:
Q: Remove Edit Delete Button When Exporting GridView To Excel I Have GridView in ASP.Net application with AutoGenerateDeleteButton & AutoGenerateEditButton Set to True. I want when exporting gridview to excel to not show these button in excel sheet. My export code below:
    Private Sub ExportGridView()
    Dim attachment As String = "attachment; filename=FileName.xls"
    Response.ClearContent()
    Response.AddHeader("content-disposition", attachment)
    Response.ContentType = "application/ms-excel"
    Dim sw As New IO.StringWriter
    Dim frm As HtmlForm = New HtmlForm()
    Page.EnableViewState = False
    Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
    frm.Attributes("runat") = "server"
    Controls.Add(frm)

    gvResults.AllowPaging = False
    gvResults.AllowSorting = False
    BindGrid()

    gvResults.DataBind()
    gvResults.Columns(14).Visible = False
    gvResults.Columns(15).Visible = False
    gvResults.Columns(16).Visible = False
    frm.Controls.Add(gvResults)
    frm.RenderControl(htw)
    Response.Write(sw.ToString())
    Response.End()
End Sub

A: After seraching i came up with this
protected void Button1_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment;filename=User.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    using (StringWriter sw = new StringWriter())
    {
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        GridView1.AllowSorting = false;
        GridView1.Columns[14].Visible = false;
        GridView1.Columns[15].Visible = false;
        GridView1.Columns[16].Visible = false;
        BindGird();
        GridView1.HeaderRow.BackColor = Color.White;
        foreach (TableCell cell in GridView1.HeaderRow.Cells)
        {
            cell.BackColor = GridView1.HeaderStyle.BackColor;
        }
        foreach (GridViewRow row in GridView1.Rows)
        {
            row.BackColor = Color.White;
            foreach (TableCell cell in row.Cells)
            {
                if (row.RowIndex % 2 == 0)
                {
                    cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
                }
                else
                {
                    cell.BackColor = GridView1.RowStyle.BackColor;
                }
                cell.CssClass = "textmode";
            }
        }

        GridView1.RenderControl(hw);

        //style to format numbers to string
        string style = @"<style> .textmode { } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();

        GridView1.Dispose();
    }
}
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

and on aspx page make change like
<%@ Page Title="" Language="C#" EnableEventValidation="false"%>

in vb i guess it look like this
 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    Response.Clear
    Response.Buffer = true
    Response.AddHeader("content-disposition", "attachment;filename=User.xls")
    Response.Charset = ""
    Response.ContentType = "application/vnd.ms-excel"
    Dim sw As StringWriter = New StringWriter
    Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
    GridView1.AllowPaging = false
    GridView1.AllowSorting = false
    GridView1.Columns(14).Visible = false
    GridView1.Columns(15).Visible = false
    GridView1.Columns(16).Visible = false
    BindGird
    GridView1.HeaderRow.BackColor = Color.White
    For Each cell As TableCell In GridView1.HeaderRow.Cells
        cell.BackColor = GridView1.HeaderStyle.BackColor
    Next
    For Each row As GridViewRow In GridView1.Rows
        row.BackColor = Color.White
        For Each cell As TableCell In row.Cells
            If ((row.RowIndex Mod 2)  _
                        = 0) Then
                cell.BackColor = GridView1.AlternatingRowStyle.BackColor
            Else
                cell.BackColor = GridView1.RowStyle.BackColor
            End If
            cell.CssClass = "textmode"
        Next
    Next
    GridView1.RenderControl(hw)
    'style to format numbers to string
    Dim style As String = "<style> .textmode { } </style>"
    Response.Write(style)
    Response.Output.Write(sw.ToString)
    Response.Flush
    Response.End
    GridView1.Dispose
End Sub

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)

End Sub

.aspx page is like this
<%@ Page Title="" Language="C#" EnableEventValidation="false"%>

A: The solution is to set them false when exporting:
    gvResults.AllowPaging = False
    gvResults.AllowSorting = False
    gvResults.AutoGenerateEditButton = False
    gvResults.AutoGenerateDeleteButton = False
    BindGrid()


text:
Q: Relocate a library folder Out of the (Win7) box, the Public Pictures library points to C:\Users\Public\Pictures. I would like to reset that so it resolves to a secondary harddrive.

A: Are you talking about the Pictures folder when you open a new windows explorer window?
If so, open the windows explorer and:

*

*Right click on Pictures

*

*Select Properties

*

*Click on Include a folder..

*

*Add the folder you wish to be used

*

*Select that folder in the Library locations: box

*Click on Set save location

*

*You can also remove the other given folders if you wish

A: Open C:\Users\Public\ in Windows Explorer, right click on the Public Pictures folder and select Properties.
Inside of the Properties window, select the Location tab. Here you can specify the location the folder should be stored in.

A: Open your Windows Explorer. Right click on the "Pictures" Library, and hit Properties. Once it opens, you will see a list of folders that can be used. Hit the include a folder button, then navigate to the folder you wish to use. I tested this myself, using the Video's folder


text:
Q: Как получить больше 1000 людей, лайкнувших пост, через VK API? Пытаюсь получить всех пользователей, кто поставил лайк под записью, через likes.getList. Но есть ограничение: получить разом можно только 1000 человек. А как получить всех пользователей, если таковых является, например, 3500?
Вот так я получаю список первой 1000 лайкнувших:
$res = file_get_contents('https://api.vk.com/method/likes.getList?type=post&owner_id=-1111&item_id=111&extended=1&count=1000&offset=0');
$resp = json_decode($res, true);
foreach($resp['response']['items'] as $val) {
    echo $val['first_name'] . "
\n";
}

A: Схематично (параметр offset описан в документации):
offset = 0;
while( likes.getList(type, owner_id, item_id, count, offset) != ERROR )
{
    users = [сколько_юзеров_получили];
    if( users == 0 )
    {
        /* всё, больше юзеров нет */
        break;
    }
    offset += users;
}

A: Небольшая функция, которая работает рекурсивно, каждый раз смещая параметр offset на нужную величину (на offset в запросе + количество уже выбранных юзеров count) пока не придет пустой ответ. Это значит, что пора обрывать рекурсию.
Однако может еще прийти ответ error вместо response. Но эта обработка на вашей совести))
Еще также указывайте версию API, а то может вернуть не те данные, которые ожидаете или вообще ошибку вернуть.
$count = 1000;
$offset = 0;
$apiVersion = 5.60;
$result = [];

getLikesData($result, $count, $offset, $apiVersion);

function getLikesData(&$output, $count, $offset, $apiVersion) {
    $query = 'https://api.vk.com/method/likes.getList?type=post&owner_id=-1111&item_id=111&extended=1&friends_only=0&v='.$apiVersion.'&count='.$count.'&offset='.$offset;
    $resp = json_decode(file_get_contents($query), true);

    if (!$resp['response'])
        return;

    $items = $resp['response']['items'];

    if (empty($items))
        return;

    foreach ($items as $item) {
        $output[] = $item;
    }

    getLikesData($output, $count, $offset + $count, $apiVersion);
}

echo '
';
print_r($result);
echo '
';

В функции находится цикл для заполнения результирующего массива по порядку. Если вместо этого воспользоваться array_push, то будет отрабатывать быстрее. Однако в результирующем наборе будет массив массивов.
Это я к чему... Выбирайте что нужно: меньшая скорость, но по порядку или большая скорость, но потом при выводе придется организовывать двойной цикл.


text:
Q: Create a shortcut for Notepad++ to reopen a closed tab? To reopen a closed tab in Notepad++ you press ALT+F&1. I was wondering if there was a way to make a macro or program to do this so that I can press link it to the shortcut CTRL+SHIFT+T instead, which is a universal reopen closed tab shortcut I'm used to.
If anyone could tell me how to make a simple program that does that, and that I could then link to Notepad++ to create a shortcut with, that would teach me a lot and help.
Thank you for reading

A: I have successfully tested the following solution: define this AutoHotKey macro:
SendMode Input                ;just to set up preferred method of sending hotkeys
SetTitleMatchMode, RegEx      ;from now on, windows titles are matched by regex

#IfWinActive Notepad\+\+      ;(open block) the following hotkeys work only in N++
+^t::Send !f1                 ;desired hotkey: Ctrl+Shift+T sends Alt+F, 1
^w::Send ^{F4}                ;bonus: Ctrl+W sends Ctrl+F4 (close file convention)
#IfWinActive                  ;(close #IfWinActive block)

do not forget to run AutoHotKey as administrator.
Using the AHK you can achieve many useful things in N++ and all other applications.

A: As of now, the shortcut CTRL+SHIFT+T is already the default for reopen closed tabs.
You can always use the ShortCut Mapper :


text:
Q: after how many days will there be closest to $10$ percent water left in the tank? a large tank filled with water is to be emptied by removing half of the water present in it every day, after how many days will there be closest to $10$ percent water left in the tank?
okay what I understood here: suppose the tank is filled $100%$ percent, then after one day it is left with $50$ percent then number of days left with $10$ percent water will be $1/2\times 10=5$ days?

A: Hint:
After 1 day the tank will be $\frac{1}{2}$ or 50% full.
After 2 days the tank will be $\frac{1}{4}$ or 25% full
Can you see a pattern.

A: HINT:
After $n$th day, the remaining water will be  $$\left(1-\sum_{1\le r\le n}\frac1{2^r}\right)\cdot100\%=\frac1{2^n}\cdot100\%$$

A: In this case, by far the easiest approach is simply to calculate the amount of water left after 1,2,3,4,... days and see which of the numbers is closest to 10%. (After 4 days there will be less than 10% left because $2^4>10$, so the answer cannot be more than 4).


text:
Q: Post Form After Server Code Execution I have created a Webform which will be posted to another Webform after executing the server side code(C#).
I want to execute server code and based on the result of that I want to post the Webform to another Webform otherwise Webform should not be posted.
So, What should i do to achieve the above result?
Thanx in advance.

A: Do you mean redirect to another page?
If so:
In your Page_Load event use the following:
var basedResult = DoMyServerCode();

if (basedResult)
{
   Response.Redirect("~/YourOtherPage.aspx");
}
else
{
   // Load this forms data.
}

Added
Passing values between page (MSDN)


text:
Q: git shows that I deleted all the files in my repo and staged them for commit after I did a git pull. Why? Here's what I did:
$ git pull
remote: Counting objects: 446, done.
remote: Compressing objects: 100% (372/372), done.
remote: Total 383 (delta 280), reused 0 (delta 0)
Receiving objects: 100% (383/383), 652.75 KiB | 381 KiB/s, done.
Resolving deltas: 100% (280/280), completed with 43 local objects.
Fast-forward
<list of files and summary of changes>

Now when I typed git status, git shows me that I deleted ALL the files in my repo and that I staged them for commit. It also shows me ALL the files as untracked.
$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   deleted:    ....
#   deleted:    ....
#   deleted:    ....
<a list of all files in the repo>
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
<a list of all top-level files and folders in the repo>

And then when I typed git add . and then git status, it showed that are no changes to be committed.
Any idea why this is happening?

A: No clue why this is happening but since it's a fast-forward pull, you could simply
git reset --hard origin/master

to unstage everything and get your WC equal to the master on origin.

A: When I had this issue (I think due to using too many Git plugins at once: Visual Studio 2013 and Git Extensions and Powershell - Powershell for the win!) - it was because I had my index file locked in the .git folder, so it was now called "index.lock".
Visual Studio 2013 informed me of this so I deleted the index.lock in the .git file in the root of my solution. However, this meant git regenerated an index file and showed me as having deleted all my files! Any of the git plugins showed the same thing as the index was telling them this was the case.
I didn't want to do a hard git reset because I annoyingly had a lot of uncommitted changes since an upgrade via nuget.
So I instead restored the deleted index.lock file, deleted the newly generated index file, and renamed index.lock to index.
Then closed and reopened the solution in Visual Studio and now it had the original index file, it no longer thought I'd wanted to delete the entire solution!


text:
Q: Test project icon not visible in android I am unit testing an android applications using Robitium. When I install the test project in to android emulator, I can't find the icon of the test project, but I can run it.
The manifest file of the test project is like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.smartek.screens.test"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="7" />

<instrumentation
    android:name="android.test.InstrumentationTestRunner"
    android:targetPackage="com.smartek.screens" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >

<uses-library android:name="android.test.runner" />
</application>

What should I do to make the test project icon visible?

A: The test project will not contain the launcher entry in manifest file, so you cannot see the icon on launcher.
<intent-filter>
   <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

A: We can do this and its same as the normal android application .
Add the following lines to the android manifest file
<activity android:name=".Testing class name">

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>


text:
Q: Boa tarde, precisava de ajuda para uma calculadora em c++ Fiz este programa para calcular áreas e perímetros de formas geométricas, mas quando pressiono "a", "b" ou "c" para escolher se queres fazer áreas ou perímetros o programa apenas fecha. Segue o código:
#include <iostream>
#include <cmath>
#include <locale>
#include <stdlib.h>
using namespace std;

    double PerimetroQuadrado (double Lado) {
        return 4 * Lado;
    }
    double AreaQuadrado (double Lado) {
        return Lado * Lado;
    }
    double PerimetroRetangulo (double Comprimento, double Altura) {
        return Comprimento*2 + Altura*2;
    }
    double AreaRetangulo (double Comprimento, double Altura) {
        return Comprimento * Altura;
    }
    double PerimetroCirculo (double Raio) {
        return 2 * M_PI * Raio;
    }
    double AreaCirculo (double Raio) {
        return M_PI * pow(Raio,2);
    }
    double PerimetroTriangulo (double Base, double Altura) {
        double hipotenusa = hypot(Base , Altura);
        return Base + Altura + hipotenusa;
    }
    double AreaTriangulo (double Base, double Altura) {
        return Base * Altura / 2;
    }
    double PerimetroTrapezio (double BaseMaior, double BaseMenor, double Altura) {
        double Hipotenusa = hypot((BaseMaior - BaseMenor) / 2 , Altura);
        return BaseMenor + BaseMaior + 2 * Hipotenusa;
    }
    double AreaTrapezio (double BaseMaior, double BaseMenor, double Altura) {
        return (BaseMenor + BaseMaior) * Altura / 2;
    }

    int main (){
        setlocale(LC_ALL, "");

        cout << "Cálculo de Perímetros e Áreas. \n";
        cout << "Escolha uma das seguintes opcões: \n";
        cout << "\t a- Perímetro \n";
        cout << "\t b- Área \n";
        cout << "\t c- Sair \n";

        int num1 , num2 , num3;
        char op;
        cin >> op;
        char pr;
        char ar;
        switch(op){
             case 'a':
             case 'A':
             break;
             cout << "Cálculo de Perímetros e Áreas. \n";
             cout << "Escolha uma das seguintes opcões: \n";
             cout << "\t 1- Quadrado \n";
             cout << "\t 2- Retângulo \n";
             cout << "\t 3- Círculo \n";
             cout << "\t 4- Triângulo Retângulo \n";
             cout << "\t 5- Trapézio \n";
             cout << "\t 6- Voltar \n";
             cout << "\t 7- Sair \n";
             cin >> pr;
                switch(pr) {
                case '1': cout << "Introduza o Valor do Lado do Quadrado:";
                          cin >> num1;
                          cout << PerimetroQuadrado(num1);
                          break;
                case '2': cout << "Introduza o Valor do Comprimento do Retângulo:";
                          cin >> num1;
                          cout << "Introduza o Valor da Altura do Retângulo:";
                          cin >> num2;
                          cout << PerimetroRetangulo(num1, num2);
                          break;
                case '3': cout << "Introduza o Valor do Raio do Círculo:";
                          cin >> num1;
                          cout << PerimetroCirculo(num1);
                          break;
                case '4': cout << "Introduza o Valor da Base do Triângulo:";
                          cin >> num1;
                          cout << "Introduza o Valor da Altura do Triângulo:";
                          cin >> num2;
                          cout << PerimetroTriangulo(num1, num2);
                          break;
                case '5': cout << "Introduza o Valor da Base Maior do Trapézio:";
                          cin >> num1;
                          cout << "Introduza o Valor da Base Menor do Trapézio:";
                          cin >> num2;
                          cout << "Introduza o Valor da Altura do Trapézio:";
                          cin >> num3;
                          cout << PerimetroTrapezio(num1, num2 , num3);
                          break;
                case '6':
                break;
                }

             case 'b':
             case 'B':
             break;
             cout << "Cálculo de Perímetros e Áreas. \n";
             cout << "Escolha uma das seguintes opcões: \n";
             cout << "\t 1- Quadrado \n";
             cout << "\t 2- Retângulo \n";
             cout << "\t 3- Círculo \n";
             cout << "\t 4- Triângulo Retângulo \n";
             cout << "\t 5- Trapézio \n";
             cout << "\t 6- Voltar \n";
             cout << "\t 7- Sair \n";
             cin >> ar;
              switch(ar) {
              case '1': cout << "Introduza o Valor do Lado do Quadrado:";
                          cin >> num1;
                          cout << AreaQuadrado(num1);
                          break;
                case '2': cout << "Introduza o Valor do Comprimento do Retângulo:";
                          cin >> num1;
                          cout << "Introduza o Valor da Altura do Retângulo:";
                          cin >> num2;
                          cout << AreaRetangulo(num1, num2);
                          break;
                case '3': cout << "Introduza o Valor do Raio do Círculo:";
                          cin >> num1;
                          cout << AreaCirculo(num1);
                          break;
                case '4': cout << "Introduza o Valor da Base do Triângulo:";
                          cin >> num1;
                          cout << "Introduza o Valor da Altura do Triângulo:";
                          cin >> num2;
                          cout << AreaTriangulo(num1, num2);
                          break;
                case '5': cout << "Introduza o Valor da Base Maior do Trapézio:";
                          cin >> num1;
                          cout << "Introduza o Valor da Base Menor do Trapézio:";
                          cin >> num2;
                          cout << "Introduza o Valor da Altura do Trapézio:";
                          cin >> num3;
                          cout << AreaTrapezio(num1, num2 , num3);
                          break;
                case '7': exit (0);
                break;

              case 'c':
              case 'C': exit (0);
              break;
              default: cout << "Inválido";
              break;
              }

        }
        return 0;
    }

A: O problema está ocorrendo pois logo após entrar nas condições do seu switch case você está dando um break:
...
switch(op){
             case 'a':
             case 'A':
        >>>  break;
...

A função do break é justamente sair de uma instrução (no seu caso, o switch case) e ir para outra. Como seu código não tem mais nenhuma instrução após o switch case (um for, ou um while, ou até mesmo outro switch, etc) ele é encerrado.
Para resolver o problema basta retirar estes breaks que estão logo após as condições do switch (tanto do case a quanto do b).


text:
Q: An example of a quotient which is NOT a manifold I want to

find a smooth action of $\mathbb R$ on a smooth n-manifold M such that the orbit space isn't a smooth manifold.

So far I only know that such a result can't happen for finite groups acting freely (Quotient Manifold Theorem).

A: The group $\mathbb R$ acts on the smooth $2$-manifold $\mathbb R^2$ by the formula $t \cdot (x,y) = (e^t x, e^{-t}y)$. The orbits of this action are:

*

*The origin $(0,0)$

*The positive $x$-axis

*The positive $y$-axis

*The negative $x$-axis

*The negative $y$-axis

*Each one of the two sheets of each 2-sheeted hyperbola of the form $xy = c$, for all $c \ne 0$.

It follows from this description that the quotient space is not Hausdorff, and therefore the orbit space is not a smooth manifold. For example, the equivalence class of the origin $(0,0)$ forms a one-point subset of the quotient that is not closed, because every open ball in $\mathbb R^2$ containing $(0,0)$ has nontrivial intersection with each positive and negative axis. Also, every neighborhood of the positive $x$-axis and every neighborhood of the positive $y$-axis have nonempty intersection, because for every open ball around $(1,0)$ in $\mathbb R^2$ and for every open ball around $(0,1)$ in $\mathbb R^2$ there exists $c>0$ such that those two balls each intersect the $xy=c$ curve in the 1st quadrant.

A: Consider $T^2$ the two dimensional torus, it is the quotient of $\mathbb{R}^2$ by $t_1(x,y)=(x+1,y)$ and $t_2(x,y)=(x,y+1)$, consider the action of $\mathbb{R}$ induced on $T^2$ by $f_t(x,y)=(x+t\alpha,y)$ where $\alpha$ is irrational, its orbits are dense and the quotient space is not Haussdorff.


text:
Q: Is it true that, for two infinite functions, $\lim_{x->x_0}\frac{f(x)}{g(x)}=1$ entails $\lim_{x->x_0}[f(x)-g(x)]=0$? Let $f,g$ be real functions defined in a neighborhood of $x_0\in \mathbb{R}$ such that $g(x)>0$,$\lim_{x\rightarrow x_0}f(x)= \lim_{x\rightarrow x_0}g(x)=+\infty$, and $\lim_{x\rightarrow x_0}\frac{f(x)}{g(x)}=1$. Is it true that $$\lim_{x\rightarrow x_0}[f(x)-g(x)]=0?$$

A: If $\lim \limits_{x \to x_0} f(x) = \lim \limits_{x \to x_0} g(x) = 0$, then $\lim \limits_{x \to x_0} \{f(x) - g(x)\} = \lim \limits_{x \to x_0} f(x) - \lim \limits_{x \to x_0} g(x) = 0 - 0 = 0$. You don't need any kind of assumption on the ratio of $f$ and $g$.
Edit: This was the answer to the old question. The new statement is incorrect. Consider e.g. $f(x) = \frac{1}{x^2}$ and $g(x) = \frac{1}{x^2} + \frac{1}{|x|}$ around $x_0 = 0$.

A: The statement is false: consider this counterexample, for $x_0=0$.
$$ f(x)=\frac1{x^2} ; g(x)=\frac1{x^2} -1$$
It is easy to see that $\lim_{x\to 0}f(x)=\lim_{x\to 0}g(x)=+\infty $, but $f(x)-g(x)=1$.

A: $$f(x)-g(x)=(\frac{f(x)}{g(x)}-1)g(x) \to(1-1)*0=0$$
for $x \to x_0$


text:
Q: jQuery stopping url click in div attached to function I've got a div set out like this

Business in
action

Develop critical and problem solving skills faculties by investigating challenges faced by business leaders and to practice the skills to devise and implement practical solutions.
http://www.ncl.ac.uk/postgraduate/modules/module/NBS8490/

and where only the h3 is visible and everything else is hidden. jQuery which shows the found out more div which has the arrow and textbox making it look like a speech bubble.
But when a user would click on the link in the hidden div when shown it hides again, without opening the link.
$(".clickformore").click(function(e){
    e.preventDefault();
    if ($(this).find(".foundoutmore").css('display') == 'none') {
        $(".foundoutmore").css("display","none");
        $(this).find(".foundoutmore").css("display","inherit");
    } else {
        $(".foundoutmore").css("display","none");
    }
});

I've tried aiming at the link with css doing a z-index hoping it would first be clickable before the div hid to no avail, I tried to figure out a way to make the showing div not hide it again but I can't figure that out and end of a tether.
Is there a way I can make the link clickable before the div hides?

A: Use this bro ..
$(".foundoutmore").css("display","none");
$("h3").click(function(e){
    e.preventDefault();

    if($(this).next().css('display')=='none'){
        $(this).next().css("display","inherit");
    } else {
        $(".foundoutmore").css("display","none");
    }
});

DEMO

A:

Business in
action

Develop critical and problem solving skills faculties by investigating challenges faced by business leaders and to practice the skills to devise and implement practical solutions.

http://www.ncl.ac.uk/postgraduate/modules/module/NBS8490/

$(".foundoutmore").hide();

or add
.hidden {
  display: none;
}

to your CSS then:
$(".clickformore").on('click', 'h3', function(e){
    e.preventDefault();
    var more = $(this).next('.foundoutmore');
    more.toggle();
});

Demo


text:
Q: Sending an entire html page with phpmailer I purchased an email template and customized it to what I want, but now I'm stuck on how to send it.
The template file is an entire html page with included fonts and even a stylesheet at the top (styletags actually, not an attached file) with mediaqueries and some font settings.
Do I send all of that? Including header tags and more? It's basically an entire html page.
How part of my emailscript is build now:
$mail->isHTML(true);
$texts = 'html template';
$mail->msgHTML($texts);

But I haven't tested my own code yet because the template file is full of single quotes and double quotes. So the variable doesn't like that, I tried replacing all single quotes to double quotes in the templatestring but then my fonts are not working anymore (I tested remotely using this site: https://putsmail.com/).

A: PHPMailer itself doesn't do anything special with HTML content (though msgHTML reads your content to make a rough plain-text version). It sounds like you're just having trouble quoting inline content. You might like to try a different form of quoting called nowdoc which will tolerate all kinds of quotes without a problem:
$texts = <<<'EOT'
html template
EOT;
$mail->msgHTML($texts);

You could also save it in an external file and read it in when you need it, which also avoids quoting issues:
$mail->msgHTML(file_get_contents('template.html'));


text:
Q: How to send an HTTPS link to telegram chat ID. using sendmessage ("https://---", chatID) I like to send a link to my Telegram application-Bot using python#. so, While I send a text I can do it but I can't send Https or Http to my app chat. also, some links are also possible to send. also, I can print it in the terminal of pycharm
if text == "link":
sendMessage("https://www.bousai.pref.kanagawa.jp/K_PUB_VF_DetailCity?cityid=", chatId)

no error and no print in Telegram-app-Bot

A: in the link we have (K_PUB_VF_) one
when I remove _, _, _ then I can print it
the next question
(How to do it with _ one not to be removed it)


text:
Q: How to create an Application Programming Interface (API) between VB.Net and Python? I have a GUI in VB.Net that needs to interface with algorithms written in Python, all to run on Windows 10 Professional.
The IDE is Visual Studio 2017.
How can the VB.Net GUI and Python communicate?
Data needs to be communicated back and forth.
The GUI will accept user commands, and then command Python to execute.
Python will have events that it needs to communicate to the GUI.
To clarify the architecture, the GUI app and the Python app are two different programs running simultaneously.
The GUI has two major functions:  1) take user commands and tell Python to execute them.  2)  Monitor/poll the Python app for data or events, and update (tell) the user via the GUI controls (textboxes, etc.).
Python mainly does two things:   1) runs the continuous control algorithm, subject to management by the GUI.  2) Reports data and events to the GUI.
A TCP socket is 100% reliable, but I have to write and debug a proprietary messaging scheme, which I've done a lot and it's fun, but I thought maybe I can accomplish same thing in substantially less time by some other equally reliable method...  such as COM, as those below suggest.
Example scenario of asynchronous usage:
1:
The Python app is running a robotic process.  Meanwhile, user presses GUI command to see latest metrics: GUI's VB.NET calls a COM function within Python which returns an array of metrics data.
2:
Python app running robotic process completes a step, and now needs a manual action. Python app calls COM function within VB.NET and passes an argument with requirements of manual action.

A: MSDN Python Script Integration
Here is what I would suggest you can read this it's a guide on the MSDN about communicating from C# to Pyhton
Basically calling a python script and reading output.
https://code.msdn.microsoft.com/windowsdesktop/C-and-Python-interprocess-171378ee

IronPython

IronPython is an open-source implementation of the Python programming
  language which is tightly integrated with the .NET Framework.
  IronPython can use the .NET Framework and Python libraries, and other
  .NET languages can use Python code just as easily.

http://ironpython.net/

Python for .NET

Python for .NET (pythonnet) is a package that gives Python programmers
  nearly seamless integration with the .NET 4.0+ Common Language Runtime
  (CLR) on Windows and Mono runtime on Linux and OSX.

However this one limits you to a certain version of python.
http://pythonnet.github.io/

Other solutions

*

*Using socket with client (python) server (c#) or vice versa.

*Using a local database or database file like mdf.

A: I found answer here.
This guy shows consisely how VB.NET calls IronPython scripts functions and also passes and retrieves VB data.  Sweet.
I believe the value here of IronPython vs. regular Python is that IronPython is compatible with any type of .NET data that VB passes to it.
Now, I can create a GUI with the supreme quality and reliability of VB.NET that uses the supreme development efficiency/productivity of Python.


text:
Q: Print quotient and remainder in NASM I'm following this tutorial
(http://www.tutorialspoint.com/assembly_programming/assembly_arithmetic_instructions.htm)
 and write this piece of code. I like to print both, the quotient and the remainder, but I don't get the desired result.
This is the code:
   section .text
       global _start

    _start:
       mov  al,9
       mov  bl,2
       div  bl

       mov bl, al
       add bl, byte '0'
       mov [res], byte bl
       mov bl, ah
       add bl, byte '0'
       mov [tm], byte bl

       mov  ecx,msg
       mov  edx, len
       mov  ebx,1   ;file descriptor (stdout)
       mov  eax,4   ;system call number (sys_write)
       int  0x80    ;call kernel

       mov  ecx,res
       mov  edx,1
       mov  ebx,1   ;file descriptor (stdout)
       mov  eax,4   ;system call number (sys_write)
       int  0x80    ;call kernel

       mov  ecx,msg2
       mov  edx,len2
       mov  ebx,1   ;file descriptor (stdout)
       mov  eax,4   ;system call number (sys_write)
       int  0x80    ;call kernel

       mov  ecx,tm
       mov  edx,1
       mov  ebx,1   ;file descriptor (stdout)
       mov  eax,4   ;system call number (sys_write)
       int  0x80    ;call kernel

       mov  eax,1   ;system call number (sys_exit)
       int  0x80    ;call kernel

    section .data
    msg db "The result is:", 0xA,0xD
    len equ $- msg
    msg2 db 0xA,0xD,"Remainder is:", 0xA,0xD
    len2 equ $- msg

    segment .bss
    tm resb 1
    res resb 1

The result:
The result is:
4
Remainder is:
141%

Any idea of what's wrong?

A: %macro print 2
mov eax,4
mov ebx,1
mov ecx,%1
mov edx,%2
int 80h
%endmacro
%macro read 2
   mov eax, 3
   mov ebx, 2
   mov ecx, %1
   mov edx, %2
   int 80h
%endmacro
section .data
   userMsg db 'Please enter a number: '
   lenUserMsg equ $-userMsg
   usermsg1 db 'enter 2nd number:'
   lenusermsg1 equ $-usermsg1
   quotient db ' quotient is : '
   quotientlength equ $-quotient
remainder db ' remainder is : '
   remainderlength equ $-remainder
   len EQU 16
section .bss           ;Uninitialized data
   n resb len
   n1 resb len
qtnt resb len
r resb len
section .text          ;Code Segment
   global _start
   _start:
print userMsg,lenUserMsg
read n,len
print usermsg1,lenusermsg1
read n1,len
mov al,[n]
sub al,'0'
mov bl,[n1]
sub bl,'0'
div bl
add al,'0'
add dl,'0'
 mov [qtnt],al
print quotient,quotientlength
print qtnt,len
mov [r],dl
print remainder,remainderlength
print r,len
Exit:
 mov eax, 1
   mov ebx, 0
   int 80h


text:
Q: Multiple threads in a python script called from the command line On a webserver i am currently implementing in web.py , I am using the following approach to perform an action periodically:
import threading

def periodicAction():
    # do something
    threading.Timer(time_interval, periodicAction).start() # when finished, wait and then start same function in a new thread

periodicAction() # start the method

While it works fine (meaning it does what it is supposed to do), I still have the problem, that when I test it from the command line, the console gets unresponsive (i can still type, but it has no affect, even ctrl + c does not stop the program). It this the normal behaviour or am I doing something wrong?

A: The background thread is still running, so if the main thread finishes, it will wait -- forever, in this case.  (It's a side-effect of how it waits that Ctrl-C doesn't work.)  If you don't want this, you can call setDaemon(True), which makes the thread a "daemon" -- meaning that it will be forcefully closed when the main thread finishes:
def periodicAction():
    print "do something"
    t = threading.Timer(1.0, periodicAction)
    t.setDaemon(True)
    t.start()


text:
Q: selecting multiple items form multiple tables with min and max I'm having a little trouble figuring out this SQL statement. I have three tables employee, job, and job type.
job type is reference table. It has the name of the job, how long that job takes, and how much is charged for that job.
job has records of what job was performed for what client by which employee and the date performed. It links to job type jobname.
employee has name of employee, and employee id. It links to job table by employee id.
I need to display a list of all employees as well as the cheapest and most expensive jobs they did for a given year.
I think I will probably have to have an embedded select and a few joins. Maybe a unionThe complexity is just too far out of my experience. I'm not even sure where to being to be honest.

A: You should use the employee table as the primary table in your query so you will get one row per employee, even if that employee is associated to 0 jobs. Then use outer joins to the job and job_type tables, group by the employee identifiers, and use the min() and max() aggregate functions on the job table to select the min and max job costs (if any).
Something like this should help you get started:
select employee.employee_id ,
  employee.employee_name,
  min(job_type.cost),
  max(job_type.cost)
from employee
  left outer join job on job.employee_id = employee.employee_id
  left outer join job_type on job_type.job_type_id = job.job_type_id
group by employee.employee_id,
  employee.employee_name


text:
Q: Which is best as a headless server? Ubuntu, Solaris, FreeBSD? I need to run three machines as a cluster at home and want maximum performance from them, running an Erlang program.
What is the best OS to use for this?

A: I'm running both an Ubuntu server and a FreeBSD server headless. The FreeBSD one sits here in a cabinet, the Ubuntu one in a co-lo facility.
The difference is negligible, both are easy enough to administer via ssh if you know what you're doing. At the end of the day it boils down to what you're most familiar with because being able to come up with an optimal hardware/software combo and administer that will make a far bigger impact on the overall performance than your choice of OS.

A: I'd say which ever you feel the most skilled with to automated/optimize/administrate.


text:
Q: Regarding extraction of data from multiple cordiantes of multiple nc files and merge to a single raster I have 365 .nc files for a single year, each containing single day soil moisture information. I want to extract soil moisture information from three different coordinates and write them into three csv files for the given year. Currently, I am able to convert all the 365 .nc files into 365 csv files as given in the attached code. How to proceed further?
rm(list = ls())
library(raster)
library(ncdf4)
ptf <- "D://SMOS_ECV_SM//SMOS_ECV_SM//ECV_SM_Data_1978_2010//1978"
setwd(ptf) # change your working directory
lf <- list.files(pattern="[.]nc$") # list of files ending in .nc
for(i in lf){
  nc.brick <- brick(i)
  nc.df <- as.data.frame(nc.brick[[1]], xy=T)
  write.csv(nc.df, sub("[.]nc$",".csv",i)) # write to the same file name substituting .nc to .csv
}

A: You should be able to do something like the below
library(raster)
ptf <- "D://SMOS_ECV_SM//SMOS_ECV_SM//ECV_SM_Data_1978_2010//1978"
ff <- list.files(path=ptf, pattern="[.]nc$", full.names=TRUE)

s <- stack(ff)
points <- rbind(c(0,1), c(100,120), c(80,5))
v <- extract(s, points)

for (i in 1:ncol(v)) {
  write.csv(v[,i,drop=FALSE], paste0("file", i, ".csv"))
}


text:
Q: Handling Large Form with React I have a large registration form in a React-redux page.
I do not need to bind any data to the forms, as it will always load blank, and on submit can just send data to API and be redirected to a "Please check our email" page.
The issue I am also having, is that I am using MaterializeReact and using their custom  Components. This just renders as a input with a name, so traditional formdata would be intact..
All the examples online, seem to want me to create a state, then for each input element I bind the state to it, and then all my values will be in this.state.
It seems a little bit of a long way around, as I have 30, 40 fields.
I found a way using refs, but I did no want to use it as I know ref strings are being deprecated. The ref solution is like so:
submitform() {
    const formData = {};
    for (const field in this.refs) {
      formData[field] = this.refs[field].value;
    }
    //Now I have the all values wrapped in a object to send to server
  }

<form>
  <Input ref="firstName" />  //MaterializeReact Component. Renders as <input>
 <button type="button" onclick="{submitForm}" />
</form>

What would be the recommend way of getting the value of many inputs without the hassle of binding each one?

A: While working with large forms there are some challenges which you may face:

*

*Performance Issues
You're components must be designed in a way that the changes in one input should not affect the other until it's required.

*

*Scalabilty
It should be easy to add & remove form controls.

*

*State Management
It's not easy to maintain a centralized state with all controls information like touched, error etc.

*

*Dynamic Changes
For example: Disable a field based on the value of other field.

*

*Validations & Errors

*Nested Forms
So, it's better to save effort & time by using some form library.
Checkout this library react-reactive-form
Some of the cool features are:

*

*UI independent.

*Zero dependencies.

*Nested forms.

*Subscribers for value & status changes of controls.

*Provides a set of validators & also supports custom sync & async validators.

*FormGenerator api to create large forms with less code.

*Better form management with FormGroup & FormArray apis.

*Customizable update strategy for better performace with large forms.

A: The two recommended ways to handle forms by the react team are controlled and uncontrolled components. Creating and maintaining a state is no more round-about than using a uncontrolled components like your initial suggestion with refs where you built your own state called formData before submitting the data.
Here's the equivalent solution using state, and it won't be deprecated.
submitform() {
    const formData = this.state
    //Now I have the all values wrapped in a object to send to server
}

handleOnChange = (e) => {
    const { value, name } = e.target
    this.setState({ [name] : value })
}

<form>
    <Input name="firstName" onChange={this.handleOnChange} /> //MaterializeReact Component. Renders as <input>
    <button type="button" onclick="{submitForm}" />
</form>


text:
Q: Ip addressing of pods in Kubernetes How does pods get unique IP addresses even if they reside in the same worker node?
Also pod is not a device what is logic behind having it an IP address?
Is the IP address assigned to a pod a virtual IP?

A: A pod is part of a cluster (group of nodes), and cluster networking tells you that:

In reality, Kubernetes applies IP addresses at the Pod scope - containers within a Pod share their network namespaces - including their IP address.
This means that containers within a Pod can all reach each other's ports on localhost.
  This does imply that containers within a Pod must coordinate port usage, but this is no different than processes in a VM.
  This is called the "IP-per-pod" model.

The constraints are:

*

*all containers can communicate with all other containers without NAT

*all nodes can communicate with all containers (and vice-versa) without NAT

*the IP that a container sees itself as is the same IP that others see it as

See more with "Networking with Kubernetes" from Alok Kumar Singh:

Here:

We have a machine, it is called a node in kubernetes.
  It has an IP 172.31.102.105 belonging to a subnet having CIDR 172.31.102.0/24.

(CIDR: Classless Inter-Domain Routing, a method for allocating IP addresses and IP routing)

The node has an network interface eth0 attached. It belongs to root network namespace of the node.
  For pods to be isolated, they were created in their own network namespaces — these are pod1 n/w ns and pod2 n/w ns.
  The pods are assigned IP addresses 100.96.243.7 and 100.96.243.8 from the CIDR range 100.96.0.0/11.

For the, see "Kubernetes Networking" from CloudNativelabs:

Kubernetes does not orchestrate setting up the network and offloads the job to the CNI (Container Network Interface) plug-ins. Please refer to the CNI spec for further details on CNI specification.
Below are possible network implementation options through CNI plugins which permits pod-to-pod communication honoring the Kubernetes requirements:

*

*layer 2 (switching) solution

*layer 3 (routing) solution

*overlay solutions

layer 2 (switching)

You can see their IP attributed as part of a container subnet address range.
layer 3 (routing)

This is about populating the default gateway router with routes for the subnet as shown in the diagram.
Routes to 10.1.1.0/24 and 10.1.2.0/24 are configured to be through node1 and node2 respectively.
overlay solutions
Generally not used.
Note: See also (Oct. 2018): "Google Kubernetes Engine networking".

A: Kubernetes creates a network within your network for the containers. in GKE, for example, by default it is a /14, but can be overwritten by a user with a range between /11 and /19.
When Kubernetes creates a pod, it assigns an IP address from these range. Now, you can't have another VM, not part of your cluster, in your network, with the same IP address that a pod has.
Why? Imagine, you have a VPN tunnel that needs to deliver a packet to an address that both, the pod and the VM are using. Who is it going to deliver to?
So, answering your question; no, it is not a virtual IP, it is a physical IP address from your network.


text:
Q: How to create a new column based on different columns in dplyr If I have a the following df

id
tiger
donkey
turtle

1
1
0
0

2
0
1
0

3
0
0
1

So that 1 equals True and 0 equals False.
And I want to create the following df

id
animal

1
tiger

2
donkey

3
turtle

How would I do this using dplyr? I first thought that I could use pivot_long() but I should not have more rows after the operation.

A: dplyr
library(dplyr)
library(tidyr) # pivot_longer
pivot_longer(dat, -id, names_to = "animal") %>%
  filter(value > 0)
# # A tibble: 3 x 3
#      id animal value
#   <int> <chr>  <int>
# 1     1 tiger      1
# 2     2 donkey     1
# 3     3 turtle     1

base plus reshape2
subset(
  reshape2::melt(dat, id.vars = "id", variable.name = "animal"),
  value > 0)


text:
Q: Issues compiling I am using this method for research I am doing, but I am having some difficulties with the setup. About half way down the page it says to run ./bootstrap.sh --with-python=python3 sudo ./b2 --with-python --with-filesystem --with-system --with-regex install, then marks what the response should be. It worked almost perfectly, but there are a few files that I cannot figure out how to install; notably /usr/local/lib/libboost_python3.so and /usr/local/lib/libboost_numpy3.so. Below is the full response: (note that root@cole-desktop:/home/cole/Downloads/Mass/boost_1_66_0# ./bootstrap.sh --with-python=python3 was autofilled and I just hit enter.)
   Building Boost.Build engine with toolset gcc... tools/build/src/engine/bin.linuxx86_64/b2
Detecting Python version... 3.8
Detecting Python root... /usr
Unicode/ICU support for Boost.Regex?... not found.
Backing up existing Boost.Build configuration in project-config.jam.2
Generating Boost.Build configuration in project-config.jam...

Bootstrapping is done. To build, run:

    ./b2

To adjust configuration, edit 'project-config.jam'.
Further information:

   - Command line help:
     ./b2 --help

   - Getting started guide:
     http://www.boost.org/more/getting_started/unix-variants.html

   - Boost.Build documentation:
     http://www.boost.org/build/doc/html/index.html

root@cole-desktop:/home/cole/Downloads/Mass/boost_1_66_0# sudo ./b2 --with-python --with-filesystem --with-system --with-regex install
Performing configuration checks

    - 32-bit                   : no  (cached)
    - 64-bit                   : yes (cached)
    - arm                      : no  (cached)
    - mips1                    : no  (cached)
    - power                    : no  (cached)
    - sparc                    : no  (cached)
    - x86                      : yes (cached)
    - symlinks supported       : yes (cached)
    - has_icu builds           : no  (cached)

Component configuration:

    - atomic                   : not building
    - chrono                   : not building
    - container                : not building
    - context                  : not building
    - coroutine                : not building
    - date_time                : not building
    - exception                : not building
    - fiber                    : not building
    - filesystem               : building
    - graph                    : not building
    - graph_parallel           : not building
    - iostreams                : not building
    - locale                   : not building
    - log                      : not building
    - math                     : not building
    - mpi                      : not building
    - program_options          : not building
    - python                   : building
    - random                   : not building
    - regex                    : building
    - serialization            : not building
    - signals                  : not building
    - stacktrace               : not building
    - system                   : building
    - test                     : not building
    - thread                   : not building
    - timer                    : not building
    - type_erasure             : not building
    - wave                     : not building

...patience...
...patience...
...found 31231 targets...
...updating 11 targets...
gcc.compile.c++ bin.v2/libs/python/build/gcc-gnu-9/release/threadapi-pthread/threading-multi/converter/builtin_converters.o
libs/python/src/converter/builtin_converters.cpp: In function 'void* boost::python::converter::{anonymous}::convert_to_cstring(PyObject*)':
libs/python/src/converter/builtin_converters.cpp:51:35: error: invalid conversion from 'const void*' to 'void*' [-fpermissive]
   51 |       return PyUnicode_Check(obj) ? _PyUnicode_AsString(obj) : 0;

    "g++"   -O3 -finline-functions -Wno-inline -Wall -pthread -fPIC -m64  -DBOOST_ALL_NO_LIB=1 -DBOOST_PYTHON_SOURCE -DNDEBUG  -I"." -I"/usr/include/python3.8" -c -o "bin.v2/libs/python/build/gcc-gnu-9/release/threadapi-pthread/threading-multi/converter/builtin_converters.o" "libs/python/src/converter/builtin_converters.cpp"

...failed gcc.compile.c++ bin.v2/libs/python/build/gcc-gnu-9/release/threadapi-pthread/threading-multi/converter/builtin_converters.o...
...skipped <pbin.v2/libs/python/build/gcc-gnu-9/release/threadapi-pthread/threading-multi>libboost_python3.so.1.66.0 for lack of <pbin.v2/libs/python/build/gcc-gnu-9/release/threadapi-pthread/threading-multi>converter/builtin_converters.o...
...skipped <p/usr/local/lib>libboost_python3.so.1.66.0 for lack of <pbin.v2/libs/python/build/gcc-gnu-9/release/threadapi-pthread/threading-multi>libboost_python3.so.1.66.0...
...skipped <p/usr/local/lib>libboost_python3.so for lack of <p/usr/local/lib>libboost_python3.so.1.66.0...
...skipped <pbin.v2/libs/python/build/gcc-gnu-9/release/threadapi-pthread/threading-multi>libboost_numpy3.so.1.66.0 for lack of <pbin.v2/libs/python/build/gcc-gnu-9/release/threadapi-pthread/threading-multi>libboost_python3.so.1.66.0...
...skipped <p/usr/local/lib>libboost_numpy3.so.1.66.0 for lack of <pbin.v2/libs/python/build/gcc-gnu-9/release/threadapi-pthread/threading-multi>libboost_numpy3.so.1.66.0...
...skipped <p/usr/local/lib>libboost_numpy3.so for lack of <p/usr/local/lib>libboost_numpy3.so.1.66.0...
gcc.compile.c++ bin.v2/libs/python/build/gcc-gnu-9/release/link-static/threadapi-pthread/threading-multi/converter/builtin_converters.o
libs/python/src/converter/builtin_converters.cpp: In function 'void* boost::python::converter::{anonymous}::convert_to_cstring(PyObject*)':
libs/python/src/converter/builtin_converters.cpp:51:35: error: invalid conversion from 'const void*' to 'void*' [-fpermissive]
   51 |       return PyUnicode_Check(obj) ? _PyUnicode_AsString(obj) : 0;

    "g++"   -O3 -finline-functions -Wno-inline -Wall -pthread -m64  -DBOOST_ALL_NO_LIB=1 -DBOOST_PYTHON_SOURCE -DBOOST_PYTHON_STATIC_LIB -DNDEBUG  -I"." -I"/usr/include/python3.8" -c -o "bin.v2/libs/python/build/gcc-gnu-9/release/link-static/threadapi-pthread/threading-multi/converter/builtin_converters.o" "libs/python/src/converter/builtin_converters.cpp"

...failed gcc.compile.c++ bin.v2/libs/python/build/gcc-gnu-9/release/link-static/threadapi-pthread/threading-multi/converter/builtin_converters.o...
...skipped <pbin.v2/libs/python/build/gcc-gnu-9/release/link-static/threadapi-pthread/threading-multi>libboost_python3.a(clean) for lack of <pbin.v2/libs/python/build/gcc-gnu-9/release/link-static/threadapi-pthread/threading-multi>converter/builtin_converters.o...
...skipped <pbin.v2/libs/python/build/gcc-gnu-9/release/link-static/threadapi-pthread/threading-multi>libboost_python3.a for lack of <pbin.v2/libs/python/build/gcc-gnu-9/release/link-static/threadapi-pthread/threading-multi>converter/builtin_converters.o...
...skipped <p/usr/local/lib>libboost_python3.a for lack of <pbin.v2/libs/python/build/gcc-gnu-9/release/link-static/threadapi-pthread/threading-multi>libboost_python3.a...
...failed updating 2 targets...
...skipped 9 targets...

I believe the issue to be related to the computer failing to find some pathway within pbin.v2, but I have no idea what/where that is.

A: I was in the same identical situation.
What worked for me was
sudo cp -r /usr/local/include/python3.6m/ /usr/local/include/python3.6/

I am not sure what kind of Python configuration you have but the solution is to copy (or create a soft link) as in the command above.
The problem is that Boost looks for pyconfig.h in the python folder without the m that doesn't not exist.