text:
Q: Get count from join table - EFCodeFirst So I've recently began checking on ASP.NET MVC3 and EFCodeFirst and have gotten stuck.
I have 2 Models:
Person:
    [Bind(Exclude = "PersonID")]
    public class Person {

        public int PersonID { get; set; }

        [Required(ErrorMessage="Given name is a required field")]
        [DisplayName("Given name")]
        public string GivenName { get; set; }

        [Required(ErrorMessage="Family name is a required field")]
        [DisplayName("family name")]
        public string FamilyName { get; set; }

        [Required(ErrorMessage = "Birthdate is a required field")]
        [DisplayFormat(DataFormatString = "{0:d}")]
        public DateTime Birthdate { get; set; }

        [DisplayName("Ingredient")]
        public virtual Ingredient Ingredient { get; set; }
}

and Ingredient:
public class Ingredient {
    public int IngredientID { get; set; }

    [Required(ErrorMessage = "Ingredient is a required field")]
    public string Name { get; set; }

    public virtual ICollection<Person> Persons { get; set; }
}

Now the point is that Ingredient is a semi-fixed table (only business users can add ingredients, but that's a different story) and a person can input his/her data and his/her favorite ingredient.
This all works fine but I wanted to create a top 10 of ingredients by joining the 2 tables, and then performing a group by, order by, count and limit (to 10 for example).
The issue here is that I've tried several things and just can't get it to work. I'm quite new to LINQ and can't get my head on how to do this.
Any suggestions would be greatly appreciated!
Edit:
To specify once more, I just need the equivalent of the following query in LINQ:
SELECT i.name, COUNT(p.Ingredient_IngredientID) AS Total
FROM People p, Ingredients i
WHERE p.Ingredient_IngredientID = i.IngredientID
GROUP BY i.name
ORDER BY total DESC;

A: You should mark the public Ingredient IngredientID { get; set; } as virtual, this way the ingredient table is loaded lazily. Also you should just call it Ingredient since it's not just the ID, it's an actual Ingredient that is referenced.
If i understand you correctly you want to figure out which ingredient is the most popular? If so just group the persons by Ingredient.IngredientID and count the amount of persons in each grouping.
Another way of doing is to add a
public virtual ICollection<Person> Persons { get; set;} field to the Ingredient class, now you can just do
var tenMostPopularIngredients = (from i in Ingredients
                            orderby i.Persons.Count() descending
                            select i).Take(10);

This gives you a dictionary with each ingredient name as key and the count as value, ordered in descending order by count. If you get a ArgumentException it's because you have multiple ingredients with the same name:
var tenMostPopularIngredients = (from i in ingredients
                                let count = i.Persons.Count()
                                orderby count descending
                                select new
                                {
                                   Ingredient = i,
                                   Count = count
                                 }
                                 ).Take(10).ToDictionary(t => t.Ingredient.Name,t => t.Count);

A: Combination of OrderBy and Take is not enough?


text:
Q: Enqueue JS + CSS via a child theme functions.php file? The below works great in loading a Javascript File into my theme (via a child theme)...
function my_scripts_method() {
        if ( is_page_template('templates/page-alert-amber.php')):
        wp_enqueue_script(
            'bootstrap js',
            get_stylesheet_directory_uri() . '/bootstrap/js/hellojs.js',
            array( 'jquery' )
        );
        endif;
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

My question is - how do I also include a style sheet? I thought the below would work but it doesn't...
function my_scripts_method() {
        if ( is_page_template('templates/page-alert-amber.php')):
        wp_enqueue_script(
            'bootstrap js',
            get_stylesheet_directory_uri() . '/bootstrap/js/hellojs.js',
            array('jquery')
        );
            wp_enqueue_style(
            'bootstrap css',
            get_stylesheet_directory_uri() . '/bootstrap/css/hello.css',
            array()
        endif;
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

thanks

A: Your issue is the dependency:
array( '' )

That's setting your stylesheet to have a dependency on a stylesheet whose name is an empty string. If you want to say that there's no dependency you need to use an empty array:
array()

Also, your second bit of code is missing an endif, which will cause a fatal error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I change Firefox bookmark toolbar icons? My Firefox bookmark toolbar items change icons every now and then for apparently no reason, especially if a site is down. I get the DNS site's icons all over, on another case I have the Facebook icon on a TOTALLY irrelevant bookmark, so the question is: How can I change the icons on my bookmarks in the bookmark toolbar?

A: Favicon Picker 2 adds a UI for replacing bookmark icons. The extension is based on the the version posted in MozillaZine. It also features an increased icon size limit.

A: The following article describes how to do it manually/without extra extension and using a css file in the firefox profile folder (did not test it yet)
http://www.tersetechtips.com/how-to-change-firefox-bookmark-icons-favicons-without-extensions-or-addons/

*

*Open up Firefox's behind-the-scenes "profile" folder on your computer. On Windows 7/8, this is located at:

C:\Users\Your_Username\AppData\Roaming\Mozilla\Firefox\Profiles\Your_Profile_Folder

*In that folder, create a new directory called "chrome", if it doesn't already exist.

*Inside the "chrome" folder, create a new file called "userChrome.css".

*Open up userChrome.css and paste the following CSS code:

/* First line of userChrome.css must be this: */
@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");

/* Custom favicon for this bookmark */
.bookmark-item[label="BOOKMARK_NAME_HERE"] image {
    width:0!important;
    height:0!important;
    padding: 0 0 16px 16px !important;
    background:url(BASE_64_STRING_HERE)!important;
}

A: Bookmark Favicon Changer

Right click at your bookmark (Bookmark menu, Bookmark toolbar, Bookmark sidebar, Bookmark manager); the popup menu with option "Change Favicon", "Reset Favicon", "Remove Favicon" and "Export Favicon" will appear.
File types support are ico, bmp, dib, gif, jpg, jpe, jpeg, jif, jfi, jfif, png, apng, svg (every file types that Firefox or SeaMonkey support including URL).

*

*To get Bookmark Favicon Changer to work in Firefox 40 go to this link

*Instead of clicking on Free Install select the Mirror for Download link and
Download to a folder of your choice

*In the main Menu of Firefox select File

*Select Open File from the drop down menu

*Navigate to the place where you downloaded Bookmark Favicon Changer and
open it

You will now find that it is in your add-on extension list

A: Point your bookmark at a local HTML document that immediately redirects to the desired destination.  Link to a local favicon in the same directory.
You may need to restart your browser before the favicon will show up on the bookmark.
file:///[path]/example.html
<html>
<head>
    <meta http-equiv="refresh" content="0; url=http://www.example.com" />
    <link rel="shortcut icon" href="example.ico" type="image/x-icon" />
</head>
<body></body>
</html>

file:///[path]/example.ico

This solution suits my personal needs in Firefox 47.0.  Note that the solution doesn't work so well where:

*

*You need to create such bookmarks frequently.

*You have disabled redirection as a security precaution.

*The bookmark must point directly at the destination.

A: Someone perhaps nixda above writes

To get Bookmark Favicon Changer to work in Firefox 40 go to this link
  But seeing as how it is off site (off the firefox official list of add-ons) I felt to afraid to install it before realising the I already had it installed. Alas it no longer works in firefox 50.

However, this below
https://addons.mozilla.org/en-US/firefox/addon/bookmarks-favicon-images/?src=search
is on the Firefox official list of add ons, and, while a little less convenient perhaps than the former, it works on firefox 50.

A: Answer for those with some SQL skills:

*

*Stop Firefox (but first copy paste this as text to your editor)

*Grab your favorite SQLite editor

*Load the favicons.sqlite DB that you will find in your firefox profile.

*For each of the problem sites execute:
delete from moz_pages_w_icons where page_url like '%superuser.com%'

*Save the DB

Restart firefox, the icons for the bookmarks will be the default icon (still better than the wrong one), and be restored to the correct icon as soon as you open the bookmark.
Firefox seems to clean off the orphan entries in the join table.


text:
Q: Convert html string to xml and populate datagrid using xml file Using htmlagilitypack i'm extracting the html content from a web page and storing it in a string. I have even removed all the tags in the output. Now i want to populate the data grid with the values inside the output string. I thought of converting this string which has html content to xml and use it as source for datagrid. When i convert html string to xml the output is looking like below code,

 CRM

        some text

          education details

          Id details
      Salary
      Experience
      Location
      Name
                    Mobile:
                    Region

        Similar Resumes    New  crm

        crm

          education details

          Id details

      Experience

      Name

                    Telephone: Region

        Similar Resumes      CRM

Here there are no tags in xml file, hence don't know how make these values display in datagrid.

A: See question What does <![CDATA[]]> in XML mean? to read more and
Remember: &nbsp; need converted to space. Text input in CDATA is your text for output in grid.
Example
<description>
<![CDATA[
    some text

      education details

      Id details
  Salary
  Experience
  Location
  Name
                Mobile:
                Region
    Similar Resumes    New crm

   ...
]]>
</description>


text:
Q: Sanitize array before echo PHP What do you consinder the best way to sanitize array below? I was thinking adding htmlentites before each $row or perhaps using the method below.
<?php
$result = $conn->query("SELECT formula.id, tokens, direction, graph, module FROM formula INNER JOIN syntics ON formula.moduleid = syntics.id");

while ($row = $result->fetch_array())
filter_var_array($row, FILTER_SANITIZE_SPECIAL_CHARS); // OK?

echo                    "".
     $row['tokens']    ."".
     $row['direction']  ."".
     $row['graph']     ."".
     $row['module ']   ."".
     "Specific type" . "
";
?>

A: I feel that you could benefit from some general information on the subject of sanitization and escaping.

*

*To understand how to write secure PHP code, you need to prevent
against XSS.

*To prevent against XSS, you need to
implement proper output escaping and may need to implement data sanitization.

*To implement data sanitization and output escaping you need to understand why it's a problem and how to do it properly.

Sanitization
Sanitization should be done before saving the data to the database.  It makes sure that things which shouldn't be saved to the database are not.  It is also good to do it again after you read data out of your database incase you miss something and your database now contains something harmful.  Generally if you are just storing text, you might want to allow any text to be saved and in this scenario sanitization is not really necessary.  But it sounds like you are storing html...
If you are storing html you probably plan to output it to browsers at some point and you don't want it to contain harmful scripts for your users to execute.  Sanitizing html to remove harmful javascript is actually very very difficult due to the many ways you can insert javascript.  Whole PHP libraries (e.g. wp_kses_*) have been written dedicated to this and it's not enough to just remove all < script> tags as some SO answers suggest.  Plus you will need to keep your html sanitization code up to date to prevent against the newest attacks.  All in all, it's a very high risk/maintenance solution.  If you want to go this route, there are some solutions here.
Usually you will want to give your users the ability to format their text with a subset of what html offers (e.g. bold, italics, underline and maybe some colours) and a better approach is to use a more lightweight language such as Markdown or BBCode
Also you should consider saving your fields as text only and handle the styling completely in your application.
Output Escaping
This is the step right before outputting the data.  When you are piecing together HTML for output in PHP, you need to convert anything which isn't html yet in to safe html.  If you use a templating language this is handled for you automatically.  In my opinion it is the most misunderstood concept of PHP developers today, and unfortunately it is one of the most important.  I won't go in to it here but I highly recommend this further reading.
Important Update
This code is NOT data sanitization, it is output escaping.
filter_var_array($row, FILTER_SANITIZE_SPECIAL_CHARS);

I can see now that confusingly, the word "Filter" has such a generic meaning in this answer and can arguably refer to both sanitization and escaping.  I have removed it from my answer to help clear up any confusion.
Your example - Sanitization
I wont go as far to say never store html in a database field, but it is a lot harder this way.  You need to decide what is expected and valid.  If you update your question with more details on the specific data, it will become clear what these restrictions should be.
Your example - Output escaping
If your variables already contain well formed HTML fragment strings then you can safely append your variables using the "." (string concatenation operator) inside an open and close tag.  What you have put in your question code is correct.  However, I prefer to use direct output with short tags as it makes the code more readable and there is no real need to put everything in to a PHP string anyway.
<?= $row['tokens'] ?>
<?= $row['direction'] ?>
<?= $row['graph'] ?>
<?= $row['module'] ?>

Note: As explained above, by outputting html you are asking clients to trust, parse and display it.  If these variables do in fact contain invalid or bad HTML, then it is a problem with your sanitization.

*

*Output escaping should/does NOT clean your data.

*Sanitization should/does NOT escape your data.

They are simply two different concepts working together.
Since your id should be an integer from your database you can cast it like this to make sure that it is.
<a href='upong.php?soya=<?= (int)$row['id'] ?>Specific type

If the value is not castable to an integer (because something unexpected happened which you didn't account for) you end up with a 0 in your url which normally isn't that harmful.

A: i believe you must use custom filter for sanitize your array.
please read php document in url

A: If you are worried about an XSS attack then you really ought to be taking care of the problem before the input is inserted into your database by using htmlentities() on it.  Never trust user input.


text:
Q: How can i remove python 2.7 as i already have 3.6.5 installed on ubuntu? i have both 2.7 as well as 3.6.5 installed , at first in ubuntu 18.04 the only python version available was 3.6 but after i installed numpy package, along with it 2.7 got installed as well and it turned into default.
Is there any solution so as to  make 3.6 the default one instead of 2.7??

A: I set python 3 version as default using the following commands:

*

*Check python version on terminal - python --version

*Get root user privileges. On terminal type - sudo su

*If needed write down the root user password.

*Execute this command to switch to python 3.6. update-alternatives --install /usr/bin/python python /usr/bin/python3 1

*Check python version - python --version

*Write exit to exit the root mode

A: Open .bashrc file nano ~/.bashrc. Type alias python=python3 on to a new line at the top of the file then save and close the file with ctrl+o and ctrl+x.


text:
Q: Form_for issue finding the current route to pass into an association I have a form:
<%= form_for(@message) do |f| %>

That's located in my groups#show page. What I want to do is build an association with the current user, message id and current group. I have nailed the first two just fine with the following code in my MessagesController but I know I'm trying to find my @group_id after the params have been changed:
def create
  @message = Message.new(:message => params[:message],
  :source => "web")

  respond_to do |format|
    if @message.save
      current_user.envelopes.create!(:user_id => current_user.id, :group_id => @group_id, :message_id => @message.id)
      format.html { redirect_to(group_path(@group_id), :notice => 'Message was sent.') }
    else
      format.html { render :action => "new" }
    end
  end
end

What I want to know is where should I catch the @group_id so that when they send a message the envelopes association is created and the user is redirected back to the group page they were just one (with the new message there now).
Thanks a lot!

A: If i've understood your problem correctly, you could stick the Group Id into the form as a hidden field:
<%= f.hidden_field :group_id, :value => @group %>


text:
Q: IE tries to download json response when using ajaxForm jQuery plugin I've tried everything and don't know what seems to be the problem.
The problem : IE downloads the json response + before submitting does not fire.
I'm using IE 11.
I'm using the jQuery - ajaxForm plugin.
Implemented file upload with it.
Everything works perfect with chrome and everything does not with IE.
IE tries to download the json response and doesn't do the plugin before function.
The JS code:
var options = {
    beforeSend: beforeSubmit,
    uploadProgress: progressSubmit,
    success: uploadSuccess,
    complete: completeSubmmit
};

form.ajaxForm(options);

The actual request performed in manual click.
('#submitBtn').click();

I'm using MVC-3 controller, the HttpPost action receives HttpPostedFile.
The response is a simple ViewModel contains several strings.
I have tried all the following, nothing worked.
Attempts :
Response.Headers.Remove("Content-Type");
Response.Headers.Add("content-type", "application/json");

return Json(vm, "text/html");
return Content(JsonSerializerHelper.Serialize(vm), "text/html");
return Json(vm);

Fiddler :
Chrome Request:
Content-Length: 606
Pragma: no-cache
Cache-Control: no-cache
Accept: */*
Content-Type: multipart/form-data; boundary=----    WebKitFormBoundary4ABojutLkBGFbphB
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,he;q=0.6,pt;q=0.4,ru;q=0.
Content-Disposition: form-data; name="file"; filename="customersBulk.csv"
Content-Type: application/vnd.ms-excel

Chrome Response :
HTTP/1.1 200 OK
Cache-Control: private, s-maxage=0
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
X-Frame-Options: SAMEORIGIN
Date: Thu, 29 Jan 2015 18:19:47 GMT
Content-Length: 469

-- and the actual Json object. --

IE Request:
Accept: text/html, application/xhtml+xml, */*
Accept-Language: he-IL
Content-Type: multipart/form-data; boundary=---------------------------7df28b2e1c126c
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Content-Length: 691
DNT: 1
Host: localhost
Pragma: no-cache
Content-Disposition: form-data; name="file";     filename="MY_PATH\..\customersBulk.csv"
Content-Type: application/vnd.ms-excel
-----------------------------7df28b2e1c126c--

IE Response:
HTTP/1.1 200 OK
Cache-Control: private, s-maxage=0
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
X-Frame-Options: SAMEORIGIN
Date: Thu, 29 Jan 2015 18:15:50 GMT
Content-Length: 558

-- and the Json as well. --

Versions:
jQuery Form Plugin
version: 3.50.0-2014.02.05
Requires jQuery v1.5 or later
Any Ideas?

A: Can you please try following thing:
$('#YourFormId').bind('submit', function() { return false; });

This will prevent the original form submission process.


text:
Q: Is it okay or safe to delete debug_kit.sqlite file I found out the debug_kit.sqlite file size is now 24MB?
Is their no effect or no conflict in my website, If I delete this file,?

A: You can delete it. If you set your debug to false than files will not be generated anymore


text:
Q: Is there a way to monitor Newly created Index Component Sync Sp2013 search I am in a process of fixing degraded Index Component in my search topology. I was able to remove and new index component. After i added index component now its stuck at status degraded, i know it takes some time before it comes online, but do we have any too to track the sync progress of that newly created index component.
Thank you

A: You should see it with:
Get-SPEnterpriseSearchStatus -SearchApplication $ssa -Text

Maybe narrow it down to the index component:
Get-SPEnterpriseSearchServiceApplication | Get-SPEnterpriseSearchStatus -HealthReport -Component IndexComponent1 -Text


text:
Q: conjugacy classes in anisotropic semisimple groups You have an anistropic semisimple algebraic group $G$ defined over a non-archimedean local field $k$. When can you say that the $k$-rational part of the conjugacy class of a $k$-rational point is compact?

A: The answer is always. If $G$ is an anisotropic group over a non-archimedean local field $k$, then $G(k)$ is compact. The elements of $G(k)$ are semi-simple (if $char k =0$) and hence their conjugacy classes are closed in the Zariski topology and therefore also in the $k$-topology.
[Edit] To round it off, the question may easily be reduced to the case when $G$ is semi-simple and simply connected; hence $G$ is a product of simply connected $k$-simple groups $G_i$, and by a restriction of scalars argument, $G$ may be assumed to be absolutely almost simple simply connected. In this case, the classification (see Tits' article in the AMS symposia series on algebraic groups, discrete subgroups...) says that $G$ is $SL_1(D)$ for a central division algebra over $k$ or $SU_1(D)$ where $D$ is a central division algebra with an involution of the second kind. The semi-siple conjugacy classes may now be described explicitly.

A: Since the literature is rather complicated (and scattered) when $k$ fails to be perfect, it's worthwhile to add to what Aakumadula says.  Over a perfect field, say in characteristic 0, the answer to your questions is straightforward based on older work of Borel and Tits.   As I commented, Cor. 9.4 in their foundational paper on reductive groups here shows that (over a local field of characteristic 0) $G_k$ is compact in the ultrametric topology iff $G$ is reductive and $k$-anisotropic.  Moreover, their Cor. 8.5 shows in this anisotropic situation that $G_k$ consists of semisimple elements.    (As in their $\S1$ and the earlier Chevalley seminar, it's true quite generally that in a reductive group the semisimple classes are precisely the closed ones.)
There are many more relevant papers by Tits, sometimes in collaboration with Borel or Bruhat, in which he explores the structure and classification of reductive groups over local fields.   An interesting early paper in a  Brussels conference volume includes some remarks on the terms $k$-isotropic and $k$-anisotropic, which arise in part from the study of quadratic forms and orthogonal groups but tend to contradict existing notions of "isotropic".   In any case, these terms have persisted.  This paper is probably hard to track down (and unfortunately there is no collection of his papers):  Groupes semi-simples isotropes. 1962
Colloq. Th´eorie des Groupes Alg´ebriques (Bruxelles, 1962) pp. 137–147. Librairie Universitaire,
Louvain; Gauthier-Villars, Paris
One result stated here by Tits shows how delicate the cas of imperfect fields is: here a simple algebraic group $G$ defined over $k$ is $k$-anisotropic if and only if $G_k$ contains no "good" unipotent element other than the identity (in a certain sense of "good" explored further in a paper with Borel in Invent. Math. 12 (1971), which can be found online at GDZ.
For a more modern treatment of structure theory of reductive groups over arbitrary (especially local) fields, you should probably look at the monograph Pseudo-reductive Groups
by Conrad-Gabber-Prasad (Cambridge Univ. Press, 2010).


text:
Q: Maintenance plan in AWS MSSQL 2017 RDS We recently migrated from MSSQL 2017 on-prim to AWS MSSQL 2017 RDS, so earlier we were using MSSQL Maintenance  plan wizard to create plans for DBCC checkDB, updatestate, Rebuild critical indexes etc.
But in RDS I dont see this option Maintenance Plan. My question is how we can achieve this in MSSQL 2017 RDS. One option is to write scripts and scheduled them in as a SQL jobs.
Any recommendations on this would be highly appreciated

A: create procedure dbo.sp_updstats
with execute as 'dbo'
as
exec sp_updatestats
go

grant execute on dbo.sp_updstats to [admin]
go

exec dbo.sp_updstats

and using the following scripts I was able to configure all the activities. Download MaintenanceSolution.sql.
Be noted: The stored procedure DatabaseBackup is not supported on Amazon RDS. There is a logic in 1 solution that checks for it.


text:
Q: Using Tooltips with link_to (Ruby on Rails 3.2.3) I have been successful in creating a tooltip for text using code similar to:
text on page

However I would like to do a tooltip for a link defined in a menu using the link_to command.  I have included the statement I would like a tooltip to appear for:

 <%= link_to current_user.first_name+' '+current_user.last_name, edit_user_path(current_user) %>

Here is the JS code in bootstrap.js.coffee:
$(".tooltip").tooltip()
$("a[rel=tooltip]").tooltip()

I am a student still learning a lot about Rails, Twitter Bootstrap, CSS3, HTML5, etc.  I have done many web searches but have not found any examples of this that I understood.  Basically there is nothing that says directly that I can do a tooltip within a link_to statement that worked.
Any help would be appreciated.

A: This way:
link_to 'Text', '/link', title: 'some title', rel: 'tooltip'

update:
It's ruby 1.9 syntax. For 1.8 it would be
link_to 'Text', '/link', :title => 'some title', :rel => 'tooltip'


text:
Q: Loading multiple files into cell array Suppose we have directory containing structured data files (text files containing matrix of numbers only).
Is it possible to load them all, no matter what filename they have, into cell array of matrices?

A: use dir to get all the files in a directory:
fls = dir( fullfile( myFolder, '*.txt' ) );
n = numel(fls);
data = cell(1,n); % preallocate
fot ii=1:n
    data{ii} = dlmread( fullfile( myFolder, fls(ii).name ) ); % read the file using importdata/dlmread/load - whatever works for you
end


text:
Q: Log in to Google Maps with my private (non-administered) account This has been driving me crazy every couple of weeks for months now...
I have two primary google accounts. One is my private account, the other is the corporate administered account. We'll call the first A and the second B.
I am (usually) able to work comfortably with both accounts open in Chrome, e.g. one tab for gmail A, one for gmail B. So far so good. Chrome is synced to A
Then, I'll open a tab for Google Maps. I am not signed in to the app at this point. I click sign in, and am presented with the login screen for B. I click sign in as a different user, and get a very incorrect (from my perspective) response, telling me that "You are trying to access Google Admin of {B}.com but you do not have a valid logged in account for it."
 (Sorry for the bookmark tooltip...)
So, without logging out of account B, I don't seem able to log into Maps with account A.
This experience is a lot like biting into a pebble in a bowl of pasta.

A: Actually this is one of the few reasons I do use Chrome on the desktop!
Chrome supports persona's so simply create a second persona and associate it with the other account. Now you can be logged into both accounts at the same time and still keep them separate. To switch, open a new window and click on the small rectangle in the top-right of the window with your name in it.
It is Microsoft I have this problem with since I have around 5 or 6 different accounts with them for different purposes.
For other browsers, you need to use a new Private Window but then you have to log in each time - Chrome keeps your Google accounts for you. The use of something like LastPass gets round the login issue by putting all of your logins just a couple of clicks away.

A: If you have only a few such accounts, one possible solution is to use different browsers, that way they will each keep their context/cookies related to the right account. E.g. Firefox for work and chrome for private or the contrary.


text:
Q: How to run a Litho animation automatically? What's the proper way to start a Litho animation when an Activity is first displayed.  All of the Litho animation examples are initiated by a user action, but I want to run one automatically.
I tried to extend a Litho animation example RTAnimationComponentSpec to fire the animation for the @OnEvent(VisibleEvent.class) instead of just @OnEvent(ClickEvent.class).  But it didn't fire though.
Existing click event handler:
  @OnEvent(ClickEvent.class)
  static void onClick(ComponentContext c) {
    RTAnimationComponent.updateStateSync(c);
  }

Additional event handler that I added:
  @OnEvent(VisibleEvent.class)
  static void onVisible(ComponentContext c) {
    RTAnimationComponent.updateStateSync(c);
  }

I confirmed the VisibleEvent didn't fire by:

*

*Loading the Render Thread example and confirmed the animation didn't start

*Setting a breakpoint in the onVisible() method

How can I run a Litho animation automatically?

A: One solution I found works is to make use of the @OnCreateInitialState
@OnCreateInitialState
static void createInitialState(
        ComponentContext c,
        StateValue<Boolean> state) {
    state.set(true);
}

This runs the animation, but I'm not sure if it's the preferred way.


text:
Q: Incorrect display of multiple boxplot in one graph I expected to see all boxplots will be overlayed at 25, 85 and 125 on x axis but they were not.  Please run the code to replicate, I can't attach the image.  Thank you so much.
library("ggplot2")
library("plyr")

df<-data.frame(T = c(25, 25, 25, 25, 25, 85, 85, 85, 125, 125, 125), V =c(1.03, 1.06, 1.1,1.08,1.87,1.56,1.75,1.82, 1.85, 1.90), type=c(2,2,2,2,2,2,2))
df1<-data.frame(T = c(25, 25,25,85, 85, 85, 85, 125, 125,125), V =c(1.13, 1.24,1.3,1.17, 1.66,1.76,1.89, 1.90, 1.95,1.97), type=c(5,5,5,5,5,5,5))
df2<-data.frame(T = c(25, 25, 25, 85, 85,85,125, 125,125), V =c(1.03, 1.06, 1.56,1.75,1.68,1.71,1.82, 1.85,1.88), type=c(7,7,7,7,7,7))

main <- rbind(df,df1,df2)
main$type <- as.factor(main$type)

main <- transform(main, type = revalue(type,c("2"="type2", "5"="type5", "7" = "type7")))

main$T <- as.factor(main$T)
ggplot(main, aes(T, V))+geom_boxplot(width=0.5/length(unique(main$type)),aes(color=type),size=.3)

A: First of all you need to make some changes to your dfs.
a) Not all variables have the same length.
b) Do not name a variable as T, it might confuse R with Boolean TRUE.
So maybe what you want is the following?
df<-data.frame(U = c(25, 25, 25, 25, 25, 85, 85, 85, 125, 125),
               V =c(1.03, 1.06, 1.1,1.08,1.87,1.56,1.75,1.82, 1.85, 1.90), type=c(2,2,2,2,2,2,2,2,2,2))

df1<-data.frame(U = c(25, 25,25,85, 85, 85, 85, 125, 125,125),
                V =c(1.13, 1.24,1.3,1.17, 1.66,1.76,1.89, 1.90, 1.95,1.97), type=c(5,5,5,5,5,5,5,5,5,5))

df2<-data.frame(U = c(25, 25, 25, 85, 85,85,125, 125,125),
                V =c(1.03, 1.06, 1.56,1.75,1.68,1.71,1.82, 1.85,1.88), type=c(7,7,7,7,7,7,7,7,7))

main <- rbind(df,df1,df2)
main$type <- as.factor(main$type)

main <- transform(main, type = revalue(type,c("2"="type2", "5"="type5", "7" = "type7")))

main$U <- as.factor(main$U)

ggplot(main, aes(U, V,color=type))+geom_boxplot(width=0.5/length(unique(main$type)),size=.3,position="identity")


text:
Q: Why the number of CPU's so Large I was installing Android studio and just so that I could delete the process I had my Task manager open and Saw that the CPU number was reaching 40 somethimes.
How is this done, are multiple CPU emulated. My machine has x86 Windows Vista quad core.

Thanks

A: The number you see in that column doesn't actually refer to the number of CPUs in use. If you look at the Microsoft page that explains the column headers (look for the heading titled "CPU Usage"), you can see that the number actually represents:

The percentage of time that a process used the CPU since the last update

This is the reason that the sum of all values in the CPU column never go above 100, as that would imply that the CPU is at more than 100% usage, which doesn't make sense.
In Windows 8, percentages are displayed instead of pure numbers, which clears up some of the inherent confusion.


text:
Q: How can I tell what version of Java I have installed? I want to start toying around with java (eventually getting to the point where I can write basic little programs for android or web), but I've managed to have java messed up on my computer (from past experiments).
I'm not sure which version of java I have, and would like to know if there is a command to see the version of java that is installed and active. Also, which version works best? All this on 32bit Ubuntu 12.04
EDIT:
Ok, so it seems like I have both openjdk 6 and 7, with openjdk 7 in use. I want to use openjdk 7, so how do I uninstall openjdk 6? Is just via USC good enough or is there a command that should be run?

A: This command should tell you what is currently providing the Java virtual machine (java) and the Java compiler (javac):
file /etc/alternatives/java /etc/alternatives/javac

This assumes the "alternatives" system is working properly, which might not be the case, depending on how Java has been "messed up" in the past. To check this, run:
file `which java javac`

If the alternatives system is working correctly and being used by Java, then you should see:
/usr/bin/java:  symbolic link to `/etc/alternatives/java'
/usr/bin/javac: symbolic link to `/etc/alternatives/javac'

Otherwise please edit your question to provide details. Then it should be possible to give a more specific answer.

You can remove openjdk-6 with the Software Center. There are multiple packages associated with it, so you may need to remove more than one packages. (All the `openjdk-6 packages are listed here.)
Or you can use the command-line:
sudo apt-get remove openjdk-6-\* icedtea-6-\*

However, whichever method you use, you may want to check first to see what depends on these packages--you might have software installed that specifically needs version 6. (Probably not, but possibly.)
You can check for this by simulating the removal operation on the command-line:
apt-get -s remove openjdk-6-\* icedtea-6-\*

This will show you the effects of removing those packages, including what other packages would be removed as well. (You'll notice that since this is a simulation, you don't need sudo.)
If you want to be able to continue using Java content online in your web browser (this is not the same thing as JavaScript), then before you remove any icedtea-6- or openjdk-6- packages (except perhaps openjdk-6-jdk), you should make sure you have icedtea-7- packages installed corresponding to whatever icedtea-6- packages are installed.

A: This what I did that worked for me :
Open your terminal :
control + alt + T
Then type ( or copy and paste from here ) these commands one at a time:
sudo rm /var/lib/dpkg/info/oracle-java7-installer*
sudo apt-get purge oracle-java7-installer*
sudo rm /etc/apt/sources.list.d/*java*
sudo apt-get update
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer

Then to be on the safe side, I would reboot.
To find your java version type
java -version

and you should see output similar to this:
java version "1.7.0_04"
Java(TM) SE Runtime Environment (build 1.7.0_04-b20)
Java HotSpot(TM) 64-Bit Server VM (build 23.0-b21, mixed mode)

Although yours will be in 32 bits.
I highly suggest using Java 7, but the updates will try to install Java 6 too. That is OK. But your default should still come up as 7. Everything I have thrown at it works as long as your video card drivers work.

*

*Are PPA's safe to add to my system and what are some "red flags" to watch out for?

A:
java -version
javac -version

These commands display what version of java (the interpreter that runs Java programs) and javac (the compiler that creates them) you have installed.
See the image above for details.

A: The simplest way is:
update-java-alternatives -l shows you all the Java versions you have installed.
java -version shows you the Java version you are using.
java -showversion shows you the Java version you are using and help.
Normally it would be OpenJDK.


text:
Q: Python Django: Handling URL with Google App Engine - Post then Get I have something like this set up:
class CategoryPage (webapp.RequestHandler):
def get(self):
    ** DO SOMETHING HERE **
def post(self):
    ** DO SOMETHING HERE **
    ** RENDER THE SAME AS get(self)

The question is, after I process the posted data, how would I be able to display the same information as the get(self) function?

A: A redirect, as others suggest, does have some advantage, but it's something of a "heavy" approach.  As an alternative, consider refactoring the rendering part into a separate auxiliary method def _Render(self): and just ending both the get and post methods with a call to self.Render().

A: Call self.redirect(url) to redirect the user back to the same page over GET. That way, they won't accidentally re-submit the form if they hit refresh.

A: create_object(request, form_class=FormClass,
        post_save_redirect=reverse('-get-url-handler-',
                                   kwargs=dict(key='%(key)s')))

I use the above django shortcut from generic views where you can specify post save redirect , get in your case .
There are few more examples in this snippet .
Btw, I assumed that you are using django ( helper or patch) with app engine , based on the title of the question.
If you are using app engine patch , check out the views.py in "myapp" app sample add_person handler does what you are looking for.

A: That's generally not a good idea as it'll cause confusion.  You should really do whatever it is you want to do and then redirect them to the get method.

A: Actually, your code isn't Django, but webapp (Google's mini-"framework"). Please read the Django documentation: http://docs.djangoproject.com/
Django's generic views are only available with app-engine-patch. The helper doesn't support them. You could take a look at the app-engine-patch sample project to learn more about Django on App Engine: http://code.google.com/p/app-engine-patch/


text:
Q: I want to use AkkaSpec in (Akka 2.3.14) I want to use AkkaSpec in (Akka 2.3.14)
I'm trying to make TCP-file-IO using actor, sbt, intellij.
I wrote the dependency in build.sbt like below code
libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-testkit" % "2.3.14",
)
They can import "akka.testkit" but when I "import akka.testkit.AkkaSpec" in my scala file, it can't.
How to use AkkaSpec in akka??? Please help me. Thx.

A: AkkaSpec is not part of the released artifacts (see here), but you could copy the source.


text:
Q: Excel & PowerShell - PasteSpecial Failure With VLOOKUPs I have a VLOOKUP being inserted into my spreadsheet's F column like this:
$vLookup = "=VLOOKUP($refCol,'$xlsLocsDIR[locs.xlsx]Device'!`$B`$2:`$C$rowsDvcs,2,FALSE)"
$sheetSave.Cells.Item(2,6).Formula = $vLookup

Which is, to be clear, saved properly in Excel like this:

=VLOOKUP(E2,'[locs.xlsx]Device'!$B$2:$C24549,2,FALSE)

(There are ~25k lines in the reference file, but there are over 200k in the file I have the VLOOKUP in.)
Because of the size of the file in which I'm doing the VLOOKUP within, and the customer could be utilizing 32-bit OS or Excel, I have to Copy/Paste no more than around 30000 rows at a time, to fill all 200k rows out, like so:
#32-bit OS/Excel app compatibility
#Excel/32-bit OS/memory errors occur if doing more than 30k cells
#instead, we do 20k, save, 20k, save, etc

for ($i=2; $i -le $rowsTrans; ($i+30000))
{
    #set the stop point, not to exceed total usedrows
    if (($i + 30000) -gt $totalRows)
        {$j = $totalRows}
    else
        {$j = ($i+30000)}

    #copy the data
    $copyCell = (("F" + $i))
    $copyRange = $sheetTrans.Range($copyCell)
    $copyRange.Copy() | Out-Null

    $sheetSave.Activate()
    $pasteRange = $sheetTrans.Range(("F"+$i+":F"+$j)).Select()
    $sheetSave.PasteSpecial(7)
    $fileWorking.Save()
}

I only want to copy the VLOOKUP formula from Cell F2, into the next 20k rows of column F, then save the file, and iterate through again until I've populated the entire file.
When I do the above, and I've tried different methods aside from this example, I always receive a MethodInvocation Error, unless I explicitly make the file/sheet visible, like so, before the above loop:
$xlsObject.Visible = $true

What am I misunderstanding about the Copy() / PasteSpecial() function calls?  Why does the sheet have to be visible?
NOTE: I've tried to anonymize the above code and limit what is necessary to understand the issue.  The code functions, I just don't want to require the Excel instance to be brought into view at any point.  I'd prefer the script run invisible to the end-user.
The MethodInvocation error I receive is typically as follows:

Exception calling "PasteSpecial" with "1" argument(s): "PasteSpecial method of
  Worksheet class failed"
  At line:1 char:25
  + $sheetTrans.PasteSpecial <<<< (9)
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : ComMethodTargetInvocation

A: I was able to solve this by doing a few direct references, and changing the way I assigned the range, and then calling PasteSpecial, like so:
$pasteRange = $sheetTrans.Range(("F"+$i+":F"+$j))
$pasteRange.PasteSpecial($xlPasteValues) | Out-Null

With declarations like this:
Add-Type -ASSEMBLY "Microsoft.Office.Interop.Excel" | out-null
$global:xlPasteFormulas = -4123
$global:xlPasteValues = -4163


text:
Q: Which one is correct $\Delta U = nC_v \Delta T$ or $q = nC_v \Delta T$? In many books, I've found that MOLAR HEAT CAPACITY $(C)$ is defined as the amount of heat required to change the temperature of 1 mole of a substance by 1K, which mathematically translates to   $C=\frac{q}{n\Delta T}$ and at constant volume, it becomes $C_v=\frac{q}{n\Delta T}$.
But in some examples, I've also seen $C_v=\frac{\Delta U}{n\Delta T}$. Even in many questions, I found answers where the relation, $\Delta U=nC_v\Delta T$ was used even though the volume wasn't constant.
So which one is correct? does that mean heat $q=C$ at all times?

A: The precise definition of Cv involves the partial derivative of U with respect to temperature at constant volume:  $$C_v=\frac{1}{n}\left(\frac{\partial U}{\partial T}\right)_V$$For an ideal gas, U and $C_v$ are functions only of temperature, so it doesn't matter if the volume changes.  But, for other equations of state, this is not necessarily the case.

A: BOTH.
In an isochoric process, the gas does not do any work - since $W=P\Delta V$ and the volume, being constant renders the work done zero.
So,the first law of thermodynamics becomes,
$$Q=\Delta U+W$$
Since $W=0$,
$$Q=\Delta U$$
So, both the formulae are correct.
EDIT
The relation $Cv=\frac{\Delta U}{n\Delta T}$  is always applicable. The relation between internal energy and temperature, as you have read from the answer, can be derived from kinetic theory (using the equipartition theorem).
$$U=\frac f2 nrt$$
Differentiating this, you will get the expression you seek. So, the term $C_v$ is in the equation only because it fits the necessary condition (it is a lot more easier to measure than the degrees of freedom).
So, in short, the $C_v$ has to be measured under constant volume, because, under constant volume, $C_v=\frac f2 R$$. But, once you have found that out, you can expect it to valid everywhere.
For an even more intuitive example, I'll give you an example.
Consider, a a system (gas) at a temperature $T_1$. Now, you give it some energy (say, under constant volume)and take its temperature to $T_2$. Let the change in internal energy be $\Delta U$. Let this be case one.
In the next case, you supply more energy, but still, bring the temperature down by the same amount (i.e. to $T_2$). Now, since the internal energy must depict the temperature (to some extent) of the gas, the change in internal energy must remain the same. So, the $\Delta U$ you defined in the first case should be valid here too, hence generalising the expression


text:
Q: Java filter numbers from num pad in JTextArea Key code for number 1 is in Java 49 and key code for number 1 from the num pad is 97.
I have a JTextArea and I need to prevent inserting numbers from the numeric pad.
I tried:

*

*using a DocumentFilter but here I don't get the key code

*using a ActionMap, here I can match the key code but I can't prevent it from adding to the JTextArea text

*the last option is to use KeyListener. I guess I could use KeyListener and a external variable and keep in this variable the data I need but I hope there is a better way to do this.
I know no direct way to prevent a key to be inserted using KeyListener.
Later edit: when using ActionMap I can't delete the last character because "actionPerformed" is executed before adding the caracter to the JTextArea. I tried this:
JTextArea jtf1 = new JTextArea();
jtf1.getActionMap().put("handleReplaceable", new AbstractAction() {
    @Override
    public void actionPerformed(java.awt.event.ActionEvent e) {
        System.err.println("Found replaceable original text is "+jtf1.getText());
        jtf1.setText(jtf1.getText().substring(0, jtf1.getText().length()-1));
    }
});

A: You could convert your String in your textArea to an Array of bytes. After that with a for-loop you should know if there is a number in your textArea. Code numbers begin at 48 (for number zero) and ends at 57 (number 9)

A: You can do it by using JTextArea#setEditable(false) method when the numpad key is pressed and then JTextArea#setEditable(true) when the numpad key is released.
An example:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class IgnoreNumpad {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            final JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JTextArea area = new JTextArea();
            area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD1, 0, false), "disable");
            area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD2, 0, false), "disable");
            area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD1, 0, true), "enable");
            area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD2, 0, true), "enable");
            //Add all keys
            area.getActionMap().put("disable", new AbstractAction() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    area.setEditable(false); //When key pressed, set it non-editable
                }
            });
            area.getActionMap().put("enable", new AbstractAction() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    area.setEditable(true); //Key released, make it editable
                }
            });
            frame.add(area);

            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}


