text:
Q: To count the frequency of each word There's a directory with a few text files. How do I count the frequency  of each word in each file? A word means a set of characters that can contain the letters, the digits and the underlining characters.

A: There is a Linq-ish alternative which imo is simpler. The key here is to use the framework built in File.ReadLines (which is lazily read which is cool) and string.Split.
private Dictionary<string, int> GetWordFrequency(string file)
{
    return File.ReadLines(file)
               .SelectMany(x => x.Split())
               .Where(x => x != string.Empty)
               .GroupBy(x => x)
               .ToDictionary(x => x.Key, x => x.Count());
}

To get frequencies from many files, you can have an overload based on params.
private Dictionary<string, int> GetWordFrequency(params string[] files)
{
    return files.SelectMany(x => File.ReadLines(x))
                .SelectMany(x => x.Split())
                .Where(x => x != string.Empty)
                .GroupBy(x => x)
                .ToDictionary(x => x.Key, x => x.Count());
}

A: Here is a solution that should count all the word frequencies in a file:
    private void countWordsInFile(string file, Dictionary<string, int> words)
    {
        var content = File.ReadAllText(file);

        var wordPattern = new Regex(@"\w+");

        foreach (Match match in wordPattern.Matches(content))
        {
            int currentCount=0;
            words.TryGetValue(match.Value, out currentCount);

            currentCount++;
            words[match.Value] = currentCount;
        }
    }

You can call this code like this:
        var words = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);

        countWordsInFile("file1.txt", words);

After this words will contain all words in the file with their frequency (e.g. words["test"] returns the number of times that "test" is in the file content. If you need to accumulate the results from more than one file, simply call the method for all files with the same dictionary. If you need separate results for each file then create a new dictionary each time and use a structure like @DarkGray suggested.

A: string input= File.ReadAllText(filename);
var arr = input.Split(' ');
// finding frequencies of words in a string
IDictionary<string, int> dict = new Dictionary<string, int>();
foreach (var item in arr)
{
    var count = 0;
    if (dict.TryGetValue(item, out count))
        dict[item] = ++a;
    else
        dict.Add(item, 1);
}

A: Word counting:
int WordCount(string text)
{
  var regex = new System.Text.RegularExpressions.Regex(@"\w+");

  var matches = regex.Matches(text);
  return matches.Count;
}

Read text from file:
string text = File.ReadAllText(filename);

Word counting structure:
class FileWordInfo
{
  public Dictionary<string, int> WordCounts = new Dictionary<string, int>();
}

List<FileWordInfo> fileInfos = new List<FileWordInfo>();

A: @aKzenT answer is good, but has a problem! his code never checks if the word is already exists in the dictionary or not! so I modified the code as following:
private void countWordsInFile(string file, Dictionary<string, int> words)
{
    var content = File.ReadAllText(file);

    var wordPattern = new Regex(@"\w+");

    foreach (Match match in wordPattern.Matches(content))
    {
        if (!words.ContainsKey(match.Value))
            words.Add(match.Value, 1);
        else
            words[match.Value]++;
    }
}


text:
Q: Forcing AngularJS to reload updated value on html end I have a timer that I am writing as my first application in AngularJS. I have been trying to teach myself angular but I believe there may be a fundamental disconnect in how I have my model set up. Although I can see the updated values in the web console via my console.log print outs, the timer on the html side is not appearing to update.

var myApp = angular.module('countdownTimer', []);

myApp.service('timerService',['$http','$timeout', function($http, $timeout){
 var time = 180;
 var self = this;

 this.getPrettyTime = function(){
  var minutes = time/60;
  var seconds = time - minutes * 60;
  if (seconds < 10){
   myDateObject.date = minutes + ":0" + seconds;
  }
  else{
   myDateObject.date = minutes + ":" + seconds;
  }
  return myDateObject;
 }

 var myDateObject = {
  date: null
 }
 var onTimeout = function() {
  time = time - 1;
  if (time > 0){
   console.log(time);
   mytimeout = $timeout(onTimeout, 1000);

  }
  else{
   time = 180;
   mytimeout = $timeout(onTimeout, 1000);
  }
 }
 this.start = function() {

  $timeout(onTimeout, 1000);
 }

}]);

myApp.controller('CounterController', ['$timeout','$scope', 'timerService', function($timeout, $scope, timerService){
 /**$scope.counter = 180;
 **/
 //var date = new Date(null);
 //date.setSeconds(timerService.getTime());
 $scope.myDateObject = timerService.getPrettyTime();

 $scope.start = function(){
  timerService.start();

 }

 $scope.stop = function(){
  $timeout.cancel(mytimeout);
 }

}]);
<!doctype html>

 <meta charset="UTF-8">
 <title> Example </title>

  {{myDateObject.date}}
  <button data-ng-click="stop()">Stop</button>
  <button data-ng-click="start()">Start</button>

As you can see in the example above, the timer is not updating on the webpage. Is there a disconnect in my logic (I am new to angular so I would love to learn where I went wrong) or am I misinterpreting angular functionality altogether?
Thanks

A: First, in getPrettyTime you need to do :
var minutes = Math.floor(time/60);

Else you will get a float number.
After that you need to call your getPrettyTime function every time your time is updated, so you can do this in your onTimeout function like this :
var onTimeout = function() {
    time = time - 1;
    self.getPrettyTime();
    ...

Here is a working snippet :

var myApp = angular.module('countdownTimer', []);

myApp.service('timerService', ['$http', '$timeout', function($http, $timeout) {
  var time = 180;
  var self = this;

  self.getPrettyTime = function() {
    var minutes = Math.floor(time / 60);
    var seconds = time - minutes * 60;
    if (seconds < 10) {
      myDateObject.date = minutes + ":0" + seconds;
    } else {
      myDateObject.date = minutes + ":" + seconds;
    }
    return myDateObject;
  }

  var myDateObject = {
    date: null
  }
  var onTimeout = function() {
    time = time - 1;
    self.getPrettyTime();
    if (time > 0) {
      console.log(time);
      mytimeout = $timeout(onTimeout, 1000);

    } else {
      time = 180;
      mytimeout = $timeout(onTimeout, 1000);
    }
  }
  this.start = function() {

    $timeout(onTimeout, 1000);
  }

}]);

myApp.controller('CounterController', ['$timeout', '$scope', 'timerService', function($timeout, $scope, timerService) {
  /**$scope.counter = 180;
   **/
  //var date = new Date(null);
  //date.setSeconds(timerService.getTime());
  $scope.myDateObject = timerService.getPrettyTime();

  $scope.start = function() {
    timerService.start();

  }

  $scope.stop = function() {
    $timeout.cancel(mytimeout);
  }

}]);
<!doctype html>

  <meta charset="UTF-8">
  <title> Example </title>

    {{myDateObject.date}}
    <button data-ng-click="stop()">Stop</button>
    <button data-ng-click="start()">Start</button>

redpajama_set_name: RedPajamaStackExchange


text:
Q: pentaho: how to pass a variable in start-job from the lowest transformation I am new at pentaho and have some problems during building my job. I have job1, which consists of job2 and other transformation. Job2 contains 3 transformations: 1, 2 and 3. The transformation3 makes some steps and calls another transformation4 (through Transformation executor step). Transformation4 compares some values and then a new variable "result" is set. Problem is that I need to use this variable in Job1. I have tried to use "set variables" step with valid in parent, root, system jobs, but the value is always empty. Are there any opportunities to pass this variable in start-job (job1)? Thank you for your help.

A: From the above Job/Transformation Flow description it would not be possible to set a value from T4 to J1 as Jobs are executed sequentially and Set_variable on the 1st iteration of T4 can not pass data to Get_Variables of J2. If J1 has been marked as "Run for each Row" (default) and data being read from a source like,
Table - make sure the DML is commited.
File - make sure file is closed.
Hope this answers the question


text:
Q: Add tabs to one fragment I am trying to add tabs to just one fragment in my app (the app has several fragments).  I am going round in circles trying to get this to work. I have found some advice from a stackoverflow answer that was posted to someones question but this crashes my app.
Fragment code
   public class salesPartsHolderFragment extends Fragment {
public salesPartsHolderFragment() {
    // Required empty public constructor

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View theView = inflater.inflate(R.layout.fragment_sales_parts_holder, container, false);
    TabHost tabs=(TabHost)getActivity().findViewById(R.id.tabhost);

    tabs.setup();

    TabHost.TabSpec spec=tabs.newTabSpec("tag1");

    spec.setContent(R.id.tab1);//here you define which tab you want to setup
    spec.setIndicator("So Close");//here you choose the text showed in the tab
    tabs.addTab(spec);

    spec=tabs.newTabSpec("tag2");
    spec.setContent(R.id.tab2);
    spec.setIndicator("Contacts");
    tabs.addTab(spec);
    return theView;
}

}
XML Code
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.alcontrol.atmis.anticimex.activities.salesPartsHolderFragment">

<TabHost
android:id="@+id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/setting" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="46dp"
        />

    <FrameLayout android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <TextView
            android:id="@+id/tab1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:textColor="@color/white"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/tab2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:textAppearance="?android:attr/textAppearanceLarge"  />

    </FrameLayout>

</LinearLayout>

LogCat
02-23 12:52:16.601    4991-4991/com.alcontrol.atmis.anticimex D/AndroidRuntime﹕ Shutting down VM
02-23 12:52:16.601    4991-4991/com.alcontrol.atmis.anticimex W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa625f288)
02-23 12:52:16.613    4991-4991/com.alcontrol.atmis.anticimex E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.alcontrol.atmis.anticimex.activities.MainActivity.loadSalesPartsFragment(MainActivity.java:244)
            at com.alcontrol.atmis.anticimex.activities.SampleFragment.showSalesPartsFragment(SampleFragment.java:292)
            at com.alcontrol.atmis.anticimex.activities.SampleFragment.saveDetailsMoveToSalesParts(SampleFragment.java:281)
            at com.alcontrol.atmis.anticimex.activities.SampleFragment$1.onClick(SampleFragment.java:71)
            at android.view.View.performClick(View.java:4084)
            at android.view.View$PerformClick.run(View.java:16966)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

A: Replace
TabHost tabs = (TabHost)getActivity().findViewById(R.id.tabhost);

with
TabHost tabs = (TabHost)theView.findViewById(R.id.tabhost);

Try this. This will work.
Calling getActivity.findViewById() will not work in onCreateView(), because the View of the Fragment has yet to be created by onCreateView().

A: You have to make a Tab Activity, in that activity you will add your fragments. I hope below code will help you:
public class TabActivity extends FragmentActivity {
private static TabHost mTabHost;

private TabSpec mTabSpec;

private final String TAG_First = "First";

private final String TAG_Second = "Second";

private final String TAG_Third = "Third";

private int mCurrentTab = 0;
private View mDecorView;

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

    setContentView(R.layout.activity_tab);

    mTabHost = (TabHost) findViewById(R.id.tabhost_lesson);
    mTabHost.setOnTabChangedListener(mTabChangeListener);
    mTabHost.setup();

    setupTabs();
}

private void setupTabs() {

    /*
     * Setup new tab
     */
    mTabSpec = mTabHost.newTabSpec(TAG_First);
    mTabHost.setCurrentTab(mCurrentTab);
    mTabSpec.setContent(new TabContentFactory() {

        @Override
        public View createTabContent(String tag) {

            return findViewById(android.R.id.tabcontent);
        }
    });

    mTabSpec.setIndicator(createTabContent(TAG_First, 14));

    mTabHost.addTab(mTabSpec);

    /*
     * Setup New Tab
     */
    mTabSpec = mTabHost.newTabSpec(TAG_Second);

    mTabSpec.setContent(new TabContentFactory() {

        @Override
        public View createTabContent(String tag) {

            return findViewById(android.R.id.tabcontent);
        }
    });

    mTabSpec.setIndicator(createTabContent(TAG_Second, 14));

    mTabHost.addTab(mTabSpec);

    mTabHost.getTabWidget().setDividerDrawable(null);

    /*
     * Setup New Tab
     */
    mTabSpec = mTabHost.newTabSpec(TAG_Third);

    mTabSpec.setContent(new TabContentFactory() {

        @Override
        public View createTabContent(String tag) {

            return findViewById(android.R.id.tabcontent);
        }
    });

    mTabSpec.setIndicator(createTabContent(TAG_Third, 14));

    mTabHost.addTab(mTabSpec);

}

/**
 * Method to Customize Tabs
 *
 * @param String
 *            TabID
 * @param Drawable
 *            drawable
 * @param int TabTextSize
 * @return
 */
public View createTabContent(String mTabLbl, int mTxtSize) {

    View mTabView = LayoutInflater.from(TabActivity.this).inflate(
            R.layout.tabs_background, null);

    TextView mTabText = (TextView) mTabView.findViewById(R.id.tabsText);

    // mTabText.setBackgroundDrawable(mTabDraw);
    mTabText.setText(mTabLbl);

    return mTabView;
}

public static void SetCurrentTab(int CurrentTab) {
    mTabHost.setCurrentTab(CurrentTab);
}

TabHost.OnTabChangeListener mTabChangeListener = new OnTabChangeListener() {

    @Override
    public void onTabChanged(String tabId) {

        if (tabId.equals(TAG_First)) {

            mCurrentTab = 0;

            FirstFrag fFragment = new FirstFrag();

            addTabFragments(tabId, fFragment);

        } else if (tabId.equals(TAG_Second)) {

            mCurrentTab = 1;

            SecondFrag sFragment = new SecondFrag();

            addTabFragments(tabId, sFragment);

        } else if (tabId.equals(TAG_Third)) {

            mCurrentTab = 2;

            ThirdFrag tFragment = new ThirdFrag();

            addTabFragments(tabId, tFragment);

        }
    }
};

/**
 * Method to add Fragment When Switching Between Tabs
 *
 * @param String
 *            Tag
 * @param Fragment
 *            TabFragment
 */
public void addTabFragments(String tag, Fragment mTabFrag) {

    FragmentManager mFragmentManager = getSupportFragmentManager();

    FragmentTransaction mFragmentTransaction = mFragmentManager
            .beginTransaction();

    mFragmentTransaction.replace(R.id.frame, mTabFrag);

    mFragmentTransaction.commit();
}

}

