text:
Q: loop key frame css3 animation 8 times Is it possible (even with the assistance of jQuery, if necessary -- to loop a CSS3 keyframe animation 8 times)
.coin{
  animation: animationFrames ease 1.5s;
  -webkit-animation: animationFrames ease 1.5s; /* Safari 4+ */
  animation-iteration-count: infinite;
  -webkit-animation-iteration-count: infinite;
  transform-origin: 50% 50%;
  -webkit-transform-origin:  50% 50%;
  animation-fill-mode:forwards;
  -webkit-animation-fill-mode: forwards;
  max-width: 55px;
  position:relative;
  top: 63px;
  left: 195px;
}

/* Chrome, Safari, Opera */

@-webkit-keyframes animationFrames {
  0% {
    -webkit-transform:  translate(-402px,55px)  ;
  }
  4% {
    -webkit-transform:  translate(-333px,26px)  ;
  }
  9% {
    -webkit-transform:  translate(-257px,-13px)  ;
  }
  14% {
    -webkit-transform:  translate(-183px,-18px)  ;
  }
  19% {
    -webkit-transform:  translate(-122px,0px)  ;
  }
  19% {
    -webkit-transform:  translate(-122px,44px)  ;
  }
  19% {
    -webkit-transform:  translate(-122px,44px)  ;
  }
  24% {
    -webkit-transform:  translate(-98px,59px)  ;
  }
  29% {
    -webkit-transform:  translate(-91px,128px)  ;
  }
  29% {
    -webkit-transform:  translate(-91px,128px)  ;
  }
  34% {
    -webkit-transform:  translate(-59px,77px)  ;
  }
  38% {
    -webkit-transform:  translate(-13px,34px)  ;
  }
  42% {
    -webkit-transform:  translate(51px,13px)  ;
  }
  46% {
    -webkit-transform:  translate(101px,39px)  ;
  }
  51% {
    -webkit-transform:  translate(141px,72px)  ;
  }
  56% {
    -webkit-transform:  translate(163px,105px)  ;
  }
  62% {
    -webkit-transform:  translate(177px,155px)  ;
  }
  68% {
    -webkit-transform:  translate(177px,155px)  ;
  }
  100% {
    -webkit-transform:  translate(177px,155px)  ;
  }
}

A: Just change animation-iteration-count: from infinite to 8


text:
Q: How to check if specific value exists in side an array? I have the following sample function.
class EquipmentReport extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Reporting/ReportModel');//load report model
        $this->load->helper('url');
        $this->load->helper('form');
        $this->Authorize(); // method inherited and returns array
 }

    /**
     * loads view if no $_POST data
     * if post data generates sql query
     * @return (query)
     **/

    public function by_category (){
         $my_array = $this->Authorize();
        if (in_array("USER_GROUP_STATUS", $my_array)) {
            echo "Got USER_GROUP_STATUS";
        }
}

dumping $my_array gives the following array
Array (
 [0] =>  'ALL',
         'USER_GROUP_STATUS',
         'USER_GROUP_HAS_PERMISSION_CREATE_DEPARTMENT',
         'USER_GROUP_HAS_PERMISSION_READ_DEPARTMENT',
         'USER_GROUP_HAS_PERMISSION_UPDATE_DEPART'
      )

but checking array keys is nt working.
what I wanted to do is to check if the one of the values exist. for example if 'USER_GROUP_STATUS' exists in the array ?

A: Try this in_array() function
    if (in_array("USER_GROUP_STATUS", $your_array)) {
    echo "Got USER_GROUP_STATUS";
}

or You can try this way
    $ary = [
 0 =>  ['ALL', 'USER_GROUP_STATUS', 'USER_GROUP_HAS_PERMISSION_CREATE_DEPARTMENT',
         'USER_GROUP_HAS_PERMISSION_READ_DEPARTMENT',
         'USER_GROUP_HAS_PERMISSION_UPDATE_DEPART']
      ];

foreach($ary as $ar)
if (in_array("USER_GROUP_STATUS", $ar)) {
            echo "Got USER_GROUP_STATUS";
        }

Live Demo

A: Simply use in_array() :
if (in_array($string, $Arr)) {
    //code
}

A: $yourArray = Array ( [0] => ALL,'USER_GROUP_STATUS','USER_GROUP_HAS_PERMISSION_CREATE_DEPARTMENT','USER_GROUP_HAS_PERMISSION_READ_DEPARTMENT','USER_GROUP_HAS_PERMISSION_UPDATE_DEPART' );

$needle = 'USER_GROUP_STATUS';

if(in_array($needle, $yourArray)) {
    echo 'found it!';
}

Hope this helps you.

A: do sth like this
public function by_category()
    {

        $key= "USER_GROUP_STATUS";
        $my_array = $this->Authorize();
        if(in_array($key,$my_array)) {
            echo 'Bravo!';
            die();
        }

    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use laravel on azure webapp My project is developed with larval, then i am trying to use azure for web server.
I am copying folder laravel in C:\inetpub\wwwroot\laravel5. Next I run php artisan serve.
Then I test on http://localhost:8000/index (test on remote websever). It's ok.
But if I access my url for example http://bobdict.cloudapp.net/index, it say page not found.
What is the problem?
I am a newbie for this, sorry.

A: It seems you are using IIS to host your PHP application on Azure VM.
As the entrance of laravel application locates in public folder in the root directory of the application. You can test to browse http://bobdict.cloudapp.net/public/index to test whether you have deploy laravel application successfully. Then to config URL rewrite for friendly URL pattern. You can create the web.config manually in your root directory of your application.
You can refer to http://blog.qbotx.com/basic-laravel-5-on-microsoft-azure-part-1/ for the content of web.config.

A: in azure portal configure docroot to
                       wwwroot/laravel5/public


text:
Q: Custom CSS breaks bootstrap modal I created my own home automation web app. To authorize actions the user needs to enter a pin. Instead of using an input/password field I want to use a dial/number pad.
I decided to go with this snippet. My big problem is: I'm not good with CSS. I understand HTML and can work with it (at least with Bootstrap). But I have not learned CSS yet.
But I want to display the number pad in a modal (which pops up when the user tries to press the "Turn of PC" button for example).
I copied the css and html from the link. But this is the outcome:

Can someone explain me which part of the css is causing this?
Thanks

A: Remove the <div class="container"> from the modal body, and change the class on your phone tag to col-md-8 col-md-offset-2 phone.
Updated JSFiddle
Full-screen results


text:
Q: Extjs4 grid is not showing updated value on grid i am working in extjs4. I have gridview with cellEditing plugin used.Its working correctly. But after editing foldername its not showing newly updated name of folder on grid. I don't want to refresh store. i just want to show updated name on grid. I have tried as=
getGridPanelStore = getGridPanel.getStore();
folderId = id;
var newtitle = newUpdatedValue;
getRecord = getGridPanelStore.getById(id);
recordToUpdate = getGridPanelStore.indexOf(getRecord ).set('title',newtitle );

But it not setting new updated value on grid. So how to show updated value on grid after editing without loading whole store.

A: Does this code actually work?
As far as I understand the method indexOf of Ext.data.Store retrieves the index of the record inside the store as an integer thus calling set('title', newTitle) probably will raise an exception of the type Uncaught TypeError: Object n has no method 'set'
Besides that you don't need to load the whole store to get your grid updated, since views are bound to the stores they auto refresh anytime a store field changes, so it should work by changing the title property as follows:
gridStore = gridPanel.getStore();
record = gridStore.getById(recordId);
record.set('title', newTitle);

If value doesn't update that way, you should check if the target column doesn't have a custom renderer associated to it that can be changing the view output for that specific field in any way.


text:
Q: How i do grouping and transform data in java language I try to use group by in Collectors.groupingBy in java but i can not get data form that i want.
I want to transform this form data :
[
    {
        "id": 1,
        "name": "A",
        "company_id": "01",
        "company_name": "Company A",
    },
    {
        "id": 2,
        "name": "B",
        "company_id": "01",
        "company_name": "Company A",
    },{
        "id": 3,
        "name": "C",
        "company_id": "02",
        "company_name": "Company B",
    }
]

to this data form:
[
    {
        "company_id": "01",
        "company_name": "Company A",
        "member":[
          {
          "id": 1,
          "name": "A"
          },
           {
          "id": 2,
          "name": "B"
          }
        ]
    },{
        "company_id": "02",
        "company_name": "Company B",
        "member":[
          {
          "id": 3,
          "name": "C"
          }
        ]
    }
]

this form group by company_id.

A: The way that I would do it:
First I would create pojo objects for both formats, then I would assign each value corresponding ones then I would convert the second object into json as using gson.


text:
Q: Error connecting from GAppEngine servlet to GoogleCloud MySQL only at first try Description:
Greetings, I have a Google App Engine standard web service deployed from Eclipse Oxygen that consists of a servlet connecting to a MySQL database with the same project id in the Google Cloud using hibernate. It is a simple event managing website where you (as an invitee) enter your email and a given code (don't worry about security at least here, please) and you confirm or cancel your assistance to a given event.
Error:
The error is the following, at localhost, the tested project will perform correctly on every connection and transference of data. But as soon as I deploy it, when I test it from the user side, on the first try (wether you confirm, cancel or enter invalid data) it will fail to connect to the database. If you redo the operation, it will work.
Information to take into account:

*

*I did not use the JDBC GoogleDriver (as I couldn't find a way to make it work [ClassNotFoundException...]). I use "com.mysql.jdbc.Driver".

*The database allows the IP 0.0.0.0/0 (everyone) to connect to it (I know, security issues).

*The servlet access the database with root + password (more security issues...).

*When the user confirms/cancels the servlet will ask the Business class instance to retrieve the user data to check if it pairs it's invitation code.

Notice:
I have no idea how is this happening. Please, ask me for the details you need, and I will edit this question with them, because I don't know where to start. I'm pretty sure this first-try-only pattern must be easily identifiable to anyone who had experienced this. Thank you very much.

A: When thing is running correctly on localhost then obviously Google Cloud has specific issue. Google Cloud's 0.0.0.0/0 is not really "whole earth". You have to add subnet from which you'll connect. That much I know.
Better you can test on some PaaS like Bluemix. Bluemix has own big Q&A - developer.ibm.com/answers/ plus StackOverflow.
Of course you can use VPS as other option than PaaS. Essentially you need to run an application NOT fight with some platform.


text:
Q: C# Array with DateTime[] How can I turn multiple If statements into a single array to check file datetime of several files with the same name?
Currently I have
if (location1)
{
    loc = 1;
    DateTime dateDailyFile1 = Convert.ToDateTime(File.GetLastWriteTime(ediFile1));
    if (Convert.ToDateTime(dateDailyFile1.ToShortDateString()) < Convert.ToDateTime(DateTime.Now.ToShortDateString()))
    {
        return false;
    }
    else
    {
        return true;
    }
}...

I do this about 20 times.  Which as you may gather is quite grueling.
I wanted to put it in an array and just loop through it but the DateTime assignment on the array keeps throwing an error.
The following is the code I'm trying to change it to.
**qualifier - location[] is a bool assigned by clicking a checkbox.
DateTime[] dateDailyFile;
string[] ediFile = { "file1", "file2", "file3", "file4" ... };
string[] loc = { "loc1", "loc2", "loc3", "loc4" ... };
int x;
for (x = 0; x < loc.length; x++)
{
    if (location[x])
        {
            dateDailyFile[x] = Convert.ToDateTime(File.GetLastWriteTime(ediFile[x]));
        }
}...

The last line
dateDailyFile[x] = Convert.ToDateTime(File.GetLastWriteTime(ediFile[x]));
is my problem.  I am getting a "Use of unassigned local variable dateDailyFile".
What exactly did I do wrong and what is the best method to solve this issue?

A: Change the first line to:
DateTime[] dateDailyFile = new DateTime[whateverIsTheExpectedLength];//20?

A: It seems like you are trying to access variables by their string name, which is not possible with that syntax.  However, you could store the values in an array like so:
var ediFile = new []{ file1, file2, file3, file4 ... };
var loc = new [] { loc1, loc2, loc3, loc4 ... };

Then access then using array indexers:
int x;
for (x = 0; x < loc.length; x++)
{
    if (location[x])
        {
            dateDailyFile[x] = Convert.ToDateTime(File.GetLastWriteTime(ediFile[x]));
        }
}...

A: Arrays need a length defined at declaration.
You can instead use a List, which doesn't need a size specified at declaration, making it more flexible:
List<DateTime> dateDailyFile;
string[] ediFile = { "file1", "file2", "file3", "file4" ... };
string[] loc = { "loc1", "loc2", "loc3", "loc4" ... };
int x;
for (x = 0; x < loc.length; x++)
{
    if (location[x])
        {
            dateDailyFile.Add(Convert.ToDateTime(File.GetLastWriteTime(ediFile[x])));
        }
}...

A: It was a combination that helped me work out the correct process. D.Stanley's explanation of my error along with ispiro's correction helped me work out the correct process - listed below.
var ediFile = new[] {loc1, loc2, loc3, loc4 ...}
DateTime[] dateDailyFile = new DateTime[20];
int x;
        for (x = 0; x < bLocation.Length; x++)
        {
            if (bLocation[x])
            {
                ....
                dateDailyFile[x] = Convert.ToDateTime(File.GetLastWriteTime(ediFile[x]));
                return false;
            }
            else
            {
                return true;
            }
        }...

D. Stanley correctly identified the root cause coupled with ispiro's suggestion I managed to get it working.
String[] loc was not needed in the correction.


text:
Q: How to prove that $3ab(a+b)$ cannot be a cube? Consider the diophantine equation: $ 3ab(a+b)=c^3 $ where $a,b,c$ are non-zero integers,how do you prove that this equation has no integral solutions?

A: Edition/Revision 2.
Equation
$$
3ab(a+b) = c^3
$$
has non-zero integer solutions.
One of "obvious" solutions is
$$
(a,b,c) = (1,8,6);\tag{A}
$$
other (not so obvious) sulutions that I've found so far, are:
$$
(a,b,c) = (3087, 4913,7140) \\
\color{gray}{ = (9 \cdot 7^3, 17^3, 3 \cdot 7\cdot 17 \cdot 20)},\tag{B}
$$
$$
(a,b,c) = (756249048, 19902511, 327250386) \\
\color{gray}{ = (9 \cdot 438^3, 271^3, 3 \cdot 438 \cdot 271 \cdot 919)},\tag{C}
$$
$$
(a,b,c) = (6646883738818239, 48707103808000, 1866552387462840) \\
\color{gray}{ = (9 \cdot 90391^3, 36520^3, 3 \cdot 90391 \cdot 36520 \cdot 188479)}.\tag{D}
$$
These solutions can be represented as sum of $3$ cubes (as metacompactness noted in comments to the question):
$$
\color{gray}{a^3 + b^3 + c^3 = (a+b)^3;}\\
\color{gray}{1^3 + 8^3 + 6^3 = (1+8)^3 = 9^3;}\\
\color{gray}{3087^3 + 4913^3 + 7140^3 = (3087+4913)^3 = 8000^3;}\\
...
$$

Here I consider only solutions with co-prime $a,b$. (It is clear why).

Way to find solutions:
we'll focus on co-prime $a,b$.
If $3| c^3$, then $27| c^3$, then $9| ab(a+b)$.
$3$ cases are here:
A) $9\mid a, \quad 3\nmid b$;
A') $3\nmid a, \quad 9\mid b$; (symmetric to case A) )
B) $3\nmid a, \quad 3\nmid b, \quad 9\mid (a+b)$.
case A):