text:
Q: gradlew assembleDebug failing when building apk with buildozer I am trying to build a signed apk using buildozer on a virtual machine which is running on windows 10 but I am getting this error:
[INFO]:    Selecting java build tool:
[INFO]:    Detected highest available build tools version to be 28.0.3
[INFO]:        Building with gradle, as gradle executable is present
[DEBUG]:   -> running gradlew assembleDebug
[DEBUG]:    > Configuring > 0/1 projects > root project > Resolving       dependen
[DEBUG]:    FAILURE: Build failed with an exception.
[DEBUG]:
[DEBUG]:    * What went wrong:
[DEBUG]:    A problem occurred configuring root project 'myapp'.
[DEBUG]:    > Could not resolve all files for configuration ':classpath'.
[DEBUG]:       > Could not find common.jar (com.android.tools:common:25.3.1).
[DEBUG]:         Searched in the following locations:
[DEBUG]:             https://jcenter.bintray.com/com/android/tools/common/25.3.1/common-25.3.1.jar
[DEBUG]:
[DEBUG]:    * Try:
[DEBUG]:    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
[DEBUG]:
[DEBUG]:    BUILD FAILED
[DEBUG]:
[DEBUG]:    Total time: 33.436 secs
[DEBUG]:
Exception in thread background thread for pid 10226:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/local/lib/python2.7/dist-packages/sh.py", line 2170, in background_thread
    handle_exit_code(exit_code)
  File "/usr/local/lib/python2.7/dist-packages/sh.py", line 1929, in fn
    return self.command.handle_command_exit_code(exit_code)
  File "/usr/local/lib/python2.7/dist-packages/sh.py", line 672, in handle_command_exit_code
    raise exc
