text:
Q: How to query the results of a query in rails (query the results of a 'DISTINCT ON' with rails & postgres Short version:
I'd like to query the result of another query, in order to select a more limited result set. However, adding a where clause rewrites the first query rather than work on the results, so I don't get the answers I need.
The detail:
I have two models, checks and ticks.  Checks has_many ticks.
The first query uses DISTINCT ON and gathers all of the 'checks' and all of the related ticks but only returns the most recent tick. I have that working as a scope in the model.
In my controller,
  def checklist
  #Filter the results by scope or return all checks with latest tick
  case params[:filter]
    when "duebylastresult"
      @checks = Check.mostrecenttickonly.duebylastresult
    when "duebydate"
      @checks = Check.mostrecenttickonly.duebydate
    else
      @checks = Check.mostrecenttickonly
    end
  end

In the model, the first scope (working):
scope :mostrecenttickonly, -> {
includes(:ticks)
.order("checks.id, ticks.created_at DESC")
.select("DISTINCT ON (checks.id) *").references(:ticks)
}

Generates the following SQL:
  Parameters: {"filter"=>""}
  SQL (1.0ms)  SELECT DISTINCT ON (checks.id) *,
"checks"."id" AS t0_r0,
"checks"."area" AS t0_r1, "checks"."frequency" AS t0_r2,
"checks"."showinadvance" AS t0_r3, "checks"."category" AS t0_r4,
"checks"."title" AS t0_r5, "checks"."description" AS t0_r6,
"checks"."created_at" AS t0_r7, "checks"."updated_at" AS t0_r8,
"ticks"."id" AS t1_r0, "ticks"."result" AS t1_r1,
"ticks"."comments" AS t1_r2, "ticks"."created_at" AS t1_r3,
"ticks"."updated_at" AS t1_r4, "ticks"."check_id" AS t1_r5
FROM "checks" LEFT OUTER JOIN "ticks"
ON "ticks"."check_id" = "checks"."id"
ORDER BY checks.id, ticks.created_at DESC

Having got that result, I want to show only the ticks that have a value equal or greater than 3, so the scope:
   scope :duebylastresult, -> { where("ticks.result >= 3") }

Generates the SQL
  Parameters: {"filter"=>"duebylastresult"}
  SQL (1.0ms)  SELECT DISTINCT ON (checks.id) *,
"checks"."id" AS t0_r0,
"checks"."area" AS t0_r1, "checks"."frequency" AS t0_r2,
"checks"."showinadvance" AS t0_r3, "checks"."category" AS t0_r4,
"checks"."title" AS t0_r5, "checks"."description" AS t0_r6,
"checks"."created_at" AS t0_r7, "checks"."updated_at" AS t0_r8,
"ticks"."id" AS t1_r0, "ticks"."result" AS t1_r1,
"ticks"."comments" AS t1_r2, "ticks"."created_at" AS t1_r3,
"ticks"."updated_at" AS t1_r4, "ticks"."check_id" AS t1_r5
FROM "checks" LEFT OUTER JOIN "ticks"
ON "ticks"."check_id" = "checks"."id"
WHERE (ticks.result >= 3)
ORDER BY checks.id, ticks.created_at DESC

As best I can tell, the WHERE statement is acting before the DISTINCT ON clause, so I now have the 'latest tick where the result is >= 3', whilst I'm looking for 'latest tick THEN only where the result is >= 3'.
Hope that makes sense & Thanks in advance!
Edit - Example of what I get and what I need:
The Data:
Table Checks:
ID: 98 Title: Eire
ID: 99 Title: Land

Table Ticks:
ID: 1 CheckID: 98 Result:1 Date: Jan12
ID: 2 CheckID: 98 Result:5 Date: Feb12
ID: 3 CheckID: 98 Result:1 Date: Mar12
ID: 4 CheckID: 99 Result:4 Date: Apr12

First query returns the most recent result, like;
Check.ID: 98  Tick.ID: 3  Tick.Result: 1 Tick.Date: Mar12
Check.ID: 99  Tick.ID: 4  Tick.Result: 4 Tick.Date: Apr12

Second query currently returns the most recent result where the result is =>3, like;
Check.ID: 98  Tick.ID: 2  Tick.Result: 5 Tick.Date: Feb12
Check.ID: 99  Tick.ID: 4  Tick.Result: 5 Tick.Date: Apr12

When I really want:
Check.ID: 99  Tick.ID: 4  Tick.Result: 5 Tick.Date: Apr12

(ID 98 doesn't show as the last Tick.Result is 1).

A: Could you try the following to see if it starts you in the right direction:
    scope :just_a_test, -> {
    includes(:ticks)
    .order("checks.id")
    .where("ticks.created_at = (SELECT MAX(ticks.created_at) FROM ticks WHERE ticks.check_id = checks.id)")
    .where("ticks.result >= 3")
    .group("checks.id")
    }

A: I'm not sure I really understand the point of the :mostrecenttickonly scope since you're just loading the checks.
That being said, if you want to get only those checks whose most recent ticks have a result greater than three, I think the best way to do that would be a window function:
check.rb
...
  scope :duebylastresult, -> {
    find_by_sql(
      'SELECT *
       FROM (SELECT checks.*,
                    ticks.id AS tick_ids,
                    ticks.date AS tick_date,
                    ticks.result AS tick_result,
                    dense_rank() OVER (
                      PARTITION BY checks.id
                      ORDER BY ticks.date DESC
                    ) AS tick_rank
             FROM checks
             LEFT OUTER JOIN ticks ON checks.id = ticks.check_id) AS ranked_ticks
       WHERE tick_rank = 1 AND tick_result >= 3;'
    )
  }
...

Basically, we're just joining everything in the checks and ticks tables, then adding another attribute called tick_rank that is ranking each row in the result set according to its date versus the other rows with the same checks.id value.
The way SQL works is that the predicates (the conditions in the WHERE clause) are evaluated prior to the evaluation of the SELECT fields, meaning we can't just write tick_rank = 1 in this statement.
So we have to go the extra step of wrapping the results (which we alias as ranked_ticks) and then just select everything and apply the predicates we want to this outer select statement. The tick_rank has to be 1, meaning it's the most recent tick, and the result has to be >= 3.

edit: I was using that article I linked as a refresher since I often forget SQL syntax, but after looking at it, I think this would be somewhat more performant (basically just wait to join checks until after the partitioning is done, that way I believe it will do fewer full scans):
  scope :duebylastresult, -> {
    find_by_sql(
      'SELECT *
       FROM checks
       LEFT OUTER JOIN
            (SELECT id AS tick_id,
                    check_id AS check_id,
                    date AS tick_date,
                    result AS tick_result,
                    dense_rank() OVER (
                      PARTITION BY ticks.check_id
                      ORDER BY ticks.date DESC
                    ) AS tick_rank
             FROM ticks) AS ranked_ticks ON checks.id = ranked_ticks.check_id
       WHERE tick_rank = 1 AND tick_result >= 3;'
    )
  }


text:
Q: Sorting 2d array in PHP overwriting index I have a 2d array like this :
array (size=3)
  0 =>
      array (size=2)
        'player_id' => string '26' (length=2)
        'score' => float 4.702030124427
  1 =>
      array (size=2)
        'player_id' => string '27' (length=2)
        'score' => float 17.891873624039
  2 =>
      array (size=2)
        'player_id' => string '29' (length=2)
        'score' => float 17.883449353824

I'm using usort to sort it and it becomes like this:
array (size=3)
   1 =>
     array (size=2)
              'player_id' => string '27' (length=2)
              'score' => float 17.891873624039
   2 =>
     array (size=2)
              'player_id' => string '29' (length=2)
              'score' => float 17.883449353824
   0 =>
     array (size=2)
             'player_id' => string '26' (length=2)
             'score' => float 4.702030124427

my usort function is this:
  uasort($scoreList,function($a, $b) {
                            if($a['score']==$b['score']) return 0;
                                return $a['score'] < $b['score']?1:-1;
                        });

is there any way I can overwrite the indexes so the sorted list becomes 0,1,2 instead of 1,2,0?

A: You're not using usort; you're using uasort. uasort keeps keys, usort will make new keys.
http://php.net/manual/en/function.usort.php

redpajama_set_name: RedPajamaStackExchange


text:
Q: Persistent routes doesn't work My pc has two network interfaces as followings.

Ethernet adapter VLAN513:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : D-Link DGE-528T Gigabit Ethernet Adapter
   Physical Address. . . . . . . . . : 1C-AF-F7-ED-30-F4
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   IPv4 Address. . . . . . . . . . . : 10.99.0.100(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 10.99.0.1
   DNS Servers . . . . . . . . . . . : 10.99.0.1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Ethernet adapter Office:

   Connection-specific DNS Suffix  . : -----.com.au
   Description . . . . . . . . . . . : Realtek PCIe GBE Family Controller
   Physical Address. . . . . . . . . : D0-50-99-77-F0-A9
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes
   IPv4 Address. . . . . . . . . . . : 192.168.100.29(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Lease Obtained. . . . . . . . . . : Tuesday, 19 April 2022 3:25:18 PM
   Lease Expires . . . . . . . . . . : Wednesday, 20 April 2022 3:25:18 PM
   Default Gateway . . . . . . . . . : 192.168.100.253
   DHCP Server . . . . . . . . . . . : 192.168.110.10
   DNS Servers . . . . . . . . . . . : 192.168.110.10
   NetBIOS over Tcpip. . . . . . . . : Enabled

There is a VPN network I want to talk to that sits on subnet 10.7.0.0/24 and it can be reachable via 10.99.0.254 which is the VPN device.
So I added this VPN IP to my routing table but my VPN packets always go to the wrong route.
route add -p 10.7.0.0/24 10.99.0.254 IF 15
Please advise me on how to resolve this problem.
This is what I can see when I run tracert -d 10.7.0.5
Tracing route to 10.7.0.5 over a maximum of 30 hops

  1     2 ms     1 ms     1 ms  192.168.100.253
  2

This is my routing table with route print.
===========================================================================
Interface List
 15...1c af f7 ed 30 f4 ......D-Link DGE-528T Gigabit Ethernet Adapter
 11...d0 50 99 77 f0 a9 ......Realtek PCIe GBE Family Controller
  1...........................Software Loopback Interface 1
 17...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter
 16...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #2
 14...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0  192.168.100.253   192.168.100.29     10
          0.0.0.0          0.0.0.0        10.99.0.1      10.99.0.100    276
         10.7.0.0    255.255.255.0      10.99.0.254      10.99.0.100     21
        10.99.0.0    255.255.255.0         On-link       10.99.0.100    276
        10.99.0.0    255.255.255.0        10.99.0.1   192.168.100.29     11
      10.99.0.100  255.255.255.255         On-link       10.99.0.100    276
      10.99.0.255  255.255.255.255         On-link       10.99.0.100    276
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    306
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    306
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    306
    192.168.100.0    255.255.255.0         On-link    192.168.100.29    266
   192.168.100.29  255.255.255.255         On-link    192.168.100.29    266
  192.168.100.255  255.255.255.255         On-link    192.168.100.29    266
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    306
        224.0.0.0        240.0.0.0         On-link    192.168.100.29    266
        224.0.0.0        240.0.0.0         On-link       10.99.0.100    276
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    306
  255.255.255.255  255.255.255.255         On-link    192.168.100.29    266
  255.255.255.255  255.255.255.255         On-link       10.99.0.100    276
===========================================================================
Persistent Routes:
  Network Address          Netmask  Gateway Address  Metric
        10.99.0.0    255.255.255.0        10.99.0.1       1
          0.0.0.0          0.0.0.0        10.99.0.1  Default
         10.7.0.0    255.255.255.0      10.99.0.254       1
===========================================================================

IPv6 Route Table
===========================================================================
Active Routes:
 If Metric Network Destination      Gateway
  1    306 ::1/128                  On-link
  1    306 ff00::/8                 On-link
===========================================================================
Persistent Routes:
  None


text:
Q: SQL Server : XQUERY namespace parsing I have the following XML:
    declare @xml    xml = '
    <DiscoverResponse xmlns="urn:schemas-microsoft-com:xml-analysis">
      <return>
        <root xmlns="urn:schemas-microsoft-com:xml-analysis:rowset">
          <row>
            <xars:METADATA xmlns="http://schemas.microsoft.com/analysisservices/2003/engine">
              <Server>
                <Name>myName</Name>
              </Server>
            </xars:METADATA>
          </row>
        </root>
       </return>
    </DiscoverResponse>'

And I have been able to parse up to the <row> tag with the following query
    ; WITH XMLNAMESPACES(
        'urn:schemas-microsoft-com:xml-analysis'                        AS ns1,
        'urn:schemas-microsoft-com:xml-analysis:rowset'                 AS ns2
    )
    select
        t.x.value('ns2:Name[1]','varchar(100)') AS Name
    from @xml.nodes('//ns1:DiscoverResponse/ns1:return/ns2:root/ns2:row') t(x)

I am stuck trying to figure out how to query past the <xars:METADATA> tag.  That is, I have not been able successfully construct a namespace declaration and path specification to get to the <Server> node (I am trying to extract the Name of the Server).  I am running afoul of the extra colon it seems.
Thanks in advance.

A: You have a couple of things going wrong:

*

*The xars namespace is not declared in the xml. I believe the namespace for xars is "urn:schemas-microsoft-com:xml-analysis:rowset" which you actually have as a default namespace (form the root) but not explicitly mapped to the xars prefix.

*The xquery is missing the reference to namespace "http://schemas.microsoft.com/analysisservices/2003/engine" which in the xml is set as the default namespace from and including METADATA.
So first, I've altered your sample xml to include a namespace for xars: I expect your actual xml has this declared elsewhere, so you problably dont need to make this change.
declare @xml    xml = N'<DiscoverResponse xmlns="urn:schemas-microsoft-com:xml-analysis">
  <return>
    <root xmlns="urn:schemas-microsoft-com:xml-analysis:rowset">
      <row>
        <xars:METADATA xmlns="http://schemas.microsoft.com/analysisservices/2003/engine" xmlns:xars="urn:schemas-microsoft-com:xml-analysis:rowset">
          <Server>
            <Name>myName</Name>
          </Server>
        </xars:METADATA>
      </row>
    </root>
   </return>
</DiscoverResponse>'

Second, I've added the 'http://schemas.microsoft.com/analysisservices/2003/engine' (as ns3) to your query and change the query to reference it.
; WITH XMLNAMESPACES(
    'urn:schemas-microsoft-com:xml-analysis'                        AS ns1,
    'urn:schemas-microsoft-com:xml-analysis:rowset'                 AS ns2,
    'http://schemas.microsoft.com/analysisservices/2003/engine'     AS ns3
)
select
    t.x.value('ns3:Name[1]','varchar(100)') AS Name
from @xml.nodes('//ns1:DiscoverResponse/ns1:return/ns2:root/ns2:row/ns2:METADATA/ns3:Server') t(x)


text:
Q: NSMutableArray is still null after calling the addObject method on it [_noteTitles addObject:@"title"];
[_noteDescriptions addObject:@"description"];
[self.tableView reloadData];
NSLog(@"%@", [_noteDescriptions description]);
NSLog(@"%@", [_noteTitles description]);

Before those lines I synthesized both "_noteDescription", "_noteTitles." When the NSLog lines are called, on the console i get "(null)" for both arrays. This function will be called multiple times (not too often) to update the contents of a table, but right now the arrays are not getting populated.

A: It looks like you did not initialize your arrays. Therefore, you are sending addObject: to nil and nothing happens. This also explains why NSLog() prints (null).
Note that @synthesize generates the accessors for your property, it does not initialize the backing instance variable.


text:
Q: Swift Package Issue after updating to MacOS Monterey I'm having this issue with my swift package. It was created a few weeks ago with BigSur, as the platform target i put iOS 15. I don't understand what it could be
ld: warning: dylib (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/pm/ManifestAPI/libPackageDescription.dylib) was built for newer macOS version (11.0) than being linked (10.15)

A: https://stackoverflow.com/a/71762933/6479729 - this works for me

*

*Enter this command in your terminal:
sudo xcode-select --switch /Applications/Xcode.app

*Relaunch Xcode


text:
Q: Can a non-constant lower-semi-continuous convex function attain the $-\infty$ value This paper that I am studying asserts in the second paragraph that the only lower-semi-continuous convex function attaining $-\infty$ is the constant $-\infty$ function. However, it seems that the function defined by:
\begin{align}
f(x)=\begin{cases}
-\infty, &x\leq 0\\
\infty, &x>0
\end{cases}
\end{align}
is both convex and lower-semi-continuous. My reasoning is that the epigraph of $f$ is a closed half-plane, which I know to be convex. For lower-semi-continuity, it seems that the only point of concern is $x=0$. But $f(0)=-\infty$, and so it is clear that for all $\epsilon>0$, we have $f(x) \geq f(0)-\epsilon = -\infty$ for any $x\in \mathbb{R}$.
Is there something I'm missing here? Is there something else we assume in the definition of convexity? Am I misinterpreting the statement in the paper?

A: You're correct, and the paper is wrong.


text:
Q: Lucene query using GetFieldQuery not getting back results? I am not sure why this is not pulling back documents:
The documents being added:
document.Add(new Field("project.id", projectId.ToString(), Field.Store.YES, Field.Index.NO));
                document.Add(new Field("contact.id", entity.Id.ToString(), Field.Store.YES, Field.Index.NO));
                document.Add(new Field("contact.businesspartnerid", entity.BusinessPartnerId.ToString(), Field.Store.YES, Field.Index.NO));
                document.Add(new Field("contact.businesspartner.name", entity.BusinessPartner.Name, Field.Store.YES, Field.Index.ANALYZED));
                document.Add(new Field("contact.emailaddress", entity.EmailAddress, Field.Store.YES, Field.Index.ANALYZED));
                document.Add(new Field("contact.firstname", entity.FirstName, Field.Store.YES, Field.Index.ANALYZED));
                document.Add(new Field("contact.lastname", entity.LastName, Field.Store.YES, Field.Index.ANALYZED));
                document.Add(new Field("contact.fullname", entity.FirstName + " " + entity.LastName, Field.Store.YES, Field.Index.ANALYZED));

The Query in Lucene.Net:
var prefix = "dan";
var fields = new {"contact.emailaddress"};
var filterFields = new Dictionary<string,string>();
filterFields.add("project.id","123456");

var parser = new MultiFieldQueryParser(Version.LUCENE_29, fields, new KeywordAnalyzer());

 var query = new BooleanQuery();
               query.Add(parser.Parse(prefix + "*"), BooleanClause.Occur.MUST);

               if (filterFields != null)
               {
                   foreach (var field in filterFields)
                   {
                       query.Add(parser.GetFieldQuery(field.Key, field.Value), BooleanClause.Occur.MUST);

                   }
               }

The query being passed to Lucene:
query.Query = {+(contact.emailaddress:dan* ) +project.id:123456}
if I remove the parser.GetFieldQuery it works great. When I physically look into the index file there is an entry with the project.id and an entry that starts with "dan".
Should I be doing something else to facet the search by project.id?

A: I ended up changing the way Lucene was storing the project.id:
document.Add(new Field("project.id", projectId.ToString(), Field.Store.NO, Field.Index.ANALYZED));


text:
Q: php laravel api test always returns 404 in the second call after a first successful call I am making an API test function that includes sending a post request twice in the same test.
the first request is successful and has no problem, and i can assert the response without any issue. however, in the second request, the route is not found and the response returns 404 error right away. even though i use the same request.
here is how the test function looks like:
public function tesAbc(\ApiTester $I)
    {
        $I->haveHttpHeader('Accept', 'application/json');
        $request = [
            'username' => 'abc',
            'password' => 'testABc',
            'data' => [
                'param1' => '123',
                'param2' => '456'
            ]
        ];

        /* the first request, response always 200 */
        $I->sendPOST('confirmation/slot', $request);

        $I->seeResponseCodeIs(200);
        $I->seeResponseIsJson();

        /* the second request, response always 404 */
        $I->sendPOST('confirmation/slot', $request);

        $I->seeResponseCodeIs(200);
        $I->seeResponseIsJson();
        $I->dontSeeResponseJsonMatchesJsonPath('$.data[*]');
    }

A: The problem is that you used relative URI confirmation/slot.
The first request goes to /confirmation/slot  then second request is relative to that and it goes to `/confirmation/confirmation/slot.
Solution is simple, use leading / in URI:
$I->sendPOST('/confirmation/slot', $request);


text:
Q: Demonstrating that a particular ideal is maximal in a number field I have three ideals, each with two elements of $\mathbb Z[\sqrt{-5}]$. If you show me how to show one of them is maximal (hence prime) then I think I can manage to do the remaining two by myself.
$\langle 2, 1 + \sqrt{-5}\rangle$

A: We have
$$\begin{eqnarray*} \Bbb{Z}[\sqrt{-5}]/(2,1+ \sqrt{-5}) &\cong& \Bbb{Z}[x]/(x^2 + 1)/\left((2,1+x)/(x^2 + 1)\right) \\
&\cong& \Bbb{Z}[x]/(2,x+1) \\
&\cong& \Bbb{Z}/2\Bbb{Z}\end{eqnarray*}$$
and so your ideal is maximal.

A: Call your ideal $I.$ You want to show that the result of quotienting out by $I$ is a field. It is very easy to see this directly. Since $a+b\sqrt{-5} = a-b + b(1+\sqrt{-5})$ we see that $$ a+b\sqrt{-5}+I = a-b + I = (a-b)\pmod 2 + I$$ so if we can show that $1\notin I$ then $a+b\sqrt{-5}+I$ is either $0+I$ or $1+I$, i.e. the quotient ring is the field with two elements.
Suppose $1 = 2(a+b\sqrt{-5})+ (1+\sqrt{-5})(c+d\sqrt{-5}) = 2a+c-5d +(2b+c+d)\sqrt{-5}.$ Then $c-d=1\pmod 2$ and $c+d=0 \pmod 2.$ But $ 2c=1 \pmod 2$ is nonsense, so the ideal is proper as suspected.


text:
Q: Laravel - displaying categories by id For a blog site, I have all the posts & lists of categories displaying on a page though now I need to display the posts for each category on it's own separate page.
Let's say I had a categorie that was 'Javascript' and I wanted only the posts with the category of javascript displayed on a page.
What's the correct code to do this? here's an example, the bold 'javascript' is what needs to be replaced with the correct code.
-- categoriesController.php ---
public function show($id)
{
$post->withCategories($Categories)->$id->($id as **javascript)**
}

--- javascript.blade.php --- ( corresponding view )

@foreach ($categories as $category->$id>**javascript**)

{{ $category->id }}
{{ $category->name }}

@endforeach

@endforeach


text:
Q: How to code backward compatible new feature in Android SDK? I want to use the actionbar feature included in SDK 11. However I also want the app to run on earlier devices from SDK 10 (2.3.3). I am willing to give up the actionbar feature for the earlier devices as it is not an important feature. I have done all the reading about reflection, wrapper class and some other techniques. I am now stumped on exactly how to make this work. I am using Eclipse.
If I don't set the target in Eclipse to sdk 11 or greater, then any place I have a reference to actionBar gives a compile error. If I put the target to sdk 11 or greater it compiles but won't show that it can run on earlier devices. I have android:minSdkVersion=10 set all the time.
Can someone give me some insight on how to make the references to actionBar and yet get it to target a previous sdk level? Thanks in advance.

A: Yes! You can definitely do this. Try following the pattern outlined below.
In your AndroidManifest.xml file declare the following (replacing the platform versions with whatever your app requires):
<!-- Build Target -->
<uses-sdk android:targetSdkVersion="14" android:minSdkVersion="7" />

By targeting a platform version of API 11 or higher, you are allowing Eclipse to link (compile) against the native ActionBar classes. Providing an earlier minimum platform version allows your app to be installed (run) on older versions of Android.
Your Activity code should then look something like this:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (CompatibilityManager.isHoneycomb()) {
        final ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowHomeEnabled(true);
        // ...
    } else {
        // The ActionBar is unavailable!
        // ...
    }
}

Where the CompatibilityManager.java class simply provides static helper methods for determining the current version of the SDK:
public class CompatibilityManager {
    public static final String KINDLE_FIRE_MODEL = "Kindle Fire";

    /**
     * Get the current Android API level.
     */
    public static int getSdkVersion() {
        return android.os.Build.VERSION.SDK_INT;
    }

    /**
     * Determine if the device is running API level 11 or higher.
     */
    public static boolean isHoneycomb() {
        return getSdkVersion() >= Build.VERSION_CODES.HONEYCOMB;
    }

    /**
     * Determine if the device is running API level 14 or higher.
     */
    public static boolean isIceCreamSandwich() {
        return getSdkVersion() >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
    }

    /**
     * Determine if the current device is a first generation Kindle Fire.
     * @return true if the device model is equal to "Kindle Fire", false if otherwise.
     */
    public static boolean isKindleFire() {
        return Build.MODEL.equals(KINDLE_FIRE_MODEL);
    }
}

You might also consider leveraging the ActionBarSherlock library, which provides a compatible ActionBar API all the way back to Android 2.x:

The library will automatically use the native action bar when
  available or will automatically wrap a custom implementation around
  your layouts. This allows you to easily develop an application with an
  action bar for every version of Android back through 2.x.

Have fun!


text:
Q: .net ComboBox.Items.Add("testvalue") throws exception I am using Compact Framework and the statement below throws exception:
 ComboBox cmbList  = new ComboBox();

    //source set here
   List<string> items = new List<string>();
   items.AddRange(GetNumbers());
   cmbList.DataSource = ovenNumbers;

    // where GetNumbers() return List<string> object
    //then down the road I need to dynamically add one more item to the list of items

     cmbList.Items.Add("TESTVALUE");

MSDN only lists one exception - for null parameter, which is clearly not the case.
What am I doing wrong?
Thanks!
EDITED: I can't view the error message since I don't have the module required to view errors installed on my thin client.

A: Found the answer
apprently once DataSource property is set,it can't be changed
http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.datasource%28v=vs.90%29.aspx
"When the DataSource property is set, a user cannot modify the items collection."

A: Well are you sure the source is filled with string objects?


text:
Q: How to set computed property a value if it's not bound to component's data I have a component that has a computed property which gets its value from the Vuex store, like following:
computed: {
  details () {
    return this.$store.getters.getDetails
  }
}

getDetails getter returns an object with several properties.
Now the problem is, how to update properties of 'details' object in the component where it is defined?
If it was through the UI, then it could be done via v-model. But it's needs to be done via component's methods. Like the following:
methods: {
  someMethod () {
    // here I need to update props of 'details' object, but how?
  }
}

A: Since you're using Vuex, do it in the store.
Let's say your details object is like this:
details: { foo: 1, bar: 2 }

Then add a mutation for modifying the details object in the state (I used and because I don't know whether you only want to modify a property of the details or actually want to assign a new object to it):
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    details: { foo: 1, bar: 2 }
  },
  getters: {
    getDetails: (state, getters) => {
      return state.details;
    }
  },
  mutations: {
    UPDATE_DETAILS (state, payload) {
      this.$set(state.details, payload.key, payload.val)
    },
    REPLACE_DETAILS (state, payload) {
      state.details = payload
    }
  }
});

Then in your component:
// ...
methods: {
  // ...
  updateDetails(key, val) {
    this.$store.commit('UPDATE_DETAILS', { key, val });
  },
  replaceDetails(obj) {
    this.$store.commit('UPDATE_DETAILS', obj);
  }
}

Update: What I said is basically a longer explanation of what @Bert was trying to say in his comment.


text:
Q: Code coverage error (No binaries were instrumented) Problem:
Microsoft Visual Studio Enterprise 2015
Version 14.0.25431.01 Update 3
I'm attempting to use the code coverage function but it returns this error:

Empty results generated: No binaries were instrumented. Make sure the
  tests ran, required binaries were loaded, had matching symbol files,
  and were not excluded through custom settings. For more information
  see http://go.microsoft.com/fwlink/?LinkID=253731

My .coverage file is full of non-sense, starting with "PCHÿ". I thought my problem looked similar to this one: Issue with Code Coverage in VS 2012, but deleting the .suo file and running Visual Studio in admnistrator didn't solve anything.
How to replicate:
1) Create new empty project "MyProject"
2) Add new file "Calculator.hpp"
#pragma once

class Calculator
{
public:
    int add(int a, int b);
    int sub(int a, int b);
};

3) Add new file "Calculator.cpp"
#include "Calculator.hpp"

int Calculator::add(int a, int b)
{
    return a + b;
}

int Calculator::sub(int a, int b)
{
    return a - b;
}

4) Add new file main.cpp
#include "Calculator.hpp"
#include <iostream>

using std::cout;

int main()
{
    Calculator calc;
    std::cout << calc.add(5, 11) << std::endl;
    std::cout << calc.add(11, 1) << std::endl;

    return 1;
}

5) Build solution. (0 errors)
6) Add new test project to solution as explained here: https://msdn.microsoft.com/en-us/library/hh419385.aspx#objectRef:

*

*Add new Native Unit Test Project to solution "CalculatorUnitTest"

*Add "main.obj" and "Calculator.obj" to Linker/Input/Additional Dependencies of "CalculatorUnitTest"

*Add path to obj files to Linker/General/Additional Library Directories of "CalculatorUnitTest". (In my case: D:\JF\Programming\Tests\MyProject\MyProject\Debug)

*Add the header directory of "MyProject" to VC++ Directories/Include Directories. (In my case: D:\JF\Programming\Tests\MyProject\MyProject).

7) Replace code in "unittest1.cpp" with:
#include "stdafx.h"
#include "CppUnitTest.h"
#include <Calculator.hpp>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace CalculatorUnitTest
{
    TEST_CLASS(UnitTest1)
    {
    public:

        TEST_METHOD(TestMethod1)
        {
            Calculator calc;
            Assert::AreEqual(5, calc.add(2, 3));
        }

    };
}

8) Build solution (0 errors, TestMethod1 appear in Test Explorer)
9) Right-click TestMethod1, "Run Selected Tests" (Test successfully passes)
10) Right-click TestMethod1, "Analyze Code Coverage for Selected Tests" (Code coverage fails).
At D:\JF\Programming\Tests\MyProject\Debug, I have both my MyProject.exe and MyProject.pdb with the CalculatorUnitTest.dll.

A: First of all, I am not sure if Visual Studio 2015 (C++) supports ".exe" type project for the unit test.  But you are using ".obj" directly from your project.  You need to place ".pdb" file in the same folder.
I created a static library project and added the unit test.  Same problem on my environment.

A: Future here. Same problem, except my test target is a Static Library project in the same Solution.

*

*MyLib - Code that will be tested.

*MyLibTests - Project containing the tests.

*Solution contains both projects.

*MyLibTests has project Reference to MyLib.

*<OutDir> (in .vcxproj) aka Output Directory aka $(OutDir) identical in both projects. (My value <OutDir>$(SolutionDir)$(Configuration)_$(Platform)\</OutDir>)

On your test project (MyLibTests), go

*

*Properties

*Select [Debug|platform]

*Linker

*Debugging

*

*Generate Debug Info = Optimize for debugging /DEBUG
Mine was initially set for /DEBUG:FASTLINK.
Via this social MSDN post I figured it had something to do with the PDB, because MSDN (aka now "learn.microsoft.com") said this is an important step in several places, and I assume PDB are used trace calls, I assume using DbgHelp.dll.
And this sort of checklist modified from another social MSDN post:

*

*Test project References properly set (MyLib.lib is in the same Solution as MyLibTests.dll)

*Build order/dependency set/verified.

*I also have Autorun on Build.

*Rebuild (this should rebuild dependencies).

*made sure all test were run(all test run successful)

*not using optimisation (Profile Guided/Instrumentation etc).

*<OutDir> aka Ouput directory should be the same, where both MyLibrary.lib/dll/exe ends up with their MyLibrary.pdb since PDB paths are linked in the exe/dll.

*not using a runsettings file

*Unload all other projects other than affected ones


text:
Q: Default arguments using mocked objects I am using Sphinx v1.8.5 to build documentation for Python 2 code that has external dependencies that I mock using autodoc_mock_imports. I get an error message when I try to use the mocked object (RAMP) as a default argument:
def foo(name, amp=RAMP):

The error says:

NameError: name 'RAMP' is not defined

If I do not use RAMP as a default argument, the error disappears. What am I doing wrong?

A: Ok, so thanks to the comment of @bad_coder I realised that the hurdle was stemming from how the modules were imported. I needed to resolve the scope with module_defining_RAMP.RAMP instead of directly accessing RAMP.
Of course, then I got the ugly value of the mocked object in the output of my documentation:

foo(name, amp=<sphinx.ext.autodoc.importer._MockObject object>)

but I have already seen the solution to this problem while searching for my own. I needed to simply state the function signature in the doc string:
def foo(name, amp=RAMP):
"""
foo(name, amp=module_defining_RAMP.RAMP)
"""


text:
Q: How to animate a triangle to move forward in Java Swing I'm creating a simulation of the Boid algorithm in Swing (Graphics2d library), so I want to animate many shapes (triangles). Right now I'm learning how to move them around and have run into a problem with fps and repainting.
The fps drop significantly when I put more than two triangles on the screen (say, 10), and I really don't know where the problem lies. Here's the code (I omitted the libraries):
public class Program {

/**
 * @param args
 */
public static void main(String[] args) {
    World world = World.getInstance();

    // Initialise and show world
    JFrame f = new JFrame();
    f.setSize(world.getBoundsX(),world.getBoundsY());
    f.setTitle("Boids Alive");
    f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(world);
    f.setResizable(false);
    f.setVisible(true);

    for(int i = 0 ; i < 10; i++)
        world.createBoid();

    while(true){
        //adjust all behaviours
        for(Boid b : world.boids){
            b.move(0, -2);
        }

        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        world.refreshAll();
    }
}

public final class World extends JPanel {

    private static final long serialVersionUID = 1L;
    private Random r = new Random();

    private static final int boundsX = 800;
    private static final int boundsY = 600;

    public ArrayList<Boid> boids = new ArrayList<Boid>();
    public ArrayList<Obstacle> obstacles = new ArrayList<Obstacle>();

    private static World instance = null;
    private World() {
        this.setBackground(Color.white);
    }

    public static World getInstance(){
        if(instance == null)
            instance = new World();

        return instance;
    }

    public int getBoundsX() { return boundsX; }
    public int getBoundsY() { return boundsY; }

    public void createBoid(){
        Boid b = new Boid() ;
        b.setX(r.nextInt(790));
        b.setY(r.nextInt(590));

        boids.add(b);
        b.start() ;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
    }

    public void refreshAll() {
        for(Boid b : boids) {
            b.graphicEle.refreshLocation();
        }
    }
}

public class Boid extends WorldObject{
    public Boid() {
        graphicEle = new GraphicElement(this);

        World world = World.getInstance() ;
        world.add(graphicEle) ;
        world.repaint() ;
        world.validate() ;
    }

    public void move(int x, int y) {
        this.x += x;
        this.y += y;

        checkBounds();
        try {
            sleep(15);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void checkBounds() {
        World world = World.getInstance() ;
        if(this.x < 0) x = world.getBoundsX();
        if(this.x > world.getBoundsX()) x = 0;
        if(this.y < -20) y = world.getBoundsY(); //TODO: get the actual size
        if(this.y > world.getBoundsY()) y = 0;
    }
}

public class GraphicElement extends JPanel {

    private static final long serialVersionUID = 1L;
    private WorldObject owner;

    public GraphicElement(WorldObject obj) {
        owner = obj ;
        setPreferredSize(new Dimension(20, 20));
        setOpaque(false);
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create(); //TODO Move to boid class
        g2d.setColor(Color.orange);

        Path2D.Double triangle = new Path2D.Double();
        triangle.moveTo(0, 20);
        triangle.lineTo(10, 0);
        triangle.lineTo(20, 20);
        triangle.closePath();

        g2d.fill(triangle);
        g2d.dispose();
    }

    protected void refreshLocation() {
        setLocation(owner.getX(), owner.getY());
    }
}

Any ideas what I am doing wrong? Should I use translate() instead of setLocation()?


text:
Q: Warning: A component is changing a controlled input of type undefined to be uncontrolled I got the following warning when using controlled components, despite having set the initial states:
Warning: A component is changing a controlled input of type undefined to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
Here is my code:
import React, { useState } from "react";

function App() {
    const [fullName, setFullName] = useState({
        fName: "",
        lName: ""
    });

    function handleChange(event) {
        const { value, name } = event.target;

        setFullName(prevValue => {
            if (name === "fName") {
                return {
                    fName: value,
                    lName: prevValue.lName
                };
            } else if (name === "lName") {
                return {
                    fName: prevValue.fName,
                    lname: value
                };
            }
        });
    }

    return (

                Hello {fullName.fName} {fullName.lName}

            <form>
                <input
                    name="fName"
                    onChange={handleChange}
                    placeholder="First Name"
                    value={fullName.fName}
                />
                <input
                    name="lName"
                    onChange={handleChange}
                    placeholder="Last Name"
                    value={fullName.lName}
                />
                <button>Submit</button>
            </form>

    );
}

export default App;

If I type John as the fName and Doe as the lName in the inputs, the headline should be Hello John Doe, but I just got Hello John with the warning. Using the condition below will get rid of the warning, but I just get Hello John again:
value={fullName.lName || ""}

How to get both fName and lName displayed at the same time without the warning?

A: This is happening because of a typo.
Change :
else if (name === "lName") {
   return {
      fName: prevValue.fName,
      lname: value
   };
}

to:
else if (name === "lName") {
   return {
      fName: prevValue.fName,
      lName: value // notice 'n' was in lowercase.
   };
}

Also, a more concise way to go about it (in my opinion) would be:
setFullName((prevValue) => ({
    ...prevValue, [name] : value
}));

Working example : here


text:
Q: Ansible error "'dict object' has no attribute u'xxxxxxxx.dev'?? I am new to ansible and vagrant, I am getting this error message when I try to run vagrant provision
fatal: [default]: FAILED! => {"failed": true, "msg": "'dict object' has no attribute u'xxxxxxxx.dev'"}

I think it is an error in this below file and i have tried to change format but it is not working
wordpress_sites:
  xxxxx.com.in:
    site_hosts:
      - xxxxx.dev
    local_path: ../site
    site_install: true
    site_title: Xxxxx
    admin_user: admin
    # admin_password: (defined in group_vars/development/vault.yml)
    admin_email: xxxxx@xxxxxx.dev
    initial_permalink_structure: /%postname%/ # applied only at time of WP install and when `site_install: true`
    multisite:
      enabled: false
      subdomains: false
    ssl:
      enabled: false
    cache:
      enabled: false
      duration: 30s
    env:
      disable_wp_cron: true
      wp_home: http://xxxxxx.dev
      wp_siteurl: http://xxxxxx.dev/wp
      wp_env: development
      db_name: xxxxxx
      db_user: xxxxxx
      # db_password: (defined in group_vars/development/vault.yml)

What am I missing?

A: This link help me
I have changed 'example.com' to 'xxxxx.com.in' in - 'group_vars/development/vault.yml'
Now it working


text:
Q: Who search a variable name with DOM? I have this code and I need know how to use "nombre" variable to find data with DOM, this aplication works without Jquery.
window.onload = function(e){
<%if(!faltanCampos.equals("")){%>alert("<%=faltanCampos%>")<%}%>
    //Ocultamos los vacios'
    var j, nombre
    i=<%=totalSig%>
    for (j=i-1;j > 0;j--){
        //nombre="txtsssiidenti" & j'
        nombre="txtissicodtui" + j
        if (document.frmDatos.nombre.value==""){
            menos();
        }
    }
    actualizaNivel();
}

Im translating the aplication from vb to js, the vb code:
Sub window_onload
<%if(!faltanCampos.equals("")){%>msgbox("<%=faltanCampos%>")<%}%>
    'Ocultamos los vacios'
    Dim j, nombre
    i=<%=totalSig%>
    for j=i-1 to 0 step -1
        'nombre="txtsssiidenti" & j'
        nombre="txtissicodtui" & j
        if (document.all(nombre).value="") then
            menos()
        end if
    next
    actualizaNivel
End sub

FireBug error:

TypeError: document.frmDatos.nombre is undefined

HTML:
<title><%=GestorIdioma.getCadena("ARGES")%> - <%=GestorIdioma.getCadena("DESCRIARCHIVO")%></title>

<body onmouseover="defaultStatus='<%=GestorIdioma.getCadena("PIEPAGINA")%>'; return true;" >

<%@ include file="../includeJSP/body_sitemap.inc" %>
<%@ include file="../includeJSP/camino.inc" %>
<%if(!Utilidades.dameElemHashtable(h,"EXPURGO").equals("S") && !Utilidades.dameElemHashtable(h,"TRANSFERENCIA").equals("S")){%>

<%@ include file="../includeJSP/OpcionesMant.inc" %>
<%}%>

<form name="frmDatos" method="post" action="">

<input type="hidden" name="apartado" value="<%=apartado%>"/>
<input type="hidden" name="hacer" value="<%=hacer%>"/>
<input type="hidden" name="acceso" value="<%=acceso%>"/>
<input type="hidden" name="totalSig" value="<%=totalSig%>"/>
<input type="hidden" name="destino" value="signatura"/>
<input type="hidden" name="txtpsarcodarc" value="<%=Utilidades.dameElemHashtable(hotros,"txtpsarcodarc")%>"/>
<input type="hidden" name="txtpsarcodarcold" value="<%=Utilidades.dameElemHashtable(hotros,"txtpsarcodarcold")%>"/>
<input type="hidden" name="txtisarcodpro" value="<%=Utilidades.dameElemHashtable(hotros,"txtisarcodpro")%>"/>
<input type="hidden" name="masCodNivelA" value="<%=Utilidades.dameElemHashtable(h,"masCodNivelA")%>"/>
<input type="hidden" name="nivelArchivoAnterior" value="<%=Utilidades.dameElemHashtable(h,"masCodNivelA")%>"/>

<%@ include file="../includeJSP/NavegaArea.inc" %>

            <%=GestorIdioma.getCadena("SIGNATURA")%>

                        <%= GestorIdioma.getCadena("TITULO")%>:
                        <%=Utilidades.dameElemHashtable(hotros,"txtssartitulo",session.getAttribute("s54b.varidioma").toString())%>

<%if(Utilidades.dameElemHashtable(h,"TRANSFERENCIA").equals("S")){%>

                        <%=GestorIdioma.getCadena("ENTRANSFERENCIA")%>

<%}
if(Utilidades.dameElemHashtable(h,"EXPURGO").equals("S")){%>

                        <%=GestorIdioma.getCadena("ENEXPURGO")%>

<%}%>

            <%=GestorIdioma.getCadena("NIVELARCHIVO")%>:
            <select name="cboNivelA" class="inpuedi" onchange="javascrip:actualizaNivel()" <%=habilitado%> >
                <%  boolean carga=false;
                                    anterior=(!Utilidades.dameElemHashtable(h,"masCodNivelA").equals("")?Utilidades.dameElemHashtable(h,"masCodNivelA").toString():"");
                                    if(lnivelAr!=null){
                        for(i=0;i<lnivelAr.size();i++){
                                            carga=false;
                            hvalores = (Hashtable)lnivelAr.get(i);
                                            //Comprobamos permisos
                                            if(hvalores.get("RECODRAR").equals("10") && per.damePermiso("MARO",request,response)){
                                                carga=true;
                                            }else if(hvalores.get("RECODRAR").equals("20") && per.damePermiso("MARD",request,response)){
                                                carga=true;
                                            }else if(hvalores.get("RECODRAR").equals("30") && per.damePermiso("MARG",request,response)){
                                                carga=true;
                                            }else if(hvalores.get("RECODRAR").equals("40") && per.damePermiso("MARH",request,response)){
                                                carga=true;
                                            }else if(hvalores.get("RECODRAR").equals("25") && per.damePermiso("MARC",request,response)){
                                                carga=true;
                                            }
                                            if(carga){
                                                if(hvalores.get("RECODRAR").equals(anterior)){
                %>
                    <option class="inpuedi" value="<%=hvalores.get("RECODRAR")%>" selected="selected"><%=hvalores.get("REDESCRI")%></option>
                <%              }else{%>
                    <option class="inpuedi" value="<%=hvalores.get("RECODRAR")%>"><%=hvalores.get("REDESCRI")%></option>
                <%              }
                                            }
                        }
                    }else{%>
                    <option class="inpuedi" value="" selected> </option>
                <%  }%>
            </select>

<%
String letras = "";
int numero = 0;
if(lclavesUI!=null){
    for(i=0;i<lclavesUI.size();i++){
        hvalores= new Hashtable();
        hvalores = (Hashtable)lclavesUI.get(i);
        letras = Utilidades.dameElemHashtable(hvalores,"letras");
        numero  = Utilidades.esNumero(Utilidades.dameElemHashtable(hvalores,"numero"))?Integer.parseInt(Utilidades.dameElemHashtable(hvalores,"numero")):0;
    }
}
for(j=0;j<Integer.parseInt(totalSig);j++){
    //Si no hay SIIDENTI, ponemos una por defecto
    if(Utilidades.dameElemHashtable(h,"txtsssiidenti" + j).equals("")) {
        numero++;
        h.put("txtsssiidenti" + j,Utilidades.formateaNumCaja(letras,numero,true));
    }
%>
<tr id="tipoUI<%=j%>">

<input type="hidden" name="masUIvalida<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"masUIvalida" + j).equals("")?"S":Utilidades.dameElemHashtable(h,"masUIvalida" + j)%>"/>
<input type="hidden" name="masUIdeposito<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"masUIdeposito" + j)%>"/>
<input type="hidden" name="txtissicodtui<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"txtissicodtui" + j)%>"/>
<input type="hidden" name="masUnDescri<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"masUnDescri" + j)%>"/>
<input type="hidden" name="masUnMetros<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"masUnMetros" + j)%>"/>

            <%=GestorIdioma.getCadena("TIPOUI")%>:
            <select name="cboTipoUI<%=j%>" class="inpuedi" onchange="javascript:actualizaTipo('<%=j%>')" <%=habilitado%> >
<option class="inpuedi" value="" selected="selected"> </option>
                <%anterior=Utilidades.dameElemHashtable(h,"txtissicodtui" + j);
                                    if(ltipoui!=null){
                        for(i=0;i<ltipoui.size();i++){
                            hvalores = (Hashtable)ltipoui.get(i);
                            if(hvalores.get("UNCODTUI").equals(anterior)){
                %>
                    <option class="inpuedi" value="<%=hvalores.get("UNCODTUI")%>~<%=Utilidades.dameElemHashtable(hvalores,"UNMETROS")%>" selected="selected"><%=hvalores.get("UNDESCRI")%> - <%if ((Utilidades.dameElemHashtable(hvalores,"UNMETROS").substring(0,1)).equals(".")) {%>0<%=Utilidades.dameElemHashtable(hvalores,"UNMETROS").replace('.',',')%><%}else{%><%=Utilidades.dameElemHashtable(hvalores,"UNMETROS").replace('.',',')%><%}%> m.</option>
                <%          }else{%>
                    <option class="inpuedi" value="<%=hvalores.get("UNCODTUI")%>~<%=Utilidades.dameElemHashtable(hvalores,"UNMETROS")%>"><%=hvalores.get("UNDESCRI")%> - <%if ((Utilidades.dameElemHashtable(hvalores,"UNMETROS").substring(0,1)).equals(".")) {%>0<%=Utilidades.dameElemHashtable(hvalores,"UNMETROS").replace('.',',')%><%}else{%><%=Utilidades.dameElemHashtable(hvalores,"UNMETROS").replace('.',',')%><%}%> m.</option>
                <%          }
                        }
                    }else{%>
                    <option class="inpuedi" value="" selected="selected"> </option>
                <%  }%>
            </select>
             - <%=GestorIdioma.getCadena("IDENCAJA")%>:
            <input type="text" class="inpuedi" name="txtsssiidenti<%=j%>" size="30" value="<%=Utilidades.formateaNumCaja(Utilidades.dameElemHashtable(h,"txtsssiidenti" + j),0,true, "mostrar")%>" maxlength="15"  onblur="javascript:formateaUI(this,'<%=GestorIdioma.getCadena("FORMATOUI")%>');" <%=soloLectura%>/>

<%if(!Utilidades.dameElemHashtable(h,"EXPURGO").equals("S") && !Utilidades.dameElemHashtable(h,"TRANSFERENCIA").equals("S")){%>
            <input type="button" name="btnBorrar" class="boton" value="<%=GestorIdioma.getCadena("BORRAR")%>" onclick="javascript:BorraDatos('<%=j%>');"/>
<%}%>

<tr id="iden<%=j%>">

            <%=GestorIdioma.getCadena("IDENEXPUI")%>:
            <input type="text" class="inpuedi" name="txtsssiexpide<%=j%>" size="10" value="<%=Utilidades.dameElemHashtable(h,"txtsssiexpide" + j)%>" maxlength="3"  onKeyPress="javascript:funValidarNumero();" onblur="javascript:formateaNumero(this);" <%=soloLectura%> />

<tr id="deposito<%=j%>">
<input type="hidden" name="txtissicodrsg<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"txtissicodrsg" + j)%>"/>
<input type="hidden" name="mastamdep<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"mastamdep" + j)%>"/>
<input type="hidden" name="masgesaut<%=j%>" value="<%=Utilidades.dameElemHashtable(h,"masgesaut" + j)%>"/>

    <%=GestorIdioma.getCadena("DEPOSITO")%>:
    <input type="text" class="inpuedi" name="masDBreve<%=j%>" size="30" value="<%=encodeHTML(Utilidades.dameElemHashtable(h,"masDBreve" + j))%>" readonly="readonly"/>
    <input type="text" class="inpuedi" name="masDDescri<%=j%>" size="40" value="<%=encodeHTML(Utilidades.dameElemHashtable(h,"masDDescri" + j))%>" readonly="readonly"/>
<%if(!Utilidades.dameElemHashtable(h,"EXPURGO").equals("S") && !Utilidades.dameElemHashtable(h,"TRANSFERENCIA").equals("S")){%>
    <input type="button" name="btnCodClas" class="boton" value="..." onclick="javascript:SelDepconEspacio('DISPONIBILIDAD',document.frmDatos.txtissicodrsg<%=j%>.value,'<%=j%>')" />
    <input type="button" name="btnCodClasT" class="boton" value="<%=GestorIdioma.getCadena("TODOS")%>" onclick="javascript:SeleccionarComponente('DISPONIBILIDAD',document.frmDatos.txtissicodrsg<%=j%>.value,'<%=j%>')"/>
<%}%>

<tr id="idendeposito<%=j%>">

            <%=GestorIdioma.getCadena("CODUBICACION")%>:
                        <input type="text" class="inpuedi" name="txtsnsirsgide<%=j%>" size="30" value="<%=Utilidades.dameElemHashtable(h,"txtsnsirsgide" + j)%>" <%=soloLectura%>/>

<tr id="obser<%=j%>">

            <%=GestorIdioma.getCadena("OBSERVACIONES")%>:

                        <textarea  name="txtsnsiobserv<%=j%>" rows="4" cols="65"  <%=soloLectura%> ><%=Utilidades.dameElemHashtable(h,"txtsnsiobserv" + j)%></textarea>

            <%=GestorIdioma.getCadena("SIGNATURA")%>   *<%=GestorIdioma.getCadena("DATOSEUSKERA")%>

            <%=GestorIdioma.getCadena("OBSERVACIONES")%>:

                        <textarea  name="txtsnsiobserv<%=j%>_e" rows="4" cols="65" <%=soloLectura%> ><%=Utilidades.dameElemHashtable(h,"txtsnsiobserv" + j+"_e")%></textarea>

<%}%>

                <%if(!Utilidades.dameElemHashtable(h,"EXPURGO").equals("S") && !Utilidades.dameElemHashtable(h,"TRANSFERENCIA").equals("S")){%>

<%@ include file="../includeJSP/OpcionesMant.inc" %>
<%}%>
</form>

A: Finally i found a solution
   window.onload = function(e){
<%if(!faltanCampos.equals("")){%>alert("<%=faltanCampos%>")<%}%>
    //Ocultamos los vacios'
    var j, nombre
    i=<%=totalSig%>
    for (j=i-1;j > 0;j--){
        nombre="txtissicodtui" + j
        if ( document.getElementsByName(nombre)[0].value == ""){
            menos();
        }
    }
    actualizaNivel();
}


text:
Q: Bash sha256 not matching erlang one Erlang returns me a different result than the bash command when I "sha256".
echo a | sha256sum, returns: 87428fc522803d31065e7bce3cf03fe475096631e5e07bbd7a0fde60c4cf25c7  -

Erlang
    Bin = crypto:hash(sha256, "a").

<<202,151,129,18,202,27,189,202,250,194,49,179,154,35,220,
      77,167,134,239,248,20,124,78,114,185,128,119,133,175,
      238,72,187>>

I tried different bin to hex from bin to hex
None of them gave the result I was expecting.
I got this as a result:
    bin_to_hex:bin_to_hex(Bin).
<<"CA978112CA1BBDCAFAC231B39A23DC4DA786EFF8147C4E72B9807785AFEE48BB">>

A: Your echo a will include a newline. When I add a newline to the erlang version, I get the expected hash:
1> Bin = crypto:hash(sha256, "a\n").
<<135,66,143,197,34,128,61,49,6,94,123,206,60,240,63,228,
  117,9,102,49,229,224,123,189,122,15,222,96,196,...>>
2> binary:encode_hex(Bin).
<<"87428FC522803D31065E7BCE3CF03FE475096631E5E07BBD7A0FDE60C4CF25C7">>

You can also tell echo not to use a newline with -n:
$ echo -n a | sha256sum
ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb  -


text:
Q: TFS 2012 rolling build builds earlier than defined If have set TFS 2012 to Rolling builds and defined 15 minutes as the minimum time between builds.
Now I see the following:
Build started 10:34:48, completed 10:39:49
Build started 10:46:53, completed 10:47:01 (fast, because it failed)
The time between those build is only 12 minutes, not 15, why?

A: Apply the latest update (Update 3) to your TFS 2012 installation.  Update 4 was also just released.  I haven't seen if there are any fixes related.
I'm glad that it helped.
Thanks,
Mike


text:
Q: How to restart merge for a "pull --rebase" conflict I am working on a Git plug-in based on JGit from the Eclipse Foundation, and I already had "Restart merge" implemented by a colleague for when conflicts occurred while trying to execute the default pull (with merge).
Now I am working on a "Pull (rebase)" action. When conflicts happen and the user makes some changes inside the conflicting file, I would like to let them be able restart the merge. I've noticed that some Git clients don't have this option (EGit for Eclipse, GitKraken Free), while some have it (SourceTree).
My current code looks like this:
public void restartMerge() {
    try {
      RepositoryState repositoryState = getRepository().getRepositoryState();
      String revision = repositoryState == RepositoryState.REBASING_MERGE ? "HEAD" : "MERGE_HEAD";
      AnyObjectId commitToMerge = getRepository().resolve(revision);
      git.clean().call();
      git.reset().setMode(ResetType.HARD).call();

      if (repositoryState == RepositoryState.REBASING_MERGE) {
        // TODO: regenerate the conflict
      } else {
        git.merge().include(commitToMerge).setStrategy(MergeStrategy.RECURSIVE).call();
      }

      fireFileStateChanged(new ChangeEvent(GitCommand.MERGE_RESTART, Collections.<String> emptyList()));
    } catch (IOException | NoRepositorySelected | GitAPIException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e, e);
        }
    }
}

I think I have to do a rebase again, or something like that, to re-generate the conflict, just as my colleague did a new merge(). But at this point I am on a detached HEAD... I tried moving to the master branch and rebasing again having origin/master as the upstream, but it didn't work...
What would the Git commands be for restarting a rebase conflict? Perhaps I can execute them using JGit...

A: You can try to run git rebase --abort, and restart your rebase using git pull --rebase in your case.

A: As you've seen, git pull is basically:

*

*run git fetch

*then run a second Git command, usually but not always git merge
The merge can stop with conflicts.  You can either allow the user to fix the conflicts and resume, or abort the merge and put everything back to the way it was before the merge started:

*

*To allow the user to resume after manually fixing conflicts, you simply invoke either git merge --continue or git commit: the git merge --continue itself verifies that there's an in-progress merge in which the conflicts are fixed, and then invokes git commit.

*To abort and put things back the way they were after the fetch but before the merge, you can use git merge --abort or git reset --merge (these do the same thing).

The second command, though, can be git rebase, which can also stop with conflicts.  It can even be git read-tree, in some corner cases.  Because you have so little control when using git pull, I'd recommend never using it programmatically: if you're writing code that runs Git commands, always split up your operation into git fetch and your own programmatically-chosen second Git command, so that you know what second command you run.
The problem with rebase, though, is that it is essentially built out of a series of git cherry-pick operations.  (Depending on how you invoke git rebase, this may actually be git apply --3way rather than git cherry-pick, or it may literally run git cherry-pick.)  Each cherry-pick operations can stop with a merge conflict.  So you don't just have one conflict, but M conflicts, M ≤ N, where N is the number of commits being copied into their new position by the rebase.
To resume rebasing after the user fixes up conflicts, invoke git rebase --continue.  This verifies that there's an ongoing rebase and that the conflicts are fixed, and commits them and moves on to the next cherry-pick operation.  The rebasing continues until it either hits another merge conflict, or has completed all cherry-picks; after completing the last cherry-pick, the rebase reassigns the branch name's value to the last-copied commit, and re-attaches HEAD to the branch name.
If you use git rebase --abort, you tell Git to stop the cherry-picking operations (including all the ones not yet started) and go back to the state you were in before any of them started.  If you allow users to resolve merge conflicts, note that this discards all the resolved-so-far cherry-picks, including all the work the user did to resolve conflicts.  If the user has enabled git rerere, the resolved-so-far merges' results are recorded in the re-use cache, so this is not always too terrible.
There are no great solutions to merge conflicts.  If there were a way to automate this reliably, Git would already do it.


text:
Q: Cannot change the style of the selected item in a ListBox I´m trying to change the focused/selected item of a ListBox. My application is based on this article.
At the moment I´m trying to set the ListBoxItem style via data templates:
    <DataTemplate x:Key="ItemTemplate">
        <TextBlock Text="{Binding}"
                   Foreground="Black"
                   FontFamily="Segoe UI"
                   FontSize="22"
                   HorizontalAlignment="Left"
                   Padding="15,10,0,0"
                   />
    </DataTemplate>

    <DataTemplate x:Key="SelectedTemplate">
        <TextBlock Text="{Binding}"
                   Foreground="Red"
                   FontFamily="Segoe UI"
                   FontSize="30"
                   HorizontalAlignment="Left"
                   Padding="15,10,0,0"
                   />
    </DataTemplate>

My idea was to switch between those templates using a trigger:
<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
        <Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" />
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" />
            </Trigger>
        </Style.Triggers>
    </Style>

The ListBox looks like this:
<ListBox x:Name="valuesItemsCtrl"
         BorderThickness="0"
         ItemContainerStyle="{StaticResource ContainerStyle}"
         Background="Transparent"
         Tag="{Binding }">
    <ListBox.AlternationCount>
        <Binding>
            <Binding.Path>Values.Count</Binding.Path>
        </Binding>
    </ListBox.AlternationCount>
        <ListBox.ItemsSource>
            <Binding>
                <Binding.Path>Values</Binding.Path>
            </Binding>
        </ListBox.ItemsSource>
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </ListBox>

At the end I add the template to another ListBox:
<ListBox x:Name="tumblersCtrl"
                 BorderThickness="0"
                 Background="Transparent"
                 ItemsSource="{Binding Tumblers, ElementName=thisCtrl}"
                 ItemTemplate="{StaticResource TumblerTemplate}">
</ListBox>

Thanks for any help or hint!

A: Use ItemTemplate and data triggers:
<ListBox ItemsSource="{Binding}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="IsSelected" Value="{Binding IsSelected}"/>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"
                       Foreground="Black"
                       FontFamily="Segoe UI"
                       FontSize="22"
                       HorizontalAlignment="Left"
                       Padding="15,10,0,0"
                       x:Name="tbName"/>
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding IsSelected}" Value="True">
                    <Setter TargetName="tbName" Property="Foreground" Value="Red"/>
                    <Setter TargetName="tbName" Property="FontSize" Value="30"/>
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

where bound data is a collection of:
public class ViewModel : ViewModelBase
{
    public String Name
    {
        get { return name; }
        set
        {
            if (name != value)
            {
                name = value;
                OnPropertyChanged("Name");
            }
        }
    }
    private String name;

    public Boolean IsSelected
    {
        get { return isSelected; }
        set
        {
            if (isSelected != value)
            {
                isSelected = value;
                OnPropertyChanged("IsSelected");
            }
        }
    }
    private Boolean isSelected;
}

Window code-behind:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new[]
        {
            new ViewModel { Name = "John", IsSelected = true },
            new ViewModel { Name = "Mary" },
            new ViewModel { Name = "Pater" },
            new ViewModel { Name = "Jane" },
            new ViewModel { Name = "James" },
        };
    }
}

A: If you want to change the templates use DataTemplateSelector.
Dismiss your ContainerStyle and instead set the ListBox.ItemsTemplateSelector to your custom datatemplateselector as static resource.
You can find a detailed example in this link.
EDIT :
According to your comment you don't need DataTemplate just set these two properties in the Trigger:
<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
    <Setter Property="Foreground" Value="Black" />
    <Setter Property="FontSize" Value="22" />
    <Setter Property="FontFamily" Value="Segoe UI" />
    <Setter Property="HorizontalAlignment" Value="Left" />
    <Setter Property="Padding" Value="15,10,0,0" />
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Foreground" Value="Red" />
            <Setter Property="FontSize" Value="30" />
        </Trigger>
    </Style.Triggers>
</Style>


text:
Q: Testing Gradle task that uses javaexec() Suppose I have a custom Gradle task that uses ExecOperations.javaexec() in its code:
public class MyTask extends DefaultTask {
    private final ExecOperations execOps

    @Inject
    public MyTask(ExecOperations execOps) {
       this.execOps = execOps;
    }

    @TaskAction
    public void run() {
        ExecResult result = execOps.javaexec(spec -> {
            // classpath is set to some jar with a main class
            spec.classpath(...);
            spec.args(...);
        });
        // Do more stuff with result
    }
}

The issue I have is that I am not sure how I can create a Spock test fixture for it to validate that the jar is being run with the correct arguments without actually running the jar itself. (The jar makes remote calls, for example, which I want to avoid).
It seems like the only plausible way forward is to potentially find a way to expose the ExecOperations for testing and possibly replace it with a stub, along with turning the Action<JavaExecSpec> from a mere lambda to something more substantial. Any ideas would be appreciated.


text:
Q: UIImage gets clipped when using UiTapGesturerecognizer I am using the code below to display my image in full screen when a user taps on the image. This image is inside a tableview.
func imageTapped(_ sender: UITapGestureRecognizer) {

    let imageView = self.moreImageView
    let newImageView = UIImageView(image: imageView?.image)
    newImageView.frame = UIScreen.main.bounds
    newImageView.backgroundColor = .black
    //newImageView.sizeToFit()
    newImageView.contentMode = .scaleAspectFill

    newImageView.isUserInteractionEnabled = true
    let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
    newImageView.addGestureRecognizer(tap)
    self.addSubview(newImageView)

}

But when I tap the screen the image renders full screen, but the upper and lower parts of the image always gets clipped. How do I make sure the image resizes and fits in correctly? Thanks

A: You want .scaleAspectFit
Fit will make it fit inside the space (and show the background color on parts that don't fill)


text:
Q: Old missing file in wp-content/uploads/ returns a 500 error, how to catch and redirect? I have a new site running but Google has an old PDF file indexed. The PDF file does not exist at that address on the new site, it's gone completely.
The odd thing to me is instead of the request coming back a 404, it's a 500. For example:
https://example.com/wp-content/uploads/2019/2/obsolete.pdf gives me a 500, but if I remove the dated directories I get a 404. It seems multiple missing directories in the request cause this?
Any advice or references for how a I can redirect to a 404 or the index when I get a 500 error for this type of request?


text:
Q: cloudbuild.yaml build pipeline for python flask app on gcloud compute engine I have a Python Flask app which needs a library which is not preinstalled on Gcloud compute instances libsndfile1 — also why I can't run this through app engine. I have set up a cloud build pipeline so my cloudbuild.yaml triggers every time I push to master on my repository.
Here are my 2 questions:

*

*Where does the cloudbuild.yaml execute it's instructions?

*How do I make the cloudbuild.yaml execute apt-get install libsndfile1 python3 python3-pip and then also execute pip3 install requirements.txt where requirements.txt is a file in the repository that triggers the cloud build?

Disclaimer: I am an ultra-beginner with docker but if you think that docker is the only way to do it then please explain how something like this can be done.

A: If you are interested in App Engine, my recommendation would be to migrate your application to the Google App Engine Flexible environment, where you could choose a Custom runtime for your Flask application. Simply include a step on your Dockerfile to install the required library. It should look similar to this:
FROM python:3.7
WORKDIR /app
COPY . /app
RUN apt-get update &&\
    apt-get install -y libsndfile1
RUN pip install -r requirements.txt
EXPOSE 8080
CMD ["gunicorn", "main:app", "-b", ":8080", "--timeout", "300"]

And within this context you could use Cloud Build to automate your deployments in a fairly easy manner by following the relevant section of the documentation.
Now regarding your questions.
(1) Where does the cloudbuild.yaml execute it's instructions?
Here you can find all the relevant information of how Cloud Build works here and to answer your first question Cloud Build is a separate service and runs each step of the build in a Docker container within Google's Infrastructure.
(2) How do I make the cloudbuild.yaml execute apt-get install libsndfile1 python3 python3-pip and then also execute pip3 install requirements.txt where requirements.txt is a file in the repo that triggers the cloud build.
Please notice that Cloud Build is more oriented to be used with other products like Cloud Run, GKE, Cloud Functions, etc. And the only fairly straightforward that I've seen Cloud Build being used in the context of Compute Engine would be to build VM images using Packer. In which case you'll need to create a custom image with all the dependencies already installed along within your application.
The specifics of the solution will vary depending on the OS of your Compute Engine instance. But you'll basically need to do the following:

*

*Upload a startup script that installs libsndfile1 as well as all the dependencies specified on the requirements.txt file to a bucket in Cloud Storage.

*Take advantage that you can use gcloud to apply a startup script to running instances in a similar fashion to.

gcloud compute instances add-metadata example-instance \
    --metadata startup-script-url=gs://bucket/file

and there is cloud builder for gcloud
3. Build a cloudbuild.yaml file that uses 2. and restart the instance (not recommended if your app is in production since it will cause downtime) in a similar fashion to:
cloudbuild.yaml
steps:
- name: gcr.io/cloud-builders/gcloud
  args: ['compute', 'instances', 'add-metadata', 'example-instance','--metadata startup-script-url=gs://bucket/file']
- name: gcr.io/cloud-builders/gcloud
  args: ['compute', 'instances', 'reset', 'example-instance']

*Give the cloud build service account enough permissions to execute that task (Compute Admin and Storage Admin).

*Run the build.

I shared the previous steps in aims of answering your concrete question but I would insist that my recommendation would be to migrate the app to App Engine Flexible environment with custom runtime as explained before.


text:
Q: nested button inside an image I try to put a regular button inside an image in android XML. How can it be done? I tried something like this:
<ImageView .......
          <Button .... />
</ImageView>

where the dots represent code. Apparently this is not the way because the platform threw an exception.
Can anyone help?

A: Use relative layout to insert button on the image.
your image should be given in background tag of RelativeLayout.
   <RelativeLayout
               android:layout_width="fill_parent"
                android:layout_height="50dp"
                android:background="@drawable/list_nav"

                >

          <Button
            android:layout_width="63dp"
            android:layout_height="36dp"

            android:id="@+id/mapbutton"
            android:layout_marginTop="7dp"
             android:layout_marginLeft="4dp"
            android:layout_alignParentLeft="true"
          />

this Example adds button on left side of the image since i used  layout_alignParentLeft="true"

A: You can use FrameLayout:

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <ImageView  android:id="@+id/myImage"
                android:layout_height="fill_parent"
                android:layout_width="fill_parent"
                android:src="@drawable/icon" />

    <Button     android:id="@+id/myButton"
                android:layout_width="150dip"
                android:layout_height="150dip"
                android:text="My Button"/>
</FrameLayout>

You don't write why you need image and button. Do you know about ImageButton?

A: @Uriel Frankel you may try creating a custom ImageView either.Here is a post regarding Creating Custom ImageView.
Hope it helps.


text:
Q: What are the various files that could have PATH declarations for OS X Terminal in them? So I'm having a path issue on OS X Leopard. It seems OS X is adding other paths that I'm not stating and it's messing with my path priority. I only have a .bash_login file, I don't have a .bashrc or a .profile file. My .bash_login file is as such:
export PATH="/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:$PATH"

When I run export this is the path it returns:
PATH="/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/opt/local/bin:/usr/local/git/bin"

Any ideas on what could be putting /usr/bin in there and how I could get /usr/local/bin to be a higher priority.
I'm tagging this for Rails too because that's what I'm working on right now... it seems the Mac built-in Ruby, Rails, and Gems are taking priority over the one I have installed at /usr/local/bin, figured maybe you fellow Rubyists could help too.

A: It looks like your changes aren't being applied. Note no /usr/local/mysql/bin
Read the bash manpage section on INVOCATION, .bash_login is only read if it is a login shell -- which the terminal shell is not. You need to put it into ~/.bashrc instead. It will be read for logins and non-login shells.

A: Have you looked inside these two directories:
/etc/paths.d/
/etc/manpaths.d

Any paths defined in files in those directories get appended automatically to PATH variable -- I mostly use those two directories to put third-party installed applications in the PATH. Also, do have a look at the man page of path_helper on OS X.
EDIT: Looking at the contents of /etc/profile, I can see that path_helper is executed first. The man page for path_helper says that prior to reading files in /etc/paths.d/ and /etc/manpaths.d/ directories, path_helper reads and sets up the paths defined in the files /etc/paths and /etc/manpaths. A look at /etc/paths reveals this:
$ cat /etc/paths
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin

And, I believe, those account for the half of what you are seeing as set in PATH.

A: You can also put stuff into ~/.MacOSX/Environment.plist, as detailed at https://web.archive.org/web/20150330034300/http://www.astro.washington.edu/users/rowen/AquaEnvVar.html
This will make the Environment Variables available to all applications, not just those started through a terminal (bash) session.
(It seems that there is a better suggestion there now, too)

A: I've also come across an interesting article on Apple's support forums:
.bash_login no longer executed
With that information I found an overlooked blank .bash_profile file that I had that was loading - and killing all of the information I was trying to set in my path.
So I guess it looks like we could have several "correct" answers depending on the situation.

A: Just put in .bashrc or .login and you'll be fine


text:
Q: undefined method `propfind' for ActionDispatch::Routing::Mapper I am trying to implement git push on my rails app and it sends PROPFIND request which rails doesn't seem to validate. When I try:
git push http://localhost:3000/satellite/.git
it gives me:

Started PROPFIND "/satellite/.git/" for 127.0.0.1 at 2015-06-08
  19:20:38 +0530
ActionController::RoutingError (No route matches [PROPFIND]
  "/satellite/.git")

however git clone http://localhost:3000/satellite/.git works just fine. (ie repo exists there.)
If I try to add propfind to my routes.rb file it gives me:

undefined method `propfind' for ActionDispatch::Routing::Mapper

I found this: https://rails.lighthouseapp.com/projects/8994/tickets/5895-allow-mounting-of-rack-apps-that-deal-with-http-extensions
I think after that patch they allowed PROPFIND in ActionDispatch, and in doc they have mentioned propfind as RFC3253 constant.Is there any way I can enable PROPFIND?

A: It would appear that you have to add PROPFIND requests to your routes via a generic matcher, (see this test), so the following should work for you:
resources :git_repos do
  member do
    match '.git' => :your_route, :via => :propfind
  end
end


text:
Q: How to make a graphic line into JFrame? I use Eclipse, and I want make a graphic line into JFrame by following code:
public void Makeline () {
    Graphics g=new Graphics(); // has error
    Graphics2D g2 = (Graphics2D) g;
    g2.draw(new Line2D.Double(0, 0, 20, 20));
}

but give followin error:
Cannot instantiate the type Graphics

A: The solution is to overwrite the paintComponent method, but the JFrame isn't a JComponent, so instead of JFrame, use JPanel and then add the JPanel to the JFrame.
paintComponent(Graphics g) {
    super.paintComponent(g)

    //here goes your code
    Graphics2D g2 = (Graphics2D) g;
    ...
}

A: Graphics is an abstract class, defining the requirements of the overall API.
Painting in Swing is done within the context of the paint chain. This is typically performed within the paintComponent method of components that extend from JComponent
Take a look at Perfoming Custom Painting for more details
You can also use a BufferdImage to generate a Graphics context, but you still need somewhere to draw the image, so it comes down what your are trying to achieve.

A: Graphics is an abstract class. You can't instantiate following way.
 Graphics g=new Graphics();

To access Graphics2D, first you need to override paint(Graphics) method.
@Override
public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
}


text:
Q: Arduino: why does simple include not work Hello in my arduino code i simple want to include another file like this:
#include "letters.h"

but it says
 error: letters.h: No such file or directory

the letters.h is definitely there, right next to the ino file from which i compile.

A: You don't need to include, just call functions from another file. It handles for you.

A: This link talks about how to do it:
http://arduino.cc/en/Guide/Libraries
For me, it was as simple as finding this menu in the editor:

Sketch -> Import Library -> Add Library

A: Try #include <letters.h> with < and > instead of double quotes.
The C++ standard says #include "header" searches the header in the same folder as the .cpp and then in the include paths, while #include <header> only searches the include paths. But the Arduino "language" is not 100% C standards compliant.
If it still doesn't work, it would mean you don't have letters.h in your libraries folder. Either add it there or copy it to your sketch folder (together with all other source files in that library), restart (all instances of) the Arduino IDE and #include "letters.h" (with the double quotes) so it is included from your sketch folder.


text:
Q: Standard node.js metrics? Are there any standard metrics publishing packages for node.js?  I'm not asking about general metrics libraries, but rather packages that produce a specific set of metrics (e.g. http QPS, runtime memory usage, gc stats, etc...)
If you wanted to offer a monitoring service for node.js users, what would you monitor?

A: I believe that Node Application Metrics ('appmetrics') provides what your looking for. This is a module that provides a set of metrics about a running Node.js process, rather than a monitoring solution in itself.
In version 1.0.2 is provides the following data types:

*

*Environment

*CPU

*Memory

*GC

*Function profiling

*HTTP

*MySQL

*MongoDB

*Request tracking

*Function trace

A: I'm not aware of any package that provides all of that metrics but you can collect most using very popular libraries like pidusage for process related metrics, mongodb driver to retrieve mongo stats, etc
You may read here (my post, bullet 12) about memory profiling


text:
Q: Solving for solutions to a congruence I am interested in solutions to this congruence:
$$2^kx \equiv x \bmod m$$
Where $m$ and $x$ are known positive integers. They may not necessarily be prime or coprime. I am looking for solutions for $k$. How can I do this?

A: Let $\,\ d = (M,X),\,\ m = M/d,\,\ x = X/d.\ $ Then
$\quad M\mid X(2^k\!-1)\!\!\overset{\ \div\,d}\iff m\mid x(2^k\!-1)\overset{(m,x)\,=\,1}\iff m\mid 2^k\!-1\iff {\rm ord}_m(2)\mid k$


text:
Q: EF Migrations error: could not load type 'System.Data.Entity.Infrastructure.DbContextInfo' I am using ContosoUniversity example. I have just used Nuget to download and install code first migrations pakage. Whe I excecute update-database command it throws an error . Is there anything to do more than installing nuget package?
Update-Database : Could not load type 'System.Data.Entity.Infrastructure.DbContextInfo' from assembly 'EntityFramework, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
At line:1 char:16
+ update-database <<<<
    + CategoryInfo          : NotSpecified: (:) [Update-Database], TypeLoadException
    + FullyQualifiedErrorId : System.TypeLoadException,System.Data.Entity.Migrations.Commands.MigrateCommand

Edit ,
Now I have installed ADO.NET Entity Framework 4.1 - Update 1  and now it throws an error
Update-Database : The project 'ContosoUniversity' does not contain or reference any contexts.
At line:1 char:16
+ update-database <<<<
    + CategoryInfo          : NotSpecified: (:) [Update-Database], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,System.Data.Entity.Migrations.Commands.MigrateCommand

I have tried the scenario in microsoft blog  but nothing changed. ( http://blogs.msdn.com/b/adonet/archive/2011/07/27/code-first-migrations-august-2011-ctp-released.aspx )

A: Try installing the msi.
http://www.microsoft.com/download/en/details.aspx?id=26825
The second error that you are getting sounds like it s having problems identifying a context within your project. Make sure that you have a class that inherits from DbContext.
I would also check that your project is referencing the correct version of the Entity Framework - 4.1 Update 1. Depending on the project type, you should be able to locate the reference in question within the References folder within your project. You may need to click on the 'Show All Files' button (second from the left in the toolbar at the top of the Solution Explorer).
Once you have the reference selected, you will see information such as the path of the DLL and its version in the Properties pane (F4 if it is not already visible).
Edit: According to JTew below, a restart of Visual Studio is required.

A: Had the same error.
I had:

*

*Installed EF 4.1 (the older version) via an .msi

*Installed the newer version (EF 4.1 Update 1 Migrations Alpha 3) via NuGet

This error turned out to be the framework complaining because it was getting the older 4.1.0.0 from the GAC.
Uninstalling the older EF 4.1 did the trick.


text:
Q: Street starting and ending point - lan/lat I searched for this one for quite some time:
I want to when having a lan/lat of the "start" of the street, get the lan/lat of the "end" of the street, is that possible using the Android location API?  or even using the Google Maps API?
And another connected question is:
Can i get the above info when having a lan/lat of a point on the street(not the "start/end" of the street)?


text:
Q: Preg replace deprecated, attempting to fix I've just upgraded to PHP 7 and have been hammering out errors associated with deprecated functions, with much success.
Sadly, I've been having trouble fixing the new preg replace methodology for my "view php array in a interactive collapsable javascript thing" code.
The following code:
function print_r_tree($data)
{

// capture the output of $this->print_r_tree
   $out = print_r($data, true);

 // replace something like '[element] => <newline> (' with ...

    $out = preg_replace('/([ \t]*)(\[[^\]]+\][ \t]*\=\>[ \t]*[a-z0-9 \t_]+)\n[ \t]*\(/iUe',"'\\1\\2
'", $out);

  // replace ')' on its own on a new line (surrounded by whitespace is ok) with '

     $out = preg_replace('/^\s*\)\s*$/m', '
', $out);

  // print the javascript function toggleDisplay() and then the transformed output
     echo ''."\n$out";

  }

Generates this warning.
Warning:  preg_replace(): The /e modifier is no longer supported, use preg_replace_callback instead
Removing the "e" in the first "preg_replace", breaks the javascript thing. I've tried a few preg_replace_callback things as well.
I've been trying to use this link Replace preg_replace() e modifier with preg_replace_callback to help me understand what's broken, but I think my issue is complicated by the javascript.
I'm hoping someone might be able to walk me through this, with respect to my code?
Thanks in advance.

A: The  e modifier is in your first $out variable. To transform that, you need to use correctly preg_replace_callback():
$out = preg_replace_callback('/([ \t]*)(\[[^\]]+\][ \t]*\=\>[ \t]*[a-z0-9 \t_]+)\n[ \t]*\(/iU', "callbackFunction", $out);

function callbackFunction($matches) {
     return "'".$matches[1]."".$matches[2]."
'";
}

See that in preg_replace_callback we define second parameter with callbackFunction, that string is parsed to call that function and it passes an array with the matches. So the replacements were in callbackFunction() function and the matches are matches[X].
More info:
http://php.net/manual/es/function.preg-replace-callback.php
Good luck!

A: This is the combination of the original with Christian's fix.
function print_r_tree($data)
{
    // capture the output of print_r
    $out = print_r($data, true);

    // replace something like '[element] => <newline> (' with ...

    $out = preg_replace_callback('/([ \t]*)(\[[^\]]+\][ \t]*\=\>[ \t]*[a-z0-9 \t_]+)\n[ \t]*\(/iU', 'print_r_tree_callback', $out);

    // replace ')' on its own on a new line (surrounded by whitespace is ok) with '

    $out = preg_replace('/^\s*\)\s*$/m', '
', $out);

    // print the javascript function toggleDisplay() and then the transformed output
    return ''."\n$out";
}

function print_r_tree_callback($matches) {
    $id = substr(md5(rand().$matches[0]), 0, 7);
    return "$matches[1]$matches[2]
";
}


text:
Q: How to install JHawk(plugin) into Eclipse I need to install JHawk onto my pc so that it works with eclipse. But there does not seem to be a clear way for me to install it. I have no experience in installing plugins to eclipse and I am wondering what im missing.

A: This is what it says in a PDF file found in that Docs directory you have there:

After you have unzipped the JHawk Distribution into a directory you
  will find a sub-folder named "plugins". Close down your Eclipse
  application if it is already running. Copy the jar in the plugins
  directory into the plugins directory of your eclipse folder. Copy the
  jhawk.properties file in the plugins directory to the root directory
  of your Eclipse installation (this is the directory where you find
  eclipse.exe). When you restart Eclipse JHawk will be ready for use.
  The Eclipse plugin has been tested used in Eclipse 4.4 (Luna), 4.5
  (Mars) and 4.6 (Neon) and will probably work in other versions.     As
  part of the distribution you will notice the following properties
  files –

*

*jhawkbase.properties

*jhawkfull.properties

*jhawkbasepluscustom.properties

*reviewfactor.properties
jhawkbase.properties is a version of the properties file with the
  base level set of  metrics that are initially enabled for JHawk. This
  is the same as the jhawk.properties file that comes with the JHawk
  Eclipse plugin distribution.    jhawkfull.properties is a version of
  the properties file with the full set of  metrics available to JHawk
  enabled.     jhawkbasepluscustom.properties is a version of the
  properties file with the base level set of  metrics that are initially
  enabled for JHawk plus the sample metric found in the
  CustomMetrics.jar that comes with the distribution. For more details
  about this metric see the "JHawk5CreateMetric" document.    You can
  use any of these sets of metrics by copying them to the
  jhawk.properties file and starting as normal or by using the –p flag
  and the property file name (JHawk Command Line only).    Properties
  loaded from these files can be amended in the usual way – see
  "Preferences" section in the documentation.
  reviewfactor.properties – this file contains properties used by the
  class and package Review Factor metrics. You can find out more about
  how to use these properties in the "Using the Review Factor Metric"
  section of the JHawk6UsingMetrics document supplied with the
  distribution.

If you actually open the JHawkDemo_6.1.0.jar archive, inside, you'll find JHawkDemo.jar, which seems to be the actual plugin archive. The instructions seem to suggest that you drop that into the plugins folder located immediately within your Eclipse workspace directory. Then launch Eclipse and you should see it work.
Having done exactly that, however, I can see no sign of JHawk within Eclipse (2019-9). Moving the archive to the dropins folder also yields nothing. Help > About Eclipse IDE > Installed Software is supposed to list all the plugins installed, and there's no JHawk. There are no JHawk tabs as indicated, and Help > Preferences shows no sign of JHawk.
The latest version of JHawk is three years out of date, and the doc doesn't seem to correspond well to what's actually on offer. I can't get this plugin to install, but I thought I'd leave this blob of information for the sake of posterity so that I won't feel like I spent 30 min and accomplished nothing.


text:
Q: Index loaded into ui-view in AngularJS with UI-router I am creating a site with AngularJS and everything works fine locally. Everything but this one thing works fine in the deployed version.
At one of the states 'orderinfo', 'index.html' is loaded in the ui-view instead of the partial in the routes.
Do any of you have any idea what might be going on?
// ...
state( 'order', {
            url: '/results/order/:id',
            templateUrl: 'views/order.html',
            controller: 'OrderController as order'
        } )
        .state( 'orderinfo', {
            url: '/results/order/edit/:id/:secret',
            templateUrl: 'views/orderinfo.html',
            controller: 'OrderInfoController as orderInfo'
        } )
        .state( 'orderconfirm', {
            url: '/results/order/confirm/:id/:secret',
            templateUrl: 'views/orderconfirm.html',
            controller: 'OrderConfirmController as orderconfirm'
        } )
// ...

A: The filename was incorrect. It worked on the local development server because it was case insensitive, but not on the deployment server.


text:
Q: Why my s3 life cycle rule not take effect or not working I configured the life cycle rule on the s3 console, transition to Intelligent-Tiering after 0 days, applied to whole bucket, However, ten days have passed and the document is still standard storage class.
I don't know where my configuration is wrong,or where can I see life cycle rule execution log.


text:
Q: Do I understand Ajax correctly? I'm been reading up on Ajax and would like to see from the stackoverflow community if I'm understanding everything correctly.
So the normal client server interaction is a user pulls up a web browser types in a url and a HTTP request is sent to the server requesting the page and resources( css, pics ) from the web server. The web server responds to the client via HTTP the page/resources requested and the browser renders the html/JavaScript for the user to view the page.
1) So would it be safe to say that XMLHttpRequest( XHR ) object is doing the same process as the browser except your not requesting html from the server, your requesting text in some type of format?
2) Is it true that a XHR object is much like a regular object that can be manipulated by the program creating the object( like a normal object ), but also sends and receives data with another program( web server ) via HTTP?
3) So in my mind when a XHR is created it is loaded into memory and we setup some of the objects arguments when we do the request.open("GET", url, true). Once we do  a request.send(null) the object basically attempts to "GET" the url via HTTP and once we get the data back from the server it is put in the responseText argument. Am I understanding this correctly?
4) Also synchronous vs asynchronous. When I think of synchronous I think of steps having to be followed in order. For example, I push a button, data gets sent to server, and I have to wait for data to come back before I can do anything else. With asynchronous connections I would push button, data gets sent to server, I do what ever I want while data gets sent back. Is this a good analogy?

A: 1) Nope. The XMLHttpRequest object does exactly what its name implies -- it initiates an HTTP request. This request can be in XML, or HTML, or PHP. At the end of the day, the browser doesn't care, because in an AJAX request, it doesn't parse the request -- you have to do it yourself. So it doesn't automatically render the HTML from an AJAX request.
2) I'm not sure about manipulation (the XHR object may be immutable) but possibly. Would you ever need to extend it or manipulate it?
Yes, you can change properties of the object and so on. I apologize. I didn't understand you at first :)
3) Yep.
4) That's a great analogy. It's exactly what happens. Another analogy is a 4 lane highway is to asynchronous as a one-way street is to synchronous. If one car breaks down on the 4 lane highway, the rest can keep moving at their normal speed -- but if one breaks down on the one-way road, everything freezes. :)

A: Here I leave you a good graphic to see clearly the behavior differences between the synchronous and asynchronous application models:

(source: adaptivepath.com)

A: It would appear that you have a job grasp of how AJAX works. I can't see much to disagree with in your summary of the plumbing of an AJAX application.
I would say however that with the XMLHttpRequest object you aren't restricted to GET. You can also use POST and other HTTP verbs.
With async calls you register a callback function, the XMLHttpRequest object calls your method when the async request completes.

A: Seems ok to me.
Your first point though is not entirely correct, you can request html from the server using ajax is doesn't have to text, json or xml like most examples show.


text:
Q: Hot reload not working in VUE3 and tailwind Hot reload is not working in Vue3 and tailwind application.
If I am changing the code(using vscode editor) and respective data is not changed in the browser. I need to logout and login again to see the new changes.
My package.json
"vue": "^3.0.0"
"@vue/cli-service": "~4.5.0",
"tailwindcss": "npm:@tailwindcss/postcss7-compat@^2.1.2"

Please help me how to fix this issue.
Thanks in advance


text:
Q: How to query a TempView in Databricks I have create a tempview as such as:
df.createOrReplaceTempView("table_test")

However, when I run the following command it doesn't work
%sql select top 10 * from table_test;

A: Try the following
%sql select * from table_test limit 10;

top 10 is more specific to sql server and not the sql engine being used by your notebooks.