$a,b,(a+b)$ are co-prime pairwice.
So, $a,b,(a+b)$ have different prime factors.
Then every of numbers $3a, b, (a+b)$ has each prime factor in $3\times$ power.
Other words, $3a,b,(a+b)$ are co-prime cubes:
$$3a = 27 p^3,\qquad b = q^3, \qquad (a+b) = r^3.$$
Then
$$3ab(a+b) = 27p^3q^3r^3 = (3pqr)^3.$$
$$c = 3pqr.$$
Thus for searching $(a,b,c)$ one needs to consider co-prime pairs $(p,q)$, such that
$$
9p^3+q^3 = r^3.\tag{*}
$$
Triple $(p,q,r) = (7,17,20)$ generates solution $(B)$,
triple $(p,q,r) = (438,271,919)$ generates solution $(С)$,
triple $(p,q,r) = (90391,36520,188479)$ generates solution $(D)$.
case B):

Similar thinking.
$a,b,3(a+b)$ are co-prime cubes:
$$a = p^3,\qquad b = q^3, \qquad 3(a+b) = 27r^3. $$
Then
$$ab\cdot3(a+b) = 27p^3q^3r^3 = (3pqr)^3.$$
Thus for searching $(a,b,c)$ one needs to consider co-prime pairs $(p,q)$, where $3\nmid p$ and/or $3\nmid q$, such that
$$
p^3+q^3 = 9r^3.\tag{**}
$$
Triple $(p,q,r)=(1,2,1)$ generates solution $(A)$.


text:
Q: Strange behavior of convertDateTime in JSF I am using JSF with richfaces. I am using convertDateTime of core ip to convert an inputText to Date.
<h:inputText styleClass="datepicker" value="#{searchBean.creationDate}" id="inputfield">
  <f:convertDateTime pattern="yyyy-MM-dd" />
</h:inputText>

Where creationDate in SearchBean is of type Java util Date and I am using a jquery datpicker to populate the input field.
The problem is that it is not working fine. When I submit form without entering any date (empty input field), everything works fine. But, when I select the date, the call doesn't reach bean (tested it in debug mode). The page just refreshes itself without any exception/logging on the server side.
I have implemented a quick LifeCycleListener which showed following output:
With input field filled with date:
START PHASE RESTORE_VIEW(1)
END PHASE RESTORE_VIEW(1)
START PHASE APPLY_REQUEST_VALUES(2)
END PHASE APPLY_REQUEST_VALUES(2)
START PHASE PROCESS_VALIDATIONS(3)
END PHASE PROCESS_VALIDATIONS(3)
START PHASE UPDATE_MODEL_VALUES(4)
END PHASE UPDATE_MODEL_VALUES(4)
START PHASE INVOKE_APPLICATION(5)
END PHASE INVOKE_APPLICATION(5)
START PHASE RENDER_RESPONSE(6)
END PHASE RENDER_RESPONSE(6)

With empty date :
START PHASE RESTORE_VIEW(1)
END PHASE RESTORE_VIEW(1)
START PHASE APPLY_REQUEST_VALUES(2)
END PHASE APPLY_REQUEST_VALUES(2)
START PHASE PROCESS_VALIDATIONS(3)
END PHASE PROCESS_VALIDATIONS(3)
START PHASE RENDER_RESPONSE(6)
END PHASE RENDER_RESPONSE(6)

It is clear that there are two steps missing in second case. I am very new to JSF and don't have much idea about internal working of it. Moreover, there are no validation/conversion exceptions. I am stuck here and I have no idea where to look for the solution. Any help is appreciated.

A: Reason for update model and invoke application not shown when you dont enter date is because your validation has failed, in case of validation failure model is not updated with UI content and application logic (your custom code) will not be invoked.
If you have added error messages in your .properties file then add the following
javax.faces.converter.DateTimeConverter.DATE=value ({0}) must be a date

Else
<h:inputText styleClass="datepicker" value="#{searchBean.creationDate}" id="inputfield" converterMessage="Please Enter creation date in yyyy-MM-dd format">
  <f:convertDateTime pattern="yyyy-MM-dd" />
</h:inputText>

This would enable to show error message when validation fails.
You will be getting conversion error when you submit null as date.

A: If you're using JSF 1.2 and RichFaces 3.x then use the rich:calendar tag component to work with dates, it uses jquery behind the scenes to get displayed. Using it in your example:
<rich:calendar id="calCreationDate" popup="true"
    value="#{searchBean.creationDate}"
    enableManualInput="true"
    locale="#{application.locale}"
    datePattern="#{application.datePattern}"
    showApplyButton="false" />

In my application:
public class ApplicationBean {
    private Locale locale;
    private String datePattern;

    public ApplicationBean() {
        locale = new Locale("es"); //for spanish
        datePattern = "dd/MM/yyyy"; //you can change it to yyyy-MM-dd
    }
}

Where ApplicationBean has ApplicationScope.
More info here:

*

*RichFaces Calendar Component Documentation

*RichFaces Calendar Component Demo


text:
Q: Is the Hadoop Split size the same? A hadoop input splits are same size, and I knew it could be customized from the developer.

In the attached figure, input split size is not same. Each input split shape is different. I'm confused about the fact that the input sizes were not the same.
The Hadoop definitive guide also mentioned that the input split size is the same.
Does the system make the input size random by the specified size?


text:
Q: Scroll to Top in iframe without reloading I tried to Scroll To top of the iframe without reloading. I have a form within iframe. When click the submit button, it should be moved to top of the iframe without reloading.
I tried with the following codes,
top.location.href = '#top';
window.parent.location.hash = "#top";
but they are reloading. I should not reload the page. Because, when it loads , validation error message from javascript becomes invalid.Please helpful to achieve this one.
Thanks in Advance

A: Use the function window.scrollTo(xPos, yPos) like window.scrollTo(0,0)
If you want this animated, then you can use jQuery's animate function, and set the scrollTop to 0, like this:
$('iframe').animate({
    scrollTop: 0
});


text:
Q: DB schema for user conversations I've been thinking about how to build a db schema for user conversations within a website I'm building up.
By "conversations" I mean a similar system to a plain-old private messaging one, but similar to Facebook's offline chat.
So far I have this :
id
from_id
to_id
content
created_on

It works, but I wasn't able to find a way to get all the last exchanged messages of each conversation into a list, which made me think that maybe this db schema isn't the way to go.
Assuming there's a users table with a primary numeric id, what would be the best db schema to handle user conversations?
Cheers!

A: I'll do it kind of this way:

*

*Table User have the User Id + other info that you have.