ErrorReturnCode_1:

  RAN: ./gradlew assembleDebug

  STDOUT:

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'myapp'.
> Could not resolve all files for configuration ':classpath'.
   > Could not find common.jar (com.android.tools:common:25.3.1).
     Searched in the following locations:
         https://jcenter.bintray.com/com/android/tools/common/25.3.1/common-25.3.1.jar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 33.436 secs

  STDERR:

[INFO]:    STDOUT:
    > Configuring > 0/1 projects > root project > Resolving dependencies ':c
FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'myapp'.
> Could not resolve all files for configuration ':classpath'.
   > Could not find common.jar (com.android.tools:common:25.3.1).
     Searched in the following locations:
         https://jcenter.bintray.com/com/android/tools/common/25.3.1/common-25.3.1.jar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 33.436 secs

[INFO]:    STDERR:

[INFO]:    COMMAND:
cd /home/kivy/helloworld/.buildozer/android/platform/build/dists/myapp && ./gradlew assembleDebug

[WARNING]: ERROR: ./gradlew failed!
# Command failed: /usr/bin/python2.7 -m pythonforandroid.toolchain apk --debug --bootstrap=sdl2 --dist_name myapp --name 'My Application' --version 0.1 --package org.test.myapp --android_api 19 --minsdk 19 --private /home/kivy/helloworld/.buildozer/android/app --icon /home/kivy/helloworld/./data/icon.png --orientation landscape --copy-libs --local-recipes /home/kivy/helloworld/.buildozer/android/platform/python-for-android-master/pythonforandroid/recipes --arch armeabi-v7a --color=always --storage-dir="/home/kivy/helloworld/.buildozer/android/platform/build"
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2