A: find help with this project SlidingTabsBasic. It is recommended by Google instead of TabHost.


text:
Q: Find and correct the error in the for loop below. The loop should print every even number from 2 to 12 Code:
for number in range(12):
  print number(12)

It didn't print 2 4 6 8 10 12 as it was supposed to. Please correct my code.


text:
Q: Converse. Divisibility of a|b What about the converse: Given that $a^2 \mid b^2$ is it necessarily the case that $a \mid b$? Justify.

My train of thought:
Proof: Direct
Assume: $a$ and $b$ are integers. And $a^2$ divides $b^2$
so,
$b^2 = ka^2$  where $k$ is some integer square: $k = j^2$
then, $b = \sqrt{k}\cdot a \implies b = ja$
This implies $a \mid b$. Done.

A: The clearest way is to use the Unique Factorization Theorem. We give a proof that bypasses it.
Assume (it makes no difference) that $a$ and $b$ are positive. Let $d=\gcd(a,b)$. We want to show that $d=a$.
Let $a=da_0$ and $b=db_0$. Then $a_0$ and $b_0$ are relatively prime. From $a^2\mid b^2$ we conclude that $a_0^2\mid b_0^2$. Since $a_0$ and $b_0$ are relatively prime, from $a_0\mid b_0\cdot b_0$ we conclude that if $a_0$ does not divide (the first) $b_0$, it must divide the second. So $a_0\mid b_0$, and therefore $a_0=1$. Thus $a=d$, and we are finished.
Added: For completeness, we write down the Unique Factorization Theorem argument that shows that your $k$ is a perfect square. Let $b=p_1^{b_1}\cdots p_t^{b_t}$, where the $p_i$ are distinct primes. Then $b^2=p_1^{2b_1}\cdots p_t^{2b_t}$. Since $a^2$ divides $b^2$, all the prime divisors of $a^2$, and hence of $a$, are among the $p_i$. So $a=p_1^{a_1}\cdots p_t^{a_t}$, where some of the $a_i$ may be $0$. It follows that $a^2=p_1^{2a_1}\cdots p_t^{2a_t}$.
Divide. We find that $k=\frac{b^2}{a^2}=p_1^{2b_1-2a_1}\cdots p_t^{2b_t-2a_t}$. Since all the exponents of the $p_i$ in the factorization of $k$ are even, it follows that $k$ is a perfect square.


text:
Q: insertNodeInto function only works in first insertion (works for leaf node) Say I'm coding for an editable tree file system and adding an action listener for my "add child" button. That is, once I select a node in the tree and click the "Add child" button. There should be a new node "New" becoming its child, which was showed in Fig.1.
(Sorry I don't have 10 reputation to post images.. But probably you can run the complete code below.)
But the thing is my listener only works in first insertion, which means it only works for leaf node.
When I'm trying to add a new node into "Thing" node, the tree doesn't change. While the figure didn't change, the return value of .childCount() function return did change according to what the console display.
    addChildButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent action)
        {
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) m_tree.
                getLastSelectedPathComponent();
            if (selectedNode == null)
            {
                System.out.println("selected null");
                return ;
            }
            DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New");
            System.out.println(selectedNode.getChildCount());
            m_model.insertNodeInto(newNode, selectedNode,
                selectedNode.getChildCount());
            // display the new node
            m_tree.scrollPathToVisible(new TreePath(newNode.getPath()));
        }
    });

For the ones who want to run the program, the complete code is here:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.tree.*;
public class TreeEditTest
{
    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                JFrame frame = new TreeEditFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

class TreeEditFrame extends JFrame
{
    public TreeEditFrame()
    {
        setTitle("TreeEditTest");
        setSize(M_DEFAULT_WIDTH, M_DEFAULT_HEIGHT);

        // construct tree
        TreeNode root = makeSampleTree();
        m_model = new DefaultTreeModel(root);
        m_tree = new JTree(root);
        m_tree.setEditable(true);
        // add scroll pane with tree
        JScrollPane scrollPane = new JScrollPane(m_tree);
        add(scrollPane, BorderLayout.CENTER);

        // make buttons
        makeButtons();
    }

    private TreeNode makeSampleTree()
    {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Thing");
        DefaultMutableTreeNode pizza = new DefaultMutableTreeNode("Pizza");
        DefaultMutableTreeNode pizzaBase = new DefaultMutableTreeNode("PizzaBase");
        DefaultMutableTreeNode pizzaTopping = new DefaultMutableTreeNode("PizzaTopping");
        root.add(pizza);
        root.add(pizzaBase);
        root.add(pizzaTopping);
        DefaultMutableTreeNode deepPanBase = new DefaultMutableTreeNode("DeepPanBase");
        DefaultMutableTreeNode thinAndCrispyBase = new DefaultMutableTreeNode("ThinAndCrispyBase");
        pizzaBase.add(deepPanBase);
        pizzaBase.add(thinAndCrispyBase);

        return root;
    }

    private void makeButtons()
    {
        JPanel panel = new JPanel();
        JButton addChildButton = new JButton("Add Child");
        JButton addSiblingButton = new JButton("Add Sibling");
        JButton deleteButton = new JButton("Delete");
        addChildButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent action)
            {
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) m_tree.
                    getLastSelectedPathComponent();
                if (selectedNode == null)
                {
                    System.out.println("selected null");
                    return ;
                }
                DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New");
                System.out.println(selectedNode.getChildCount());
                m_model.insertNodeInto(newNode, selectedNode,
                    selectedNode.getChildCount());

//              display the new node
                m_tree.scrollPathToVisible(new TreePath(newNode.getPath()));
            }
        });
        addSiblingButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent action)
            {
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) m_tree.
                    getLastSelectedPathComponent();
                if (selectedNode == null)
                {
                    System.out.println("selected null");
                    return ;
                }
                DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.
                    getParent();
                if (parent == null)
                {
                    System.out.println("parent null");
                    return ;
                }
                DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New");
                int selectedIndex = parent.getIndex(selectedNode);
//              System.out.println(parent.getChildCount());
//              m_model.insertNodeInto(newNode, parent, parent.getChildCount());
                System.out.println(selectedIndex+1);
                m_model.insertNodeInto(newNode, parent, selectedIndex+1);

                // now display the new node
                TreeNode[] nodes = m_model.getPathToRoot(newNode);
                TreePath path = new TreePath(nodes);
                m_tree.scrollPathToVisible(path);
            }
        });
        deleteButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent action)
            {
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) m_tree.
                    getLastSelectedPathComponent();
                if (selectedNode == null)
                {
                    System.out.println("selected null");
                    return ;
                }
                DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.
                    getParent();
                if (parent == null)
                {
                    System.out.println("Cannot delete the \"Thing\" node");
                    return ;
                }
                m_model.removeNodeFromParent(selectedNode);
            }
        });
        panel.add(addChildButton);
        panel.add(addSiblingButton);
        panel.add(deleteButton);

        add(panel, BorderLayout.NORTH);
    }

    private DefaultTreeModel m_model;
    private JTree m_tree;
    private static final int M_DEFAULT_WIDTH = 400;
    private static final int M_DEFAULT_HEIGHT = 200;
}

A: That's simply because the JTree doesn't use your model. It uses another model it creates from the root tree you passed as argument to the tree constructor. Replace
m_tree = new JTree(root);

by
m_tree = new JTree(m_model);


text:
Q: How to find xpath of an element under a heading in a Web page :

Units Currently On Bed List

"[total beds=0]
"

i want to find xpath of total beds=0.
how can i do?