*Relational table to store user speak with user, but this is a 1 chat with 1 user, if you want N user speak with M users at the same time it should be different design.

for Now I think this is pretty ok, because you can save who send the message, to who, what's the message, the TIME, and Status (read, delete, unread, hidden, etc).
I'm pretty sure there is more than one way to do it.

A: I don't think you want a from_id and to_id, just a from_id. You'll determine the first and last message in the conversation by the date.
However, for simplicity and performance sake, I'd make a junction table that's user centric:
user_id  with_user_id conversation_id  last_read_id
-------  ------------ ---------------  --------------
1        2            1                1
1        3            2                0
2        1            1                2
3        1            2                1

Then, for the conversations:
id  conversation_id  from_id  content  created_on
--  ---------------  -------  -------  ----------
1   1                1        hello    2012-06-01 12:00:00
2   1                2        hi       2012-06-01 12:10:01
3   2                3        howdy    2012-06-01 12:40:10

So, when someone wants to begin a conversation, you check the junction table to see if they're already in a conversation with that person. If they are, resume it.
If it's a new conversation, then make sure to add the record in the junction table for each user. The last_read_id column in the junction table refers to id in the conversations table.
To get all the unread messages for user 1:
SELECT c.* FROM junction j
JOIN conversation c
ON c.conversation_id = j.conversation_id
AND c.id > j.last_read_id
WHERE j.user_id = 1
ORDER BY c.created_on DESC

Results in:
id  conversation_id  from_id  content  created_on
--  ---------------  -------  -------  ----------
3   2                3        howdy    2012-06-01 12:40:10
2   1                2        hi       2012-06-01 12:10:01

To get all messages between user 1 and user 2 (from user 1's point of view):
SELECT c.* FROM junction j
JOIN conversation c
ON c.conversation_id = j.conversation_id
WHERE j.user_id = 1 AND j.with_user_id = 2
ORDER BY c.created_on DESC

Results in:
id  conversation_id  from_id  content  created_on
--  ---------------  -------  -------  ----------
2   1                2        hi       2012-06-01 12:10:01
1   1                1        hello    2012-06-01 12:00:00


text:
Q: Remove last n chars from a column in a CSV? Is there a way in microsoft excel or open office calc to remove the last n chars from a field.
Lets say all fields in one column are 31 chars long and I want to remove the last 6 chars.
Is there an easy way with excel or calc to do this?

A: If your data is in A1, you could put the following formula in B1 (or elsewhere):
=LEFT(A1,LEN(A1)-6)

If you want a fixed result rather than a calculated one, you could then copy the result and use 'paste as values'.


text:
Q: I am confused about how git revert works I want to know what's going on. I created an HTML file and put some lines in it
this is first line
this is second line
this is third line
this is fourth line

and committed after each line like commit a, commit b, commit c, commit d respectively.
Now I performed a revert to commit c, but it throws an error :
could not revert 82b69e5... c

hint: after resolving the conflicts, mark the corrected paths

hint: with 'git add <paths>' or 'git rm <paths>'

hint: and commit the result with 'git commit'

I want to know how git-revert works. I know something like it "undoes a commit and add a new commit", but don't know to successfully use it.

A: It creates an invert patch to the commit you want to revert, so in your case, the commit c looked like:
 this is first line
 this is second line
+this is third line
# End of file

Then, from d you run git revert c, so it tries to create the following and apply it on your tree:
 this is first line
 this is second line
-this is third line
# End of file

However, your file looks like:
this is first line
this is second line
this is third line
this is fourth line
# End of file

So the created patch does not apply (end of file vs fourth line conflicting). So when Git tells you:
could not revert 82b69e5... c
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add ' or 'git rm '
hint: and commit the result with 'git commit'

It means "I tried to do what you asked but I face a case I can't solve", so you need to either:

*

*Solve the conflict, using How to resolve merge conflicts in Git

*or cancel the revert with git revert --quit
Most likely, your resolution would be:
this is first line
this is second line
this is fourth line

A: The git revert command can be considered an 'undo' type command, however, it is not a traditional undo operation.
Essentially, it undoes everything that was done in the specified commit and then creates a new commit in the process. You can check this for more information.
And regarding your issue, you are getting merge conflicts. For fixing those conflicts you can use the git mergetools (Ex. Meld).

A: The git revert command can be considered an 'undo' type command, however, it is not a traditional undo operation.
Essentially, it undoes everything that was done in the specified commit and then creates a new commit in the process.


text:
Q: Installed OpenCV but no module found "cv2" in IDLE I have been trying to install OpenCV for ages now and finally I succeeded using this tutorial: http://www.pyimagesearch.com/2016/12/05/macos-install-opencv-3-and-python-3-5/.
However, whenever I try to import cv2 in IDLE, it is not found but I am certain I installed OpenCV.
The cv2.so file exists at:
/usr/local/lib/python3.5/site-packages/cv2.so
I believe it may have something to do with the interpreter but I am not sure how to fix it. In terminal, when I try importing it, it works. I included the terminal message to prove it.

Any help is appreciated. Thank you.

A: ok i found the answer! after you activate the virtual environment with:
work on cv

type this on the terminal to open the IDLE with the current virtual environment
python -c "from idlelib.PyShell import main; main()"

or
python -m idlelib

and it will do the trick!

A: Dumb approach but does your IDLE run the same python environment as your terminal?


text:
Q: Android AlarmManager - Cancel from another Activity I have a Homework Planner application which I want to create an Alarm for to remind users of the homework the night before/at a certain time. I have an Activity called AddNewHomework which is where the user creates a new homework item and it is added to the database. This code is then called.
Intent i = new Intent(this, AlarmNotificationReceiver.class);
i.putExtra("title", title);
PendingIntent pi = PendingIntent.getBroadcast(this.getApplicationContext(), (int) id, i, 0);
AlarmManager mAlarm = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
mAlarm.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 10 * 1000, pi);

This creates a new Alarm which is triggered in 10 seconds and creates a notification.
My problem is that I have another activity called HomeworkList which contains a ListView and displays all of the homeworks stored in the database. If a user long clicks on one then they have the option to delete it, however removing it from the database will not remove the alarm.
I have looked for code I can use to remove the alarm however I have not found anything that allows me to understand how to cancel the alarm from this different activity. I know that I need to make the PendingIntent's the same, but how do I do this as I cannot access the context from the other class. (I don't think).

A: If it helps, you could access your context from another activity, by making a static getter for the current context. In your above class, just make a private field:
private static Context context;

public static Context getAppContext(){
    return MyActivity.context;
}

Then, simply add in the onCreate method a:
MyActivity.context = getApplicationContext();

Accessing the context from another activity is now pretty easy. You can use the context retrieved from "MyActivity" to cancel your alarm.

A: According to this Android: Does context affect filterEquals(), used to cancel alarm? it doesn't matter if you use different contexts, this doesn't affect the recognition of the PendingIntent as matching. I have confirmed this in my own app, I set an alarm from one activity using the activity as the context, and cancelled it from a different activity using that activity's context, and it was successfully cancelled (the action wasn't triggered).


text:
Q: Q : MDC TextField margin as far as I understood, using Sass Mixins is the proper way to customize an MDC element. I have an issue regarding MDC TextField : I am using multiple outlined TextFields to create a form, TextFields are set that way :
<TextField label="Foo" outlined={true} dense={true}>
    <Input
        name="item.foo"
        value={item.foo}
        onChange={this.handleChange}
    />
</TextField>
<p />
<TextField label="Bar" outlined={true} dense={true}>
    <Input
        name="item.bar"
        value={item.bar}
        onChange={this.handleChange}
    />
</TextField>

The issue : floating labels on the top left are overlaping the previous field, in that case, a floating 'Bar' will overlap the outline of the previous element.
To solve this I used a scss file containing this :
.mdc-text-field {
    margin-top: 7px;
}

This is working as intended and solves the overlap issue, but I don't know if I am doing it correctly as I thought only Sass Mixins are the proper way to customize MDC elements.


text:
Q: What would be a more efficient / optimized way of writing this function I have been trying to learn how to write faster more efficient jQuery and would like to get some insight on how I should write this function so it will work faster.  Should i use variables,  I am most concerned with speed on a page so what will run more optimal cross browser and why is the answer I would like to see.
    $("#div-one, #div-two").find('tr').hover(function(){
    $(this).find('a').stop().animate({color:"#FFF"}, 'fast');
    $(this).stop().animate({
        backgroundColor:"#7DBE36"
    }, 'fast');
}, function(){
    $(this).find('a').stop().animate({color:"#000"}, 'fast');
    $(this).stop().animate({
        backgroundColor:"#FFF"
     }, 'fast')
});

Thanks all in advance.

A: You can use .delegate() here, like this:
$("#div-one, #div-two").delegate('tr', 'mouseenter', function(){
    $(this).stop().animate({ backgroundColor:"#7DBE36" }, 'fast')
           .find('a').stop().animate({ color:"#FFF" }, 'fast');
}).delegate('tr', 'mouseleave', function(){
    $(this).stop().animate({ backgroundColor:"#FFF" }, 'fast')
           .find('a').stop().animate({ color:"#000" }, 'fast');
});

This attaches a pair of handlers on #div-one and #div-two instead of a pair per <tr> inside each, this means quicker binding and just relies on event bubbling for listening to the events.  Also inside the function you can chain, no need to create another $(this) jQuery object.

A: You could write another utility function to give you the toggle callbacks:
function animCallback(linkColor, bgColor) {
  return function() {
    $(this).stop().animate({backgroundColor: bgColor}, 'fast')
      .find('a').stop().animate({color: linkColor}, 'fast');
  };
}
$('#div-one, #div-two').find('tr').hover(
  animCallback('#FFF', '#7DBE36'),
  animCallback('#000', '#FFF')
);

edit also Nick's idea is good - you can combine both our answers!

A: As well as using delegate as suggested by Nick, you can also reuse the result of $(this) for an additional micro optimization.
$("#div-one, #div-two").delegate('tr', 'mouseenter', function(){
    var $this = $(this);
    $this.find('a').stop().animate({color:"#FFF"}, 'fast');
    $this.stop().animate({ backgroundColor:"#7DBE36" }, 'fast');
}).delegate('tr', 'mouseleave', function(){
    var $this = $(this);
    $this.find('a').stop().animate({color:"#000"}, 'fast');
    $this.stop().animate({ backgroundColor:"#FFF" }, 'fast');
});

Edit Nick changed his answer to use chaining thus avoiding the reuse of $(this) in the first place. So I'd go with his version instead.

A: As a jQuery developer I have a simple rule, if I will use a selector more than one time in a scope I store it in a variable.
$("#div-one tr, #div-two tr").hover(function() {
    var $this = $(this);
    $this.find('a').stop().animate({color:"#FFF"}, 'fast');
    $this.stop().animate({backgroundColor:"#7DBE36"}, 'fast');
}, function(){
    var $this = $(this);
    $this.find('a').stop().animate({color:"#000"}, 'fast');
    $this.stop().animate({backgroundColor:"#FFF"}, 'fast');
});