I checked the address displayed in the error log 1 and common-25.3.1.jar does not seems to exist there.
Here is my main.py:
__version__ = "0.1"
from kivy.app import App
from kivy.uix.scatter import Scatter
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout

class TutorialApp(App):
    def build(self):
        f = FloatLayout()
        s = Scatter()
        l = Label(text="Hello!",
                  font_size=150)

        f.add_widget(s)
        s.add_widget(l)
        return f

    if __name__ == "__main__":
        TutorialApp().run()

and here is my buildozer.spec:
[app]

# (str) Title of your application
title = My Application

# (str) Package name
package.name = myapp

# (str) Package domain (needed for android/ios packaging)
package.domain = org.test

# (str) Source code where the main.py live
source.dir = .

# (list) Source files to include (let empty to include all the files)
source.include_exts = py,png,jpg,kv,atlas

# (list) List of inclusions using pattern matching
#source.include_patterns = assets/*,images/*.png

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin

# (list) List of exclusions using pattern matching
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
version = 0.1

# (str) Application versioning (method 2)
# version.regex = __version__ = ['"](.*)['"]
# version.filename = %(source.dir)s/main.py

# (list) Application requirements
# comma seperated e.g. requirements = sqlite3,kivy
requirements = kivy,python2

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy

# (list) Garden requirements
#garden_requirements =