A: Your question and your comment are a bit contradictory. Do you want to find the text after a heading or do you want to find the element containing the text [total beds=0]? Also, how exact do you want to navigate your document?
To find a text after any h3 element you can use this: //h3/following-sibling::text()[1] (see XPath - select text after certain node).
To find a text after an h3 element with the class "xs-highlight" you can use this: //h3[@class='xh-highlight']/following-sibling::text()[1]
To be even more precise you can also look for the heading text: //h3[@class='xh-highlight' and text()='Units Currently On Bed List']/following-sibling::text()[1]
This doesn't match the html in your first comment however, so you might want to adjust the header class and text values. Also, it will find any first text even if there are other elements between it and the h3 element.
Now, your second comment makes it seem you actually want to find the element containing the text. The reason //*[text()='[total beds=0]'] doesn't work is because of the newline in the text. If you can get rid of that in the source it should match, otherwise you can "ignore" it in the xpath by using //*[normalize-space(text())='[total beds=0]']. (This is assuming the quotes around the text in your question aren't actually in the document.)


text:
Q: How can I write the results of a SQL query to azure cloud storage? Our current data set is not friendly in terms of looking at historic records. I can see what a value for an account is at the time of execution but if I want to look up last month's counts and values that's often lost. To fix this I want to take a "snapshot" of our data by running it at specific times and storing the results in the cloud. We're looking at just over 30,000 records and I'd only run it at the end of the month keeping 12 separate months at a time so the count doesn't get too high.
I can't seem to find anything about how I could do this so I'm hoping someone has experience or knowledge and would like to share.
FYI we're using an on premise oracle DB.
Thanks!

A: You can use Azure Data Factory (ADF) to schedule a monthly run for a pipe that execute a query/stored procedure against your Azure SQL and writes the data to Azure Storage.


text:
Q: Генерация звука Здравствуйте.
Недавно задали написать программу, генерирующую определенную частоту звучания, зависящую от нажатия клавиш на клавиатуре. Клавиатура должна содержать не менее двух октав звуков на ассемблере i8086. Ничего в голову не приходит, даже как начать программу.
Помогите, пожалуйста. Заранее спасибо
A: .286
.model small
.stack 20h
.data

.code

sound proc
    pusha
    ;mov di,6000   ;частота звука
    ;mov bx,2000   ;длительность
    mov al,0b6H
    out 43H,al
    mov dx,0014H
    mov ax,4f38H
    div di
    out 42H,al
    mov al,ah
    out 42H,al
    in al,61H
    mov ah,al
    or al,3
    out 61H,al
    l1:     mov cx,2801H
    l2:     loop l2
    dec bx
    jnz l1
    mov al,ah
    out 61H,al
    popa
    ret
sound endp

start:
    mov di,500 ;     загрузка частоты звучания динамика
    mov bx,2000;    загрузка длительности звучания в тактах м/п
    call sound

    mov di,1000 ;     загрузка частоты звучания динамика
    mov bx,2000;    загрузка длительности звучания в тактах м/п
    call sound

    mov di,1500 ;     загрузка частоты звучания динамика
    mov bx,2000;    загрузка длительности звучания в тактах м/п
    call sound

    mov ah,4cH
    int 21H

end start


text:
Q: Analytic solution for high-order non-linear differential equation Is there a way to analytically solve an equation of this form:
$$y''''[x]+y[x]*y'''[x]=0$$
where the initial conditions for y through the fourth derivatives are known.
I have used lower-order substitutions to convert the equation to a system of first-order differential equations, and now I am appeared forced to apply a numerical method e.g., Runge-Kutta. However, an analytical form would be much more appreciated.
Thanks!


text:
Q: using bitmap to find resources of an imageview in another layout Is it possible to use bitmap to get resources from an image view that is in another layout?
I am able to get resource from the image using this code below
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.large_icon);

But is there a way to getResouce from an imageview? I want to be able to choose an image from gallery or take a photo and put It in imageView. And to process the image.

A: If you want to pick image from galery or take a photo from camera - you should ask system to do it and the use bitmap object to process it and to set it to image view
First, ask system to provide image to you:
    public void onSelectFromGalery() {
            Intent requestIntent = new Intent(Intent.ACTION_PICK);
            requestIntent.setType("image/jpeg,image/png");
            startActivityForResult(requestIntent, SELECT_REQUEST_CODE);
    }

Then process result:
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if (requestCode == SELECT_REQUEST_CODE && resultCode == RESULT_OK) {
            if (Build.VERSION.SDK_INT >= 16 && data.getClipData() != null) {
                ClipData clipData = data.getClipData();
                for (int i = 0; i < clipData.getItemCount(); i++) {
                    ClipData.Item item = clipData.getItemAt(i);
                    Uri uri = item.getUri();
                    String path = getImagePathFromUri(uri);
                    if (path != null) {
                        Bitmap bitmap = BitmapFactory.decodeFile(path);
                        //process bitmap
                        imageView.setImageBitmap(bitmap);
                    }
                }
            } else if (data.getData() != null) {
                Uri imageUri = data.getData();
                String path = getImagePathFromUri(imageUri);
                if (path != null) {
                        Bitmap bitmap = BitmapFactory.decodeFile(path);
                        //process bitmap
                        imageView.setImageBitmap(bitmap);
                }
            }
        }
}


text:
Q: CloudWatch Custom Metric Names Not Showing in Grafana I'm new to Grafana and have a query.
I have created a Grafana instance running on EC2 and attached a role with Cloudwatch permisisons to it.
I've configured the Cloudwatch datasource and tested it and it all works fine.
It doesn't look like Grafana is able to load custom metrics by default, so I've specified the names of the custom namespace in the Namespaces of Custom Metrics field and I can see them now in the query editor.
However, I don't see any metric names, even though they are present in Cloudwatch.

But when I select one of the default AWS namespaces, I see all the metric names populated.

Is there a way to get Metric Names for custom namespaces to show up in Grafana?

A: Make sure you have correct name in Namespaces of Custom Metrics field config. It is case sensitive. Also space there can be a problem. You may try to upgrade your Grafana. It works fine for me with Grafana 8.3.x version.


text:
Q: Get file locking handle I would like to close the handles of all processes that access a certain file. To retrieve the processes, I use the solution of Eric J. in this thread. Now, unfortunately, it does not work to close the Process.Handle with the Winapi function CloseHandle(). The Process class returns the correct pid, but not the correct handle.
This can also be seen when using Handle from Mark Russinovich. This returns a different handle, which you can actually close with the given function.
So, can I get the file locking handle from the Process class? And if not, which Winapi should I use for it?
(Working) Handle by Mark Russinovich:
C:\dev\Handles\Handle>handle.exe C:\dev\Handles\test.accdb

MSACCESS.EXE       pid: 5952   type: File           EA4: C:\dev\Handles\test.accdb

Process Handle:
List<Process> LockingProcesses = FileUtil.WhoIsLocking(@"C:\dev\Handles\test.accdb");
foreach (Process process in LockingProcesses)
{
    CloseHandle(process.Handle);
}

Solution (credit to Remy Lebeau):
Handle.exe is reporting the actual file handle within the target process. Process.Handle returns the process handle of the EXE file that created the process which FileUtil.WhoIsLocking() says has the target file open. Two completely different things, which is why they are different values.
See How can I close a handle in another process? for a detailed explanation of how to find and close handles in other processes, similar to how SysInternals Process Explorer does.


text:
Q: Share a picture on facebook, not via URL I have a website and I would like to share pictures to Facebook using a button.
I am confused about how the share of a picture really works, I have easily implemented the share of the picture via URL http://m.facebook.com/sharer.php?u=[URL]&title=[title] and this requires my picture to be hosted on my server.
But I am wondering what other options are available?
Is it possible to share a picture directly on Facebook (like if the user was uploading it on Facebook itself)? I have heard about oAuth but I don't understand if this is using 3rd party libraries or if it is part of the Facebook libraries?
Many thanks

A: You would need to use the /me/photos endpoint to upload a picture, there is example code in the docs: https://developers.facebook.com/docs/graph-api/reference/user/photos/
The user must be authorized with the publish_actions in order to make this work.
Here´s some more information about authorization/login:

*

*https://developers.facebook.com/docs/facebook-login/

*http://www.devils-heaven.com/facebook-javascript-sdk-login/


text:
Q: UIView doesn't resize to full screen when hiding the nav bar & tab bar I have an app that has a tab bar & nav bar for normal interaction.  One of my screens is a large portion of text, so I allow the user to tap to go full screen (sort of like Photos.app).
The nav bar & tab bar are hidden, and I set the the text view's frame to be full screen.  The problem is, there is about 50px of white space where the tab bar used to be.  You can see if from this screen shot:
removed dead ImageShack link
I'm not sure what's causing this.  The whitespace is definitely not the view behind the text view, as I set it's background color to red just to be sure.  What could be causing this?
** UPDATE **
I did some hit testing in a UIWindow subclass and found out that the whitespace is actually the undocumented/unpublished UILayoutContainerView.  This is the parent view of the tabBar.  I don't think it's recommended to directly manipulate this view, so how can I hide the tab bar?
** UPDATE # 2 **
I checked self.view's frame before & after animation, and it looks like the parent view is not resizing enough.
after going fullscreen, the view's frame is only 411 pixels tall.  I've tried messing with the frame manually and also setting autoResizeMask with no luck.
**** UPDATE:  Here's the end result ****
- (void)toggleFullscreen {
    isFullScreen = !isFullScreen;  //ivar

    //hide status bar & navigation bar
    [[UIApplication sharedApplication] setStatusBarHidden:isFullScreen animated:YES];
    [self.navigationController setNavigationBarHidden:isFullScreen animated:YES];

    [UIView beginAnimations:@"fullscreen" context:nil];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:.3];

    //move tab bar up/down
    CGRect tabBarFrame = self.tabBarController.tabBar.frame;
    int tabBarHeight = tabBarFrame.size.height;
    int offset = isFullScreen ? tabBarHeight : -1 * tabBarHeight;
    int tabBarY = tabBarFrame.origin.y + offset;
    tabBarFrame.origin.y = tabBarY;
    self.tabBarController.tabBar.frame = tabBarFrame;

    //fade it in/out
    self.tabBarController.tabBar.alpha = isFullScreen ? 0 : 1;

    //resize webview to be full screen / normal
    [webView removeFromSuperview];
    if(isFullScreen) {
                //previousTabBarView is an ivar to hang on to the original view...
        previousTabBarView = self.tabBarController.view;
        [self.tabBarController.view addSubview:webView];

        webView.frame = [self getOrientationRect];  //checks orientation to provide the correct rect

    } else {
        [self.view addSubview:webView];
        self.tabBarController.view = previousTabBarView;
    }

    [UIView commitAnimations];
}

(note that I switched textview to webview, but the same works for the original text view)

A: You can definitely make something that appears correct by shifting the frame of the view such that the tab bar is off screen. I know someone else mentioned trying that, and you said it didn't work, but I suspect the issue is that you did not have the textviews resize mask setup properly when you tried. Below is code that should work:
- (void)viewDidLoad {
  [super viewDidLoad];
  currentlyHidden = NO;
}