I have heard or read that jQuery use some kind of cache when using $(...) for same selectors or objects. jQuery itself use to wrap the keyword this and store it in local variable.
Brief, to optimize jQuery code you should avoid to use $(...) for the same selector in a function scope. A better practice to improve performance is to use it once and store in a variable.
EDIT
After reading answers from Pointy and Nick Craver it wouldn't be necessary this kind of optimization for your code. Because in both answers, they make use of $(this) once.
PD Thanks for your comment/feedback!


text:
Q: convert a dictionary with list of tuples to dataframe I have a dictionary like this:
pred_dict = {('african zebra', 'arabian horse'): [('Blue Whale', 0.49859235), ('Ferrari', 0.5013809), ('african zebra', 0.49264234), ('ara
    ...: bian horse', 0.5186422), ('bobcat', 0.5096679)], ('cheetah', 'mountain lion'): [('Blue Whale', 0.48881102), ('Ferrari', 0.502793), ('afric
    ...: an zebra', 0.48751196), ('arabian horse', 0.49272105), ('bobcat', 0.5228181)]}

Would like to convert to a dataframe like this:
Text | Blue Whale | Ferrari | african zebra| arabian horse | bobcat |
('african zebra', 'arabian horse') 0.49859235 0.5013809 0.49264234 0.5186422 0.5096679
('cheetah', 'mountain lion') 0.48881102 0.502793 0.48751196 0.49272105 0.5228181

The each value in the given dictionary has the exact same number of  tuples with identical first-values in the tuple list. What is to be done is to place the keys of the dict in the 'text' column, and then, have the first values in the tuples as other column-names. The values will be the scores - floats.
Any suggestions would be helpful. here is some stuff I am trying now:
In [12]: text = list(pred_dict.keys())

In [13]: values = list(pred_dict.values())

In [14]: pred_df = pd.DataFrame({'text': text, 'label_scores': values})

In [15]: pred_df
Out[15]:
                             text                                       label_scores
0  (african zebra, arabian horse)  [(Blue Whale, 0.49859235), (Ferrari, 0.5013809...
1        (cheetah, mountain lion)  [(Blue Whale, 0.48881102), (Ferrari, 0.502793)...

In [19]: df_scores = pred_df['label_scores']
In [21]: df_scores
Out[21]:
0    [(Blue Whale, 0.49859235), (Ferrari, 0.5013809...
1    [(Blue Whale, 0.48881102), (Ferrari, 0.502793)...
Name: label_scores, dtype: object

In [22]: labels = [t[1] for t in df_scores[0]]

In [23]: labels
Out[23]: [0.49859235, 0.5013809, 0.49264234, 0.5186422, 0.5096679]

In [24]: labels = [t[0] for t in df_scores[0]]

In [25]: labels
Out[25]: ['Blue Whale', 'Ferrari', 'african zebra', 'arabian horse', 'bobcat']

In [26]: scores = [t[1] for t in df_scores[0]]

In [27]: scores
Out[27]: [0.49859235, 0.5013809, 0.49264234, 0.5186422, 0.5096679]

In [28]: scores = [t[1] for t in df_scores[1]]

In [29]: scores
Out[29]: [0.48881102, 0.502793, 0.48751196, 0.49272105, 0.5228181]

A: pred_dict = {('african zebra', 'arabian horse'): [('Blue Whale', 0.49859235), ('Ferrari', 0.5013809), ('african zebra', 0.49264234), ('arabian horse', 0.5186422), ('bobcat', 0.5096679)], ('cheetah', 'mountain lion'): [('Blue Whale', 0.48881102), ('Ferrari', 0.502793), ('african zebra', 0.48751196), ('arabian horse', 0.49272105), ('bobcat', 0.5228181)]}

This should do it:
pd.concat([pd.DataFrame(r,columns=['Text','value'],index=[t]*len(r)) for (t, r) in pred_dict.items()]).set_index('Text',append=True).unstack('Text')['value']

Produces this:

A: It's not pretty but it works:
pred_dict = {
    ('african zebra', 'arabian horse'): [('Blue Whale', 0.49859235),
                                         ('Ferrari', 0.5013809),
                                         ('african zebra', 0.49264234),
                                         ('arabian horse', 0.5186422),
                                         ('bobcat', 0.5096679)],
    ('cheetah', 'mountain lion'): [('Blue Whale', 0.48881102),
                                   ('Ferrari', 0.502793),
                                   ('african zebra', 0.48751196),
                                   ('arabian horse', 0.49272105),
                                   ('bobcat', 0.5228181)]
}

df = pd.DataFrame(pred_dict).T
df.columns = [tuple[0] for tuple in list(df.iloc[0])]
df = df.apply(lambda x:  [tuple[1] for tuple in x])
df.reset_index(inplace=True)
df.insert(0, "Text", list(zip(df.level_0, df.level_1)))
df.drop(["level_0", "level_1"], axis=1, inplace=True)

The output of which is:
                             Text  Blue Whale  ...  arabian horse    bobcat
0  (african zebra, arabian horse)    0.498592  ...       0.518642  0.509668
1        (cheetah, mountain lion)    0.488811  ...       0.492721  0.522818

A: ok. After some trials, was able to do it. here is how I did it:
text = list(pred_dict.keys())
values = list(pred_dict.values())
df_1 = pd.DataFrame({'text': text})

score_dict = {}
for label in mlb_classes:
     score_list = []
     for t_list in values:
         for t in t_list:
             if t[0] == label:
                 score_list.append(t[1])
     score_dict[label] = score_list

df_2 = pd.DataFrame(score_dict)

score_df = pd.concat([df_1, df_2], axis=1)
print(score_df)

Output:
     text  Blue Whale   Ferrari  african zebra  arabian horse    bobcat
0  (african zebra, arabian horse)    0.519343  0.511951       0.512639       0.527919  0.491461  0.516240
1        (cheetah, mountain lion)    0.495197  0.527627       0.497516       0.512571  0.488823  0.510277


text:
Q: Number fields without abstract algebra I have a student who has taken some linear algebra but no abstract algebra, and he wants to learn some interesting math.
I explained how, by using companion matrices, one can represent and work with roots of polynomials via matrices. The resulting expanded number system is a finite dimensional vector space over the base field (here just the rationals) and multiplication by elements is actually a linear transformation of that space.
He seemed intrigued, and I would like to know how much more of the wonderful world of number fields he could learn just from the linear algebra perspective, avoiding abstract algebra (e.g. groups and rings). That probably means most Galois theory is out. I think a very light amount of abstract algebra might be okay, but I don't want that to be what he is spending most time learning during this semester's project. Some modular arithmetic would also be fine.
Does anyone know a good reference (book/chapter/article) that might suit this purpose? Or maybe a nice theorem we could study?
Thanks.

A: I guess you are looking for the appendix by Olga Taussky in Harvey Cohn's "A Classical Invitation to Algebraic Numbers and Class Fields". This being said, there is a reason why algebraic number theory is called "algebraic".


text:
Q: rlang: refer var in the tidyr unite function Here is my data:
df <- tibble::tribble(
   ~A,  ~B, ~C,
  "a", "b", 2L,
  "a", "b", 4L,
  "c", "d", 3L,
  "c", "d", 5L
  )

var <- "AB"

I want to get this output:
df1 <- df %>%
  unite("AB", c("A", "B")) %>%
  group_by(AB) %>%
  nest()

However, I want to refer var, maybe using rlang. I do not want to manually input "AB". I tried the following, but not getting the desired output.
df1 <- df %>%
  unite(var, c("A", "B")) %>%
  group_by(!!var) %>%
  nest()

A: This solved the problem:
df1 <- df %>%
  unite(!!var, c("A", "B")) %>%
  group_by(!!sym(var)) %>%
  nest()


text:
Q: Inherit Grails Domain Class properties from a base Class Im trying to create a Domain Class Constructor that inherits another class properties dynamically. But I cannot get it to work properly.
Heres an example:
class Example1 {

  String name;
  String location;
}

class Example2 extends Example1 {

  String status;

  public Example2 (Example1 orig){
    // Code here to set this.name and this.location  to name and location from orig
    // dynamically, so adding a field in Example1 does not require me to add that
    // field here.
  }
}

A: You're working too hard, just copy the properties:
class Example2 extends Example1 {

   String status

   Example2() {}

   Example2(Example1 orig) {
      this.properties = orig.properties
   }
}

A: After enough troubleshooting and searching online I found a solution, here it is in case anyone is ever looking for something similar:
public Example2(Example1 orig){
   def d = new DefaultGrailsDomainClass(Example1.class)
   d.persistentProperties.each { val ->
       this[val.name] = orig[val.name]
   }
}

Include this:
import org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass

A: I'm not entirely clear on what it is that you want to accomplish, but is there any reason that you can't just have an "Example1" field in the "Example2" class?


text:
Q: Associate each enum member to a class and get generic info from that class Suppose I have lots of audio effects into an enum:
enum AudioEffect {
    CHORUS,
    FILTER,
    GAIN,
    OSCILATOR,
    PHASER
};

and for each one, there's a class that specifies how the audio bytes will be processed:
class ChorusProcessor  : public ProcessorBase
{
public:
    ChorusProcessor()
    {
    }
}

class FilterProcessor  : public ProcessorBase
{
public:
    FilterProcessor()
    {
    }
}

Each of these processor classes will have parameters that can be changed, these are the audio controllers (mute/unmute, sliders, etc).
Without making an instance of the processors, is it possible to traverse the enum, and for each enum, get the list of controllable values with its min and max values?
I think C++ is smart enough to let us do these things. I'd begin thinking on how to associate Chorus with ChorusProcessor, Filter with FilterProcessor etc. How would I do that?
Then I'd make all the processor classes derive from a class like AudioEffectDescription which has some constexprs that describe each parameter.

A: You can do that with a bit of trickery but I am not sure how useful it really is.
The main problem you will have to face it that generally you can't iterate easily through all values of an enum. As the underlying data type for a normal enum is integer starting you might use a simple loop for a plain enum but this fails for any enum where values are set manually such as
enum class AudioEffect {
  Chorus = 3,
  Filter = 6,
  Gain = 5,
  Oscillator = 2,
  Phaser = 1
};

Generally you will have to create an additional data structure like a std::tuple or a std::vector<AudioEffect>, add all the possible values and loop over using something like a variadic template (As soon as you use template parameters a normal loop won't suffice anymore). Furthermore in C++ there is no such thing as virtual static functions.

Specialised template class
The best I can come up with is:

*

*Declare a class template <AudioEffect E> class Processor and specialise it for all possible template parameters. I added two static constexpr functions for getting the min and the max. These will have to be declared in all specialisations. I have used two functions min and max that return a minimum and a maximum value but you could return a std::string_view (or in C++20 you will be able to return a constexpr std::string) that contains more information about the different limits.
template <AudioEffect E>
class Processor: ProcessorBase {
};

template <>
class Processor<AudioEffect::Chorus>: ProcessorBase {
  public:
    // Or a single function for printing all the settings of this class
    static constexpr int min() {
      return 1;
    }
    static constexpr int max() {
      return 99;
    }
};

*Then I can print all the limits with a variadic template function and C++17 fold expressions (assuming here that each instance of the template class Preprocessor has a static constexpr function min and another one max
template <AudioEffect... E>
std::string print() {
  std::stringstream ss;
  ((ss << E << "\t min: " << Processor<E>::min() << ",\t max: " << Processor<E>::max() << std::endl), ...);
  return ss.str();
}

*This print function can be called inside the main listing all possible parameters
std::cout << print<AudioEffect::Chorus,AudioEffect::Filter,AudioEffect::Gain,AudioEffect::Oscillator,AudioEffect::Phaser>() << std::endl;

Try it here!

Map
Another similar way would be to map the enum to the classes (that do not have to be specialised templates anymore) with traits like here by

*

*Defining your classes like
class ChorusProcessor: ProcessorBase {
  public:
    static constexpr int min() {
      return 1;
    }
    static constexpr int max() {
      return 99;
    }
};

*Then specialising a template struct Map that maps in between the enum values and the classes
template<AudioEffect> struct Map;

template<> struct Map<AudioEffect::Chorus> {
  using type = ChorusProcessor;
};

*And introducting a print function again with variadic templates like
template <AudioEffect... E>
std::string print() {
  std::stringstream ss;
  ((ss << E << "\t min: " << Map<E>::type::min() << ",\t max: " << Map<E>::type::max() << std::endl), ...);
  return ss.str();
}

Try it here!
This is pretty similar to the solution proposed in the comments that makes use of an std::tuple
using Processors = std::tuple<
  ChorusProcessor,
  FilterProcessor,
  GainProcessor,
  OscilatorProcessor,
  PhaserProcessor
>;

std::tuple_element_t<AudioEffect::Filter, Processors>::value

Brief but dirty
If you use an enum without specifying values explicitly you could also go away with a dirty solution only supplying the first and the last value of the enum (C++17)
template <AudioEffect Begin, AudioEffect End>
std::string print() {
  std::stringstream ss;
  ss << Begin << "\t min: " << Processor<Begin>::min() << ",\t max: " << Processor<Begin>::max() << std::endl;
  if constexpr (Begin != End) {
    ss << print<static_cast<AudioEffect>(static_cast<int>(Begin)+1), End>();
  }
  return ss.str();
}

This way you could simply call it with the first and the last value of the enum
std::cout << print<AudioEffect::Chorus,AudioEffect::Phaser>() << std::endl;

Try it here!

Enum reflection
Finally with the GCC, Clang and MSVC compiler there is a hacky way to get some enum properties with the __PRETTY_FUNCTION__ identifier which is described here. (There are a few typos in the original code and it is not constexpr so better try it here.)
With it you could completely get rid of the Begin and End by looping from 0 to the detected number of enum values. This is a bit more complicated so I will just leave the code here for you to try. With it you can output all classes without specifying all the enum values explicitly:
std::cout << print<AudioEffect>() << std::endl;


text:
Q: Dygraphs skip column I'm working on a project with Dygraphs and here is my problem :
My data looks like this (loaded from a CSV file URL):
"TimeInt";"TimeStr";"A_DP_01012_H";
1471443131;"17/08/2016 14:12:11";0;0.314072;

Data is generated automatically from an external source.
So my problem is that I cannot remove TimeInt or TimeStr column, but right now if I use those data as is I get :

dygraph-combined-dev.js:7015 Unable to parse '"17/08/2016 14:17:18"' as a number on line 59

So is there any way to skid first column of data and use second column as Xdata
Also, is there any problem using "TimeStr" or it really needs to be without it?
Thanks.


text:
Q: Synchronous Bonjour resolution with NSNetService (why is it taking so long to return control from the runloop?) I am trying to do a Bonjour resolution of a service name synchronously, so I am trying to figure out how to properly wait for the netServiceDidResolveAddress() call of NSNetService.
My code looks like this:
service = [[NSNetService alloc] initWithDomain:@"local." type:@"_myservice._tcp" name:[self name]];
[service retain];
[service setDelegate:self];
waitingOnResolution = true;
[service resolveWithTimeout:5.0];

for (int i=0;i<5;i++) {
    DebugLog(@"resolve: resolve iteraton %u\n", i);
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]]; // run loop for one second
    DebugLog(@"resolve: resolve iteraton %u (after run loop)\n", i);
    if (!waitingOnResolution) break;
}

// continue processing...

And here is my function that handles the resolution success:
- (void)netServiceDidResolveAddress:(NSNetService *)sender
{
    // do processing...
    waitingOnResolution = false;
    CFRunLoopStop([[NSRunLoop currentRunLoop] getCFRunLoop]); // has no effect
}

As long as my code continues to run a second or so after the resolve event comes in, I'll be happy.
What is actually happening is the resolve happens pretty quickly, and I see the code in netServiceDidResolveAddress() complete, but then there is consistently an undesirable 5-6 second wait until control returns from runUntilDate and I see the "...(after run loop) debug statement.
I looked around on several message boards and saw similar questions, but their solutions (like using CFRunLoopStop) don't seem to have any effect.
Here is an example of logging I receive:
2011-07-11 09:38:07.267 MyProgram[1822:707] resolve: resolve iteraton 0
2011-07-11 09:38:07.299 MyProgram[1822:707] netService: netServiceDidResolveAddress function ended

[5+ second delay]

2011-07-11 09:38:12.907 MyProgram[1822:707] resolve: resolve iteraton 0 (after run loop)

If someone can tell me of a different way to use NSNetService resolution to get a synchronous result, or refactor my runloop-related code to avoid this (seemingly OS-created) 5-6 second delay, I would appreciate it.

A: You really shouldn't be doing this. Network resolution is asynchronous for a good reason: it might take a long time to perform the resolution, and in most cases, you don't want to block your thread for the duration. If you are doing the resolution on the main thread, you really do not want to do it synchronously. On Mac OS X, a long-running operation blocking the main thread will result in a spinning beachball. On iOS, the watchdog might kill your app entirely.
The API is asynchronous to encourage you to use it properly. Don't try to fight it.
Since you don't explain why you're trying to do this synchronously, I can't help much more, but keep in mind that Cocoa is event driven. Break your synchronous steps into states and let the callbacks from Cocoa during each stage drive your state machine forward. It won't look as nice as a line-by-line procedural function, but it will keep your UI responsive and avoid ugly workarounds.

A: Just remove the CFRunLoopStop and it should work fine. Stopping the NSRunLoop will stop any other events on this NSThread. I did the same (without stopping the RunLoop) for synchronously resolving some NSNetServices and it worked fine.


text:
Q: JQM jump to previous page after clicking link I'm using prestashop (1.4), I've installed 'mobile theme' module (for mobile client) which uses jqm (1.3.2) on top of jquery (1.9.1)
If I go to a page and as soon as the page displayed but before the page is fully loaded , I click on a link, the new page is displayed and then after a few second the previous page is displayed.
I think that when JQM finished to load the previous page it's call some handler that cause it to display.
I solve it by changing the JQM code (line 5021, http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.js) so that it will display any link as an external link.
but I would like to know if I can fix it without changing the JQM code


text:
Q: snackbar con base de datos, quiero mostrar un snackbar con datos obtenidos a través de una base de datos, el problema es que el snackbar no se muestra, les dejare el codigo que estoy utilzando:
edit: borre el codigo y este es el actual
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(final Marker marker) {

                    View v1 = findViewById(R.id.content_main);
                    int height = 20;
                    int width = 20;
                    String query = "select top 1 tipo,descripcion from reporte where nombre_ruta = '"+marker.getTitle()+"';";
                    String query2="select AVG(valoracion)as valoracion from valorar where nombre_ruta = '"+marker.getTitle()+"';";

                    BitmapDrawable bitmapdraw = (BitmapDrawable) getResources().getDrawable(R.drawable.starmarcadores);
                    Bitmap b = bitmapdraw.getBitmap();
                    Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
                    Drawable drawable= new BitmapDrawable(getResources(), smallMarker);

                    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                    ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);

                    try {
                                    con = connectionclass (un, passwords, db, ip);
                                    if (con == null) {
                                        isConnected(getApplicationContext());
                                    } else if(con!=null){
                                        Log.d("este camino","este camino");
                                        stmt = con.prepareStatement(query);
                                        stmt.setQueryTimeout(2);
                                        rs = stmt.executeQuery();
                                        while (rs.next()) {
                                            Log.d("tipo",rs.getString("tipo"));
                                            Log.d("descripcion",rs.getString("descripcion"));

                                            SpannableStringBuilder snackbarText = new SpannableStringBuilder();
                                            snackbarText.append("Valoración: ");
                                            snackbarText.append("");
                                           // snackbarText.setSpan(span, 13, 14, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                            snackbarText.append(System.getProperty("line.separator"));
                                            snackbarText.append("Estado de la ruta: posible " + rs.getString("tipo") );
                                            snackbarText.append(System.getProperty("line.separator"));
                                            snackbarText.append("Descripción del reporte: " + rs.getString("descripcion"));

                                            snackbar = Snackbar.make(v1, snackbarText, Snackbar.LENGTH_INDEFINITE)
                                                    .setActionTextColor(Color.YELLOW)
                                                    .setAction("Opciones", new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View v) {
                                                            new AlertDialog.Builder(MainActivity.this)
                                                                    .setIcon(R.drawable.cerrar)
                                                                    .setTitle("Opciones")
                                                                    .setMessage("Te gustaria valorar o reportar la ruta?")
                                                                    .setCancelable(true)
                                                                    .setPositiveButton("Valorar", new DialogInterface.OnClickListener() {
                                                                        @Override
                                                                        public void onClick(DialogInterface dialog, int which) {
                                                                            Intent i = new Intent(getApplicationContext(), Valoracion2.class);
                                                                            i.putExtra("Nruta", marker.getTitle().toString());
                                                                            startActivity(i);
                                                                        }
                                                                    })
                                                                    .setNeutralButton("Cancelar", null)
                                                                    .setNegativeButton("Reportar", new DialogInterface.OnClickListener() {
                                                                        @Override
                                                                        public void onClick(DialogInterface dialog, int which) {

                                                                        }
                                                                    }).show();
                                                        }
                                                    });
                                            View snackbarView = snackbar.getView();
                                            TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
                                            textView.setMaxLines(5);
                                            snackbar.show();
                                            con.close();
                                        }
                                    }
                    } catch (SQLException e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
                    }
                    return false;
                }
            });

el problema ahora es este

pero ya carga la snackbar y los datos, solo el mensaje es el problema

A: Fíjate en este código
con = connectionclass(un, passwords, db, ip);
if (con == null) {
    isConnected(getApplicationContext());
    //creas el snackbarText sin los datos de la base
}else{
    //creas el snackbarText con los datos de la base
}

Si la conexión es nula, no crea por lo tanto parece ser que el error es eso, que si es nula no hace nada por eso no se dibuja, debes iniciar la variable con y asegurarte que hay una conexion a la base de datos SI Y SOLO SI, quieres que tu snackbarText tenga datos de la base de datos, deberia ser algo asi :
con = connectionclass(un, passwords, db, ip);
if (con == null) {
    //aqui conectar correctamente la base de datos
}
//seguir el tratamiento
stmt = con.prepareStatement(query);
stmt.setQueryTimeout(1);
rs = stmt.executeQuery();

SI, el escenario es distinto y NO NECESARIAMENTE los datos van a salir de la base de datos, deberias seguir el orden que tienes
con = connectionclass(un, passwords, db, ip);
if (con == null) {
    isConnected(getApplicationContext());
}else{
    //creas el snackbarText
}

Con la diferencia que en el if (con == null) aparte de llamar al metodo isConnected(getApplicationContext()); dibujar tu snackbarText sin los datos de la base.

A: Debes revisar tu conexión ya que es la que determina que se muestre el SnackBar
 con = connectionclass (un, passwords, db, ip);
    if (con == null) {
             isConnected(getApplicationContext());
     } else {
             //Muestra SnackBar.

Es importante también, revises dentro de tu LogCat, ya que pudieras tener una buena conexión, y obtener correctamente el Resultset pero al obtener datos como  "tipo"  y "descripcion" estos no se obtengan realmente:
rs = stmt.executeQuery();
 if (rs.next()) {
    SpannableStringBuilder snackbarText = new SpannableStringBuilder();
    snackbarText.append("Valoración: ");
    snackbarText.append(valoracion + " ");
    snackbarText.setSpan(span, 13, 14, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    snackbarText.append(System.getProperty("line.separator"));
    snackbarText.append("Estado de la ruta: posible " +  rs.getString("tipo"));
    snackbarText.append(System.getProperty("line.separator"));
    snackbarText.append("Descripción del reporte: " + rs.getString("descripcion"));

El problema es cierras la conexión pero la instancia es nula!
con.close();

Debes validar
if(con != null){
  con.close();
}

o únicamente cerrar la conexión al final del else, en el cual se determina que la conexión se realizo:
con = connectionclass (un, passwords, db, ip);
    if (con == null) {
        isConnected(getApplicationContext());
        Log.d("conexion nula","conexion nula");
    } else {
       ...
       ...
       con.close();
     }

El error que ahora comentas:

Invalid State : the resultSet object is closed()

Se debe a que intentas obtener datos del cursor (rs) pero no existe.


text:
Q: UINavigationController Back Button Chevron in iOS 7 I would love to say that I'm enjoying this transition to iOS 7, but it feels like battle after battle to just get the app functional again.
My current issue is with a uinavigationcontroller. It's embedded in a tab controller. The problem occurs when the user starts drilling down into categories. The back button chevron moves to the upper left portion of the navigation bar while the actual back button remains fixed in its normal spot. The code isn't doing any manipulation. It's just pushing and popping view controllers.
Here's a screenshot of the issue:

Has anyone encountered this problem and have any ideas how I may fix it? All suggestions are welcome.

A: Have you changed the font size - this may have changed the line-height value causing displacement?
It maybe best to opt for a custom back button so you have more control of the placement. You can place this snippet in viewDidLoad
if ( [self.navigationController.viewControllers count] > 1 )
{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setAdjustsImageWhenHighlighted:NO];
    [backBtn setShowsTouchWhenHighlighted:YES];
    [backBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    UIImage *backBtnImage = [UIImage imageNamed:@"back.png"]; // <-- Use your own image
    [backBtn setImage:backBtnImage forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    backBtn.frame = CGRectMake(0, 0, 40, 40);
    UIBarButtonItem *backBarBtnItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backBarBtnItem;
}

Also add the method for custom back button touch event:
- (void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}


text:
Q: Ruby Typhoeus gem - Invalid Json in body? I have the following code:
require 'Typhoeus'

  url = Typhoeus::Request.new("https://fluidsurveys.com/api/v2/webhooks/subscribe/",
        userpwd: "username_test:password_test",
        method: :post,
        body: {
             'subscription_url' => 'http://glacial-spire-test.herokuapp.com/hooks/response_created_callback',
             'event' => 'response_complete'
        },
        headers: { 'Content-Type' => "application/json"})

    response = url.run.body
    puts response

This returns a response code of 400 and an error:
Content-Type set to application/json but could not decode valid JSON in request body.
Here are the docs for the API call I am making: http://docs.fluidsurveys.com/api/webhooks.html
POST /api/v2/webhooks/subscribe/¶
Returns a status of 409 if a webhook with the subscription url already exists. Returns a
status of 201 if the webhook was successfully created. Requests must be sent as an
application/json-encoded dictionary with the required fields subscription_url and event

Sample request (ACCORDING TO DOCS):
{
  "subscription_url": "http://fluidsurveys.com/api/v2/callback/",
  "event": "response_complete",
  "survey": 1,
  "collector": 1
}

What am I doing wrong here? survey and collector are optional params, and I don't see an issue with the json in my body.

A: I am guessing you might need to convert the request body into JSON using a library like Oj (https://github.com/ohler55/oj). Using the Oj library:
requestBody = {
  'subscription_url' => 'http://glacial-spire-test.herokuapp.com/hook/response_created_callback',
  'event' => 'response_complete'
}

url = Typhoeus::Request.new("https://fluidsurveys.com/api/v2/webhooks/subscribe/",
        userpwd: "username_test:password_test",
        method: :post,
        body: Oj.dump(requestBody, mode: :compat),
        headers: { 'Content-Type' => "application/json"})

response = url.run.body
puts response

The critical line is:
        body: Oj.dump(requestBody, mode: :compat)

If you need to load any JSON content to Ruby, just use Oj.load


text:
Q: How to access PersistentVolume files on docker-for-desktop? I'd like to access and edit files in my Kubernetes PersistentVolume on my local computer (macOS), but I cannot understand where to find those files!
I'm pointing my hostPath to /tmp/wordpress-volume but I cannot find it anywhere. What is the hidden secret I'm missing
I'm using the following configuration on a docker-for-desktop cluster Version 2.0.0.2 (30215).
PersistentVolume
kind: PersistentVolume
metadata:
  name: wordpress-volume
spec:
  # ...
  hostPath:
    path: /tmp/wordpress-volume

PersistentVolumeClaim
kind: PersistentVolumeClaim
metadata:
  name: wordpress-volume-claim
# ...

Deployment
kind: Deployment
metadata:
  name: wordpress
# ...
spec:
  containers:
  - image: wordpress:4.8-apache
    # ...
    volumeMounts:
    - name: wordpress-volume
      mountPath: /var/www/html
  volumes:
  - name: wordpress-volume
    persistentVolumeClaim:
      claimName: wordpress-volume-claim

A: First this you need to remember is that Kubernetes is running on minikube cluster.
minikube itself run on Virtual Machine. So that path won't be on you host machine, rather it is the path in Virtual Machine.
But with minikube we have easy way to do this. First you have to mount host directory to minikube.
(If you are using cloud providers you will have some way to create a storage. For GCE you have gcePersistentDisk)
minikube mount /path/to/dir/to/mount:/vm-mount-path
Now
kind: PersistentVolume
metadata:
  name: wordpress-volume
spec:
  # ...
  hostPath:
    path: /vm-mount-path

If you create this resource this should save file in your host machine.
Follow this minikube documentation for more detail

A: In case of MacOS and Kubernetes inside Docker for Mac. How to find a real location of dir-based local volume into VM
1) Create a new PersistentVolume with unique path:
blablabla.yml:
kind: PersistentVolume
apiVersion: v1
metadata:
  name: blablabla
spec:
  storageClassName: manual
  capacity:
    storage: 1G
  accessModes:
    - ReadWriteMany
  hostPath:
    path: "/mnt/blablabla"

kubectl apply -f blablabla.yml
2) Log into VM:
screen ~/Library/Containers/com.docker.docker/Data/vms/0/tty
# then press Enter

3) Find your volume:
find / -name blablabla
/containers/services/docker/rootfs/mnt/blablabla # <= got it!
/containers/services/docker/tmp/upper/mnt/blablabla

4) Exit from screen: Ctrl-a k y, Detach from screen: Ctrl-a d
Note
Sometimes you have a chance to get a broken screen session, it seems like a  garbaged stdout with messed symbols, stdin still works fine. In that case, try to terminate all screen sessions and reconnect to the first one. Or just restart you docker for mac.

A: I create a PersistentVolume and use the storageClassName (local-storage in my example below). Make sure to replace the path (/Users/user/data-pv1) with an actual path on your Mac.
apiVersion: v1
kind: PersistentVolume
metadata:
  name: local-pv1
spec:
  capacity:
    storage: 30Gi
  accessModes:
  - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: local-storage
  local:
    path: /Users/user/data-pv1
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - docker-desktop

If you'd like to access the hostPath, you need to use nsenter:
docker run -it --rm --privileged --pid=host alpine:edge nsenter -t 1 -m -u -n -i sh

or nsenter1
docker run -it --rm --privileged --pid=host justincormack/nsenter1

and navigate to the following directory:
/var/lib/k8s-pvs

A: Thanks to @aman-tuladhar and some hours lost on the internet I've found out that you just need to make sure storageClassName is set for you PersistentVolume and PersistentVolumeClaim.
As per documentation if you want to avoid that Kubernetes dynamically generetes PersistentVolumes without considering the one you statically declared, you can just set a empty string " ".
In my case I've set storageClassName: manual.
PersistentVolume
kind: PersistentVolume
metadata:
  name: wordpress-volume
spec:
  # ...
  storageClassName: manual
  hostPath:
    path: /tmp/wordpress-volume

PersistentVolumeClaim
kind: PersistentVolumeClaim
metadata:
  name: wordpress-volume-claim
spec:
  storageClassName: manual
  # ...

This works out of the box with docker-for-desktop cluster (as long as mountPath is set to a absolute path).
References:

*

*Kubernetes: Binding PersistentVolumes and PersistentVolumeClaims

*Storing data into Persistent Volumes on Kubernetes


text:
Q: Are there homomorphisms $SU(2) \xrightarrow{} SU(2)$ with higher homotopy? I am quite new to the subject, so I apologize in advance for anything sloppy which I may write.
The homotopy group $\pi_3(SU(2))= \mathbb{Z}$ classifies maps of the form $S^3 \simeq SU(2) \xrightarrow{} SU(2)$, where $\mathbb{Z}$, roughly speaking, measures how many times $SU(2)$ wraps onto itself.
These maps, and their homotopy classification, appear in the standard construction of instantons via bundles. For example, we have that the map $g_0: x \in S^3 \mapsto e \in SU(2)$, with $e$ being the identity, belongs to the class $0$ of $\pi_3(SU(2))$.
The following map belongs to the class $1$: $g_1: (x_1,x_2,x_3,x_4)\in S^3 \mapsto \frac{1}{r} (x^4 \mathbb{1} + \sum_i x_i \sigma_i) \in SU(2)$, where $r^2=x_1^2 + x_2^2 + x_3^2 +x_4^2$, $\sigma_i$ are the Pauli matrices and $\mathbb{1}$ is the identity.
For $n>1$, the map $g_n: x \mapsto r^{-n}(x^4 \mathbb{1} + \sum_i x_i \sigma_i)^n$ belongs to the class $n$ of $\pi_3(SU(2))$.
Clearly, all these maps can be thought to be maps from $SU(2)$ to $SU(2)$. $g_0$ and $g_1$ are homomorphisms, i.e. $g(x y)=g(x)g(y)$. However, since $SU(2)$ is not abelian, it is evident that $g_n$ with $n>1$ is $not$ a homomorphism.
Now, finally to my question: are there homomorphisms $SU(2) \xrightarrow{} SU(2)$ that belong to the class $n$ of $\pi_3(SU(2))$ for $n>1$? If so, could you give me an example?
Thanks in advance!

A: No, there a no homomorphisms belonging to class $n$ for $|n| > 1$.
More generally, we have the following:
Proposition:  Suppose $G$ is a connected simple Lie group (meaning all proper normal subgroups are finite).  Then every homomorphism is either trivial or an isomorphism.
Proof:  Suppose $f:G\rightarrow G$ is non-trivial.  Moving to the Lie algebra level, the induced map $f_\ast$ must also be non-trivial.  So $\ker f_\ast$ is a proper ideal, and hence is trivial.  This implies $f_\ast$ is an isomorphism, which, in turn, implies $f$ is an isomorphism.  $\square$
Of course, a trivial map induces the $0$ map on $\pi_k$ for any $k$.
On the other hand, an isomorphism must induce an isomorphism on $\pi_k$ for any $k$.  Thus, in your particular case, only $n\in \{0, \pm 1\}$ is possible.
In fact, $n = -1$ is not possible when $G = SU(2)$.  Probably the easiest way to see this is to note that $SU(2)$ has trivial outer automorphism group, so all automorphisms are isotopic to the identity map, which clearly is the $n=1$ case.


text:
Q: Tkinter - How would I go about resetting list of objects? Yesterday I asked this question Creating elements by loop Tkinter to find out how to dynamically create some bullet points. Now I'm looking to add a clear button so when pressed, will reset the entire form. I have tried setting the list back to [] but it didn't work.
edit - So basically when I press reset I'd like it to look exactly like it did when the form was loaded.

A: The buttons are removed with the destroy method:
    for button in self.button:
        button.destroy()

import Tkinter as tk

class ButtonBlock(object):
    def __init__(self, master):
        self.master = master
        self.button = []
        self.button_val = tk.IntVar()
        entry = tk.Entry()
        entry.grid(row=0, column=0)
        entry.bind('<Return>', self.onEnter)
        entry.focus()
        clear_button = tk.Button(master, text='Clear', command=self.onClear)
        clear_button.grid(row=0, column=1)
    def onClear(self):
        for button in self.button:
            button.destroy()
    def onEnter(self, event):
        entry = event.widget
        num = int(entry.get())
        self.onClear()
        for i in range(1, num+1):
            self.button.append(tk.Radiobutton(
                self.master, text=str(i), variable=self.button_val, value=i,
                command=self.onSelect))
            self.button[-1].grid(sticky='WENS', row=i, column=0, padx=1, pady=1)
    def onSelect(self):
        print(self.button_val.get())

if __name__ == '__main__':
    root = tk.Tk()
    ButtonBlock(root)
    root.mainloop()

A: Setting the list back (i.e. using self.button = []) just clears the data stored in the button variable. That action alone is not connected to the user interface (UI). You have to explicitly remove the widget objects which were created (by the onEnter method).
So the clearing feature you are looking for should be feasible by extending the answer from your previous question. Add an onClear method to the ButtonBlock class so that when your "Clear" control (i.e. using a button widget) is selected its callback function calls ButtonBlock.onClear(), similar to how your Entry widget invokes the onEnter method.
EDIT: See unutbu's answer to this question. When selected, the clear_button control calls ButtonBlock.onClear(). The for loop in onClear gets a reference to each button ojbect from the button list and calls the object's destroy method, which removes it from the UI.


text:
Q: How do I prove that the following sets are Borel sets? I have the following problem.

Let $f_n:\mathbb{R}\rightarrow \mathbb{R}$ be Borel-measurable functions. Show that
$$\{x|\limsup\, f_n(x)=\infty\}, \,\,\{x|\limsup \,f_n(x)=c\}, c\in \mathbb{R}$$ are borel sets.

From the lecture we just know that since $f_n$ are Borel-measurable, then also $g(x)=\limsup \,f_n(x)$ is Borel-measurable.
I only looked at the second set for the moment and I thought if $g(x)$ is measurable, we get that $g^{-1}(c)=\{x|g(x)=c\}\subset B(\mathbb{R})$. Remark that $c\in B(\mathbb{R})$.
But I'm not sure if this works because somehow I found it too easy.


text:
Q: Background Audio play - app rejected I set Background Modes in my plist to "App plays Audio"
As audio player I use StreamingKit
I add this code NOT in AppDelegate, but in some method in audioPlayer class
NSError *setCategoryErr = nil;
NSError *activationErr  = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];

And I have answer
We found that your app uses a background mode but does not include functionality that requires that mode to run persistently. This behavior is not in compliance with the App Store Review Guidelines.
We noticed your app declares support for audio in the UIBackgroundModes key in your Info.plist, but did not include features that require persistent audio.
As indicated in the iOS Application Programming Guide:
"This key is intended for use by applications that provide audible content to the user while in the background, such as music-player or streaming-audio applications."
Therefore, it would be appropriate to provide audible content to the user while the app is in the background or remove the "audio" setting from the UIBackgroundModes key.
What can cause this rejection?

A: You should make sure that you can listen to music with your app while the device is locked. On the lock-screen you should see the name of the app, and there should be a pause button on the lock screen and the pause button should work and silence the music.
(As usual, you should test the result on multiple devices, on iOS 7, and if you are supporting iOS 6 also on an iOS 6 device.)
Then you can re-submit... :)


text:
Q: Function getAccountBalance() doesn't work I am creating examples to share with another developers but i try to keep for now very simple the code, all the basic functions  are working:
I am using the oficial documentation.LINK
account.deleteAccount()
account.getAccountDetails()
account.createAccount()

etc... but this function:
account.getAccountBalance();

Send me a error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading "storage_amount _per_byte" )
at Account.getAccountBalance (VM3453 near-api-is.is:346)
at async main.is: 46

+++++UPDATE++++++
const CONTRACT_NAME = 'josedlujan.testnet'; /* TODO: fill this in! */
const config = {
    nodeUrl: "https://rpc.testnet.near.org",
    //deps: {
        keyStore: new nearApi.keyStores.BrowserLocalStorageKeyStore(),
    //},
    networkId: 'testnet',
        nodeUrl: 'https://rpc.testnet.near.org',
    contractName: CONTRACT_NAME,
    walletUrl: 'https://wallet.testnet.near.org',
    helperUrl: 'https://helper.testnet.near.org'

};

async function () {
    window.near = await nearApi.connect(config);
    console.log(near)
    // ---------------------------------------------------------------------------
    // here you have access to `near-api-js` and a valid connection object `near`
    // ---------------------------------------------------------------------------
    window.walletConnection = new nearApi.WalletConnection(near);
    console.log(window.walletConnection)

    // Initializing our contract APIs by contract name and configuration.
    window.contract = await new nearApi.Contract(window.walletConnection.account(), near.contractName, {
        // View methods are read-only – they don't modify the state, but usually return some value
        viewMethods: ['get_num'],
        // Change methods can modify the state, but you don't receive the returned value when called
        changeMethods: ['increment', 'decrement', 'reset'],
        // Sender is the account ID to initialize transactions.
        // getAccountId() will return empty string if user is still unauthorized
        sender: window.walletConnection.getAccountId()
    });

 window.account = await near.account(walletConnection.getAccountId());
    console.log(window.account);

 const balance = await window.account.getAccountBalance();
    console.log(balance);

A: while trying to understand what may be breaking, this is what I did ...
(1) look at the source code
this is the code you are running when calling that method.  I found it by searching for the string "getAccountBalance" in the near-api-js repo because I see you're running in a JavaScript context and I know that NEAR wraps its API with near-api-js to make life easier for JavaScript devs.
account.getAccountBalance()
async getAccountBalance(): Promise < AccountBalance > {
  const protocolConfig = await this.connection.provider.experimental_protocolConfig({ finality: 'final' });
  const state = await this.state();

  const costPerByte = new BN(protocolConfig.runtime_config.storage_amount_per_byte);
  const stateStaked = new BN(state.storage_usage).mul(costPerByte);
  const staked = new BN(state.locked);
  const totalBalance = new BN(state.amount).add(staked);
  const availableBalance = totalBalance.sub(BN.max(staked, stateStaked));

  return {
    total: totalBalance.toString(),
    stateStaked: stateStaked.toString(),
    staked: staked.toString(),
    available: availableBalance.toString()
  };
}

the first line in the function calls experimental_protocolConfig
await this.connection.provider.experimental_protocolConfig({ finality: 'final' });

(2) test it in pieces
I can take each piece of this function and call it one by one from the REPL available in NEAR CLI and check what it returns
first, start the repl with your account in context
near repl --accountId sherif.testnet

then, call the method
await account.getAccountBalance()

and the result is fine for me
{
  total: '21795471561668895374325524265',
  stateStaked: '212510000000000000000000',
  staked: '0',
  available: '21795259051668895374325524265'
}

then, call the method
await account.connection.provider.experimental_protocolConfig({ finality: 'final'})

and you'll see the return value
{
  "protocol_version": 50,
  "genesis_time": "2020-07-31T03:39:42.911378Z",
  "chain_id": "testnet",
  "genesis_height": 42376888,
  "num_block_producer_seats": 200,
  "num_block_producer_seats_per_shard": [
    200,
    200,
    200,
    200
  ],
  "avg_hidden_validator_seats_per_shard": [
    0,
    0,
    0,
    0
  ],
  "dynamic_resharding": false,
  "protocol_upgrade_stake_threshold": [
    4,
    5
  ],
  "epoch_length": 43200,
  "gas_limit": 1000000000000000,
  "min_gas_price": "5000",
  "max_gas_price": "10000000000000000000000",
  "block_producer_kickout_threshold": 80,
  "chunk_producer_kickout_threshold": 90,
  "online_min_threshold": [
    90,
    100
  ],
  "online_max_threshold": [
    99,
    100
  ],
  "gas_price_adjustment_rate": [
    1,
    100
  ],
  "runtime_config": {
    "storage_amount_per_byte": "10000000000000000000",
    "transaction_costs": {
      "action_receipt_creation_config": {
        "send_sir": 108059500000,
        "send_not_sir": 108059500000,
        "execution": 108059500000
      },
      "data_receipt_creation_config": {
        "base_cost": {
          "send_sir": 36486732312,
          "send_not_sir": 36486732312,
          "execution": 36486732312
        },
        "cost_per_byte": {
          "send_sir": 17212011,
          "send_not_sir": 17212011,
          "execution": 17212011
        }
      },
      "action_creation_config": {
        "create_account_cost": {
          "send_sir": 99607375000,
          "send_not_sir": 99607375000,
          "execution": 99607375000
        },
        "deploy_contract_cost": {
          "send_sir": 184765750000,
          "send_not_sir": 184765750000,
          "execution": 184765750000
        },
        "deploy_contract_cost_per_byte": {
          "send_sir": 6812999,
          "send_not_sir": 6812999,
          "execution": 6812999
        },
        "function_call_cost": {
          "send_sir": 2319861500000,
          "send_not_sir": 2319861500000,
          "execution": 2319861500000
        },
        "function_call_cost_per_byte": {
          "send_sir": 2235934,
          "send_not_sir": 2235934,
          "execution": 2235934
        },
        "transfer_cost": {
          "send_sir": 115123062500,
          "send_not_sir": 115123062500,
          "execution": 115123062500
        },
        "stake_cost": {
          "send_sir": 141715687500,
          "send_not_sir": 141715687500,
          "execution": 102217625000
        },
        "add_key_cost": {
          "full_access_cost": {
            "send_sir": 101765125000,
            "send_not_sir": 101765125000,
            "execution": 101765125000
          },
          "function_call_cost": {
            "send_sir": 102217625000,
            "send_not_sir": 102217625000,
            "execution": 102217625000
          },
          "function_call_cost_per_byte": {
            "send_sir": 1925331,
            "send_not_sir": 1925331,
            "execution": 1925331
          }
        },
        "delete_key_cost": {
          "send_sir": 94946625000,
          "send_not_sir": 94946625000,
          "execution": 94946625000
        },
        "delete_account_cost": {
          "send_sir": 147489000000,
          "send_not_sir": 147489000000,
          "execution": 147489000000
        }
      },
      "storage_usage_config": {
        "num_bytes_account": 100,
        "num_extra_bytes_record": 40
      },
      "burnt_gas_reward": [
        3,
        10
      ],
      "pessimistic_gas_price_inflation_ratio": [
        103,
        100
      ]
    },
    "wasm_config": {
      "ext_costs": {
        "base": 264768111,
        "contract_compile_base": 35445963,
        "contract_compile_bytes": 216750,
        "read_memory_base": 2609863200,
        "read_memory_byte": 3801333,
        "write_memory_base": 2803794861,
        "write_memory_byte": 2723772,
        "read_register_base": 2517165186,
        "read_register_byte": 98562,
        "write_register_base": 2865522486,
        "write_register_byte": 3801564,
        "utf8_decoding_base": 3111779061,
        "utf8_decoding_byte": 291580479,
        "utf16_decoding_base": 3543313050,
        "utf16_decoding_byte": 163577493,
        "sha256_base": 4540970250,
        "sha256_byte": 24117351,
        "keccak256_base": 5879491275,
        "keccak256_byte": 21471105,
        "keccak512_base": 5811388236,
        "keccak512_byte": 36649701,
        "ripemd160_base": 853675086,
        "ripemd160_block": 680107584,
        "ecrecover_base": 278821988457,
        "log_base": 3543313050,
        "log_byte": 13198791,
        "storage_write_base": 64196736000,
        "storage_write_key_byte": 70482867,
        "storage_write_value_byte": 31018539,
        "storage_write_evicted_byte": 32117307,
        "storage_read_base": 56356845750,
        "storage_read_key_byte": 30952533,
        "storage_read_value_byte": 5611005,
        "storage_remove_base": 53473030500,
        "storage_remove_key_byte": 38220384,
        "storage_remove_ret_value_byte": 11531556,
        "storage_has_key_base": 54039896625,
        "storage_has_key_byte": 30790845,
        "storage_iter_create_prefix_base": 0,
        "storage_iter_create_prefix_byte": 0,
        "storage_iter_create_range_base": 0,
        "storage_iter_create_from_byte": 0,
        "storage_iter_create_to_byte": 0,
        "storage_iter_next_base": 0,
        "storage_iter_next_key_byte": 0,
        "storage_iter_next_value_byte": 0,
        "touching_trie_node": 16101955926,
        "promise_and_base": 1465013400,
        "promise_and_per_promise": 5452176,
        "promise_return": 560152386,
        "validator_stake_base": 911834726400,
        "validator_total_stake_base": 911834726400
      },
      "grow_mem_cost": 1,
      "regular_op_cost": 822756,
      "limit_config": {
        "max_gas_burnt": 200000000000000,
        "max_stack_height": 16384,
        "stack_limiter_version": 1,
        "initial_memory_pages": 1024,
        "max_memory_pages": 2048,
        "registers_memory_limit": 1073741824,
        "max_register_size": 104857600,
        "max_number_registers": 100,
        "max_number_logs": 100,
        "max_total_log_length": 16384,
        "max_total_prepaid_gas": 300000000000000,
        "max_actions_per_receipt": 100,
        "max_number_bytes_method_names": 2000,
        "max_length_method_name": 256,
        "max_arguments_length": 4194304,
        "max_length_returned_data": 4194304,
        "max_contract_size": 4194304,
        "max_transaction_size": 4194304,
        "max_length_storage_key": 4194304,
        "max_length_storage_value": 4194304,
        "max_promises_per_function_call_action": 1024,
        "max_number_input_data_dependencies": 128,
        "max_functions_number_per_contract": 10000
      }
    },
    "account_creation_config": {
      "min_allowed_top_level_account_length": 32,
      "registrar_account_id": "registrar"
    }
  },
  "transaction_validity_period": 86400,
  "protocol_reward_rate": [
    1,
    10
  ],
  "max_inflation_rate": [
    1,
    20
  ],
  "num_blocks_per_year": 31536000,
  "protocol_treasury_account": "near",
  "fishermen_threshold": "340282366920938463463374607431768211455",
  "minimum_stake_divisor": 10
}

looks like storage_amount_per_byte is right there under runtime_config as expected.
conclusion
not sure what's going on with your code but this seems to work just fine for me

A: I found the solution. The problem is the documentation is some documents refers to different versions of the API, the first documentation that I consult uses API 36 with which I show the error, in another example as I paste on the screen they use version 41:

I had to look for the last ncd on my own and use version 44. LINK
The recommendation is always be careful with the versions some documentation needs an update.
Be careful when you find specific errors with values of the variables that are not parameters that are requested since it is very likely that the documentation you use is not updated, thanks Sherif for the support and John too.
NCD


text:
Q: What am i doing wrong? And what should i be doing differently? (Auto complete winforms textbox) c# winform
I have read multiple articles/suggestions on how to do this, and below is one of the few I have tried, but it's not working.  In fact, when user types into the textbox, nothing happens.
private void OperationListForm_Load(object sender, EventArgs e)
    {
        AutoCompleteStringCollection textBoxCollection = new AutoCompleteStringCollection();

        foreach (var item in _oiList)  //_oiList is a list of objects
        {
            textBoxCollection.Add(item.ToString());
        }

        textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
        textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
        textBox1.AutoCompleteCustomSource = textBoxCollection;
    }

I'm new so, If I need to provide more info, please let me know.

A: A few things you need to double check:

*

*Make sure that textBoxCollection has valid items in it

*Make sure that your 'OperationListForm_Load' method is being called by setting a breakpoint and running your application

*Make sure your textBox1 is added to the form properly

I tested your code and it works for me. This is what I did to check:

*

*Created a new Windows Form project

*Added a Text Box to the form

*Added the following code to the Form1.cs:
public partial class Form1 : Form
{
  public Form1()
  {
    InitializeComponent();
    InitTextBox();
  }

  void InitTextBox()
  {
     AutoCompleteStringCollection textBoxCollection = new AutoCompleteStringCollection();
     textBoxCollection.Add("Bobby");
     textBoxCollection.Add("Billy");
     textBoxCollection.Add("Britney");

     textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
     textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
     textBox1.AutoCompleteCustomSource = textBoxCollection;
  }
}

and here is a screenshot of this working:

A: First you must create array and add it to AutoCompleteStringCollection, next set it as data source. You can do it like my sample, its working. Your problem is with your datasource which you try add. It's list of object you cant do that.
AutoCompleteStringCollection stringCollection = new AutoCompleteStringCollection();
String[] yourArray = new[] {"Cat", "Car", "Dog", "Dinner", "War", "White"};
stringCollection.AddRange(yourArray);
textBox1.AutoCompleteCustomSource = stringCollection;
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;


text:
Q: how to select particular element from following matrix?(in matlab) data = rand(N,2);             %# generate random points
index = (rand(N,1) <= p);     %# roll coins to pick with prob p
data(~index, :) = [];         %# keep only selected points
plot(x(index),y(index),'r*');

dist=sqrt((data(1,1)-data(~index,1))^2+(data(1,2)-data(~index,2))^2); % ques is what to put for data(~index,:) 's first or any element?

If we have to find distance between any point of data=rand(N,2) (say first) from any point of data(~index, :) = []; (say first of this also), how can we use data(~index, :) = []; matrix in following statement?
dist=sqrt((data(1,1)-data(~index,1))^2+(data(1,2)-data(~index,2))^2)

My question is as we are taking first element of data as data(1,1) and data (1,2), how do we take take first element of data(~index,:) matrix?

A: I'm not quite sure what you want to do.
The command data(~index, :) = [] removes all rows for which the random number is larger than p, so after that command data will no longer be an N-by-2 matrix but it will be a smaller matrix. I'll assume you won't give that command, because afterwards you can no longer refer to the points in data that were removed.
If you want to take the distance between the first point in data and the first point in data selected by the random coin throw, one possibility is to use the find function (look it up to see what it does):
indexList = find(index);
firstIndex = indexList(1);
dist = sqrt((data(1,1)-data(firstIndex,1))^2 + (data(1,2)-data(firstIndex,2))^2);

The last line can also be written as:
dist = norm(data(1,:) - data(firstIndex,:));

If you want something else, please explain.

A: Assuming that you by 'first element of data(~index,:)' you mean the first element for which ~index is true then the following would also work
firstValue = data(find(~index,1,'first'),:)


text:
Q: Mac OS X: pushing all traffic through a VMWare VM I want to set up an Astaro (Sophos) UTM in a Virtual Machine.
The Setup should be at the end the following:
Cable Modem (one IP adress)
  | [Ethernet]
Sophos UTM (running as VM [VMWare Fusion 5] on the MacMini)
  | [WIFI]
Airport Express v2 (for sharing Local Network to wireless and wired clients)
1)| [WIFI]   2)| [Ethernet over Thunderbolt Ethernet Adapter]*
Clients     MacMini (Local File Server)

*To have the Mini also protected behind the UTM

So the setup process for the UTM works fine, but then the problems start:

*

*I just have one external IP (from my cable modem provider)==> So if I put the VM in briged mode my Internet connection drops, because the MacMini also has its IP adress.

*If I put the VM to NAT mode the Mini itself is not protected by the UTM

So: is there a way to hide the en0 interface(Ethernet) and the en1 interface (Wifi) from the MacMini, so that they not even appear in System Preferences Network section but are available to the VM?
That way the Mini must connect to the en2 interface (Thunderbolt adapter) to make any Internet/LAN connection and I just use the given single IP from the Cable Modem.
Thaks for any suggestions...
Sebastian