# (str) Presplash of the application
#presplash.filename = %(source.dir)s/data/presplash.png

# (str) Icon of the application
icon.filename = %(source.dir)s/data/icon.png

# (str) Supported orientation (one of landscape, portrait or all)
orientation = landscape

# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY

#
# OSX Specific
#

#
# author = © Copyright Info

#
# Android specific
#

# (bool) Indicate if the application should be fullscreen or not
fullscreen = 1

# (list) Permissions
#android.permissions = INTERNET

# (int) Android API to use
android.api = 19

# (int) Minimum API required
android.minapi = 19

# (int) Android SDK version to use
#android.sdk = 20

# (str) Android NDK version to use
#android.ndk = 9c

# (bool) Use --private data storage (True) or --dir public storage (False)
#android.private_storage = True

# (str) Android NDK directory (if empty, it will be automatically downloaded.)
#android.ndk_path =

# (str) Android SDK directory (if empty, it will be automatically downloaded.)
#android.sdk_path =

# (str) ANT directory (if empty, it will be automatically downloaded.)
#android.ant_path =

# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
#p4a.source_dir =

p4a.local_recipes = %(source.dir)s/.buildozer/android/platform/python-for-android-master/pythonforandroid/recipes
# (list) python-for-android whitelist
#android.p4a_whitelist =

# (bool) If True, then skip trying to update the Android sdk
# This can be useful to avoid excess Internet downloads or save time
# when an update is due and you just want to test/build your package
# android.skip_update = False

# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.renpy.android.PythonActivity

# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
#android.add_jars = foo.jar,bar.jar,path/to/more/*.jar

# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
#android.add_src =

# (str) python-for-android branch to use, if not master, useful to try
# not yet merged features.
#android.branch = master

# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME

# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png

# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =

# (list) Android additionnal libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so
#android.add_libs_armeabi_v7a = libs/android-v7/*.so
#android.add_libs_x86 = libs/android-x86/*.so
#android.add_libs_mips = libs/android-mips/*.so

# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
#android.wakelock = False

# (list) Android application meta-data to set (key=value format)
#android.meta_data =

# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =

# (str) Android logcat filters to use
#android.logcat_filters = *:S python:D

# (bool) Copy library instead of making a libpymodules.so
#android.copy_libs = 1

#
# iOS specific
#

# (str) Path to a custom kivy-ios folder
#ios.kivy_ios_dir = ../kivy-ios

# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"

# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s

[buildozer]

# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 2

# (int) Display warning if buildozer is run as root (0 = False, 1 = True)
warn_on_root = 1

# (str) Path to build artifact storage, absolute or relative to spec file
# build_dir = ./.buildozer

# (str) Path to build output (i.e. .apk, .ipa) storage
# bin_dir = ./bin

#    -----------------------------------------------------------------------------
#    List as sections
#
#    You can define all the "list" as [section:key].
#    Each line will be considered as a option to the list.
#    Let's take [app] / source.exclude_patterns.
#    Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
#    This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#

#    -----------------------------------------------------------------------------
#    Profiles
#
#    You can extend section / key with a profile
#    For example, you want to deploy a demo version of your application without
#    HD content. You could first change the title to add "(demo)" in the name
#    and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
#    Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug

I need help getting around this issue. Thank you in advance.

A: maybe you need this :
#(list) Gradle dependencies to add

#android.gradle_dependencies =

because your buildozer.spec doesn't exist


text:
Q: About calculating log-likelihood with zeroes I would like to use the maximum log-likelihood method to find which continuous uniform distribution with the parameters $a$ and $b$ fits best to some observed data values $(x_{0}, \dots, x_{n})$.
I guess the best answer is always $[\min(x), \max(x)]$ but I am using this for the purpose of implementing the relevant algorithms.
The log-likelihood is equal to $$\mathcal{L} = \sum_{i=1}^{n} \log f(x_{i} | a, b).$$
Interestingly, there is a problem with observations $x_{i} < a$ and $x_{i} > b$ (where the density is zero) since the logarithm is undefined at zero.
What's the preferred way to correct for this? I first though to calculate $\log(1 + x_{i})$ (since the optimization algorithm does not care about the plus one) but then I started to think whether some other alternative would be better. Is there any best practice regarding this?

A: The problem is that the objective function of your optimization problem is not defined for all $a$ and $b$.  Let's begin by taking a closer look at $f$:
$$
 f(x | a, b) =
  \begin{cases}
      \hfill \frac{1}{b - a} \hfill & \text{ if $a \leq x \leq b$} \\
      \hfill 0 \hfill & \text{otherwise} \\
  \end{cases}
$$
Now let's formulate the optimization problem:
$$
\underset{a,b}{\text{max}} \sum \log f(x_i | a, b) \\
$$
Given the definition of $f$ above, it should be clear that the objective function is only defined when $a \leq x_i \leq b\ \ \forall i$.  You could address this problem by maximizing the likelihood instead of the log-likelihood, like so:
$$
\underset{a,b}{\text{max}} \prod f(x_i | a, b) \\
$$
But now you'll have a discontinuity at $a = \min x_i$ and $b = \max x_i$.  Most optimization routines are going to have issues with this.  So you need to put bounds on your problem.  If you properly bound your problem, you can maximize either the likelihood or the log-likelihood:
$$
\begin{equation*}
\begin{aligned}
& \underset{a, b}{\text{max}}
& & \sum \log f(x_i | a, b) \\
& \text{subject to}
& & a \leq \min x_i, \\
&&& b \geq \max x_i
\end{aligned}
\end{equation*}
$$


text:
Q: Python: 2 level sibling import given the following file structure (example)
library_project\
 |- __init__.py
 |
 |--- utils_a\
 |     |- __init__.py
 |     |- util_functions_a.py
 |
 |--- utils_b\
 |     |- __init__.py
 |     |
 |     |--- utils_b_1\
 |     |     |- __init__.py
 |     |     |- util_function_b1.py
 |     |
 |     |--- utils_b_2\
 |     |     |- __init__.py
 |     |     |- util_function_b2.py

and a second project
other_project\
 |- __init__.py
 |- run.py

in run.py
from library_project.utils_b.util_function_b2 import do_something
do_something()