- (void) hideStuff {
  SO2AppDelegate *appDelegate = (id)[[UIApplication sharedApplication] delegate];
  self.navigationController.navigationBarHidden = YES;

  CGRect newFrame = appDelegate.tabBarController.view.frame;
  newFrame.size.height += appDelegate.tabBarController.tabBar.frame.size.height;
  appDelegate.tabBarController.view.frame = newFrame;
}

- (void) showStuff {
  SO2AppDelegate *appDelegate = (id)[[UIApplication sharedApplication] delegate];

  CGRect newFrame = appDelegate.tabBarController.view.frame;
  newFrame.size.height -= appDelegate.tabBarController.tabBar.frame.size.height;
  appDelegate.tabBarController.view.frame = newFrame;

  self.navigationController.navigationBarHidden = NO;
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  if (currentlyHidden) {
    [self showStuff];
    currentlyHidden = NO;
  } else {
    [self hideStuff];
    currentlyHidden = YES;
  }
}

Additionally, since this is definitely sensitive to how you have your nibs etc setup, I am posting a a project online so you can download it and get a look at it. It is a pretty minimal demo, just a Navigation based project where the delegate sets up a tab controller and embeds the view controller from the main nib. The rest is in the RootViewController nib and class. The bars are toggled whenever a touch begins, so just tap the screen. Obviously in a real app you might need to adjust the scroll view so stuff the content doesn't appear to jump.

A: I had this exact problem where I was animating the tab bar and navigation bar off the bottom and top of the screen respectively, leaving a 49px high white space where the tab bar was.
It turns out that the reason my new "fullscreen" view wasn't actually filling the space was because I was adding the fullscreen view as a subview of the navigation controller's view, which itself was a child of the tab bar controller.
To fix it, I simply added the new fullscreen view (in your case the view with all the text) as a subview of the UITabBarController's view.

[[[self tabBarController] view] addSubview:yourTextView];

Then all you need to do is make sure that your subview's frame is 480 x 320px and it should fill the screen (including the area that was previously the mysterious white space)

A: Have you set your view controller's hidesBottomBarWhenPushed property to YES?  You need to set this in your initWithNibName:bundle: or initWithCoder: method.  When it gets pushed to the nav controller, this should hide the tab bar and make the content view extend down to the bottom.

A: Maybe there's another view that is a built-in part of the tab bar area?  That is to say, something additional to hide.  This will help you see what views are around.
for (UIView *viewy in [self.navigationController.view subviews])
{
    NSLog([viewy description]);
}

A: I found that if you mark the new view you will be pushing onto the navigation stack with the following line hides the tab bar as long as it is on the stack.
scrollViewController.hidesBottomBarWhenPushed = YES;

A: I had similar issue. As Harry mentioned it's a reason of Navigation Controller that is inner controller of Tab Bar Controller. Found another way how to redraw your view and have correct frame., In your controller add following:
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    // Here you can make your tabBarControlelr.view.hidde = true or use any animation that hides UITabBar. I made
    [TabBarController setTabBarHidden:YES];

    self.navigationController.view.frame = CGRectMake(self.navigationController.view.frame.origin.x, self.navigationController.view.frame.origin.y, self.navigationController.view.frame.size.width, self.navigationController.view.frame.size.height + 50);
    [self.navigationController.view setNeedsLayout];

 }

And here is how I hide it. I can make it directly calling method of TabBarControlelr or class method wrapper:
+ (void)setTabBarHidden:(BOOL)hidden
{
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    TabBarController *tabBarController = (TabBarController *) delegate.window.rootViewController;

    if ([tabBarController isKindOfClass:[TabBarController class]]) {
        [tabBarController setTabBarHidden:hidden];
    }
}

- (void)setTabBarHidden:(BOOL)hidden
{
    if (self.tabBar.hidden == hidden) {
        return;
    }

    if (hidden == NO) {
        self.tabBar.hidden = hidden;
    }

    [UIView animateWithDuration:0.15 animations:^{
        self.tabBar.frame = CGRectOffset(self.tabBar.frame, 0, ( hidden ? 50 : -50 ));
    } completion:^(BOOL finished) {
        self.tabBar.hidden = hidden;
    }];
}

A: I believe the issue is that you're still in the tab bar controller, I've hit a few issues with this as well, and ended up creating two views for my app delegate to control, the tab bar controller , and a separate uiview that holds anything that the tab bar controller tries to take command of.  You could pass your view to the app delegate and use it there perhaps?

A: Try making the TabBarControllers view larger than the screen so that the tab bar is hidden off screen, as long as you do this before the new ViewController is set, then its view will resize to fill the new frame!
In my test I used the tabBarController:shouldSelectViewController: delegate method to check which view controller is about to become current and set the TabBarController.view.frame accordingly. For example:
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    if( viewController == second)
        tabBarController.view.frame = CGRectMake( 0, 20, 320, 500);
    else
        tabBarController.view.frame = CGRectMake( 0, 20, 320, 460);
}

If this still isn't quite what you need, try looking into the hidesBottomBarWhenPushed property of UIViewController. When set to yes this will make the bottom bar hide if the Controller is pushed onto a Navigation stack.

A: I would move the view to the window when you choose to go fullscreen. e.g.
myView = [self.view retain];
self.view = nil;
[window addSubview:myView];

and to go back:
[myView removeFromSuperView];
self.view = myView;
[myView release];
myView = nil;

By adding the view as a child of the window, it can be totally fullscreen and will be on top of the tab bar.
You can then combine this with
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didRotate:) name:@"UIDeviceOrientationDidChangeNotification" object:nil];

to detect rotation. (I think that you combine this with view.transform = CGAffineTransformMakeRotation to make it rotate...?)

A: If you are using Interface Builder, ensure autoresizing is set properly in the Size Inspector.
If you creating the UITextView in code, make sure you set the frame to be large enough and that the view's parent (and it's parent) are also large enough. For simplicity, add the view to the window directly, and then move inward from there.
To move a view to its superview:
- (void)moveViewToSuperview:(UIView *)view
{
    UIView *newSuperview = [[view superview] superview];
    [view removeFromSuperview];
    [newSuperview addSubview:view];
    [newSuperview bringSubviewToFront:view];
}

A: Have you attempted to force the text to "re-write" itself (resetting the .text property of whatever object you're using)? I have had many instances where views simply do not re-check or repaint their data, and forcing seems to be the only fix.  If this is not good from a user experience standpoint, you might try making the nav/tabbars transparent after the user touches, and before they disappear. This normally extends the view to the full size of the screen.

A: If the UITabBarController is pushed by a rootViewController (navigationController). You can try the following:
First hide the status Bar / Tab Bar;
[self.navigationController pushViewController:aBlankViewController animated:NO];
[self.navigationController popViewControllerAnimated:NO];

You should be able to reclaim the white space, though the screen will shock during the adjustment...

A: I've experienced a similar issue, this discussion was helpful: UIWebView on iPad size
Tony's answer helped me discover that when you create a subview it's helpful to setup code similar to this:
self.tabBarController.tabBar.frame = self.view.bounds;

A: Put the code in a prepare for segue like this, works perfectly for me:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"ViewPhoto"]) {

    ImageView *vc = [segue destinationViewController];

    NSInteger selectedIndex = [[self.tableView indexPathForSelectedRow] row];

        NSString *Title = [photoNames objectAtIndex:selectedIndex];
        [vc setSelectedTitle:[NSString stringWithFormat:@"%@", Title]];

        vc.hidesBottomBarWhenPushed = YES;

        }
    }

A: Add the extra amt of space to the dimension of the view, so if it was rectangle CGRectMake(0,0,320,460) make it CGRectMake(0,0,320,480)... This has happened to me, Im n ot exactly sure why, it might ahve to do with the underlying view you are putting your text view on top off, but just adding the dimension should do it


text:
Q: setting toolchain file in visual studio code and cmake tool for vsc doesn't work I am using visual studio code on Ubuntu 20.04 and cmake tools for visual studio code.
I am trying to use opencv in a project. I used vcpkg to build OpenCV and it is installed:
The cmakeList.txt is as follow:
cmake_minimum_required(VERSION 3.0.0)
set(CMAKE_TOOLCHAIN_FILE /home/m/vcpkg/scripts/buildsystems/vcpkg.cmake)
project(testcmake VERSION 0.1.0)

include(CTest)
enable_testing()
find_package(OpenCV REQUIRED)

add_executable(testcmake main.cpp)

set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)

I also added this line to setting.json:
{
    "cmake.configureOnOpen": false,
    "C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools",

    "cmake.configureSettings": {
      "CMAKE_TOOLCHAIN_FILE": "/home/m/vcpkg/scripts/buildsystems/vcpkg.cmake"
    }
  }

but when I run cmake, I am getting this error:
[main] Building folder: cmakeTest
[main] Configuring folder: cmakeTest
[proc] Executing command: /usr/bin/cmake --no-warn-unused-cli -DCMAKE_TOOLCHAIN_FILE:STRING=/home/m/vcpkg/scripts/buildsystems/vcpkg.cmake -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -DCMAKE_BUILD_TYPE:STRING=Debug -DCMAKE_C_COMPILER:FILEPATH=/bin/gcc-9 -DCMAKE_CXX_COMPILER:FILEPATH=/bin/g++-9 -H/home/m/MyData/sourceCode/cmakeTest -B/home/m/MyData/sourceCode/cmakeTest/build -G "Unix Makefiles"
[cmake] Not searching for unused variables given on the command line.
[cmake] -- Configuring incomplete, errors occurred!
[cmake] See also "/home/m/MyData/sourceCode/cmakeTest/build/CMakeFiles/CMakeOutput.log".
[cmake] CMake Error at CMakeLists.txt:7 (find_package):
[cmake]   By not providing "FindOpenCV.cmake" in CMAKE_MODULE_PATH this project has
[cmake]   asked CMake to find a package configuration file provided by "OpenCV", but
[cmake]   CMake did not find one.
[cmake]
[cmake]   Could not find a package configuration file provided by "OpenCV" with any
[cmake]   of the following names:
[cmake]
[cmake]     OpenCVConfig.cmake
[cmake]     opencv-config.cmake
[cmake]
[cmake]   Add the installation prefix of "OpenCV" to CMAKE_PREFIX_PATH or set
[cmake]   "OpenCV_DIR" to a directory containing one of the above files.  If "OpenCV"
[cmake]   provides a separate development package or SDK, be sure it has been
[cmake]   installed.
[cmake]
[cmake]

Why make can not find opencv using vcpkg?
Edit 1
I compiled OpenCV for x64:
opencv4:x64-linux                                  4.3.0#1          computer vision library
opencv4[dnn]:x64-linux                                              Enable dnn module
opencv4[jpeg]:x64-linux                                             JPEG support for opencv
opencv4[opengl]:x64-linux                                           opengl support for opencv
opencv4[png]:x64-linux                                              PNG support for opencv
opencv4[tiff]:x64-linux                                             TIFF support for opencv
opencv4[webp]:x64-linux                                             WebP support for opencv
opencv:x64-linux                                   4.3.0            Computer vision library
opencv[dnn]:x64-linux                                               Enable dnn module
opencv[jpeg]:x64-linux                                              JPEG support for opencv
opencv[opengl]:x64-linux                                            opengl support for opencv
opencv[png]:x64-linux                                               PNG support for opencv
opencv[tiff]:x64-linux                                              TIFF support for opencv
opencv[webp]:x64-linux                                              WebP support for opencv

I know that I should set the vcpkg triplets, how can I set it by default so all applications use it instead of putting it in cmake?
Update 2
I set the triplets as following but still getting the same error:
cmake_minimum_required(VERSION 3.0.0)
set(CMAKE_TOOLCHAIN_FILE /home/m/vcpkg/scripts/buildsystems/vcpkg.cmake)
set(VCPKG_TARGET_TRIPLET x64-linux CACHE STRING "VCPKG Target Triplet to use")
project(testcmake VERSION 0.1.0)

include(CTest)
enable_testing()
find_package(OpenCV REQUIRED)

add_executable(testcmake main.cpp)

set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)


text:
Q: AWS - Iniciar Segunda Instância Via Cloudwatch Olá, eu tenho um cenário com 2 instâncias, em um "load balance no iis - Windows Server", porém na maior parte do tempo, apenas uma instância aguenta a carga.
Portanto, o cliente me solicitou, para manter a segunda instância desligada e startar ela apenas quando a primeira instância atingir 90% de uso de CPU.
Verifiquei e via EC2-Load Balance, ou CloudWatch, eu só tenho a opção de subir uma AMI da primeira instância (instância onde foi detectado o alto uso de CPU), mas uma AMI não atende este cenário visto que são instâncias um pouco diferentes.
Teria alguma forma, talvez via LAMBDA, para, quando ocorrer o evento (USO de CPU alto), eu startar remotamente a segunda instância?
Obrigado.

A: Seria mais simples criar um auto-scaling grup para a segunda instancia com o minimo de 0 e maximo de 1, mudando em reacao ao alarme. A função funcionaria também, mas dá mais trabalho.


text:
Q: Using clojure to scrape a web page with dynamic content For learning purpose, I am trying to use Clojure to scrape data from the following site.
I would like to know how do to get the data in the table "bm_center bm_dataTable".
The challenge I have is that this table's DOM is not available on this page's html source, because it is dynamically generated in the browser.
How do I get the hml source of the table?
I know very little about web programming but am willing to learn. Thank you in advance for your patience.

A: The DOM is normally a thing that lives in the browser. The browser pulls down the same text that you're seeing in Clojure and then builds the DOM that it uses to render the page etc...
You can manipulate the text manually to pull out what you want by writing Clojure code. You could use a Java library like JSoup to extract information from the HTML. The standard Java libraries also come with an HTML parser, but I would avoid it. It is difficult to use and doesn't really bring much benefit.


text:
Q: setTimeout não funciona com For no javascript Estou começando no mundo de javascript e estou com um dúvida que mata minha lógica. Eu quero que um método repita uma quantidade de vezes a cada certo tempo, porém não funcionando ao usar a estrutura de repetição For, podem me ajuda a entender por favor?

var repetirFunc = function(){
  for (var i = 1; i <= 11; i++){
    setTimeout(function(){
      console.log('Texto');
    }, 2000);
  }
}

repetirFunc();

No exemplo acima eu gostaria que o "texto" repetisse 11 vezes a cada 2 segundos, porém demora 2 segundos somente o primeiro loop, depois disso ele te lança na tela todas as repetições.
Imagem 1: Os primeiros 2 segundo fica assim

Imagem 2: Depois dos primeiros 2 segundos, ele te lança as 11 repetições de uma só vez

obrigado

A: O código está fazendo justamente o que foi pedido para ser feito. Você registra uma função no setTimeout e informa que daqui 2000 milissegundos essa função deve ser disparada. Note que quando você chama o método setTimeout o código continua executando normalmente, ele não aguarda 2000 milissegundos para continuar. Esse na verdade é o motivo de existir o setTimeout, para deixar seu código assíncrono, para que nesse tempo ocioso o JavaScript possa trabalhar com outras coisas.
Você terá que usar outra solução para o seu problema, um deles pode ser o uso do setInterval com um controle de variável.
var repetirFunc = function(empresa){
  var limite = 11;
  var i = 0;

  var intervalId = setInterval(function() {
    if (i++ > 11) return clearInterval(intervalId);

    console.log('Texto');
  }, 2000);
}

repetirFunc();

Se quiser manter o uso de setTimeout, você pode calcular os milissegundos em cada iteração.
var repetirFunc = function(empresa){
  for (var i = 1; i <= 11; i++){
    setTimeout(function(){
      console.log('Texto');
    }, 2000 * i);
  }
}

repetirFunc();

A: Acredito que o que você esteja buscando seja o setInterval e não o setTimeout.

*

*setInterval: Vai rodar 1 vez a cada 2 segundos;

*setTimeout: Vai esperar 2 segundos para rodar todo o código;

Tente o seguinte código:
var repetirFunc = function(empresa){
    for (var i = 1; i <= 11; i++){
        setInterval(function(){
            console.log('Texto');
        }, 2000);
    }
}


text:
Q: CompletableFuture uniApply method I want to know that the using about uniApply of Java8 CompletableFuture class.
And I fell confused it. For example,the section of the code:
private <V> CompletableFuture<V> uniApplyStage(
    Executor e, Function<? super T,? extends V> f) {
    if (f == null) throw new NullPointerException();
    CompletableFuture<V> d =  new CompletableFuture<V>();
    if (e != null || !d.uniApply(this, f, null)) {
        UniApply<T,V> c = new UniApply<T,V>(e, d, this, f);
        push(c);
        c.tryFire(SYNC);
    }
    return d;
}


text:
Q: Image in Action bar without AppCompatActivity and with android:Theme.Holo.Light theme I want to place an image(ImageView) in top right corner of an Action bar. I don't want to use AppCompatActivity library and so my MainActivity extends Activity instead of AppCompatActivity.
I use theme:  <style name="AppTheme" parent="android:Theme.Holo.Light">
I tried with this code but it doesn't work because I don't extend AppCompatActivity:
 actionBar = getSupportActionBar();
        actionBar.setDisplayShowCustomEnabled(true);

        LayoutInflater inflator = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflator.inflate(R.layout.custom_imageview, null);

        v1 = inflator.inflate(R.layout.custom_imageview1, null);

        actionBar.setCustomView(v);

EDIT: I run this code on a device that runs Android 4.4.2

A: You can use Toolbar for this. It is best option for you.Toolbar is a new standard replacement for ActionBar, introduced in Android Lollipop. It supports whole bunch of customization as you wish along with no or less modification to ActionBar logic.
Or you can use code :`
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ActionBar mActionBar = getActionBar();
    mActionBar.setDisplayShowHomeEnabled(false);
    mActionBar.setDisplayShowTitleEnabled(false);
    LayoutInflater mInflater = LayoutInflater.from(this);

    View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
    TextView mTitleTextView = (TextView) mCustomView.findViewById(R.id.title_text);
    mTitleTextView.setText("Title");

    ImageButton imageButton = (ImageButton) mCustomView
            .findViewById(R.id.imageButton);
    imageButton.setOnClickListener(new OnClickListener() {

        //if you want..You can set action
        }
    });`

A: Since you are using a simple Activity you have to change this line
actionBar = getSupportActionBar();

with (check the doc)
actionBar = getActionBar();


text:
Q: AWS S3 uploads stuck in WAITING state I've looked at several questions and answers about this but I'm still unable to upload to an S3 bucket. I have alreadydeclared the service in the manifest within the application tags.
Every log statement returns the correct information, but the status is always WAITING and none of the transfer listeners are triggered. I do not receive any errors whatsoever and the S3 bucket continues to be empty.
What am I doing wrong?
public void uploadStoredItems() {

    TransferUtility transferUtility = TransferUtility.builder()
            .context(AWSProvider.getInstance().getContext())
            .awsConfiguration(AWSProvider.getInstance().getConfiguration())
            .s3Client(new AmazonS3Client(AWSProvider.getInstance().getIdentityManager().getCredentialsProvider()))
            .build();

    try {
        for (File csvFile : csvFiles) {
            String filename = csvFile.getName(); //.substring(csvFile.getName().lastIndexOf('/') + 1);
            Log.d(TAG, "This is the filename for upload: " + filename);

            // FileReader reads text files in the default encoding.
            String line = null;
            FileReader fileReader = new FileReader(csvFile);

            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            while ((line = bufferedReader.readLine()) != null) {
                Log.d(TAG, "Here are the lines: " + line);
            }

            // Always close files.
            bufferedReader.close();

            TransferObserver uploadObserver = transferUtility.upload(filename, csvFile);
            // Gets id of the transfer.
            Log.d(TAG, "This is the bucket: " + uploadObserver.getBucket());
            Log.d(TAG, "This is the state: " + uploadObserver.getState());
            Log.d(TAG, "This is the id: " + uploadObserver.getId());

            observers = transferUtility.getTransfersWithType(TransferType.UPLOAD);
            TransferListener listener = new TransferListener() {
                @Override
                public void onStateChanged(int id, TransferState state) {
                    Log.d(TAG, "onStateChanged: " + state.toString());
                    if (TransferState.COMPLETED == state) {
                        Log.d(TAG, "COMPLETE: " + state.toString());
                    }
                }

                @Override
                public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
                    float percentDonef = ((float) bytesCurrent / (float) bytesTotal) * 100;
                    int percentDone = (int) percentDonef;

                    Log.d(TAG, "ID:" + id + " bytesCurrent: " + bytesCurrent
                            + " bytesTotal: " + bytesTotal + " " + percentDone + "%");
                }

                @Override
                public void onError(int id, Exception ex) {
                    // Handle errors
                    Log.d(TAG, "ERROR ID:" + id + " " + ex.getMessage());
                }
            };

            for (TransferObserver observer : observers) {

                if (TransferState.WAITING.equals(observer.getState())
                        || TransferState.WAITING_FOR_NETWORK.equals(observer.getState())
                        || TransferState.IN_PROGRESS.equals(observer.getState())) {
                    observer.setTransferListener(listener);
                }

                Log.d(TAG, "\n observers - id: " + observer.getId() + " state: " + observer.getState() + " key: " + observer.getKey() + " bytes total: " + observer.getBytesTotal());
            }
            Log.d(TAG, "Bytes Total: " + uploadObserver.getBytesTotal());

        }
        csvFiles.clear();
    } catch(java.io.FileNotFoundException ex) {
        System.out.println("Unable to open file");
    } catch(java.io.IOException ex) {
        System.out.println("Error reading file");
    }
}