How can util_function_b2.py use functions from util_functions_a.py?
All examples for relative imports that I found assume that the imported package is a sibling package (e.g. https://docs.python.org/2/tutorial/modules.html#intra-package-references) and not 2 levels up

A: The import statement allows you to use an arbitrary number of . dots to refer to packages further up the tree.

*

*. refers to the same package; utils_b_2.

*.. refers to the same shared parent package, utils_b

*... refers to library_project
From util_function_b2 you can refer to util_functions_a with 3 dots:
from ...utils_a.util_functions_a import somename

A: Given the Directory structure, to import "util_function_b2.py"
from library_project.urils_b.utils_b_2.until_function_b2 import *

How can util_function_b2.py use functions from util_functions_a.py -
You can either add the project to python path.
sys.path.append('/path/to/library_project/')

then,
from  from library_project.utils_a imoprt *

or there is a way to do with relative addressing using "."


text:
Q: Using abraham's twitteroauth: The "followers/ids" next_cursor is always 0 twitteroauth has been fantastic up until now, but I'm having trouble gathering all of the followers of certain users.
For example:
$method = 'followers/ids';
$params = array("screen_name"=>"governoromalley","cursor"=>"-1");
print_r($conn->get($method));

Returns / Prints the object claiming that there is only a 0 for next_cursor:
stdClass Object ( [previous_cursor_str] => 0 [next_cursor] => 0 [ids] =>
Array ( [0] => 353642204 [1] => 98012791 [2] => 72607824 [3] =>...

But, when curling via the http://dev.twitter.com OAuth tool, I get something showing that the next_cursor is there, but I can't seem to get it via the PHP SDK.
{"previous_cursor_str":"0","next_cursor":1380213447767347311,"ids":
[23639237,324619439,282668815,...

How can I solve this conundrum? I'm willing to do any silly hacks as necessary.
Thanks for any help!

A: Ended up figuring it out.
Seems like twitteroauth sdk wants user_ids instead:
//Where GovernorOMalley's user_id = 15824288
$method = 'followers/ids/15824288';
print_r($conn->get($method));

Gives the proper cursor elements.


text:
Q: Creating a Restaurant Menu I have an html menu on a site for a client. I'm trying to transition it to WP so he can edit it. I'm having trouble with the menu. Here's an image to show my current setup.

I assume this can be achieved in WP, but is there a widget or something that would allow the user to upload an image and type into fields (Title: [], Price 1: [], ect.) and save it as an item (item1, item2.) Then have a page that automatically lists every item?
Furthermore, is there an way to get variables for each using Wordpress, so I have more control over the style?

A: I'm not sure if suggesting plugins here is still taboo, but I'm going to go that route for you, because it's going to be the most effective and simple method for you to achieve this.
Install two plugins: Custom Post Type UI, and Advanced Custom Fields
Alternatively, forego CPTUI (it's just nice to have a visual) and create a new custom post type via your theme's functions.php file. (instructions for this should be easy to find on the wordpress codex.)
Make sure your new post type is set as "has archive".
Once you have done that, go to "custom fields" and "add new"
Now add all the fields that will be on the menu. For ease of client use, you can also hide fields that are unnecessary. Where it says "location" make sure it's set to "Show if post type is equal to "
For your image bit, you can have those be the post's "featured image" or you can add an image field through custom fields.
Then onto your theme. Create a new file: archive-menu.php, where "menu" is whatever name you gave your post type.
Then run a normal loop, and now all of those fields that you created, that your client can easily edit, are now variables that you can use inside your loop by calling those custom fields (which are essentially just fancy meta boxes) like so:
<?php the_field( "subtitle" ); ?>

Where 'subtitle' is the name/slug of your field.
Make sure pretty permalinks are enabled, and then going to www.sitename.com/menu (custom post type name/slug) should pull your archive.
So every item is going to be its own "post" inside the "menu" custom post type, and you use an archive template to display those posts, with the ACF plugin to help format and separate info.
I used this approach when building a menu for this restaurant, and it worked nicely.
Hope this helps. Let me know if anything is unclear.


text:
Q: Python-CAN script receiving half of the expected CAN messages I have written a Python script utilizing the Python-CAN library which records received CAN messages at a 1 second rate for 5 minutes, before logging all the messages into a file and exiting. The computer has a CAN module which is connecting to the CAN bus. (The other device on the bus is an engine) I communicate with it using the SocketCAN interface.
The test engine system that this computer is connected to is sending around 114 messages at what I believe is a 250kb baud rate. I am expecting to see 114 messages recorded in the file for each 1 second period, but instead I'm seeing about half that count. (~65 messages)
Could it be possible that the engine's ECU is set to a 500kb baud rate, and that's why I'm not getting the count I am expecting? I would think there would be no communication if the baud rates do not match, but I do not have physical access to the system because I'm sending the script remotely through an OTA update and not running it myself. (The device is headless, but is setup to run the script on startup) I just see the log files that are generated.
Here is the python code:
(A note, I have code parsing the received messages into the contained signals, but I did not include this code here because it happens at the end, and it is not relevant)
class logging:

    def __init__(self):
        #Dictionary to hold received CAN messages
        self.message_Dict = {}

        #List to hold queued dictionaries
        self.message_Queue = []

        #A "filters" object is also created here, but I did not include it
        #I have verified the filters are correct on my test system

    def main(self):

        #Record the current time
        currentTime = datetime.datetime.now()

        #Record the overall start time
        startTime = datetime.datetime.now()

        #Record the iteration start time
        lastIterationStartTime = currentTime

        #Create the CanBus that will be used to send and receive CAN msgs from the MCU
        canbus = can.interfaces.socketcan.SocketcanBus(channel='can0', bitrate=250000)
        #These filters are setup correctly, because all the messages come through
        #on my test system, but I did not include them here
        canbus.set_filters(self.Filters)

        # Creating Listener filters and notifier
        listener = can.Listener()

        #Main loop
        while 1:

            #create a variable to hold received data
            msg2 = canbus.recv()

            #Record the current time
            currentTime = datetime.datetime.now()

            #If a valid message is detected
            if(msg2 != None):
               if(len(msg2.data) > 0):
                   try:
                       #Save the message data into a queue (will be processed later)
                       self.message_Dict[msg2.arbitration_id] = msg2.data

                   except:
                       print("Error in storing CAN message")

            #If 1 second has passed since the last iteration,
            #add the dictionary to a new spot in the queue
            if((currentTime - lastIterationStartTime) >= datetime.timedelta(seconds=1)):

                #Add the dictionary with messages into the queue for later processing
                messageDict_Copy = self.message_Dict.copy()
                self.message_Queue.append(messageDict_Copy)

                print("Number of messages in dictionary: " + str(len(self.message_Dict)) + "
                   Number of reports in queue: " + str(len(self.message_Queue)))

                #Clear the dictionary for new messages for every iteration
                self.message_Dict.clear()

                #Record the reset time
                lastIterationStartTime = datetime.datetime.now()

            #Once 5 minutes of data has been recorded, write to the file
            if((currentTime - startTime) > datetime.timedelta(minutes=5)):

                #Here is where I write the data to a file. This is too long to include

                #Clear the queue
                self.message_Queue = []

                #Clear the dictionary for new messages for every iteration
                self.message_Dict.clear()

#When the script is run, execute the Main method
if __name__ == '__main__':
    mainClass = logging()
    mainClass.main()

I appreciate any ideas or input you have. Thank you

A: In my experience, most of the engine's ECU usually uses 250kb, but the newest ones are using 500kb. I would suggest you too also try the both.
Also, the messages will only come to the bus if they have been sent, it seems silly but for example a truck, if you don't step on the accelerator the messages referring to the accelerator will not appear. So, maybe you need to check if all components are being using as you expect. The lib of can-utils has a 'Can sniffer' that can also help you.
I suggest you to use 'can-utils' to help you in that. It is a powerful tool to can analyses.
Did you try to loop the baudrate? Maybe can also help to find another.


text:
Q: How to improve the textarea element? I'm building a small plug-in that has a text editor to edit HTML and CSS code. My problem is that when trying to edit the HTML and CSS code from the text area element, I found out that it's not convenient.
For example, the tab button jumps you to the next element instead of inserting a tab.
I'm looking for a lightweight script to improve the textarea element. Any ideas?

A: Unless you are trying to build your own because you

*

*need specific, custom functionality or

*want to teach yourself how to do it

you should consider something like
http://www.tinymce.com/

A: I've used this in the past.  Works well for tabs.
http://teddevito.com/demos/textarea.html
Beyond that, TinyMCE is fairly standard for more rich-text situations.


text:
Q: How do I make a pandas datatimeindex into twice daily frequency? I have a pandas df that looks like this:
           Open_fut  Close_fut
Date
2017-05-12   20873.0    20850.0
2017-05-11   20887.0    20869.0
2017-05-10   20891.0    20888.0
2017-05-09   20943.0    20886.0
2017-05-08   21001.0    20943.0

My dates are datetime64[ns] and the other columns float64.
How can I make my time series so that Open_fut comes at 2017-05-12 09:30:00 and Close_fut at 2017-05-12 15:30:00 and so on for each day?
EDIT:
Ideally the new df would look like this:
                    fut
Date
2017-05-12 09:30:00 20873.0
2017-05-12 15:30:00 20850.0
.
.

A: It seems you need MultiIndex.from_arrays with adding times by to_timedelta:
time1 = '09:30:00'
time2 = '15:30:00'

df.index = pd.MultiIndex.from_arrays([df.index + pd.to_timedelta(time1),
                                      df.index + pd.to_timedelta(time2)],
                                      names=['date1','date2'])
print (df)
                                         Open_fut  Close_fut
date1               date2
2017-05-12 09:30:00 2017-05-12 15:30:00   20873.0    20850.0
2017-05-11 09:30:00 2017-05-11 15:30:00   20887.0    20869.0
2017-05-10 09:30:00 2017-05-10 15:30:00   20891.0    20888.0
2017-05-09 09:30:00 2017-05-09 15:30:00   20943.0    20886.0
2017-05-08 09:30:00 2017-05-08 15:30:00   21001.0    20943.0

For your output is solution similar, only is used lreshape for reshaping + set_index + sort_index:
time1 = '09:30:00'
time2 = '15:30:00'

df['date1'] = df.index + pd.to_timedelta(time1)
df['date2'] = df.index + pd.to_timedelta(time2)
df = pd.lreshape(df, {'date':['date1', 'date2'], 'fut':['Open_fut', 'Close_fut']})
df = df.set_index('date').sort_index()
print (df)
                         fut
date
2017-05-08 09:30:00  21001.0
2017-05-08 15:30:00  20943.0
2017-05-09 09:30:00  20943.0
2017-05-09 15:30:00  20886.0
2017-05-10 09:30:00  20891.0
2017-05-10 15:30:00  20888.0
2017-05-11 09:30:00  20887.0
2017-05-11 15:30:00  20869.0
2017-05-12 09:30:00  20873.0
2017-05-12 15:30:00  20850.0

EDIT:
lreshape is now undocumented, but is possible in future will by removed (with pd.wide_to_long too).
Possible solution is merging all 3 functions to one - maybe melt, but now it is not implementated. Maybe in some new version of pandas. Then my answer will be updated.


text:
Q: Realtime Database triggers executed multiple times on a value change? Is there any guarantee that Realtime Database trigger is executed only once after a value changes?
https://firebase.google.com/docs/functions/database-events
My exact scenario is:

*

*A Realtime database trigger in placed on a database node

*The node has value "A"

*Multiple clients in parallel trigger a cloud function that changes on a single value "A" to value "B".

While the value changes only once from A->B, I wouldn't be surprised if the tigger can be executed several times (just like for PubSub). Is there any docs on this?

A: An update to the database that doesn't actually change any values shouldn't trigger any Cloud Functions, nor trigger any client side listeners on that data.  This is something you can pretty easily test for yourself.
If you're really worried about it, you can always compare the change snapshots in your function yourself, and return early before doing any work.


text:
Q: Require dynamic fields on form Quick question.
I have a form that contains both dynamic checkboxes and textboxes which are paired. When I submit the form and print_r out the $_POST info, this is what I get.
    Array
(
    [chkname_156] => chkname_156
    [txtID_156] =>
    [chkname_157] => chkname_157
    [txtID_157] =>
    [doChooseAppSvc] => doChooseAppSvc
)

As you can see above, the checkboxes have been checked, but the txtID(s) are empty. What I'm trying to acomplish is this. If the checkboxes are present, which means they've been checked, but the textboxes are empty, I need to alert the user. Since each is dynamic, the numbers after the underscore change, but the beginning of the name stays the same.
I've gotten, I think, half way to a solution by doing the following. I am using preg_grep to create an array of checkboxes that have been checked. Here is that code.
$pm = preg_grep("/^chkname.*/", $p);

Now, I'm stuck. Any help would be greatly appreciated.

A: I suggest using arrays in your form.
It may make it easier to compare values.
For example:
<input type="checkbox" name="chkname[<?=$id?>]" value="" />
<input type="text" name="txtID[<?=$id?>]" value="" />

Then, for each iteration, you can check:
if (isset($posted['chkname'][$id]) && $posted['txtID'][$id]=='') {
   // alert the user
}

Edit:
Here's an example of a loop to check the inputs:
// loop through all text inputs
foreach ($posted['txtID'] as $id => $txtID_value) {

  // for each text input, validate against checkbox with the same $id
  if (isset($posted['chkname'][$id]) && $txtID_value!='') {

    // output an error message
    echo "
You checked box #$id but didn't fill in text input #$id.
";

  }

}


text:
Q: Sign of a multiple integral involving multiple exponential functions I am working on a research project (math bio), and I found that the sign of an expression depends on a multiple integral $I$ defined below. $I$ involves plenty of nested undefined functions. I conjecture that $I<0$, but do not manage to properly determine the sign of $I$.
Given:

*

*an increasing function $f:\mathbb{R}^+ \rightarrow \mathbb{R}^+$ with $f(0)=0$ and $\lim_{x\rightarrow+\infty} f(x) = +\infty$,

*an increasing function $g:\mathbb{R}^+ \rightarrow \mathbb{R}^+$ with $g(0)=0$ and $\lim_{x\rightarrow+\infty} g(x) = +\infty$,

*an increasing function $h:\mathbb{R}^+ \rightarrow \mathbb{R}^+$ with $h(0)=0$ and $\lim_{x\rightarrow+\infty} h(x) = +\infty$,

The multiple integral $I$ is defined as:
$I=\int_{x=0}^{+\infty} \int_{y=0}^{+\infty}  e^{-f(x)}  e^{-f(y)} \left(e^{-g(x)}-e^{-g(y)} \right) \left( 1-e^{-h(x)} \right) \text{d}x\text{d}y$
Could you help me determining the sign of $I$?
Thank you.


text:
Q: Are SOA based apps/websites fast, how to improve performance and speed Currently I have a Java based website which have integration with DB natively using JDBC. But now I have developed an android app and a iOS app which offering same website functionality in native apps. And both android and iOS app are presently connected with website project to access APIs
What I am thinking now is to create a separate project in Java which would offer only API interface to website, android app and iOS app and in future if anything also comes which requires integration with either same business logic or with DB.
But before proceeding with it, I would like to understand whether this approach is right or not. In my opinion it would hamper speed and performance of website as it needs to access data from a service using JSON data which require conversion of objects to JSON and again parsing them to render views.
Questions:

*

*Is this approach right? To create a SOA like architecture where service project will offer just APIs?

*Will it impact performance and speed

*If yes, how to tackle this issue?

*Are there any other option to explore to make such architecture where several apps access same business logic or data

A: *

*Your idea is correct. By implementing a federated service layer that exposes APIs to all consuming apps you'll achieve separation of concerns, you will decouple UI and data model and will be able to implement core logic changes without breaking any application that uses the common layer. You will also be able to easily add more consuming apps to the scenario.

*Yes, any processing of data in the service layer will naturally impact speed and performance.

*There are many approaches to solving performance issues and it depends on the specific issue and your budget. Some solutions that come to mind are:

*

*Scaling the layer on multiple servers + Load balancing

*Avoiding transformations of data as much as possible (by employing a common data model for example)

*Microservices come to mind as an alternative to a common, centralized service layer. It has its own benefits and complications. You can check out this Martin Fowler article.
Hope this helps!


text:
Q: How to correctly set GSL path on mac I have 'correctly' installed gsl on mac 10.13.2.
In my c++ program, I am calling like usual, for example:
#include <gsl/gsl_math.h>

However while running the code, it can not find the gsl.
fatal error: 'gsl/gsl_math.h' file not found

I was wondering how to correctly link gsl PATH and libraries.
I have tried,

*

*setting PATH and LD_LIBRARY_PATH in .bash_profile

*setting PKG_CONFIG_PATH to .../Gsl2.3/lib/pkgconfig

$which gsl-config returns
/Users/gkdgoutam/Softwares/HEP_Softwares/Install/Gsl2.3/bin/gsl-config

$pkg-config --libs gsl returns
-L/Users/gkdgoutam/Softwares/HEP_Softwares/Install/Gsl2.3/lib -lgsl -lgslcblas -lm

The only solution I can find is to run everytime with gsl linked.
Like:
g++ $(gsl-config --cflags) mycode.cc $(gsl-config --libs) && ./a.out

But I was wondering if the GSL PATH can be set globally so that I can simply run
g++ mycode.cc && ./a.out

A: This is how c++ code is compiled and built:
COMPILATION
A compilation unit will take each cpp file and work its way through included headers to locate forward declaration of implementations of symbol signatures of used functionality in your code. In your case this involves gsl/gsl.h. If the file cannot be found in the search directories, which you can expand by specifying C_INCLUDE_PATH and or CPLUS_INCLUDE_PATH. If you omit #include <gsl/gsl_math.h>, your code will not compile as there are signatures, which cannot be found for GSL functions, which you use.
LINKING
Once you have compiled all cpp/cc files you need to link the binary, which can be executed. The linking process consists of a search through all symbols in your .o/.obj... files and a matching of the same to what it can find in your object files and the libraries, which you have specified using for example -lgsl. If all goes well, every lookup finds an according binary implementation for your machine's hardware model (i.e. 64bit/32bit ..., Arm, Intel, ... etc). If some are not found you will find linkage errors.
What you are asking is, is there a way that C++ does not work as above? No!
If you leave out #include <gsl/gsl.h> or if said file is not found in your search paths, compilation will not work or. If you omit -lgsl, linking will fail. If you find it annoying to write all the above stuff in the command line, write a Makefile to reduce the building process to ideally a simple command: make.
Don't forget, that if you are linking against the shared library version of GSL, you might need specifying LD_LIBARAY_PATH on Linux and DYLD_LIBRARY_PATH on Macs as well.
TLDR: you cannot ask a c++ compiler / linker to work differently as designed.


text:
Q: determine which table element is pressed I made an HTML table and now i am trying to change the background color of the clicked element. The problem is the fact that the table elements don't have the exact same width.
When i press the corner of some elements it interprets it as the wrong one.
It doesn't always interpret it as the wrong one but i'd still like it to work every time

var table = document.getElementById("table");

var wsquare = 25, hsquare = 25;

var w = window.innerWidth;
var h = window.innerHeight;

var m = parseInt(w / wsquare), n = parseInt(h / hsquare);
wsquare = w / m;
hsquare = h / n;

var col = [], pressed = [];
var starty = Math.floor(n / 2), startx = Math.floor(m / 3), endy = starty, endx = 2 * startx;

for(var i = 0; i < n; i++) {
  pressed[i] = [];
  col[i] = [];
  var row = table.insertRow(i);
  for(var j = 0; j < m; j++) {
    var cell1 = row.insertCell(j);
    col[i][j] = '#FFFFFF';
    pressed[i][j] = 0;
  }
}

var col = '#585858';

table.addEventListener('mousedown', e => {
  x = Math.floor(e.clientX / wsquare);
  y = Math.floor(e.clientY / hsquare);

  if(!pressed[y][x]) {
    table.rows[y].cells[x].style.backgroundColor = col;
    pressed[y][x] = 1;
  }
  else {
    table.rows[y].cells[x].style.backgroundColor = '#FFFFFF';
    pressed[y][x] = 0;
  }
});
th, table, td{
  border: 1px solid black;
  border-collapse: collapse;
}

table {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

* {
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

A: Try this. I have added a padding: 1px to the table, th and td.

var table = document.getElementById("table");

var wsquare = 25, hsquare = 25;

var w = window.innerWidth;
var h = window.innerHeight;

var m = parseInt(w / wsquare), n = parseInt(h / hsquare);
wsquare = w / m;
hsquare = h / n;

var col = [], pressed = [];
var starty = Math.floor(n / 2), startx = Math.floor(m / 3), endy = starty, endx = 2 * startx;

for(var i = 0; i < n; i++) {
  pressed[i] = [];
  col[i] = [];
  var row = table.insertRow(i);
  for(var j = 0; j < m; j++) {
    var cell1 = row.insertCell(j);
    col[i][j] = '#FFFFFF';
    pressed[i][j] = 0;
  }
}

var col = '#585858';

table.addEventListener('mousedown', e => {
  x = Math.floor(e.clientX / wsquare);
  y = Math.floor(e.clientY / hsquare);

  if(!pressed[y][x]) {
    table.rows[y].cells[x].style.backgroundColor = col;
    pressed[y][x] = 1;
  }
  else {
    table.rows[y].cells[x].style.backgroundColor = '#FFFFFF';
    pressed[y][x] = 0;
  }
});
th, table, td{
  border: 1px solid black;
  border-collapse: collapse;
  padding: 1px; // Observe this padding
}

table {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

* {
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

A: This i believe is a fix to some extend:
// border-collapse: collapse -> remove
border-collapse: separate;
border-spacing: 0px;

Now the border is a little thicker than before but maybe you already know a good fix for that :)


text:
Q: Pentahoo - configure dynamic database name I want to use a table in penthaoo spoon. The table exists, I double-checked it. My connection to database configuration uses dynamics variables, so it shows an error when configuring table exists step. You can see the error below:
Transformation

Error


text:
Q: WordPress SDL Translation for shortcodes I have some sort of sort of shortcodes like [wp-text text="Lorem Impsum etc" button_text="Read More"][/wp-text].
I want to extract this shortcode from post content field and then send these two attributes: text and button_text for translation to SDL World Server.
After getting response from SDL, I want to replace that shortcode accordingly.
Any Suggestion or Help?

A: Here is a suggestion about your approach:

*

*Parse the shortcode attributes

Having the content you can parse the variable and extract all short code attributes with the provided Wordpress function shortcode_parse_atts

*For each parsed value make a API call to the provided SDL World Server REST API (Or for better performance you can group all the translations and translate them with one complex API call if supported from the API)

*After getting the response replace the original strings with the translated strings.
Here is example pseudo code in PHP:
$shotcode_attributes = shortcode_parse_atts( $post->post_content );

foreach ( $shortcode_attributes as $attribute => $value ) {
  // Make SDL World Server API call refer to the API documentation for the exact way
  $translated_value = $sdlApiClient->translate( $value );

  // Replace the translated value.
  // You can be more precise here ensuring that the value is inside the shortcode
  $post->post_content = str_replace(
    "{$attribute}=\"{$value}\"",
    "{$attribute}=\"{$translated_value}\"",
    $post->post_content
  );
}

You can also research and examine the provided SDL WordPress Connector


text:
Q: Undoing and Redoing NSView Object Move Made by NSPanGestureRecognizer I am working on a sample desktop application to test the UndoManager class, which I don't often get to use.  Anyway, the following is the idea.

*

*I create two NSView sub view objects (red & blue).  They are added to an IBOutlet-connected NSView object (panView).

*I add the pan gesture (NSPanGestureRecognizer) to these two sub view objects.

*The applications calls the undo manager when the user moves either sub view object.

The following is my entire code from top to bottom.
 import Cocoa

 class ViewController: NSViewController {
     // MARK: - Variables
     var myView1 = NSView()
     var myView2 = NSView()
     var uuid1 = String()
     var uuid2 = String()

     // MARK: - IBOutlet
     @IBOutlet weak var panView: NSView!

     // MARK: - Life cycle
     override func viewDidLoad() {
         super.viewDidLoad()

         /* myView */
         uuid1 = UUID().uuidString
         myView1 = NSView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 100, height: 100)))
         myView1.identifier = NSUserInterfaceItemIdentifier(rawValue: uuid1)
         myView1.wantsLayer = true
         if let myLayer1 = myView1.layer {
          myLayer1.backgroundColor = NSColor.red.cgColor
         }
         panView.addSubview(myView1)

         uuid2 = UUID().uuidString
         myView2 = NSView(frame: CGRect(origin: CGPoint(x: 400, y: 200), size: CGSize(width: 100, height: 100)))
         myView2.identifier = NSUserInterfaceItemIdentifier(rawValue: uuid2)
         myView2.wantsLayer = true
         if let myLayer2 = myView2.layer {
          myLayer2.backgroundColor = NSColor.blue.cgColor
         }
         panView.addSubview(myView2)

         /* pangesture */
         let panRecognizer1 = NSPanGestureRecognizer.init(target: self, action: #selector(panPictureView(_:)))
         let panRecognizer2 = NSPanGestureRecognizer.init(target: self, action: #selector(panPictureView(_:)))
         myView1.addGestureRecognizer(panRecognizer1)
         myView2.addGestureRecognizer(panRecognizer2)
     }

     // MARK: - Pan gesture
     @objc func panPictureView(_ sender: NSPanGestureRecognizer) {
         let translation = sender.translation(in: self.view)
         if let movingObject = sender.view {
          let newPosition = CGPoint(x: movingObject.frame.origin.x + translation.x, y: movingObject.frame.origin.y + translation.y)
          movingObject.setFrameOrigin(newPosition)
          sender.setTranslation(CGPoint.zero, in: self.view)
          if sender.state == .began {
              if let rawID = sender.view?.identifier?.rawValue {
                  let dict = ["point": movingObject.frame.origin, "rawID": rawID] as [String : Any]
                  redoMoveObject(dict)
              }
          }
          else if sender.state == .ended {
              if let rawID = sender.view?.identifier?.rawValue {
                  let dict = ["point": movingObject.frame.origin, "rawID": rawID] as [String : Any]
                  undoMoveObject(dict)
              }
          }
         }
     }

     // MARK: - Undoing move
     @objc func undoMoveObject(_ newObject: [String : Any]) {
         undoManager?.registerUndo(withTarget: self, selector: #selector(redoMoveObject(_:)), object: newObject)
         undoManager?.setActionName("Move Object")
         if let point = newObject["point"] as? CGPoint, let rawID = newObject["rawID"] as? String {
          if rawID == uuid1 {
              myView1.frame.origin = point
          }
          else {
              myView2.frame.origin = point
          }
         }
     }

     @objc func redoMoveObject(_ newObject: [String : Any]) {
         undoManager?.registerUndo(withTarget: self, selector: #selector(undoMoveObject(_:)), object: newObject)
         undoManager?.setActionName("Move Object")
         if let point = newObject["point"] as? CGPoint, let rawID = newObject["rawID"] as? String {
          if rawID == uuid1 {
              myView1.frame.origin = point
          }
          else {
              myView2.frame.origin = point
          }
         }
     }
 }

It works.  It doesn't crash.  It's just that I have to press Command + Z twice to undo the move.  And I have to press Command + Shift + Z twice to redo the move.  So I don't know where this pause comes from.  What am I doing wrong, do you know?  Thanks.

A: Undo is registered twice:  at sender.state == .began in redoMoveObject and  at sender.state == .ended in undoMoveObject(dict). undoMoveObject and redoMoveObject do the same thing and register each other, they can be merged into one function that registers itself.
Example:
// MARK: - Pan gesture
@objc func panPictureView(_ sender: NSPanGestureRecognizer) {
    if let movingObject = sender.view {
        if sender.state == .began { // register undo before first move
            if let rawID = movingObject.identifier?.rawValue {
                let dict = ["point": movingObject.frame.origin, "rawID": rawID] as [String : Any]
                undoMoveObject(dict)
            }
        }
        let translation = sender.translation(in: self.view)
        sender.setTranslation(CGPoint.zero, in: self.view)
        let newPosition = CGPoint(x: movingObject.frame.origin.x + translation.x, y: movingObject.frame.origin.y + translation.y)
        movingObject.setFrameOrigin(newPosition)
    }
}

// MARK: - Undoing move
@objc func undoMoveObject(_ newObject: [String : Any]) {
    if let point = newObject["point"] as? CGPoint, let rawID = newObject["rawID"] as? String {
        var movingObject: NSView
        if rawID == uuid1 {
            movingObject = myView1
        }
        else {
            movingObject = myView2
        }
        // register current frame origin for redo/undo
        let dict = ["point": movingObject.frame.origin, "rawID": rawID] as [String : Any]
        undoManager?.registerUndo(withTarget: self, selector: #selector(undoMoveObject(_:)), object: dict)
        undoManager?.setActionName("Move Object")
        // undo/redo
        movingObject.frame.origin = point
    }
}


text:
Q: How can I group data from multiple rows into the same row? I have a query:
select * from dwtrat_edu_tempdb.test1

That returns
tile_to_update elementary_school   high_school   university
2270210        583                 null          null
2270210        321                 10529         null
2270210        null                null          58151

I want to combine the rows and take one value from each column (doesn't matter which, first, last, can be any) So one elementary school, one high school, one university.
It would look like:
tile_to_update elementary_school   high_school   university
2270210        583                 10529         58151

However, when I try to group by:
select * from dwtrat_edu_tempdb.test1
group by tile_to_update

I'm getting only a value for one of the columns and not a combination of all
tile_to_update elementary_school   high_school   university
2270210        null                10529         null

Thanks in advance for help.

A: If you don't care about any specific value then ANY_VALUE/MIN/MAX is an option:
select tile_to_update,
       ANY_VALUE(elementary_school),ANY_VALUE(high_school),ANY_VALUE(university)
from dwtrat_edu_tempdb.test1
group by tile_to_update

A: Please try below query as well and let me know is it working for you or not.
SELECT DISTINCT tile_to_update
  ,COALESCE(elementary_school)
  ,COALESCE(high_school)
  ,COALESCE(university)
FROM dwtrat_edu_tempdb.test1

A: Lukasz Szozda answered your question as asked; however, since you have more than 1 not null value per column, I can almost guarantee you are setting yourself up for failure because this results in unnecessary data loss.  Instead of returning a single value using ANY_VALUE(), MIN(), MAX(), or COALESCE(), you may actually wish to use GROUP_CONCAT so that you can generate lists of values like this:
SELECT tile_to_update,
  GROUP_CONCAT(elementary_school),
  GROUP_CONCAT(high_school),
  GROUP_CONCAT(university)
FROM dwtrat_edu_tempdb.test1
GROUP BY tile_to_update

Results in:
"tile_to_update"=>"2270210", "elementary_school" =>"583, 321", "high_school" =>"10529",  "university" =>"10529


text:
Q: VSCode: Is it possible to have global search combined with search by filename (functionality of ctrl+shift+f & ctrl+p combined) I would like to be able to search for file contents AS WELL AS to include files with matching path- and/or filenames in the results when using ctrl+shift+f global search.
So, basically, akin to ctrl+shift+f (global search) and ctrl+p (goto file) combined.
Is it possible or is there any extension out there to make it possible?


text:
Q: How to get exit code from power shell when executing from Control-M Power shell script return specific exit status, which Control-M is unable to read but exiting with different status. Please let us know how to exit Control-M job with same exit status as returned by power shell script.

A: Exit <custom error codes> will return custom return codes from the script

A: In addition to that it is often best to call your Power Shell script via a .bat file. E.g.

*

*Have a Control-M job that is a "command" and has this in the command field -

C:\Program Files\BMC Software\Control-M Agent\Default\Scripts\PS_log_check.bat

*The .bat file should then point to your Power Shell script -

powershell -command "& 'C:\Program Files\BMC Software\Control-M Agent\Default\Scripts\PS_log_check.ps1'"