A: Turns out I have to declare the TransferUtility service to run in the same process that the service I am calling it from is running:
<application

    ...

    <service
      android:name=".MainService"
      android:enabled="true"
      android:process=":main_service"
      android:stopWithTask="false" />
    <service
      android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
      android:process=":main_service"
      android:enabled="true" />

    ...

</application>


text:
Q: QtCreator's qmake with nvcc and CUDA, Windows 7 I've seen many old tries to combine QtCreator with CUDA, but they all don't work anymore.
So I'm starting this topic so that there could be a new reference for everyone.
First, I tried to compile the code like the book mentions, with the following command:
nvcc seqCuda.cu -o seqCuda

But I got the error: invalid redecleration of type name "size_t".
The only thing I was able to do was compiling this sample code from the book "CUDA Application Design and Development" using Visual Studio 2010; however, VS2010 isn't the environment I wanna use. So I went to log files and took the execution command it uses, and it's the following:
nvcc -gencode=arch=compute_10,code=\"sm_10,compute_10\" --use-local-env --cl-version 2010 -ccbin "c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin"  -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.1\include"    --keep-dir "Release" -maxrregcount=0  --machine 32 --compile      -Xcompiler "/EHsc /nologo /Od /Zi  /MD " -o "Release\main.cu.obj" "C:\Users\Sam\Documents\Visual Studio 2010\Projects\CUDA_TestVS2010\CUDA_TestVS2010\main.cu"

This command creates an object file. I could execute it for the sample code from seqCuda.cu successfully, but I don't know how to go from the object file to the executable. I want to do that in Qt using a qmake file.
Could anyone please tell me what are the important parts of this compiling command and how I can do it the merge it the right way in a qmake file?
Now my problem is, I tried to disassemble this command and rewrite it with qmake, and yes I was stabbing in the dark, and couldn't achieve any satisfying result. The following is my "try" to do that in qmake. If you could replace any of the commands in the following qmake with environment variables, I'd be thankful, especially the VC2010 bin dir.
win32 {
    INCLUDEPATH += $(CUDA_INC_PATH)
    QMAKE_LIBDIR += $(CUDA_LIB_PATH)
    ARCFLAGS = -gencode=arch=compute_10,code=\"sm_10,compute_10\" --use-local-env
    VSVERSIONFLAGS = --cl-version 2010
    VSDIRFLAG = -ccbin "c:/Program Files (x86)/Microsoft Visual Studio 10.0/VC/bin"
    OTHERFLAGS = -maxrregcount=0  --machine 32 --compile
    -Xcompiler "/EHsc /nologo /Od /Zi  /MD "
    LIBS += -lcudart

    cuda.output = ./${QMAKE_FILE_BASE}_cuda.obj
    cuda.commands = $(CUDA_BIN_PATH)/nvcc.exe $$ARCFLAGS $$VSVERSIONFLAGS $$VSDIRFLAG -
    I$(CUDA_INC_DIR)     $$OTHERFLAGS
}

CUDA_SOURCES += seqCuda.cu
cuda.input = CUDA_SOURCES
QMAKE_EXTRA_COMPILERS += cuda


text:
Q: Scale docker container with ENV settings If I have a simple counting program: given a starting number, the program will output 10 numbers from the starting number with increment of 1.
I want to have 0 to 49 as output (order is not a hard requirement). Can I use docker to do something like scale to 5 containers, but setting some ENV as the starting point of each container? Assuming I'm fine with multiple containers will not guarantee the order.
For example: container 1 will start with 0, container 2 will start with 10...container 5 will start at 40. The output may be [0, 9], [40, 49], [30, 39], [10, 19], [20, 29].

A: You can certainly achieve this using the -e argument with the docker run command. The sample below shows how to launch containers with an environment variable 0-49 and uses the alpine image for demonstration purposes:
for i in {0..49}
do
    docker run -it -e "IDX_ENV=$i" alpine:latest env
done

Note the output will just print the environment for each invocation:
...
IDX_ENV=0
HOME=/root
...

Each container will, of course, exit after printing the environment. If you need to run something more "real" such as a long running process, I suggest that you run the containers in detached mode with the -d option and set an entrypoint that makes use of the environment passed in.


text:
Q: Can't access Entity Framework table with no primary key I am creating an application to transfer data from one database into another for a new application and I am running into an issue access some of the data in the old database. The old database was created using Ruby on Rails and they way it was designed and created through Rails, the database in SQL Server has no primary keys and all the columns are nullable. The new database was designed and built in SQL Server with proper keys and nullable columns. Since both databases are in SQL Server I wanted to use Entity Framework Database First to make the data transition easier.
In the EF Desginer I was able to assign entity keys to all of the tables except for one (Response), which is keeping me from correctly accessing the data in the table. The table definition is as follows:
assess_id [int] NULL
person_id [int] NULL
question_id [int] NULL
question_version [int] NULL
answer_id [int] NULL
answer_version [int] NULL
text [nvarchar(4000)] NULL
created_at [datetime] NOT NULL
updated_at [datetime] NOT NULL

Because of the allowed records the primary key should consist of
assess_id
person_id
question_id
question_version
answer_id
answer_version

but there may be multiple answer_id and answer_version records to the same question_id and question_version or the answer_id and answer_version are null so I cannot use that. Any subset of this key would not allow me to properly retrieve all the data. Also I cannot use the created_at or updated_at columns as there are multiple instances of rows being written with the same time stamp.
I only need to read the data, not write, since it is being transformed into the new database and there is no way for me to change the existing database. Is there any way around the key issue?

A: Before I answer I would like to point out that this solution only works for read-only situations and if you need to write to the table it will not help. In that case I point you to this answer where you will find some help.

I managed to find a work around for this scenario and while easy enough to use, I would not consider it optimal.
In order to get around the key issue, I picked a primary key that would at least not fail a null check, in this case just the assess_id and person_id columns. This let me build without any errors but I still could not retrieve all the data correctly.
The workaround is to use a SqlQuery on the database.
var responses = context.Database.SqlQuery<Response>("SELECT * FROM dbo.responses");

This executed the query on the whole database and casted the result set into a list of responses with the correct data. Make sure you execute the query  on the database and not the table, otherwise the incorrect key specified in the designer will be used and you won't get the correct data back.

A: Put your SQL in a stored procedure and call that from your application.
If you cannot modify the source database, you can put the stored procedure in the destination.


text:
Q: Python: A very simple star patterned box I have to make a box that is empty from inside.
I want to make a box that looks somthing like this:
+++
+ +
+++

The width can vary. This is my code so far.
width = int(input("Enter box size(3-30) >>>"))
top = "+" * width
middle =
bottom = "+" * width

Not sure what to put in the middle.

A: Since the middle is "+" followed by width - 2 empty spaces and then another "+", you can set middle to "+" + " " * (width - 2) + "+".


text:
Q: Preferable to vs. Better than Staying at home is "preferable to" going out with someone you don't like.
Staying at home is "better than" going out with someone you don't like.
Do the two sentences mean exactly the same thing? If not, could you please explain it?

A: To say something is preferable is to say it is a better choice. This does not always mean it is better. For example, in the context of some vaccinations "old people are preferable to young people" may be true (if they are more likely to get sick when unvaccinated) while "old people are better than young people" may be false.
In your example the two sentences are almost the same, though there may be some reason I can't think of to prefer the worse alternative.


text:
Q: Why does Fedora not include GCC by default? I just finished a Fedora 21 clean installation. I have updated and upgraded, but I notice the following: GNU GDB is installed by default, as GNU Make is. However, GCC is not. Is that supposed to happen? If so, why is that? And how should I install all necessary components of GCC to work with C? Is yum install gcc is enough? Thanks.

A: I'm not sure what sort of install you did, but if you tell it you want a software development you should get gcc I think.  After the fact if you want a lot of those common tools you can do
yum groupinstall 'C Development Tools and Libraries'


text:
Q: Better methodology for indicating thread finished than MsgWaitForMultipleObjects? So I came across some code similar to this:
aThread := TmyThread.Create(param1, param2);
h := aThread.handle;
repeat
  if (MsgWaitForMultipleObjects(1, h, False, INFINITE, QS_ALLINPUT) = WAIT_OBJECT_0)
    then break;
  Application.ProcessMessages
until False;

aThread.Free;
myProgressBar.Progress := myProgressBar.Max;  //an internal component, not really important here

Which, I assume, is meant to provide a way of updating the GUI so it doesn't appear blocked, but also allow for the end process GUI to be updated (the progress bar), while some long task is taking place.
But it contains the dreaded Application.ProcessMessages.
I've read The Darkside of Application.ProcessMessages and many other Delphi blogs suggesting it's time to use a new thread instead when Application.ProcessMessages is being used.
So, is it wise to phase out this method of keeping the main/GUI threaded idle for something like the AnonymousThread approach shown here?  Or something else?
This Noob is confused as to why it's suggested that a process that calls Application.ProcessMessages is a good candidate for a Thread, but the thread in question relies on the very thing we're being told not to do!

A: The main idea is not to wait for the thread. Thread should inform your form when it finished. In other words the code which should be executed after the the thread is finished should be isolated to a separate procedure (see TForm1.ThreadCompletedHandler) and thread should call it after it is finished.
Here is a small sample:
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages,
  System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls;

type
  TmyThread = class(TThread)
  private
    FParam1, FParam2: Integer;
    FUpdateProc: TProc<TmyThread, Integer>;
    FCompleteProc: TProc<TmyThread>;

    procedure SyncCompleteProc;
    procedure QueueUpdateProc(APosition: Integer);
  protected
    procedure Execute; override;
  public
    constructor Create(AParam1, AParam2: Integer;
      AUpdateProc: TProc<TmyThread, Integer>;
      ACompleteProc: TProc<TmyThread>);
  end;

  TForm1 = class(TForm)
    Button1: TButton;
    myProgressBar: TProgressBar;
    procedure Button1Click(Sender: TObject);
  private
    FThread: TThread;

    procedure ThreadUpdateHandler(AThread: TMyThread; APosition: Integer);
    procedure ThreadCompletedHandler(AThread: TMyThread);
  protected
    procedure UpdateActions; override;
  public
    destructor Destroy; override;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TmyThread }

constructor TmyThread.Create(AParam1, AParam2: Integer; AUpdateProc: TProc<TMyThread, Integer>;
  ACompleteProc: TProc<TMyThread>);
begin
  FParam1 := AParam1;
  FParam2 := AParam2;
  FUpdateProc := AUpdateProc;
  FCompleteProc := ACompleteProc;
  inherited Create(False);
end;

procedure TmyThread.Execute;
var
  I: Integer;
begin
  //inherited; - abstract
  try
    I := FParam1;
    while not Terminated and (I < FParam2) do
    begin
      Sleep(1000);
      Inc(I);
      QueueUpdateProc(I);
    end;
  finally
    if Assigned(FCompleteProc) then
      TThread.Queue(Self, SyncCompleteProc);
  end;
end;

procedure TmyThread.QueueUpdateProc(APosition: Integer);
begin
  if Terminated or not Assigned(FUpdateProc) then
    Exit;

  TThread.Queue(Self,
    procedure
    begin
      FUpdateProc(Self, APosition);
    end);
end;

procedure TmyThread.SyncCompleteProc;
begin
  FCompleteProc(Self);
end;

{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);
const
  param1 = 1;
  param2 = 5;
begin
  myProgressBar.Min := param1;
  myProgressBar.Max := param2 + 1;
  myProgressBar.Position := param1;

  FThread := TmyThread.Create(param1, param2, ThreadUpdateHandler, ThreadCompletedHandler);
end;

destructor TForm1.Destroy;
begin
  if Assigned(FThread) then
    FThread.Terminate;

  inherited;
end;

procedure TForm1.ThreadCompletedHandler(AThread: TmyThread);
begin
  try
    if not AThread.Terminated then // check form is not destroye yet
    begin
      FThread := nil;
      myProgressBar.Position := myProgressBar.Max;  //an internal component, not really important}
    end;
  finally
    FreeAndNil(AThread);
  end;
end;

procedure TForm1.ThreadUpdateHandler(AThread: TMyThread; APosition: Integer);
begin
  if not AThread.Terminated then // check form is not destroye yet
    myProgressBar.Position := APosition;
end;

procedure TForm1.UpdateActions;
begin
  inherited;
  Button1.Enabled := not Assigned(FThread);
end;

end.

and DFM file
object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 290
  ClientWidth = 554
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton
    Left = 24
    Top = 16
    Width = 75
    Height = 25
    Caption = 'Button1'
    TabOrder = 0
    OnClick = Button1Click
  end
  object myProgressBar: TProgressBar
    Left = 120
    Top = 108
    Width = 150
    Height = 17
    TabOrder = 1
  end
end

NB In this sample form does not wait for the thread so potentially we may close the application before the thread is terminated. It should not be a problem for this sample as it simple enough but in real live you may need to wait for the thread in Form.Destroy or create some thread manager which should wait for all running threads before application is finished.


text:
Q: how to direct a sh script to run a python script? I wrote a python script that calls two files to perform some calculations and asks for a name for the new file to place the calculation in so my code runs like this:
python code.py in_file1 in_file2 outfile

Now, I have several files that need the same calculation and their names only change by the last numbers, so I wanted to do a script that takes the different needed files in a folder performs the python script and name the outputs changing only the las number according to the given in_file1 (infield_2 actually does not change).
I tried something simple but is not working
#!/bin/bash
python code.py in_file[19]* infile_2 outfile[19]*

I get an error from the usage of python saying that usage: python code.py [-h] in in2 out unrecognized arguments
I know for sure that code.py works, I just wanted to spare to do it one file at a time. Thank you. I am really new in python and linux, appreciate any help you can give.

A: You can do the same in Python
from subprocess import call

fname="in_file{} infile2 outfile{}"
for x in xrange(1,11):
    d=call(["python","code.py",fname.format(x,x)])
    if d:
        print "Error executing: {}".format(d)

If you execute the following
fname="in_file{}"
for x in xrange(1,11):
    print ["python","code.py",fname.format(x)]

It will print the following
['python', 'code.py', 'in_file1']
['python', 'code.py', 'in_file2']
['python', 'code.py', 'in_file3']
['python', 'code.py', 'in_file4']
['python', 'code.py', 'in_file5']
['python', 'code.py', 'in_file6']
['python', 'code.py', 'in_file7']
['python', 'code.py', 'in_file8']
['python', 'code.py', 'in_file9']
['python', 'code.py', 'in_file10']

A: The shell simply expands the wildcard in_file[19]* there and then into list of all matching files. There is no loop here. If you want a loop, you will need an explicit loop, something like
#!/bin/bash
for file in in_file[19]*; do
    python code.py "$file" infile_2 "out${file#in}"
done

where the variable file gets assigned to each matching file in turn, and the variable substitution ${var#prefix} expands to the value of var with any string prefix removed from the beginning.
Incidentally, the python is redundant if you make code.py executable, and ensure it has a correct shebang line.
Note also that [19] matches a single character, so your wildcard matches any files whose name starts with in_file1 or in_file9 but no others. I'm speculating maybe that's not what you mean.

A: You can do this in python:
import os

name = "in_file%d"
for i in range(1, 21):
    os.system("python code.py in_file{} in_file2 outfile{}".format(i, i))

This works as the following, with the os library calling the outputted strings:
>>> for i in range(1, 21):
...     "python code.py in_file{} in_file2 outfile{}".format(i, i)
...
'python code.py in_file1 in_file2 outfile1'
'python code.py in_file2 in_file2 outfile2'
'python code.py in_file3 in_file2 outfile3'
'python code.py in_file4 in_file2 outfile4'
'python code.py in_file5 in_file2 outfile5'
'python code.py in_file6 in_file2 outfile6'
'python code.py in_file7 in_file2 outfile7'
'python code.py in_file8 in_file2 outfile8'
'python code.py in_file9 in_file2 outfile9'
'python code.py in_file10 in_file2 outfile10'
'python code.py in_file11 in_file2 outfile11'
'python code.py in_file12 in_file2 outfile12'
'python code.py in_file13 in_file2 outfile13'
'python code.py in_file14 in_file2 outfile14'
'python code.py in_file15 in_file2 outfile15'
'python code.py in_file16 in_file2 outfile16'
'python code.py in_file17 in_file2 outfile17'
'python code.py in_file18 in_file2 outfile18'
'python code.py in_file19 in_file2 outfile19'
'python code.py in_file20 in_file2 outfile20'
>>>


text:
Q: How can I auto deploy from a Git branch from VisualStudio.com to Azure? LS,
I am happily using the new VisualStudio.com service to host my repository. Now I want to deploy from that to Azure, which supports TFS and Git (not sure if it supports it together).
I'm assuming it is not possible right now, to do automatically from VS.com, because when I authorize my VS.com account, it tells me it can't find any projects.
Would love to hear more about the possibilities of doing this.

A: At this point in time (early March 2013), visualstudio.com does not support automated git push to Windows Azure Web Sites.
When you check the "Publishing a web site with Git" page, you see that (currently) deployment to Windows Azure Web Sites is supported for

*

*'local files', a.k.a. 'git push azure master',

*CodePlex

*GitHub

*BitBucket

A: you can always setup your repo on azure with your remote info. then manually call git pull from the cloud to get the newest commits.
(not sure about this answer)
if you can execute shell commands from visual studio you can add a hook to your git repo to ping a script on azure that will automatically do the pull. i use this methodology with github and php. nettuts+ has a great video explaining it http://net.tutsplus.com/tutorials/other/the-perfect-workflow-with-git-github-and-ssh/
and here's some info on git hooks http://git-scm.com/book/ch7-3.html

A: I just checked it, and it is possible to deploy using VisualStudio.com and Git now.


text: Q: What is the graph of$|x|+2|y|+3|z|\leq 1$? What is the graph of$|x|+2|y|+3|z|\leq 1$ ? And determine its geometrical figure. I know that the graph will be 3D. If I assume that $x \geq 0$,$y \geq 0$,$z \geq 0$. So let $x'^2 = x \geq 0$,$y'^2 = y \geq 0$,$y'^2 = z \geq 0$. Then above inequality can be written as $x+2y+3z\leq 1$ and $x'^2+2y'^2+3z'^2\leq 1 \implies \frac{x'^2}{1}+\frac{y'^2}{1\over2}+\frac{z'^2}{1\over3}\leq 1$ which is ellipsoid and its interior. Please help me.


text:
Q: Handling User Error with Sets I'm pretty much done with this code and it runs almost correctly other than the fact that I need the user to enter numbers within the boundaries of the universe. I've made sure the user can't enter anything but an integer. But I'm not sure how to go about making sure the number is 1-10 (the universe set). Can someone give me some guidance?
Here is my code:

import java.util.*;
public class sets {
  public static void main (String[] args) {
  Scanner in = new Scanner(System.in);

  //declare the universe in a set
  Set universe = new HashSet();
  for (int i = 1; i <= 10; i++) {
    universe.add(i);
  }

  //Ask the user how many elements and declare set A
  System.out.print("How many elements in Set A? ");
  int elementsA = in.nextInt();
  Set A = new HashSet();

 for (int j = 1; j <= elementsA; j++) {
   System.out.print("Enter a number 1-10: ");
   while (!in.hasNextInt()) {
     in.next();
     System.out.println("Input must be a number.");
     System.out.print("Enter a number 1-10: ");
   }
   int numA = in.nextInt();
   A.add(numA);
 }

 //Ask the user how many elements and declare set B
 System.out.print("How many elements in Set B? ");
 int elementsB = in.nextInt();
 Set B = new HashSet();

 for (int k = 1; k <= elementsB; k++) {
  System.out.print("Enter a number 1-10: ");
  while (!in.hasNextInt()) {
   in.next();
   System.out.println("Input must be a number.");
   System.out.print("Enter a number 1-10: ");
  }
  int numB = in.nextInt();
  B.add(numB);
}

//get the union of the sets
Set union = new HashSet(A);
union.addAll(B);
System.out.println("The union of A and B: "+union);

//get the intersection of the sets
Set intersect = new HashSet(A);
intersect.retainAll(B);
System.out.println("The intersection of A and B: "+intersect);
}
}

A: Something like
while (!in.hasNextInt()) {
  in.next();
  System.out.println("Input must be a number.");
}

int numA = in.nextInt();

while (numA < 0 || numA > 10) {
  System.out.print("Enter a number 1-10: ");
  numA = in.nextInt();
}

A.add(numA);

Edit: Considering the above, I would harden the solution more like the following
while (true) {
    if (!in.hasNextInt()) {
        System.out.println("Input must be a number.");
        in.next();
    } else {
        int num = in.nextInt();

        if (num < 0 || num > 10) {
            System.out.println("Input must be between 1 and 10 (inclusive).");
        } else {
            // add num to collection
            break;
        }
    }
}


text:
Q: Another Limit Conundrum
For what values of $a$ and $b$ is the following limit true?
  $$\lim_{x\to0}\left(\frac{\tan2x}{x^3}+\frac{a}{x^2}+\frac{\sin bx}{x}\right)=0$$

This question is really confusing me. I know that $\tan(2x)/x^3$ approaches infinity as $x$ goes to $0$ (L'Hôpital's). I also understand that $\sin(bx)/x$ goes to $b$ as $x$ approaches $0$. However, I am not sure how to get rid of this infinity with the middle term. Any ideas?
Thanks!

A: Since $\lim_{x\to 0}\dfrac{\sin bx} {x} =b$ the given condition is equivalent to $$\lim_{x\to 0}\frac{\tan 2x+ax}{x^3}=-b$$ or $$\lim_{x\to 0}\frac{\tan 2x-2x}{x^3}+\frac{a+2}{x^2}=-b$$ Substituting $t=2x$ we get $$\lim_{t\to 0}8\cdot \frac{\tan t-t} {t^3}+\dfrac{4a+8}{t^2}=-b$$ The first fraction tends to $1/3$ (as can be easily seen via L'Hospital's Rule or Taylor series) and therefore the above equation is equivalent to $$\lim_{t\to 0}\frac{4a+8}{t^2}=-b-\frac{8}{3}$$ Multiplication by $t^2$ now gives us $4a+8=0$ or $a=-2$ and then from the above equation we get $b=-8/3$.

A: First, notice that your limit exists if and only if it exists without the last term (since, as you said, the limit of the last term exists).
You have
$$\tag1
\frac{\tan2x}{x^3}+\frac a{x^2}=\frac{\tan2x+ax}{x^3}.
$$
Note that if $a\ne0$ you cannot apply L'Hôpital. The expression in $(1)$ is, close to $0$,
$$\tag2
\frac{\tan2x+ax}{x^3}=\frac{x+o(x^3)+ax}{x^3}.
$$
This requires $a=-1$ for the limit to exist. In more detail,
$$\tag2
\frac{\tan2x+ax}{x^3}=\frac{2x+\tfrac{(2x)^3}3+o(x^5)+ax}{x^3}=\frac{2+a}{x^2}+\tfrac83+o(x^2).
$$
So it converges to $\tfrac13$ when $a=-2$. For the whole limit to be zero, we need that $$\tag3\lim_{x\to0}\frac{\sin bx}{x}=-\frac83.$$
In the end, we need $a=-2$, $b=-\tfrac83$.

A: Using the usual Taylor series for
$$y=\frac{\tan(2x)}{x^3}+\frac{a}{x^2}+\frac{\sin (bx)}{x}=\frac{\tan(2x)+ax+x^2\sin (bx)}{x^3}$$ The numerator write
$$\left(2 x+\frac{8 x^3}{3}+\frac{64 x^5}{15}+O\left(x^7\right) \right)+a x+x^2\left(b x-\frac{b^3 x^3}{6}+\frac{b^5 x^5}{120}+O\left(x^7\right) \right)$$ that is to say
$$(a+2) x+\left(b+\frac{8}{3}\right) x^3+\left(\frac{64}{15}-\frac{b^3}{6}\right)
   x^5+O\left(x^7\right)$$ making $$y=\frac{a+2}{x^2}+\left(b+\frac{8}{3}\right)+\left(\frac{64}{15}-\frac{b^3}{6}\right)
   x^2+O\left(x^4\right)$$ So, in order to have a limit equal to $0$, you need $a=-2$, $b=-\frac{8}{3}$ and then
$$y=\frac{3008 }{405}x^2+O\left(x^4\right)$$

A: We have that
$$\frac{\tan (2x)}{x^3}+\frac{a}{x^2}+\frac{\sin bx}{x}=\frac{\tan (2x)+ax+x^2\sin bx}{x^3}$$
and from here since $x^2\sin bx\sim bx^3$ and $\tan (2x)\sim 2x$ we need $a=-2$ as a necessary condition for the limit to exist then we can consider by standard limits
$$\frac{\tan (2x)-2x+x^2\sin bx}{x^3}=8\frac{\tan (2x)-2x}{(2x)^3}+b\frac{\sin bx}{bx}\to \frac83+b=0$$


text:
Q: Identify debugging in VisualStudio I have an interesting problem.
Is it possible to identify if an assembly is running in Visual Studio?
Look at the following code.
if(FoundThatYouAreDebuggingInVisualStudio)
{
    Print "Hello"
}
else
{
    Print "Hi"
}

The above code is present in a .NET assembly (say XYZ) which is built in Release mode. The user is debugging his/her application (say ABC) that references to XYZ assembly.
I need to identify if the user is debugging in the Visual Studio or he is just running the ABC application.
Any ideas?
-D

A: Perhaps you're looking for System.Diagnostics.Debugger.IsAttached


text:
Q: I just recently installed Ubuntu 14.04 and I can't seem to download anything Let me just start with saying that I am very new to Linux in general. I recently installed 14.04 and I downloaded a couple of things first: Gimp and Chrome, but when I tried to get Steam it downloads but when I launch it, the terminal says:

Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

Then the terminal closes and a box comes up saying:

You are missing the following 32-bit libraries, and Steam may not run:
  libc.so.6

When I try to run "sudo apt-get -f install" it does this:

Reading package lists... Done
  Building dependency tree
  Reading state information... Done
  Correcting dependencies... Done
  The following extra packages will be installed:
    libc-bin
  The following NEW packages will be installed:
    libc-bin
  0 upgraded, 1 newly installed, 0 to remove and 77 not upgraded.
  Need to get 0 B/1,168 kB of archives.
  After this operation, 3,529 kB of additional disk space will be used.
  Do you want to continue? [Y/n] y
  Can't exec "locale": No such file or directory at /usr/share/perl5/Debconf/Encoding.pm line 16.
  Use of uninitialized value $Debconf::Encoding::charmap in scalar chomp at /usr/share/perl5/Debconf/Encoding.pm line 17.
  dpkg: warning: 'ldconfig' not found in PATH or not executable
  dpkg: error: 1 expected program not found in PATH or not executable
  Note: root's PATH should usually contain /usr/local/sbin, /usr/sbin and /sbin
  E: Sub-process /usr/bin/dpkg returned an error code (2)

And then the software center says there is a problem with my current software. Can someone help?

A: I'm pretty sure this is a duplicate, but here's the answer. You need to install that library that Steam needs. Do so by running sudo apt-get install libc6*. This should fix the Steam problem and will hopefully solve the other one as well.

A: Your problem is you are missing libc-bin but can't install it.
To install it:
Boot from an ubuntu installation media and open a terminal
Mount your ubuntu root partition: sudo mount /dev/sdX /mnt
Chroot into your system: sudo chroot /mnt /bin/bash
Install libc-bin: sudo apt-get install libc-bin
Reboot your system and it should work fine


text:
Q: How to wrap text in plotly.py's sunburst diagram? I want to wrap text, as in if it is a long sentence, add line breaks so the font has bigger size, for example, like here
I have the following data that can be downloaded from https://gofile.io/d/8djNCU:

Here is my code:
import plotly.express as px
import pandas as pd

df = pd.read_excel("/Users/stuff/Desktop/test.xlsx")

g1 = df.Group1
g2 = df.Group2
g3 = df.Group3
g4 = df.Group4
my_values = df.Values

df = pd.DataFrame(
    dict(group1=g1, group2=g2, group3=g3, group4=g4, my_values=my_values)
)

fig = px.sunburst(df, path=['group1', 'group2', 'group3', 'group4'], values='my_values')

fig.show()

The current sunburst diagram looks like this:

Is it possible to wrap the text? I would like the long text to be as big as possible and split by break line as I would like to use the image for a presentation.

A: By adjusting the width in the customwrap function, I was able to make a nice sunburst. The answer was provided by the plotly's GitHub community.
import plotly.express as px
import pandas as pd
import textwrap

def customwrap(s,width=30):
    return "<br>".join(textwrap.wrap(s,width=width))

df = pd.read_excel("/Users/stuff/Desktop/test.xlsx")

g1 = df.Group1.map(customwrap)
g2 = df.Group2.map(customwrap)
g3 = df.Group3.map(customwrap)
g4 = df.Group4.map(customwrap)
my_values = df.Values

df = pd.DataFrame(
    dict(group1=g1, group2=g2, group3=g3, group4=g4, my_values=my_values)
)
fig = px.sunburst(df, path=['group1', 'group2', 'group3', 'group4'], values='my_values')

fig.show()


text:
Q: Is a repository return a graph of entities violating SRP? I'm working in this scenario
Post entity has many Image entities.
I also have repository to both entities:

*

*PostRepository

*ImageRepository

Since this entities are tightly related, when I get a Post I want to return the list of images also.
I have to possible ways of do this:

*

*The orchestator (in this case a PostService) will call indepently each one of the Repositories to fecth the data.
PROs:

*

*For sure don't violates SRP
CONs:

*Create extra dependencies PostService might not have need to have a dependency with ImageRepository.

*Unnecesary calls to database

*The PostRepository will return the whole Graph Post with Images
PROs:

*

*Reduce dependencies

*Simplify the database query.
CONs:

*Might violate SRP.

In the case of a writting scenario I clearly prefer the 1st option, since I want to keep validation of entities completely segreggated. But for reading scenario I thinkg 2nd option could be more optimal, however I couldn't find any good argument or reading for this.
So which option is better for the reading scenario?

A: In my experience, at least in in application development, it is seldom necessary to decide this beforehand.
Instead, I would recommend to start with one repo class and see how far it brings you. When the code base grows and you get some indications that splitting up the repo into two becomes beneficial, then refactor immediately. Such indications are

*

*the class becomes "too large", readibility decreases and it takes more and more time to find the right place in that class for extensions and changes

*you want to mock out either the db access for images or posts (independently from each other) for testing the other in isolation

*you want to reuse the repo functionality of images or posts on its own.

*the API of your repos gets simpler to use when split up into two classes.
There is also a third alternative to the two designs you suggested: let PostRepository provide an API which can return the whole graph, but let it internally use a ImageRepository for it, which is injected at construction time of PostRepository. That may be useful when the orchestration between both repos is so simple it does not seem to be worth introducing a separate orchestrating class.
The SRP is not an end in itself, it is a means to an end. So apply it when your code requires it, not "just in case".
Of course, you have to make sure you don't miss the point in time when you have to refactor. And things may look different when you are trying to design a library with a stable (=hard to refactor) API.

A: Yes, it is a violation of SRP. The repositories are designed with the intent to each handle one particular entity, and you're having your repository handle two (or more) entity types at the same time.
However, it is not wrong to do this*, because it dramatically reduces performance hits. If you handle each entity in their own repository, that means you need to do two database calls, which is more expensive.
This is one of those cases where practical considerations (performance due to networked database calls) outweigh the theoretical (perfectly adhering to SRP).

*There are other solutions to this problem. I'm merely pointing out that returning a graph is acceptable because of the performance benefits you get from doing so, as opposed to sticking with a pure one-entity-per-repository approach.

A: What you are experiencing is normal and it's due to the dual nature of the application: write and read. In your case the something does in fact have 2 responsibilities but not who you thing: the model is used to write and also to read. So not the Repository is the problem but the Aggregates.
CQRS solves this modeling problem. It splits the model in two: write/command and read/query.
In your case you would have the Post and Image Aggregates with the corresponding repositories or the write side. For the read side you would have a specially designed ReadModel that would give you a list of posts and their images, in a optimized format. This would be its single responsibility. This ReadModel would be kept up-to-date by listening to changes from the Aggregates in the write side. The most common solution is to use Domain events.
As a note, you create a ReadModel per use case. In this way the ReadModel is simple, fast and perfectly fitted for one job. For example, for the Newest posts widget on the Homepage you have a NewestPostsHomepageReadModel that contains only 10 rows, the newest 10 posts, each post having only one image, the main image.
CQRS is not trivial but it makes your models a lot simpler, as they should.