text:
Q: Document transformation based type Lets say I have a mongodb document
{
  "id" : 1,
  "types" : ["online" ,"offline"],
  "applications" : [ ["online", "online"], ["offline"] ]
}

I would like to transformed into
{
"id" : 1,
"types" : [
        {
          "type" : "online",
          "count" : 2,
          "applications" : [ "online", "online"]
        },
        {
          "type" : "offline",
          "count" : 1,
          "applications" : [ "offline" ]
        }
    ]
}

here types and applications arrays can be of any size.

A: You can do that in two steps, use $map with $filter to match type with applications and then run $reduce to get count:
db.collection.aggregate([
    {
        $project: {
            id: 1,
            types: {
                $map: {
                    input: "$types",
                    as: "type",
                    in: {
                        type: "$$type",
                        applications: {
                            $filter: {
                                input: "$applications",
                                as: "application",
                                cond: {
                                    $allElementsTrue: {
                                        $map: { input: "$$application", in: { $eq: [ "$$this", "$$type" ] } }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    {
        $addFields: {
            types: {
                $map: {
                    input: "$types",
                    in: {
                        $mergeObjects: [
                            "$$this",
                            {
                                count: {
                                    $reduce: {
                                        input: "$$this.applications",
                                        initialValue: 0,
                                        in: { $add: [ "$$value", { $size: "$$this" }  ] }
                                    }
                                }
                            }
                        ]
                    }
                }
            }
        }
    }
])

You can decide whether it's better to use $allElementsTrue or $anyElementTrue when building your filtering criteria.
Mongo Playground


text:
Q: Remove a procedure that's been hacked for elevated rights So I needed to migrate a database but kept getting FK constraint issues, when there shouldn't have been any. Tried to turn off the FK checking, discovered a lack of SUPER privileges. Created a Procedure to change the privilege:
set Global foreign_key_checks=0;
Saved it then modified the definer for it to the rdsadmin user to grant it the rights. It executed fine and did what it was supposed to do. Now I need to switch it back on:
set Global foreign_key_checks=1;
And remove the procedure. I thought I'd use the same technique; just change the definer back to another user, and drop procedure. This does not work:
'CANNOT MODIFY RDSDMIN OBJECT' in 'field list'
Thought about creating a second procedure to remove the right and switch the param, then drop itself , works in MS SQL but not in Oracle apparently.
I'm kind of at a loss on how to do this, any ideas?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reflexive sheaves on stable curves Let $C$ be a stable curve over an algebraically closed field of positive characteristic and $\mathcal{F}$ be a reflexive sheaf on $C$. Is $\mathcal{F}$ locally free?
EDIT Is the projective dimension of $\mathcal{F}$  less than or equal to $1$?

A: Equivalently: is every f.g. reflexive module $M$ over  $R=k[[x,y]]/(xy)$ projective? The answer is no: let $M = R/xR$, then ${\rm Hom}_R(M, R) = \{f\in R\,:xf=0\} = yR \cong M$. Thus $M$ is reflexive, but is not projective.


text:
Q: How to upload image to an Amazon S3 bucket using React js? I am a newbie on Amazon S3. I am facing the issue regarding uploading the image directly from frontend to an Amazon S3 bucket. I viewed many tutorials but there is no proper explanation about uploading image directly to s3. Need a solution to it using React js only.

A: One solution is to import the AWS SDK for JavaScript v3 into your React app and then use the s3Client within your React app. There are instructions on how to use this SDK in a React app here:
Getting started in React Native
Here is more content that shows HOW TO use the AWS SDK for JavaScript in a React App:
Integrate the AWS SDK for JavaScript into a React App
To upload an object to an Amazon S3 bucket using the s3Client, use this code example:
// Import required AWS SDK clients and commands for Node.js.
import { PutObjectCommand } from "@aws-sdk/client-s3";
import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module.

// Set the parameters.
export const bucketParams = {
  Bucket: "BUCKET_NAME",
  // Specify the name of the new object. For example, 'index.html'.
  // To create a directory for the object, use '/'. For example, 'myApp/package.json'.
  Key: "OBJECT_NAME",
  // Content of the new object.
  Body: "BODY",
};

// Create and upload the object to the S3 bucket.
export const run = async () => {
  try {
    const data = await s3Client.send(new PutObjectCommand(bucketParams));
    return data; // For unit tests.
    console.log(
      "Successfully uploaded object: " +
        bucketParams.Bucket +
        "/" +
        bucketParams.Key
    );
  } catch (err) {
    console.log("Error", err);
  }
};
run();

You can view more Amazon S3 code examples for the the s3Client in the AWS Github repo:
Amazon S3 JavaScript SDK v3 code examples


text:
Q: Subversion Server Using Active Directory error I am using apache subversion running on linux 7. from front end i am using tortoise svn. I am trying to integrate my subversion with current AD. For which i have opened /etc/httpd/conf.d directory and given below details in subversion.conf file. Details are mentioned below
<location /svn>
DAV svn
SVNParentPath /u01/ciroot/subversion
AuthType Basic
AuthBasicProvider ldap
AuthName "Root Repo"
AuthLDAPURL "ldap://100.100.10.2:388/DC=macgroup,DC=local?sAMAccountName?sub?(&(ObjectClass=*)memberOf=CN=OBIEE_Admin,OU=OBIEE,OU=Security,OU=Groups,OU=Global Resources,DC=MACGROUP,DC=LOCAL))"
AuthLDAPBindDN "CN=oidkerbt,OU=Service Accounts,OU=Users,OU=Global Resources,DC=MACGROUP,DC=LOCAL"
AuthLDAPBindPassword welcome123@
Require valid-user
</location>

With above conf file details, when i am trying open the folders under /u01/ciroot/subversion, i am prompting the user password dialog box but when giving correct user of this group, it is not authenticating and giving below error

Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log.

But when i am editing this file as below then it is working fine.
<location /svn>
DAV svn
SVNParentPath /u01/ciroot/subversion
AuthType Basic
AuthBasicProvider ldap
AuthName "Root Repo"
AuthLDAPURL "ldap://100.100.10.2:388/DC=macgroup,DC=local?sAMAccountName?sub?(&(ObjectClass=*))"
AuthLDAPBindDN "CN=oidkerbt,OU=Service Accounts,OU=Users,OU=Global Resources,DC=MACGROUP,DC=LOCAL"
AuthLDAPBindPassword welcome123@
Require valid-user
</location>

Can someone please help me where i am getting wrong when adding group it is failing.
Regards

A: There is a parenthesis missing in the LDAP filter. Each attr=value pair needs to be enclosed in parenthesis. The string should read:
"ldap://100.100.10.2:388/DC=macgroup,DC=local?sAMAccountName?sub?(&(ObjectClass=*)(memberOf=CN=OBIEE_Admin,OU=OBIEE,OU=Security,OU=Groups,OU=Global Resources,DC=MACGROUP,DC=LOCAL))" None

Replacing the "None" with "STARTTLS" if you want to encrypt the communication after connection. I generally start with clear text & get everything else sorted before moving over to an encrypted connection. Then any failure can be isolated to certificate/trust issues.
I would expect the clear text LDAP port to be 389 ... but if authentication is working without the filter, then there must be an unusual port mapping / port bound to the directory service.
If authentication still fails, you might try capturing the network traffic to your LDAP server on the specified port. This will show you the exact LDAP query that is being made and the response from the directory server.


text:
Q: Matplotlib basemap polygon throws an error but succeeds if something is plotted I've been using basemap with matplotlib in python for quite a while now but was building up a new piece of code and came across this really strange anomaly and I don't know how to get round it.
If I have a polygon that I want to plot in matplotlib using (lonList,latList) the show command will throw an error when plotting the polygon with an allocation error. Or on another machine I've seen that it will plot a blank screen.
However if I use the same list and add a scatter plot (commented line below) it will work. Also if I plot a line or scatter plot on its own it will work, but plotting the polygon patch on its own fails. I have no clue why this is and cannot find any bug report on it. Please help?
By the way I'm running Debian Jessie 8 with python 2.7 if that helps.
#!/usr/bin/env python

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.collections    import PatchCollection
from matplotlib.patches        import Polygon

def singlePatchExample():
  patches = []
  fig = plt.figure(figsize=(19.2,10.8))
  ax  = plt.subplot(111)

  lonSW = -8.0
  latSW = 51.0
  lonNE = -6.0
  latNE = 53.0
  centLon = ( lonSW + lonNE ) / 2.0
  centLat = ( latSW + latNE ) / 2.0

  baseMap = Basemap(llcrnrlon=lonSW,llcrnrlat=latSW,urcrnrlon=lonNE,urcrnrlat=latNE,\
                resolution='i', lat_0 = centLon, lon_0 = centLat)

  longList = [ -7.0, -7.5, -7.7 ]
  latList  = [ 51.5, 52.0, 52.5 ]

  x, y    = baseMap( longList, latList )
  polygon = Polygon(zip(x,y), True )
  patches.append(polygon)

  patchInSingleImage = PatchCollection(patches, alpha=0.2)
  ax.add_collection(patchInSingleImage)
  ax.set_title("Single Patch Example, (without points????)")

  #baseMap.scatter( x, y, color='r' )

  plt.show()

singlePatchExample()

A: When running the code I get a figure with axes but no polygon being shown. This should actually be the same with and without basemap. The reason is that matplotlib does not autoscale when the only artist inside an axes is a PatchCollection (or probably just any collection).
The solution in such cases would be to add
ax.autoscale()

after adding the collection.
The main point is that since there isn't actually anything on the map, the scaling needs to be taken over by the matplotlib axes. You can make sure the map is actually being connected to the axes by drawing something unneeded with zero linewidth to the map.
baseMap.drawrivers(linewidth=0)

This would make ax.autoscale() superfluous and will scale the map just as if it had a some data on it. Equally, drawing parallels or meridians would have the same effect - just anything that would actually draw the map to the axes.
baseMap.drawparallels(latList)


text:
Q: Phase 3 Binary Bomb Assembly I am having major difficulty disassembling this code. I understand the function calls for 3 inputs, 1 decimal and 2 characters. I have concluded that the decimal is 7, though I am not entirely sure this is correct. I know that I have to use a jump table somewhere, i believe it's at 0x08048d50, again I would like some verification and correction, but I am not sure how to type in the command?
Dump of assembler code for function phase_3:
0x08048cfa <+0>:    push   %ebp
0x08048cfb <+1>:    mov    %esp,%ebp
0x08048cfd <+3>:    sub    $0x38,%esp
=>  0x08048d00 <+6>:    movl   $0x0,-0xc(%ebp)
0x08048d07 <+13>:   lea    -0x12(%ebp),%eax
0x08048d0a <+16>:   mov    %eax,0x10(%esp)
0x08048d0e <+20>:   lea    -0x13(%ebp),%eax
0x08048d11 <+23>:   mov    %eax,0xc(%esp)
0x08048d15 <+27>:   lea    -0x10(%ebp),%eax
0x08048d18 <+30>:   mov    %eax,0x8(%esp)
0x08048d1c <+34>:   movl   $0x804a7ff,0x4(%esp)
0x08048d24 <+42>:   mov    0x8(%ebp),%eax
0x08048d27 <+45>:   mov    %eax,(%esp)
0x08048d2a <+48>:   call   0x8048960 <__isoc99_sscanf@plt>
0x08048d2f <+53>:   mov    %eax,-0xc(%ebp)
0x08048d32 <+56>:   cmpl   $0x2,-0xc(%ebp)
0x08048d36 <+60>:   jg     0x8048d3d <phase_3+67>
0x08048d38 <+62>:   call   0x8049675 <explode_bomb>
0x08048d3d <+67>:   mov    -0x10(%ebp),%eax
0x08048d40 <+70>:   cmp    $0x7,%eax
0x08048d43 <+73>:   ja     0x8048e56 <phase_3+348>
0x08048d49 <+79>:   mov    0x804a808(,%eax,4),%eax
0x08048d50 <+86>:   jmp    *%eax
0x08048d52 <+88>:   movb   $0x6d,-0x11(%ebp)
0x08048d56 <+92>:   movzbl -0x12(%ebp),%eax
0x08048d5a <+96>:   movsbl %al,%eax
0x08048d5d <+99>:   lea    0x20(%eax),%edx
0x08048d60 <+102>:  movsbl -0x11(%ebp),%eax
0x08048d64 <+106>:  cmp    %eax,%edx
0x08048d66 <+108>:  je     0x8048e61 <phase_3+359>
0x08048d6c <+114>:  call   0x8049675 <explode_bomb>
0x08048d71 <+119>:  jmp    0x8048e61 <phase_3+359>
0x08048d76 <+124>:  movb   $0x68,-0x11(%ebp)
0x08048d7a <+128>:  movzbl -0x12(%ebp),%eax
0x08048d7e <+132>:  movsbl %al,%eax
0x08048d81 <+135>:  lea    0x20(%eax),%edx
0x08048d84 <+138>:  movsbl -0x11(%ebp),%eax
---Type <return> to continue, or q <return> to quit---
0x08048d88 <+142>:  cmp    %eax,%edx
0x08048d8a <+144>:  je     0x8048e64 <phase_3+362>
0x08048d90 <+150>:  call   0x8049675 <explode_bomb>
0x08048d95 <+155>:  jmp    0x8048e64 <phase_3+362>
0x08048d9a <+160>:  movb   $0x63,-0x11(%ebp)
0x08048d9e <+164>:  movzbl -0x12(%ebp),%eax
0x08048da2 <+168>:  movsbl %al,%eax
0x08048da5 <+171>:  lea    0x20(%eax),%edx
0x08048da8 <+174>:  movsbl -0x11(%ebp),%eax
0x08048dac <+178>:  cmp    %eax,%edx
0x08048dae <+180>:  je     0x8048e67 <phase_3+365>
0x08048db4 <+186>:  call   0x8049675 <explode_bomb>
0x08048db9 <+191>:  jmp    0x8048e67 <phase_3+365>
0x08048dbe <+196>:  movb   $0x6f,-0x11(%ebp)
0x08048dc2 <+200>:  movzbl -0x12(%ebp),%eax
0x08048dc6 <+204>:  movsbl %al,%eax
0x08048dc9 <+207>:  lea    0x20(%eax),%edx
0x08048dcc <+210>:  movsbl -0x11(%ebp),%eax
0x08048dd0 <+214>:  cmp    %eax,%edx
0x08048dd2 <+216>:  je     0x8048e6a <phase_3+368>
0x08048dd8 <+222>:  call   0x8049675 <explode_bomb>
0x08048ddd <+227>:  jmp    0x8048e6a <phase_3+368>
0x08048de2 <+232>:  movb   $0x6d,-0x11(%ebp)
0x08048de6 <+236>:  movzbl -0x12(%ebp),%eax
0x08048dea <+240>:  movsbl %al,%eax
0x08048ded <+243>:  lea    0x20(%eax),%edx
0x08048df0 <+246>:  movsbl -0x11(%ebp),%eax
0x08048df4 <+250>:  cmp    %eax,%edx
0x08048df6 <+252>:  je     0x8048e6d <phase_3+371>
0x08048df8 <+254>:  call   0x8049675 <explode_bomb>
0x08048dfd <+259>:  jmp    0x8048e6d <phase_3+371>
0x08048dff <+261>:  movb   $0x76,-0x11(%ebp)
0x08048e03 <+265>:  movzbl -0x12(%ebp),%eax
0x08048e07 <+269>:  movsbl %al,%eax
0x08048e0a <+272>:  lea    0x20(%eax),%edx
0x08048e0d <+275>:  movsbl -0x11(%ebp),%eax
0x08048e11 <+279>:  cmp    %eax,%edx
0x08048e13 <+281>:  je     0x8048e70 <phase_3+374>
---Type <return> to continue, or q <return> to quit---
0x08048e15 <+283>:  call   0x8049675 <explode_bomb>
0x08048e1a <+288>:  jmp    0x8048e70 <phase_3+374>
0x08048e1c <+290>:  movb   $0x70,-0x11(%ebp)
0x08048e20 <+294>:  movzbl -0x12(%ebp),%eax
0x08048e24 <+298>:  movsbl %al,%eax
0x08048e27 <+301>:  lea    0x20(%eax),%edx
0x08048e2a <+304>:  movsbl -0x11(%ebp),%eax
0x08048e2e <+308>:  cmp    %eax,%edx
0x08048e30 <+310>:  je     0x8048e73 <phase_3+377>
0x08048e32 <+312>:  call   0x8049675 <explode_bomb>
0x08048e37 <+317>:  jmp    0x8048e73 <phase_3+377>
0x08048e39 <+319>:  movb   $0x6f,-0x11(%ebp)
0x08048e3d <+323>:  movzbl -0x12(%ebp),%eax
0x08048e41 <+327>:  movsbl %al,%eax
0x08048e44 <+330>:  lea    0x20(%eax),%edx
0x08048e47 <+333>:  movsbl -0x11(%ebp),%eax
0x08048e4b <+337>:  cmp    %eax,%edx
0x08048e4d <+339>:  je     0x8048e76 <phase_3+380>
0x08048e4f <+341>:  call   0x8049675 <explode_bomb>
0x08048e54 <+346>:  jmp    0x8048e76 <phase_3+380>
0x08048e56 <+348>:  movb   $0x69,-0x11(%ebp)
0x08048e5a <+352>:  call   0x8049675 <explode_bomb>
0x08048e5f <+357>:  jmp    0x8048e77 <phase_3+381>
0x08048e61 <+359>:  nop
0x08048e62 <+360>:  jmp    0x8048e77 <phase_3+381>
0x08048e64 <+362>:  nop
0x08048e65 <+363>:  jmp    0x8048e77 <phase_3+381>
0x08048e67 <+365>:  nop
0x08048e68 <+366>:  jmp    0x8048e77 <phase_3+381>
0x08048e6a <+368>:  nop
0x08048e6b <+369>:  jmp    0x8048e77 <phase_3+381>
0x08048e6d <+371>:  nop
0x08048e6e <+372>:  jmp    0x8048e77 <phase_3+381>
0x08048e70 <+374>:  nop
0x08048e71 <+375>:  jmp    0x8048e77 <phase_3+381>
0x08048e73 <+377>:  nop
0x08048e74 <+378>:  jmp    0x8048e77 <phase_3+381>
0x08048e76 <+380>:  nop

A: 0x08048d49 <+79>:   mov    0x804a808(,%eax,4),%eax

This syntax says: Move 0x804a808+4*%eax into %eax. This should help you to figure out what the jump address in the following line is.


text:
Q: JQuery Auto-Complete: How do I handle modifications? I have auto-complete working, but how do I handle modifications?
What happens when the user modifies the original selection? I've got an auto-complete that, when a listing is chosen, other fields are filled in. If the user chooses a listing, then tries to modify it to something that is new (does not match anything in our DB), the other fields need to be cleared.
Another way of asking: How do I handle 'new' listings?
My code below
$(function() {
    $( "#oName" ).autocomplete({
        source: "include/organizerList.php",
        minLength: 3,
        select: function( event, ui ) {
            $("input#oID").val(ui.item.oID);
            $("input#oCID").val(ui.item.oCID);
            $("div#organCity").text(ui.item.oCity);
            $("div#organCountry").text(ui.item.oCountry);
        }
    });
});

organizerList.php
// important to set header with charset
header('Content-Type: text/html; charset=utf-8');

$term = htmlspecialchars(strtolower($_GET["term"]));

$return = array();
    $query = mssql_query("SELECT CID, oID, oName, oCity, oCountry FROM TradeShowDB_Organizers WHERE oName LIKE '%$term%'");
    while ($row = mssql_fetch_array($query)) {
    array_push($return,array( 'oCID'=>$row['CID'], 'oID'=>$row['oID'], 'label'=>$row['oName'] . ', ' . $row['oCity'], 'value'=>$row['oName'], 'oCity'=>$row['oCity'], 'oCountry'=>$row['oCountry'] ));
}

// encode it to json format
echo(json_encode($return));

My html:
<input type="text" tabindex='20' id="oName" name="oName" size="60" maxlength="200" value="<?php echo $oName; ?>">

<input type="hidden" id="oID" name="oID" value="<?php echo $oID; ?>">
<input type="hidden" id="oCID" name="oCID" value="<?php echo $oCID; ?>">

A: You can use the autocomplete select event http://jqueryui.com/demos/autocomplete/#event-select
Disable the input once the user selects an option
$("#oName").autocomplete({
    source: "include/organizerList.php",
    minLength: 3,
    select: function (event, ui) {
        this.value = ui.item.value;
        $('#autocomplete').autocomplete("disable");
        $('#autocomplete').trigger('keypress'); //needed to fix bug with enter on chrome and IE
        $(this).attr('disabled','disabled');
        return false;
    },
    autoFocus: true
});

http://jsfiddle.net/HKxua/6/
Then in your server side script, you can check the input to see if the value posted exists in the database.


text:
Q: Comparing two arrays and not getting expected output in rails console I have the following controller action that builds two arrays.
current_event = Event.find(params[:event_id])

campaign_titles = Relationship::CampaignTitleRelationship.where(campaign_id: current_event.campaign_id)

campaign_title_ids = Array.new

campaign_titles.each do |title|

  campaign_title_ids << [title.title_id]

end

event_title_ids = Array.new

params[:title_ids].each do |title|

  event_title_ids << [title]

end

The two arrays output like this
[["6556"], ["9359"], ["11319"], ["12952"], ["14389"], ["14955"], ["16823"]]
[[6556], [9359], [11319], [12952], [14389], [14955], [16823]]

I'm trying to compare these two arrays using the - symbol, but am only getting an output of each id, instead of what I expect (nothing) since both arrays contain the same items.
I can see that the first array has quotations around each key inside the bracket.  The second does not.  How do I compare these two arrays?

A: Just add params as integers to your array
params[:title_ids].each do |title|
  event_title_ids << [title.to_i]
end


text:
Q: Возведение в степень(x**n)%m Возведение в степень
По трем натуральным числам x, n и m вычислить значение xn mod m.
Входные данные
Три натуральных числа x, n, m (1 ≤ x, m ≤ 109, 2 ≤ n ≤ 107).
Выходные данные
Вывести xn mod m.
Я сделал вот так:
x,n,m = map(int, input().split())

answer = (x**n)%m

print(answer)

Но не принимает, один тест не проходит, а результаты теста нельзя увидеть, что бы исправить ошибку. ПОмогите, плиз.
Пример:
Вход:  2 3 100
Выход: 8

A: У всем известной функции pow(base, exp, mod) есть малоизвестный третий параметр, который как раз и предназначен для того, чтобы возвращать остаток от деления: base ** exp % mod.
Попробуйте воспользоваться этой функцией:
answer = pow(x, n, m)


text: Q: How can resume a backgroundtask instead of creating a new one? I'm trying to implement a BackgroundAudioTask using this example, but when I close my app while the task is running, and reopen my app, it creates a new task instead of resuming the task that was already running. Because it creates a new one, it also plays 2 songs at once then. What is the best way to check if the task is running and resume the task then?


text:
Q: SQLAlchemy Installation in PyPy I have a database project that could greatly benefit from the speed boost PyPy provides. I have been unable to install one of the core libraries I am using, sqlalchemy, under PyPy, however. I drop it into the Site-Packges directory but then PyPy squawks at me, saying it also needs PyODBC, whose default source code does not include python files, but only .CPP files and headers. Any and all help is greatly appreciated.

A: As far as I know standard pyodbc package currently can not run with PyPy without patches.
However, you can try pypyodbc, which is similar to pyodbc, and it enables running SQLAlchemy under PyPy. This how-to describes the 4 steps to enable it.
Disclaimer: I'm the maintainer of pypyodbc.


text:
Q: SQL Select Statement - Selecting using one column equal to tow variables in the following select statement I want to put two values when
@PAPCOD = 'SIN' = values are 'DD' and 'SD'
and
@PAPCOD = 'ENG' = values are 'DI' and 'SI'
how can i do this. Only I can put one value
SELECT ISNULL((SUM(Con_Amount)),0) +
       (SELECT DISTINCT ISNULL(SUM(Correspondent_Other_Payments.Oth_Pmt_Amount),0)
               FROM Correspondent_Other_Payments
                    WHERE Correspondent_Other_Payments.Oth_Cnt_Code = Contributions.Con_Cnt_Code and
                          Correspondent_Other_Payments.Oth_Prv_Code = Contributions.Con_Prv_Code and
                          Correspondent_Other_Payments.Oth_Dst_Code = Contributions.Con_Dst_Code and
                          Correspondent_Other_Payments.Oth_Cor_Code = Contributions.Con_Cor_Code and
                          Correspondent_Other_Payments.Oth_Pmt_Date = CONVERT(DATE, @PubDatE, 111) and
                          Correspondent_Other_Payments.Oth_AuditChk = 'Y')
       FROM Contributions
            INNER JOIN Correspondent_Master
                       ON Contributions.Con_Cnt_Code = Correspondent_Master.Cor_Country_Code and
                          Contributions.Con_Prv_Code = Correspondent_Master.Cor_Province_Code and
                          Contributions.Con_Dst_Code = Correspondent_Master.Cor_District_Code and
                          Contributions.Con_Cor_Code = Correspondent_Master.Cor_Code
                          WHERE Con_paper LIKE
                                               CASE
                                                    WHEN @PapCod = 'SIN' THEN
                                                         'DD'
                                                    WHEN @PapCod = 'ENG' THEN
                                                         'DI'
                                                    ELSE
                                                         @PapCod
                                               END and
                               (Con_PubDate BETWEEN CONVERT(DATE, @PubDatB, 111) and
                                                    CONVERT(DATE, @PubDatE, 111)) and
                                Contributions.Audit_Chk = 'Y' /* Audited */
                                GROUP BY Contributions.Con_Cnt_Code,
                                         Contributions.Con_Prv_Code,
                                         Contributions.Con_Dst_Code,
                                         Contributions.Con_Cor_Code,
                                         Contributions.Con_Paper
                                         ORDER BY Contributions.Con_Cnt_Code,
                                                  Contributions.Con_Prv_Code,
                                                  Contributions.Con_Dst_Code,
                                                  Contributions.Con_Cor_Code

A: Just add an OR replicate the same CASE and change the values to SD and SI.
DECLARE
    @t TABLE(Con_Paper VARCHAR(50), Con_Amount INT)

    INSERT INTO @t VALUES
    ('DD', 100)
    ,('SD', 250)
    ,('BN',450)
    ,('DD',50)
    ,('DI',350)
    ,('NL',65)

DECLARE @PapCod VARCHAR(50) = 'ENG'

SELECT SUM(Con_Amount)
FROM @t
WHERE
    (Con_paper LIKE
                   CASE
                        WHEN @PapCod = 'SIN' THEN 'DD'
                        WHEN @PapCod = 'ENG' THEN 'DI'
                        ELSE @PapCod
                   END
    OR
    Con_paper LIKE
                   CASE
                        WHEN @PapCod = 'SIN' THEN 'SD'
                        WHEN @PapCod = 'ENG' THEN 'SI'
                        ELSE @PapCod
                   END
    )


text:
Q: Set height and width for popup window in variable (syntax issue probably) I got the basics of my javascript to function with help I got here on Stackoverflow. I see a bit of room for improvement on what I have now though. A lack of Javascript knowledge keeps me stuck unfortunately.
I'm trying to set arguments such as width, height, toolbar, status for a popup window in a variable. I tried every way I could find both here and via Google to get the syntax right but whatever I try it doesn't seem to work.
See below in Function1 what I ended up with (Function2 still has the hardcoded parameters that I'm trying to put in the variable called windowSpecs).

var windowSpecs   = "\'toolbar=no,status=no,scrollbars=yes,resizable=yes,top=500,left=500,width=600,height=745\'";

var function1Name  = "test_function_1";
var function1Url  = "https://www.google.com";
var function1Class  = ".test_function_class1";

var function2Name  = "test_function_2";
var function2Url  = "https://www.cnn.com";
var function2Class  = ".test_function_class2";

// Function 1
window[function1Name] = function () {
    window.open(function1Url, windowSpecs,"_blank",);
}

jQuery(function1Class).click(function() {
    window[function1Name]();
});

// Function 2
window[function2Name] = function () {
    window.open(function2Url, "_blank", "toolbar=no,status=no,scrollbars=yes,resizable=yes,top=500,left=500,width=600,height=745");
}

jQuery(function2Class).click(function() {
    window[function2Name]();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Any pointers that could help me figure this out would be greatly appreciated!


text:
Q: Component rendered before correct prop data is passed in from another component I have a component called EditPost and that uses another component called PostForm. I am using vuex store to make an api call to retrieve the post object to be edited from the backend in the EditPost beforeCreate method and using a computed property to get the retrieved post from the store which I then pass as a prop to the PostForm component.
Since the object exists already, I want its data to be populated in the input fields of the PostForm. But the values of the object aren't there since the component is rendered before. How can I make sure the data is safely reached before the component gets rendered.
My EditPost component is basically like this:
<template>
    <PostForm v-bind:key="fetchPost" />
</template>

<script>
beforeCreate() {
    this.$store.dispatch('loadPost');
}
computed:
    fetchPost() {
        return this.$store.getters.getPost;
    }

</script>

A: You can wait for the loadPost action to be completed in beforeCreated(), then the component won't be created before the API responds. But be aware that this is not the best practice since the user won't see anything before the API returns a response.
Example:
<template>
    <PostForm v-bind:key="fetchPost" />
</template>

<script>
async beforeCreate() {
    await this.$store.dispatch('loadPost');
}
computed:
    fetchPost() {
        return this.$store.getters.getPost;
    }

</script>


text:
Q: Intellij Idea: how to open files in specific tabs? Short: how to open FileA in a Tab Group 1, FileB in a Tab Group 2 and FileC in a Tab Group 3 without making too many moves?
The problem: I have a wide screen split into three editing groups. When I press Ctrl+N or Ctrl+Shift+N and type the name of the file or class to open, I expect it to be opened in the currently active pane. This however happens in 33% of the cases - depending if the file is present that current group.
So I am editing FileA in Group 1  and I want to open FileC in Group 3. I navigate to Group 3 and press Ctrl+N to open the files. It unfortunately pops out in Group 1, the file which I was editing. Which is a bit frustrating, because I lose focus of what I was working on. I then drag this file into Group 3. And then I try to reopen the file I was working on in Group 1. Which won't necessary open in Group 1. So I have to do the moves again.
The best thing I found was to enable bookmarks in the files I want to edit and after opening them, rearrange the tabs.


text:
Q: How to start an activity Dialog I have one activity which i am using for displaying Dialogs and as a normal layout.
So what i want to do is, sometimes i want to start activity as Theme Dialog and some times using setContentView.
I can't use <activity android:theme="@android:style/Theme.Dialog"> in manifest file as it will always display activity as dialog.
So can we do it programmatic, i have also tried setTheme() method but it did't work.
Thanks,
PP.

A: If you know the dialog/fullscreen style before starting the activity, you could add 2 subclasses and declare them in your manifest. Then you start one or the other depending on the desired style.


text:
Q: Visiting zero-sum triples in a vector space
Is it true that for any set $A\subset\mathbb F_5^n$ satisfying $A\cap(-A)=\varnothing$, there is a subset $A'\subseteq A$ such any triple $(a,b,c)\in A\times A\times A$ with $a+b+c=0$ has exactly one or two of its components lying in $A'$? That is, no zero-sum triple has all of its components in $A'$, and no zero-sum triple is completely avoided by $A'$.

The same question can be asked for any abelian group, but (the additive group of) $\mathbb F_5^n$ is what I presently need. I do not know how relevant the assumption $A\cap(-A)=\varnothing$ is.


text:
Q: How can I edit the Keywords field in SharePoint using c#? I can edit other fields like Title and even my own created fields, but I cant figure out how to add in Keywords to a document I upload. This is what I have so far. The error I get says that the Keywords column does not exist. The Keywords fields type is Managed Metadata. Here is a image of where I want to add keywords into Here is a image of where I want to add keywords into
Update: Here is the updated code of what worked
    static void AddMetaData(ClientContext ctx, string fName, string kWords )
    {
        List list = ctx.Web.Lists.GetByTitle("Documents");
        ListItemCollection items = list.GetItems(CamlQuery.CreateAllItemsQuery());
        ctx.Load(items); // loading all the fields
        ctx.ExecuteQuery();

        TaxonomySession session = TaxonomySession.GetTaxonomySession(ctx);
        var store = session.GetDefaultKeywordsTermStore();
        var terms = store.KeywordsTermSet.GetAllTerms();
        ctx.Load(store, i => i.DefaultLanguage);
        ctx.ExecuteQuery();

        var collection = new System.Collections.ObjectModel.Collection<Term>();
        var keywords = kWords.Split(';');
        foreach (var key in keywords)
        {
            var filtered = ctx.LoadQuery(terms.Where(t => t.Name == key));
            ctx.ExecuteQuery();
            var term = filtered.SingleOrDefault();
            if (term != null)
                collection.Add(term);
        }

        foreach (var item in items)
        {
            var taxonomyField = ctx.CastTo<TaxonomyField>(list.Fields.GetByInternalNameOrTitle("Keywords"));
            ctx.Load(taxonomyField);
            ctx.ExecuteQuery();
            taxonomyField.SetFieldValueByCollection(item, collection, store.DefaultLanguage);
            item.Update();
            ctx.ExecuteQuery();
        }
    }

A: It's a taxonomy field so first you have to get your keywords from the managed metadata store:
TaxonomySession session = TaxonomySession.GetTaxonomySession(context);
var store = session.GetDefaultKeywordsTermStore();
var terms = store.KeywordsTermSet.GetAllTerms();
context.Load(store, i => i.DefaultLanguage);
context.ExecuteQuery();

var collection = new System.Collections.ObjectModel.Collection<Term>();
var keywords = new string[] { "Key1", "Key2" };
foreach (var key in keywords)
{
    var filtered = context.LoadQuery(terms.Where(t => t.Name == key));
    context.ExecuteQuery();
    var term = filtered.SingleOrDefault();
    if (term != null)
        collection.Add(term);
}

Then set field using method contained in TaxonomyField class:
var taxonomyField = context.CastTo<TaxonomyField>(list.Fields.GetByInternalNameOrTitle("Keywords"));
context.Load(taxonomyField);
context.ExecuteQuery();
taxonomyField.SetFieldValueByCollection(item, collection, store.DefaultLanguage);
item.Update();
context.ExecuteQuery();


text:
Q: Cargar datos de tabla Mysql hace que el combobox no se visualice
El problema

Al cargar los datos al combobox este los carga pero el recuadro no se visualiza.
Asi se deberia ver

Pero al correr la aplicacion se ve asi

Y si clickeo en el lugar donde deberia estar el combobox pasa esto

Codigos

Tengo una funcion que carga todos los items de una columna en un combobox.

Funcion (A)

   Function MySQL_DataRead_VariacionCombobox(_Comboboxallenar As ComboBox, _Tabla As String, _Rangos As String)
        _MSQLDataAdapter = New MySqlDataAdapter("SELECT " & _Rangos & " FROM " & _Tabla, _SqlConnection_String_As_MYSQL)
        _MSQLDataTable = New DataTable

        Try

            _MSQLDataAdapter.Fill(_MSQLDataTable)

            _Comboboxallenar.DataSource = _MSQLDataTable

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Function

Luego tengo otra funcion que dependiendo que item se selecciona son los datos que trae llenando una serie de textboxs

Funcion (B)

    Function MySQL_DataRead(_Rangos As String, _Tabla As String, _SegunCol As String) As DataTable
        _MSQLDataAdapter = New MySqlDataAdapter("SELECT " & _Rangos & " FROM " & _Tabla & " WHERE Usuario='" & _SegunCol & "'", _SqlConnection_String_As_MYSQL)
        _MSQLDataTable = New DataTable

        Try

            _MSQLDataAdapter.Fill(_MSQLDataTable)

            MySQL_DataRead = _MSQLDataTable

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Function

Y para llamarlas hago lo siguiente

LLamada de funcion (A)

 Dim Pilares As Pilares = New Pilares
        Dim _Tabla As String = "Usuarios"
        Dim _Rangos As String = "*"
        Val1.DataSource = Pilares.MySQL_DataRead_VariacionCombobox(Val1, _Tabla, _Rangos)
    Val1.DisplayMember = "Usuario"

Llamada de funcion (B)
   '{[Parte 1]
    Dim Pilares As Pilares = New Pilares
    Dim _Rangos As String = "*"
    Dim _Tabla As String = "CredencialesDeUsuarios"
    Dim _TablaCredenciales As DataTable = Pilares.MySQL_DataRead(_Rangos, _Tabla, Val1.Text)

    val3.Text = _TablaCredenciales.Rows(0)("Nombre").ToString
    val4.Text = _TablaCredenciales.Rows(0)("Horario").ToString
    val5.Text = _TablaCredenciales.Rows(0)("Apellido").ToString
    val6.Text = _TablaCredenciales.Rows(0)("Mail").ToString
    val7.Text = _TablaCredenciales.Rows(0)("Sexo").ToString
    val8.Text = _TablaCredenciales.Rows(0)("Puesto").ToString
    val9.Text = _TablaCredenciales.Rows(0)("FechaDeNacimiento").ToString
    val10.Text = _TablaCredenciales.Rows(0)("Nivel").ToString
    '}

    '{[Parte 2]

    _Tabla = "Usuarios"
    Dim _TablaUsuarios As DataTable = Pilares.MySQL_DataRead(_Rangos, _Tabla, Val1.Text)
    val2.Text = _TablaUsuarios.Rows(0)("Contraseña").ToString

    '}

En la llamada de la funcion B uso dos veces la funcion porque tengo datos en 2 tablas distintas que debo recuperar
Mis tablas en MySql se componen de la siguiente manera


text:
Q: Data issues on SQL I'm not able to fetch  data only for the BUY parameter. SEL parameter is working fine. May be an issue with joins.
SELECT DISTINCT
    RP.RP_RECORD_ID,
    RP.RATE_PROFILE_NAME,
    RPH.RATE_TYPE,
    RPH.CHARGE_CODE,
    RPH.TRANSPORT_MODE,
    RPH.PLACE_OF_RECEIPT_CODE,
    (SELECT CD_DESCRIPTION FROM CODE_DETAIL
     WHERE CM_CODE ='145' AND CD_CODE = RPH.ORIGIN_TYPE),
    DECODE(RPH.ORIGIN_TYPE, 'PO', RPH.ORIGIN_PORT_CODE, 'CNT' , ORIGIN_COUNTRY_CODE, 'A', ORIGIN_AREA_CODE, 'CIT', CITY_ORIGIN, 'PV', RPH.ORIGIN_REGION_CODE) ORIGIN,
    RPH.PLACE_OF_DELIVERY_CODE,
    RPH.CARRIER_CODE,
    PCP.PARTNER_ID,
    PARTNER.PARTNER_NAME,
    COM.COMMODITY_DESCRIPTION,
    RPH.REMARK, RPH.RPH_RECORD_ID,
    RPH.ORIGIN_TYPE, RPH.DESTINATION_TYPE,
    (SELECT DISTINCT EMP.employee_name
     FROM partner PAR, employee EMP, partner_relationships PRE
     WHERE PARTNER.partner_id = PAR.partner_id
       AND PAR.partner_id = PRE.partner_id
       AND PRE.EMPLOYEE_NO = EMP.EMPLOYEE_NO
       AND PRE.transport_mode = RPH.transport_mode
       AND (PRE.IMPORT_EXPORT_IND IS NULL OR    -- ' Start of New code by SB on 16-FEB-2010 for WHD136784
            PRE.IMPORT_EXPORT_IND = (CASE
                                        WHEN (RPH.City_Origin = 'VNSGN' OR rph.origin_country_code ='VN' OR rph.origin_port_code ='VN' OR RPH.origin_port_code = 'VNSGN')
                                           THEN 'E'
                                        WHEN (RPH.City_Dest = 'VNSGN' OR RPH.dest_country_code = 'VN' OR RPH.dest_port_code = 'VNSGN' OR  RPH.dest_port_code = 'VNSGN')
                                           THEN 'I'
                                        ELSE ''
                                   END))        --  'End of New code by SB on 16-FEB-2010 for WHD136784
       AND PRE.company_id = CP.company_id
       AND rownum = 1) salesman,                            --   'End of WHD136784 new code
      RPH.RPH_RECORD_ID, RPH.CURRENCY_CODE
  FROM
      RATE_PROFILE RP, RATE_PROFILE_HEADER RPH,
      PARTNER_CHARGE_PROFILE PCP,  PARTNER ,
      COMMODITY_CODES com, OFFICES,
      company_partners CP
  WHERE
      RP.RP_RECORD_ID =  RPH.RP_RECORD_ID
      AND PCP.PARTNER_ID = PARTNER.PARTNER_ID
      AND RPH.COMMCODE_RECORD_ID = COM.CC_RECORD_ID(+)
      AND PCP.COMPANY_ID = OFFICES.COMPANY_ID
      AND OFFICES.OFFICE_TYPE = 'T'
      AND partner.partner_id = CP.partner_id
      AND CP.COMPANY_ID = '{?CompanyID}'
      AND CP.company_id = PCP.company_id
      AND PCP.charge_code = RPH.Charge_code
      AND (('&psRate_type') = 'SEL' AND  PCP.charge_calculation_method = 'R' AND RPH.RP_RECORD_ID = PCP.CHARGE_RATEPROF_RECORD_ID
      OR
           ('&psRate_type') = 'BUY' AND  PCP.cost_calculation_method = 'R' AND RPH.RP_RECORD_ID = PCP.COST_RATEPROF_RECORD_ID)
       )

Data is coming for the 'SEL' parameter but for 'BUY' it is fetching 0 records.
I checked the joins everything but unable to figured out what's the problem.
No issue with AND OR condition under where clause.
Please suggest

A: I have resolved this issue using below joins conditions:
(RPH.RP_RECORD_ID = PCP.CHARGE_RATEPROF_RECORD_ID OR RPH.RP_RECORD_ID = PCP.COST_RATEPROF_RECORD_ID)


text:
Q: Dynamically adding options to a listpreference I am writing a program that has a PreferenceActivity and multiple PreferenceFragment. One of the options the user selects is a server to connect to, this is populated from the XML.
<string-array name="server_names">
    <item>test</item>
    <item>item1</item>
    <item>item2</item>
</string-array>

<string-array name="server_addresses">
    <item>10.10.10.1</item>
    <item>10.10.10.2</item>
    <item>10.10.10.3</item>
</string-array>

This obviously works fine and you get the three names in the list. However there is a separate fragment that allows the user to enter a name and ip address which is then added to the drop down as an extra option.
I have got a working solution that involved loading an external file, clearing the entries and adding the ones from the file. This is 'ok' but I want to use sharedpreferences to save these extra values. My question is this, how do I use the editor to write extra options that will be saved each time the app is launched?
I have looked at using the Editor, putStringSet and commit but the added option doesn't appear in the drop down. There are related posts that seem to deal with a TextPreference but those solutions haven't solved my problem.
edit, this is how i create my ListPreference:
    <ListPreference
      android:entries="@array/server_names"
      android:entryValues="@array/server_addresses"
      android:key="@string/countryListId"
      android:negativeButtonText="@null"
      android:positiveButtonText="@null"
      android:title="@string/pref_title_select_com_target"
      android:enabled="true"
    android:shouldDisableView="false" />

I have a click handler on a label to add to the ListPreference:
 public boolean onPreferenceClick(Preference preference) {
                new AlertDialog.Builder(getActivity())
                        .setTitle("Add new server")
                        .setMessage("Confirm you wish to add the server?")
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int whichButton) {
                                SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = sharedPref.edit();

       /*  command in here to edit the server_names and server_addresses */
                            }})
                        .setNegativeButton(android.R.string.no, null).show();

                return true;
            }
        });

A: Write to shared pref
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("highscore", 5);
editor.commit();

Read from:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = 0;
long highScore = sharedPref.getInt("highscore"), defaultValue);

Is this what you are asking?
EDIT:
Looking at your code, you seem to be missing the actual saving.
Check the answer from Gregor:
How to add new value to listpreference and save it?
He basically says that everytime you open your dialog, the list from xml is loaded. You need to change the behaviour to include the preferences from the SharedPreferences.

You can change this behavior using the setEntries() and
  setEntryVaues() methods of ListPreference


text:
Q: store exception ex as string in db? public static bool download()
{
    try
    {
        //perform up dates, if successful
        UpdateActionResultTable("DownloadPOS", "N/A - No Sales file to upload", "Success", "N/A");
        return true;
    }
    catch (Exeption ex)
    {
        UpdateActionResultTable("DownloadPOS", "N/A - No Sales file to upload", "Fail", ex.ToString());
        return false;
    }
}

If unsuccessful I want to store the exception as a string in the db. This is from the UpdateActionResultTable function but it throws error:

String or binary data would be truncated.
The statement has been terminated.

Any idea as to why?
works fine when the update is successful so my only guess is because of the exception?
public static void UpdateActionResultTable(string actionCalled, string salesFile, string result, string reason)
{
    EPOSEntities db = new EPOSEntities();

    ActionResult action = new ActionResult()
    {
         Action = actionCalled,
         File = salesFile,
         TimeStamp =  DateTime.Now,
         Result = result,
         Reason = reason
    };

    db.AddToActionResults(action);
    db.SaveChanges();
}

A: It means that your final parameter is too long:
ex.ToString()

It cannot be written to the database, because the column you are writing to has a lower size limit.
So, either make that string you write shorter (filter out unnecessary data or take only the first n characters) or make the field you are writing that string to in the DB bigger.

A: The column you have in your database where you are storing the string value for the exception is not large enough to hold the exception string you are giving it.
I would change that column in the database to NVARCHAR(MAX). To do that just run the SQL script below on your database if you are using SQL Server.
SQL:
ALTER TABLE table_name
ALTER COLUMN column_name NVARCHAR(MAX)

A: Looks like your database field is not big enough to store the exception string
N/A takes only 3 characters, but exceptions can get quite big. So if your field is lets say varchar(50), "N/A" would be no problem because the field can hold up to 50 characters. But an exception stored as string will be way bigger


text:
Q: Select Child ByClassName Javascript I have many divs like the following rendering on the same page:

        Some data

        Some buttons

I need to trigger a style change on "contentButtonWrap" when "contentUser is clicked".
I don't know how I can select a child element of a certain class name. Notice that the number of elements that can be rendered within "contentUser" changes from div(contentUser) to div. But there is all ways only one "contentButtonWrap" element within "ContentUser".
This is what I have:
function avoidHover() {
    var userDivs = document.getElementsByClassName('contentUser');
    [].forEach.call(userDivs, function(e){
        e.click = function(){

            var target = e.getElementsByClassName('contentButtonWrap');
            target[0].style.backgroundColor='green';
            };
    });
};

A: "onclick" instead of "click". Sorry about that...
function avoidHover() {
    var userDivs = document.getElementsByClassName('contentUser');
    [].forEach.call(userDivs, function(e){
        e.onclick = function(){

            var target = e.getElementsByClassName('contentButtonWrap');
            target[0].style.backgroundColor='green';
            };
    });
};

A: Here is my take at it : http://jsfiddle.net/cdL51w2g/
function avoidHover() {
    var userDivs = document.getElementsByClassName('contentUser');

    for(var i=0; i<userDivs.length; i++){
        userDivs[i].onclick = function(){
            var target = this.getElementsByClassName('contentButtonWrap');
            target[0].style.backgroundColor='green';
        };
    }
};

I changed the way to access the children in the parent divand used the function onclick instead of click in the question.


text:
Q: Mysterious rpy2 with Anaconda (Windows) error OK, after a lot of Hassle, I finally installed Rpy2 on windows 7 x64.
VERSION INFO:
R version 3.2.0 (2015-04-16) -- "Full of Ingredients"
   Copyright (C) 2015 The R Foundation for Statistical Computing
   Platform: x86_64-w64-mingw32/x64 (64-bit)
C:\Anaconda>conda -V
   conda 3.18.5
   C:\Anaconda>python
   Python 2.7.10 |Anaconda 2.1.0 (64-bit)| (default, Nov  7 2015, 13:18:40) [MSC v. 1500 64 bit (AMD64)] on win32
Now, it is running, but I had to do strange things
How to setup environment variable R_user to use rpy2 in python
So, I have Anaconda and R installed for all users, not just for myself.  So this changes things slightly according to that post.
I had to set up environment variables
R_HOME C:\Program Files\R\R-3.2.0\
R_USER C:\Anaconda\Lib\site-packages\rpy2\

When running my program, I get an error in Python:
rpy2.rinterface.RRuntimeError: Error in library(modeltools) : there is no package called 'modeltools'
Error in library(modeltools) : there is no package called 'modeltools'

So I loaded R and modeltools was not installed.  So installed modeltools and other necessary packages I found in Python source code.
I even rebooted.
And the error remains.  I am totally stumped.

A: The RRuntimeError is an exception coming from the embedded R: it does not find the package "modeltools". Really.
So now how can this happen while when running R the package is installed ?

*

*`rpy2 is linking to a different R

*the paths in which R packages are installed differs

Try checking if what the R function .libPaths() is returning differs between R, or the R embedded in rpy2.


text:
Q: Problem in connecting the database in Cpanel I am new in upload the laravel project in c Panel, now I have problem in connect the database , I am import migration in the phpMyAdmin in c panel but in registration I have an error :
Access denied for user 'root@localhost' (using password:NO)
this my phpMyAdmin in c panel:

and its my databse :

and this my env in file manger in c panel :

A: *

*Confirm the database server address. It is usually localhost but it might have a different address.

*Usually when you make a database in CPanel you will also create a user with access permission on the new database. Try using that user.


text:
Q: Need Help in maintaining session in PHP Curl I want to grab images from http://www.ps3-themes.com/, but whenever i directly enter image URL it doesn't work. It redirects it to main URL of site. I'm using following code.
$cookie_file = 'c:/tmp-cookie.txt';
$crl = curl_init();
curl_setopt($crl, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($crl, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($crl, CURLOPT_URL, "http://www.ps3-themes.com/wp-content/uploads/2011/03/11414-FordF150RaptorSVT.jpg");
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($crl, CURLOPT_FOLLOWLOCATION, 1);
$html = curl_exec($crl);

if (file_exists($cookie_file)) {
print 'Created cookie file ' . $cookie_file;
} else {
print 'Could not create cookie file ' . $cookie_file;
}

I can say it requires maintaining session but not sure how to do that.-

A: From the looks of it, this isn't a cookie issue but a referrer issue — attempting to display the image from anywhere but the site itself will redirect to the site home instead. This is usually done to prevent hotlinking, which is a bandwidth annoyance.
You can work around this by setting your cURL HTTP referrer to an appropriate URL.

A: Try using session_write_close() before you make the CURL request.

A: 1st you try to open the image directly in browser. It does not open up. May be the image is not there or authorization is needed.


text:
Q: Echo the UTC time I have this vendor-supplied script that retrieves the UTC time from the vendor's server.
<script>
var button = $('button[api_access_id]');
$.getJSON('https://sandbox.forte.net/checkout/getUTC?callback=?').done(function (utc) {
button.attr('utc_time', utc);
});
</script>

I want to just echo the UTC time to the browser window.
How do i do?

A: You can alert it to browser window like this(if utc from get request is string not object or array)
<script>
$.getJSON('https://sandbox.forte.net/checkout/getUTC?callback=?').done(function(utc) {
    window.alert(utc);
  })
</script>

Note: you don't need even run this in your app, you can test it directy from console, if you open browser inspector. And in console tab paste
$.getJSON('https://sandbox.forte.net/checkout/getUTC?callback=?').done(function(utc) {
    window.alert(utc);
  })


text:
Q: Lift session-valid ajax callback from a static javascript I am currently implementing a graph visualisation tool using lift on the server side and d3 ( a javascript visualisation framework) for all the visualisation. The problem I have is that in the script I want to get session dependent data from the server.
So basically, my objective is to write lift-valid ajax callbacks in a static js script.
What I have tried so far
If you feel that the best solution is one that I already tried feel free to post a detailed answer telling me how to use it exactly and how it completely solves my problem.
Write the ajax callback in another script using lift and call it from the main script
This solution, which is similar to a hidden text input is probably the more likely to work. However it is not elegant and it would mean that I would have to load a lot of scripts on load, which is not really conveniant.
This seems to be one of the prefered solutions in the lift community as explained in this discussion on the mailing list.
REST interface
Usually what one would do to get data from a javascript function in lift is to create a REST interface. However this interface will not be linked to any session. This is the solution I got from my previous question: Get json data in d3 from lift snippet
Give function as argument of script
Another solution would be to give the ajaxcallback as an argument of the main script called to generate my graph. However I expect to have a lot of callbacks and I don't want to have to mess with the arguments of my script.
Write the whole script in lift and then serve it to the client
This solution can be elegant, however my script is very long and I would really prefer that it remainss static.
What I want
On client side
While reviewing the source code of my webpage I found that the callback for an ajaxSelect is:
<select onchange="liftAjax.lift_ajaxHandler('F966066257023LYKF4=' + encodeURIComponent(this.value), null, null, null)" name="F96606625703QXTSWU" id="node_delete" class="input">

Moreover, there is a variable containing the state of the page in the end of the webpage:
var lift_page = "F96606625700QRXLDO";

So, I am wondering if it is possible to simulate that my ajaxcall is valid using this liftAjax.lift_ajaxHandler function. However I don't know the exact synthax to use.
On server side
Since I "forged" a request on client side, I would now like to get the request on client side and to dispatch it to the correct function. This is where the LiftRules.dispatch object seems the best solution: when it is called, all the session management has been made (the request is authentified and linked to a session), however I don't know how to write the correct piece of code in the append function.
Remark
In lift all names of variables are changed to a random string in order to increase the security, I would like to have the same behavior in my application even if that will probably mean that I will have to "give" the javascript these values. However an array of 15 string values is still a better tradeoff than 15 functions as argument of a javascript function.
Edit
While following my research I found this page : Mapping server functions to client actions which somehow explains the goal of named functions even if it stil didn't lead me to a working solution.

A: Quick Answer
Rest in Lift does not have to be stateless.  If you register your RestHelper with LiftRules.dispatch.append, then it will be handled statefully and Session information will be available through the S object as usual.
Long Answer
Since you seem interested, and it's come up on SO before, here's a more detailed explanation of how server-side functions are registered and called in Lift.  If you haven't worked with Lift for some time, look away.  What follows should not in any way be used to evaluate Lift or its complexity.  This is purely library developer level stuff and a majority of Lift users go about their development blissfully unaware of it.
How it works
When you create stateful callbacks, typically by using the methods within the SHtml object, what you are really doing is registering objects of type S.AFuncHolder within the context of the users session, each with a unique ID.  The unique ID that was generated during this process is what you're seeing when you come across a pattern like F96606625700QRXLDO.  When data is submitted, via form post, ajax, or whatever, Lift will check the request for these function ids and execute the associated function if they exist.  There are several helpers that provide more specific types of AFuncHolder, like S.SFuncHolder (accepts a single string query parameter) and S.BinFuncHolder (parameter is multipart form data) but they all return Any and behind the scenes Lift will collect those return values to create the proper type of response. A JsCmd, for instance, will result in a JavaScriptResponse that executes the command.  You can also return a LiftResponse directly.
How to use it
AFuncHolders are registered using the S.fmapFunc method.  You'd call it like this
S.fmapFunc(SFuncHolder({ (str: String) =>
  doSomethingAwesomeWithAString(str)
}))(id => <input type="text" name={id} value=""/>)

The first parameter is your function, wrapped in the proper *FuncHolder type and the second parameter is a function that takes the generated id and outputs something.  The something that gets output is what you will include on the page.  It should somehow result in the id being sent to the server as a query parameter so that your function is executed.
Putting it all together
You could use the above to make your own Ajax calls, but when Lift makes an ajax call there are a few other considerations:
1) Most browsers only allow so many simultaneous connections to a given domain.  Three seems to be the magic number.
2) AFuncHolders will often close over the scope of the snippet they are contained within and if multiple ajax requests are handled at once, each in its own thread, bad things can happen.
To combat these issues, the liftAjax.lift_ajaxHandler function queues each ajax request, ensuring that only one at a time is sent to the server.
The drawback to this approach is that it can make it difficult to make an Ajax call where the result needs to be passed to a callback.  JQuery autocomplete, for instance, provides a callback function when input changes that accepts a list of matches.  If you are manually calling LiftAjax.lift_ajaxHandler though, you can provide your own callback functions for success & error and I would recommend that you look at the source of those functions in your browser for more information on how they work.
There's actually more to it, like how Lift restores RequestVars on ajax callbacks (which is where the lift_page comes in, but that's about all I'm prepared to explain over coffee on a Saturday morning :)
Good luck with your app!


text:
Q: How to read if the UUID format from a json file? I have a json file say file.json
It has a json body like this
{
   "input": {
   "url": "/abc/def/efg/{UUID}.txt",
   "type": "text"
},
   "output": {
   "result": 10,
   "content": ""
   }
}

{UUID} is any valid UUID.
How do I allow any UUID as regex / generic form in place {UUID} ??

A: You can use this regex to find and match the 'GUID' part or your text:
/\"url\":\s?\"[^{]+\{([^}]+)/

The regex matches '"url": "' at start, then matches up to '{' before it creates a Group where it stores the 'UUID'
You get an array as result, where you should grap Group 1.
How to use:
if your text is in a variable called 'text', then you can do:
var UUID = text.match(/\"url\":\s?\"[^{]+\{([^}]+)/)[1];


text:
Q: One dataset controls other in SSRS *.rdl? I see a mystery behaviour in my *.rdl. I have 2 datasets defined.
I have 4 parameters defined,

*

*StartDate,EndDate, companyid, sitecode
For both datasets,I have defined a select query.

*

*DatasetA uses @Enddate

*

*DatasetB not using it( it uses, startdate, companyid, sitecode)

I want to getrid of @EndDate from datasetA too. So, im using @startdate parameter to define enddate and using that in my sql query.
eg :
DECLARE @eDate AS date =EOMonth(@StartDate)

But after getting rid of this, @EndDate, my second data retrieves less data.(ie: if it should return data from september and october, now it returns only from September)
I checked the rdl, rowgroup/column group everywhere, but there is no any filter defined like that. I see this behaviour, only if i change @EndDate parameter from 1st dataset.
eg:
DECLARE @eDate AS date =EOMonth(@StartDate)
Select ..
Where date>=@StartDate AND date<=@Enddate to date<=@eDate

Is there any place we use parameter as a filter check? If so, how can I check it, where it has been used in the *.rdl?

A: I figured out the issue. This is due to Lookup function I use between both datasets. So, when dataset2 is trying to retrieve the correct number of rows, dataset1 was controlling it, becuase it didnt return rows for that date.
eg: dataset1 returns September data, while dataset 2 returns September+October data.
Due to lookup function, Dataset1 controls the dataset2's October data.


text:
Q: How to force LaTeX only commands? Recently, I learned that for a long time I have been doing all of my mathematics in LaTeX incorrectly!
I was using the $ TeX commands instead of the \( and \) LaTeX commands!
I immediately went back and fixed my error, but it got me wondering, is there a way to make the LaTeX compiler and TexStudio (Or another editor) not use the TeX commands in order to preserve proper typesetting?
Furthermore, would it possible to write a macro to automatically make the $ signs into the respective \( and \)?
I've tried
\renewcommand{$}{\relax\ifmmode\)\else\(\fi}

But this is full or errors due to the handling of the special signs.
There are probably many places where I may be making similar mistakes, so I was also wondering if there was a LaTeX syntax checker sort of like the W3C HTML validator for websites, or an IDE that would force me to use proper commands.

A: Where did you "learn" that using $ as a switch to initiate and terminate inline math mode is incorrect for LaTeX users?
I'd go even further than @egreg does in his comment and state that not only is using $ to start and end inline math mode not wrong, it has certain advantages over \( and \). Consider the following MWE:
\documentclass{article}
\begin{document}
\tableofcontents
\section{\(1+1=2\)}
\end{document}

If you compile it twice, you'll get the following, not particularly enlightening error message:
>  LaTeX Error: Bad math environment delimiter.

The reason one gets this error message is that \( and \) are not "robust" (in the TeX/LaTeX sense of the word), which trips up the LaTeX code that generates the table of contents. To avoid getting this error message, you could type
\section{\protect\(1+1=2\protect\)}

but I dare-say that you'll soon decide it's preferable to write
\section{$1+1=2$}

Addendum: It may be instructive to examine how \( and \) are defined in the LaTeX kernel (see, e.g, the file latex.ltx):
\def\({\relax\ifmmode\@badmath\else$\fi}
\def\){\relax\ifmmode\ifinner$\else\@badmath\fi\else \@badmath\fi}

where \@badmath is defined as
\gdef\@badmath{\@latex@error{Bad math environment delimiter}\@eha}

Thus, \( and \) both eventually invoke $, with some error checking thrown in: \( throws an error if it's encountered while already in math mode, and \) generates an error if it's encountered while not in so-called "inner" math mode.
In practice, unless the macros \( and \) are made robust in the LaTeX sense of the word (e.g., by loading the package fixltx2e), using them may lead to other error messages -- see the example above -- that are just as confusing as those that tend to arise when $ is used incorrectly.

A: As already mentioned in comments, the nag package does its best to pick up not only use of TeX rather than LaTeX syntax but also deprecated LaTeX stuff. That is the best you can do with LaTeX2e because of the way the kernel itself and packages are written: they use TeX constructs without 'LaTeX wrappers'.
One of the aims of the LaTeX3 Project is to develop a new LaTeX which provides these low-level constructs with 'proper' LaTeX (code) interfaces. However, at this stage this does not reach the point of having a fully working format, so the restrictions of LaTeX2e remain.
On the specific question of $...$ versus \( ... \), note that the TeX-like syntax is explicitly allowed by LaTeX2e: it's in LaTeX: A Document Preparation System (2nd ed., page 39). Thus quite apart from any technical discussions, disabling $ really doesn't make sense as you (and by extension package authors) are allowed to use it for inline math mode. (This does not extend to $$ for display math mode, for which the official LaTeX interface is \[ ... \].)


text:
Q: How to use resValue in build.gradle? I am trying this trick to keep the Sentry DSN and other keys out of the respository of my open source app (so everyone can add their own key via local.properties) but I'm failing already with the first step ("Move Manifest keys to Gradle").
Here's exactly what I did:
For debugging purposes I added this code to my MainActivity.kt to show me the current value:
val app: ApplicationInfo = this.getPackageManager()
    .getApplicationInfo(this.getPackageName(), PackageManager.GET_META_DATA)
val bundle = app.metaData
Toast.makeText(this, bundle.getString("foo"), Toast.LENGTH_LONG).show()

Then I replaced the value in AndroidManifest.xml with a string resource:
<manifest>
  <application>
    <meta-data android:name="foo" android:value="@string/manifest_foo" />
  </application>
</manifest>

In app/build.gradle I added:
android {
    ...
    defaultConfig {
        ...
        resValue "string", "manifest_foo", 'gradle_space'
        resValue("string", "manifest_foo", "gradle_parens")
    }
    ...
}

After this I got a build error AAPT: error: resource string/manifest_foo not found..
So I added in strings.xml:
<string name="manifest_foo">from_strings_xml</string>

It builds and runs, but the value from build.gradle is not used:


text:
Q: jquery ajax script is run successfully but results in error I have a simple script that keeps resulting in error, even though the PHP script is run successfully.
PHP
require('/connect.php');  //Has my $link variable

if(isset($_POST['pass'])){

    $user = $_POST['user'];
    $oldpass = md5(urldecode($_POST['op']));
    $newpass = md5(urldecode($_POST['np']));

    $q = "SELECT * FROM `nht_users` WHERE usr = '".$user."' AND pass = '".$oldpass."'";
    $r = mysqli_query($link,$q);
    $n = mysqli_num_rows($r);

    if( $n > 0){

        $u = "UPDATE `nht_users` SET pass = '".$newpass."' WHERE usr = '".$user."'";
        mysqli_query($link,$u);

    }

    else{

        echo json_encode('FALSE');

    }

}

JQuery
$('#pass-submit').click(function() {

        var npp = $('#npp').val(),
            np = $('#np').val(),
            data = $('#pass-form').serialize(),
            url = 'http://www.<?php echo DOMAIN; ?>/functions.php';

        if (npp == np) {
            $('#test').html(url);
            $.ajax({
                type: 'POST',
                url: url,
                data: 'pass=true&'+data,
                success: function(data){

                    $('#pass-form').slideUp(800);
                    $('.pass-true').fadeIn(800);

                },
                error: function(){

                    $('.pass-false').fadeIn(800);

                }
            });
        }
        else {
            $('.pass-check').fadeIn(800);
        }

    });

A: To catch the error
error: function(xhr, textStatus, errorThrown) {
    alert(xhr.responseText);
}

A: To get a better idea of what is happening in your response, you can try to use the network tab in Chrome (hit F12) and run your process. You should see your ajax request and response come through. Internet Explorer also has a similar option, but you will need to tell it to explicitly watch the network. One other option for tracing this type of issue is to install a desktop application like Fiddler2 (http://fiddler2.com/).
I have used all 3 of these to varying levels to hunt down why my AJAX requests are not running as expected.


text:
Q: breaking infinite loop / proper loop setting In my application I have a mysql db table with many numerical records. I am doing some computations to these records. I would like to perform this computation in a loop with a ending condition. I was thinking about do-while loop, but I have scenario like this:
LOOP: {
    LOOP for computing euklidian distances between chosen records
    // HERE I WOULD LIKE TO CHCECK IF MY ENDING CONDITION IS TRUE.
    // IF YES, WHOLE LOOP WILL END, AND IF NO, IT WILL CONTINUE
    LOOP for updating table records according to euklidian distances.
}

Can anyone help me please?

A: I think you can solve that with a simple endless loop and break:
while (true)
{
    // do computation
    if (/* check condition */)
        break;
    // update DB
}

Then the loop will run until the condition is met. You may should also ensure that this will not turn into an endless loop...

A: while (true)
{
  // some code

  if (condition)
    break; // HERE

  // some other code
}

A: "Foreach" loop may be better for you to use for computing for each record from the table.
foreach(var record in listOfRecords)
{
    //LOOP for computing euklidian distances between chosen records

    if(condition)
    {
        break;
    }

    //LOOP for updating table records according to euklidian distances.
}


text:
Q: php isset not working I want to set $choice_1 and $choice_2 but only once per session. I am using $choice_1 and $choice_2 to create image names and I want to avoid drawing different jpegs within a session. I display two chess pieces at http://communitychessclub.com/rabren and I want those two images used for the entire user session.
<?php
if (!isset($_SESSION['choice_1'])) {$chessmen = array("N","Q","R","B","K","P");

$random_piece = array_rand($chessmen);
$choice_1 = $chessmen[$random_piece];
unset($chessmen[$random_piece]);

$random_piece = array_rand($chessmen);
$choice_2 = $chessmen[$random_piece];}
?>

A: use session_start() before printing any output or set session auto start to 1 in php.ini
<?php
session_start();
if(!isset($_SESSION['test']))
echo "no test session";
else
echo $_SESSION['test'];
if($sth)
{
 $_SESSION['test'] = 'sth...';
}

A: Try it this way...
<?php
session_start();

if(!isset($_SESSION['choice_1'])) {
    $chessmen = array("N","Q","R","B","K","P");

    $random_piece = array_rand($chessmen);
    $_SESSION['choice_1'] = $chessmen[$random_piece];

    unset($chessmen[$random_piece]);

    $random_piece = array_rand($chessmen);
    $_SESSION['choice_2'] = $chessmen[$random_piece];
}
?>

Your session data is stored inside your $_SESSION-Array and not outside as a common php variable. So if you want to - for example - print "choise_1" later, you will need to echo $_SESSION['choise_1'];.


text:
Q: What tools in Python are available for doing great circle distance + line creation? I need to use Python to create a great circle distance -- both a number, and preferably some kind of 'curve' that I can use to draw in a client-side map. I don't care about the format of the curve -- be it WKT, or a set of pairs of coordinates -- but just want to get the data out.
What tools are there out there? What should I use?

A: The answers provided by others are a little more elegant, but here's an ultrasimple, somewhat unpythonic, bit of Python that provides the basics. The function takes two coordinate pairs and a user-specified number of segments. It yields a set of intermediate points along a great circle path. Output: text ready to write as KML. Caveats: The code does not consider antipodes, and assumes a spherical earth.
Code by Alan Glennon http://enj.com July 2010 (author places this code in the public domain. Use at your own risk).
--
def tweensegs(longitude1,latitude1,longitude2,latitude2,num_of_segments):
import math

ptlon1 = longitude1
ptlat1 = latitude1
ptlon2 = longitude2
ptlat2 = latitude2

numberofsegments = num_of_segments
onelessthansegments = numberofsegments - 1
fractionalincrement = (1.0/onelessthansegments)

ptlon1_radians = math.radians(ptlon1)
ptlat1_radians = math.radians(ptlat1)
ptlon2_radians = math.radians(ptlon2)
ptlat2_radians = math.radians(ptlat2)

distance_radians=2*math.asin(math.sqrt(math.pow((math.sin((ptlat1_radians-ptlat2_radians)/2)),2) + math.cos(ptlat1_radians)*math.cos(ptlat2_radians)*math.pow((math.sin((ptlon1_radians-ptlon2_radians)/2)),2)))
# 6371.009 represents the mean radius of the earth
# shortest path distance
distance_km = 6371.009 * distance_radians

mylats = []
mylons = []

# write the starting coordinates
mylats.append([])
mylons.append([])
mylats[0] = ptlat1
mylons[0] = ptlon1

f = fractionalincrement
icounter = 1
while (icounter <  onelessthansegments):
        icountmin1 = icounter - 1
        mylats.append([])
        mylons.append([])
        # f is expressed as a fraction along the route from point 1 to point 2
        A=math.sin((1-f)*distance_radians)/math.sin(distance_radians)
        B=math.sin(f*distance_radians)/math.sin(distance_radians)
        x = A*math.cos(ptlat1_radians)*math.cos(ptlon1_radians) + B*math.cos(ptlat2_radians)*math.cos(ptlon2_radians)
        y = A*math.cos(ptlat1_radians)*math.sin(ptlon1_radians) +  B*math.cos(ptlat2_radians)*math.sin(ptlon2_radians)
        z = A*math.sin(ptlat1_radians) + B*math.sin(ptlat2_radians)
        newlat=math.atan2(z,math.sqrt(math.pow(x,2)+math.pow(y,2)))
        newlon=math.atan2(y,x)
        newlat_degrees = math.degrees(newlat)
        newlon_degrees = math.degrees(newlon)
        mylats[icounter] = newlat_degrees
        mylons[icounter] = newlon_degrees
        icounter += 1
        f = f + fractionalincrement

# write the ending coordinates
mylats.append([])
mylons.append([])
mylats[onelessthansegments] = ptlat2
mylons[onelessthansegments] = ptlon2

# Now, the array mylats[] and mylons[] have the coordinate pairs for intermediate points along the geodesic
# My mylat[0],mylat[0] and mylat[num_of_segments-1],mylat[num_of_segments-1] are the geodesic end points

# write a kml of the results
zipcounter = 0
kmlheader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><kml xmlns=\"http://www.opengis.net/kml/2.2\"><Document><name>LineString.kml</name><open>1</open><Placemark><name>unextruded</name><LineString><extrude>1</extrude><tessellate>1</tessellate><coordinates>"
print kmlheader
while (zipcounter < numberofsegments):
        outputstuff = repr(mylons[zipcounter]) + "," + repr(mylats[zipcounter]) + ",0 "
        print outputstuff
        zipcounter += 1
kmlfooter = "</coordinates></LineString></Placemark></Document></kml>"
print kmlfooter

A: Here are some links that might help:
http://www.koders.com/python/fid0A930D7924AE856342437CA1F5A9A3EC0CAEACE2.aspx
http://code.activestate.com/recipes/393241-calculating-the-distance-between-zip-codes/

A: geopy
A Geocoding Toolbox for Python
http://code.google.com/p/geopy/wiki/GettingStarted#Calculating_distances

A: pyproj has the Geod.npts function that will return an array of points along the path. Note that it doesn't include the terminal points in the array, so you need to take them into account:
import pyproj
# calculate distance between points
g = pyproj.Geod(ellps='WGS84')
(az12, az21, dist) = g.inv(startlong, startlat, endlong, endlat)

# calculate line string along path with segments <= 1 km
lonlats = g.npts(startlong, startlat, endlong, endlat,
                 1 + int(dist / 1000))

# npts doesn't include start/end points, so prepend/append them
lonlats.insert(0, (startlong, startlat))
lonlats.append((endlong, endlat))

A: GeographicLib has a python interface:
This can computer geodesics on an ellipsoid (set flattening to zero to get great circles) and can generate intermediate points on a geodesic (see the "Line" commands in the sample).
Here's how to print out points on the geodesic line from
JFK to Changi Airport (Singapore):
from geographiclib.geodesic import Geodesic
geod = Geodesic.WGS84

g = geod.Inverse(40.6, -73.8, 1.4, 104)
l = geod.Line(g['lat1'], g['lon1'], g['azi1'])
num = 15  # 15 intermediate steps

for i in range(num+1):
    pos = l.Position(i * g['s12'] / num)
    print(pos['lat2'], pos['lon2'])

->
(40.60, -73.8)
(49.78, -72.99)
(58.95, -71.81)
(68.09, -69.76)
(77.15, -65.01)
(85.76, -40.31)
(83.77, 80.76)
(74.92, 94.85)
...

A: I haven't used this package, but it seems interesting, and a possible solution: http://trac.gispython.org/lab/wiki/Shapely


text:
Q: How do I Convert DateTime from UTC to Local and then Capture elements reliably I'm storing the Date/Time in SQL in UTC time zone regardless of the time zone the user is in.
Now I need to display the D/T in local time zone on the client machine - in separate fields (dropdowns for month, day, hour, etc), thus after converting the D/T to local, I need to break it apart, but using .toLocal and .toLocalString are not consistent across browsers and user preferences; I therefore can not break the string apart consistantly.
Here's what I'm doing:
var utcDTString=$("#utcDateTime"); // this is in format YYYY-MM-DD HH:MM:SS coming from SQL in UTC Time zone
var utcDateObj=new Date(utcDTString+' UTC'); // create a date obj of UTC DateTime in UTC time zone
var localDT=utcDateObj.toLocaleString(); // convert the DT to local Time zone

Now, how do I reliably extrapolate the Year, Month, Day, Hour, Minute from localDT given that different browsers and user preferences could cause the string to be in various formats.
I looked to see if I could specify a layout for .toLocaleString but couldn't find anything.

A: I was making this more difficult than it needed to be. I assumed that when I used .getHours() that it would simply return the hours value of the current date object in its current time zone (in my case UTC). I was wrong.  When using .getHours() on a Date object that is in UTC time zone, it returns all the values in local client time - not the object's time zone. Therefore I didn't need to use .toLocaleString I could simply start grabbing the values from the date object and it is automatically converted to local time. Therefore this worked perfectly:
var sDT=$("#startMonth").data("startingvalue");
var utcdt=new Date(sDT+' UTC');
var startDateTime = utcdt;
$("#startMonth").val(startDateTime.getMonth()+1);
$("#startDay").val(startDateTime.getDate());
$("#startYear").val(startDateTime.getFullYear());
var sH=startDateTime.getHours();
if(sH>=12){
    $("#startAMPM").val("PM");
    if(sH>12){
        sH-=12;
    }
}else{
    $("#startAMPM").val("AM");
}
if(parseInt(sH)<10){
    sH="0"+sH;
}
$("#startHour").val(sH);
$("#startMinute").val(startDateTime.getMinutes());


text:
Q: How much space dose list re-allocation cost in Python? I'm trying to solve a problem with O(1) in space. Could anyone help me determine if the following code is taking O(1) space?
I got a list as input and every time I ran a loop I do
list = list[:len(list)/2+1]

Does list re-allocation use the original memory of that list, or should it create extra memory usage? Thanks.

A: You can see it's a shallow copy with a simple test
list = [1,2,3,4,5,6,7,8]
list2 = list[:len(list)//2+1]

list2[0] = 999
print(list)
print(list2)

This prints
[1, 2, 3, 4, 5, 6, 7, 8]
[999, 2, 3, 4, 5]

So clearly they aren't sharing memory. This is not O(1) space


text:
Q: How to add datat to MySQL from CGI script with static html? I have a CGI script that reads an HTML file. The HTML file is located in directory called htdocs and CGI file is located in directory called cgi-bin. I can access the html form from the web and when I submit I see the result I expect, but when I check MySQL the table has a new blank line.
I usually put CGI and HTML in same file because I find it easy, but I was wondering how I can do same action with CGI and HTML in different files. Here is my CGI file code:
    #!/usr/bin/perl -w

use DBI;

$db="user1";
$user="user1";
$passwd="P@ssw0rd";
$host="db-mysql.system1";
$connectionInfo="dbi:mysql:$db;$host";

#print HTTP Header
print "Content-type:text/html\n\n";

if ($ENV{REQUEST_METHOD} eq "GET") {
    &parseform();
    &insertperson();
}
#else {
#   &parseform();
#   &insertperson();
#   exit;
#}

sub parseform {
    read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
    @pairs = split(/&/, $buffer);
    foreach $pair (@pairs) {
        ($name, $value) = split(/=/, $pair);
        $value =~ tr/+/ /;
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
        $FORM{$name} = $value;
}

sub insertperson {
    $insert=qq~insert person(name,email,age,color)
        values('name','email','age','color')~;
    $dbh=DBI->connect($connectionInfo,$user,$passwd);
    $sth=$dbh->prepare($insert);
    if ($sth->execute()) {
        &displaysuccess;
    }
    else {
        &displayfail;
    }
    $dbh->disconnect0;
}

sub displaysuccess {
    print qq~\n

        <title>Person</title>

Record Added

    ~;
}

sub displayfail {
    print qq~\n

        <title>Person</title>

Record Not Added

    ~;
}

A: *

*Perl is case sensitive.

You used the variable $FORM to set values, but later on you use $form (in '$form{name}','$form{email}','$form{age}','$form{color}').
Change them to '$FORM{name}','$FORM{email}','$FORM{age}','$FORM{color}'

*The $FORM variable is local to the parseform routine (therefor - it is not available inside the insertperson routine).

A: Here's the subroutine you use to insert the data into the database:
sub insertperson {
    $insert=qq~insert person(name,email,age,color)
        values('name','email','age','color')~;
    $dbh=DBI->connect($connectionInfo,$user,$passwd);
    $sth=$dbh->prepare($insert);
    if ($sth->execute()) {
        &displaysuccess;
    }
    else {
        &displayfail;
    }
    $dbh->disconnect;
}

The SQL you execute is:

insert person(name,email,age,color) values('name','email','age','color')

That's inserting hard-coded values into your database. You want to insert data from your %FORM hash.
%insert = "insert person(name,email,age,color)
           values('$FORM{name}','$FORM{email}',
                  '$FORM{age}','$FORM{color}')";

But this code is a terrible idea. You are taking data from an unknown user and inserting it into an SQL statement. That's an SQL injection attack waiting to happen.
A far better approach is to use bind variables and extra parameters to execute().
sub insertperson {
    $insert = "insert person(name,email,age,color)
               values(?, ?, ?, ?)";
    $dbh=DBI->connect($connectionInfo,$user,$passwd);
    $sth=$dbh->prepare($insert);
    if ($sth->execute($FORM{name}, $FORM{email},
                      $FORM{age},$FORM{color})) {
        &displaysuccess;
    }
    else {
        &displayfail;
    }
    $dbh->disconnect;
}

An even better idea is to look at DBIx::Class - but I'm guessing that's a step too far at this point.
Some other points on your code:

*

*Please replace -w with use warnings and add use strict (you will then need to declare all of your variables).

*Please use CGI.pm to parse your CGI parameters and print the CGI header.

*Please stop using & to call subroutines. Something like displaysuccess() looks more recognisable as a subroutine call and doesn't have hidden side effects that will bite you one day.

*Please use a templating engine (I recommend the Template Toolkit) to handle your HTML.

*Your HTML should really have an h1 element before the h2 element. You should use CSS to fix the appearance, rather than messing with the semantics.


text:
Q: SetWindowsHookEx HCBT_CREATEWND GetWindowText Anyboby knows how to get text of a created window? I set hook on CreateWindow, but GetWindowText returns empty string.
hCBTHook = SetWindowsHookEx(WH_CBT, (HOOKPROC) &CBTHook, g_appInstance, 0);

LRESULT CALLBACK CBTHook(int nCode, WPARAM wParam, LPARAM lParam)
{
     if(nCode == HCBT_CREATEWND)
     {
          HWND hwnd = (HWND)wParam;
          CHAR buf[256];
          GetWindowText(hwnd, buf, 256);
     }

     return CallNextHookEx(hCBTHook, nCode, wParam, lParam);
}

A: "The system calls the hook procedure before sending the WM_CREATE or WM_NCCREATE message to the window."
The window may not have text yet, your callback is invoked very early in the process of window creation. The name of the window gets passed in as part of the CREATESTRUCT message sent with WM_CREATE which would be the earliest the window could do something about having text. Even to hard code something, it would have to be in WM_NCCREATE, which still hasn't happened yet when your callback is called.
However, the callback itself also gets passed the the CREATESTRUCT. If the name that was passed to CreateWindow is what you are after, that's available to you as well.


text:
Q: how to add a checkbox in a datatable php I have a table that displays the result of a query. I am using codeigniter by the way. I want to add a checkbox in every row. And everytime a checkbox is checked, I will enable the edit button and the delete button..
I made it this way but only on the first row, it enable and disable the button:

                <a type="button" class="btn btn-default" href="<?php echo site_url('home/create')?>" > Create
                <button type="button" id="edit" class="btn btn-default" disabled> Edit</button>
                <button type="button" class="btn btn-default" disabled >  Delete</button>

                Date
                Name
                Status

            <?php if($result!=null){
                 foreach($result as $row){?>

                    <input type="checkbox" id="recs" name="recs[]" value="<?php echo $row->id;?>"/>
                 <?php echo $row->datee;?>
                  <?php echo $row->name;?>
                  <?php echo $row->status;?>

                <?php }
                }
                ?>

here's my jquery:

A: You have to class instead of using id for the checkbox. Check if any of the checkbox is checked and enable edit, delete button.
<input type="checkbox" class="recs" name="recs[]" value="<?php echo $row->id;?>"/>

A: Add class in this line
<input type="checkbox" id="recs" name="recs[]" value="<?php echo $row->id;?>"/>

Bind jquery on change event like
$(document).ready(function(){
    $('.your_class').click(function(){
        // check if checkbox is checked
        var checked = false;
        $(".your_class").each(function () {
            if($(this).is(":checked"))
            {
                checked = true;
            }
        });
        if(checked)
        {
            // enable buttons here

            return;
        }
        // disable buttons here
    });
});


text:
Q: Time-Series Forecasting using SVM in Matlab I want to forecast the next week (horizon = 7) electric load with lag=7 using AR, KNN and SVM, and I need help with that.
I've already wrote a code for all of them and i got results which is not as I expected it should be.
I have a time-series (7160-by-1) and here is a part of my code:
SVM:
Part of Training Data
52538   51690   55509   56740   58106   58280   57395
51690   55509   56740   58106   58280   57395   55425
55509   56740   58106   58280   57395   55425   55755
56740   58106   58280   57395   55425   55755   58563

Part of Training Targets
55425   55755   58563   58705   58245   61880   61540
55755   58563   58705   58245   61880   61540   59791
58563   58705   58245   61880   61540   59791   57945
58705   58245   61880   61540   59791   57945   59198

Part of Validate Data
101750  97201   98986   99491   99778   99711   100701
97201   98986   99491   99778   99711   100701  102790
98986   99491   99778   99711   100701  102790  98277
99491   99778   99711   100701  102790  98277   99520

Part of Validate Data Targets
102790  98277   99520   102719  103308  103750  103582
98277   99520   102719  103308  103750  103582  103193
99520   102719  103308  103750  103582  103193  98592
102719  103308  103750  103582  103193  98592   102985

Creating SVM model using LSSVM library
model = initlssvm(Train_Data,Train_Data_Targets,'f',[],[],'RBF_kernel','o');
model = tunelssvm(model,'simplex','crossvalidatelssvm',{5,'mse'});
model = trainlssvm(model);

Predicting future values
Estimated_Value = simlssvm(model,Validate_Data(1));

but results is not so good, so can you help me ? I can provide the KNN and AR code too is needed.


text:
Q: Nodejs Mongoose - Serve clients a single query result I'm looking to implement a solution where I can query the Mongoose Database on a regular interval and then store the results to serve to my clients.
I'm assuming this will reduce my response time when my users pull the collection.
I attempted to implement this plan by creating an empty global object and then writing a function that queries the db and then stores the results as the global object mentioned previously. At the end of the function I setTimeout for 60 seconds and then ran the function again. I call this function the first time the server controller gets called when the app is first run.
I then set my clients up so that when they requested the collection, it would first look to see if the global object exists, and if so return that as the response. I figured this would cut my 7-10 second queries down to < 1 sec.
In my novice thinking I assumed that Nodejs being 'single-threaded' something like this could work quite well - but it just seemed to eat up all my RAM and cause fatal errors.
Am I on the right track with my thinking or is it better to query the db every time people pull the collection?
Here is the code in question:
var allLeads = {};

var getAllLeads = function(){
    allLeads = {};
    console.log('Getting All Leads...');
    Lead.find().sort('-lastCalled').exec(function(err, leads) {
        if (err) {
            console.log('Error getting leads');
        } else {

            allLeads = leads;
        }
    });

setTimeout(function(){
    getAllLeads();
  }, 60000);
};
getAllLeads();

Thanks in advance for your assistance.


text:
Q: C# DLL exception not caught in unmanaged C++ As part of this excercise in familiarizing myself with using C# DLLs in unmanaged C++ via COM, I am trying to see how exception handling works.  I wrote a tiny C# dll that just contains a functon that throws an exception, and a C++ function that calls that function and tries to catch the exception.
Here's the DLL, written in C# using Visual Studio 2012:
namespace ExceptionThrowingLib
{
    public interface IExceptionThrower
    {
        void ThrowException();
    }

    public class ExceptionThrower : IExceptionThrower
    {
        public ExceptionThrower() { }
        public void ThrowException()
        {
            using (StreamWriter writer = new StreamWriter("c:/misc/exceptionthrower.txt", true))
            {
                writer.WriteLine("Exception generation request received at " + DateTime.Now.ToString());
            }
            throw new Exception("This is a requested exception.");
            using (StreamWriter writer = new StreamWriter("c:/misc/exceptionthrower.txt", true))
            {
                writer.WriteLine("This should never appear in the output file.");
            }
        }
    }
}

And here's the function that tries to use it, written in C++ using Visual Studio 2008:
void HandleException()
{
    IExceptionThrowerPtr pThrower(__uuidof(ExceptionThrower));
    try
    {
        pThrower->ThrowException();
        AfxMessageBox(_T("No exception caught."));
    }
    catch (...)
    {
        AfxMessageBox(_T("I caught an exception!"));
    }
}

When I call this function, the "No exception caught" message appears.
I expected that the client (C++) side would be able to catch a _com_error object and process it appropriately to learn what happened, but it appears nothing is being caught.  Why not?  Am I doing something wrong?
Thank you.

A: Did you use #import to generate the _com_ptr implementation?
If so, take care to omit the raw_interfaces_only directive, since it suppresses the generation of error-handling wrapper functions.

A: You're not really doing anything wrong, but have a wrong understanding.
The C++ code is not catching an exception because no exception is being thrown to the C++ code. The CLR/interop layer in the .NET runtime catches the exception before it is passed back. All good COM code never throws an exception from the COM method or property but returns a failure code.
What is the return code (HRESULT) from ThrowException().  It should not be S_OK but maybe E_FAIL or some other descriptive error.


text:
Q: Goolgle Chart vertical labels I can't don't find the property to modify the size of the label font.
My labels are not clearly displayed in front of the bars and some of them is missing.
I tried with the property below but nothing changed.
vAxis:{titleTextStyle:  { color: '#000', fontSize: 8, bold: true,  italic: false }}

A: see the config options for the Timeline, there is no vAxis.
use instead...
timeline:{rowLabelStyle: { color: '#000', fontSize: 8, bold: true, italic: false }}


text:
Q: Is there anyway to customize number keyboard for iOS (not iOS 8)? I need to customize iOS's native number keyboard for entering PIN in iOS 7 and earlier.
The requirement is: Numbers on keyboard should be random position each time the keyboard display.

So I cannot use the Phone keyboard of iOS.
Is there any native way to do this (without creating a fake keyboard)?
Thank you so much


text:
Q: open a web link in java netbeans I want to open a web page after clicking a button. I have a button and a text field. in that text field i type a web address. then i click the button.after that i want to show the result in my frame. is this possible? is there a component in palette to do so? .can i open a web page in java frame instead of opening in a browser. If it's impossible please guide me to open a web page in chrome or IE using java in net beans. Thanks in advance.
i tried this in event of button .
 try {
        Runtime r = Runtime.getRuntime();
        r.exec("C:\Users\K-9\AppData\Local\Google\Chrome\Application\chrome.exe");
    } catch (Exception e) {
        e.printStackTrace();
    }

Am i in a correct path.?

A: Since you use java you need to escape back slashes. This code perfectly works for me:
    String fileName="test.html";
    try {
        Runtime r = Runtime.getRuntime();
        r.exec("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe file:///C:/temp/" + fileName);
    } catch (Exception e) {
        e.printStackTrace();
    }

Note: put the path in a properties file to get more felxibility

A: 1 .I have made a new project in that I have selected a new frame and drag a button from the swing controls to your frame.

*In the buttons action event type the following code
String url="www.google.com";
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));

*Then run the project
And you can also follow this tutorial
Open a web link in java netbeans


text:
Q: Conditions on $X$ ensuring that a non-constant continuous function $f: X\to \mathbb{C}$ exists Let $X$ be a compact Hausdorff space. I would like to find a (minimal) condition on $X$, which is sufficient to guarantee that one can always find a non-constant continuous function
$f : X \to \mathbb{C}$.
Clearly we need to assume that $|X|>1$, but what else can we say?

A: Just to give this an answer:
As has been pointed out in the comments, $|X|>1$ is both necessary and sufficient: if $x,y\in X$ are distinct, Urysohn's lemma ensures that there is a continuous function $f:X\to[0,1]$ such that $f(x)=0$ and $f(y)=1$.


text:
Q: Managing Advanced Security Settings Active Directory User Accounts I have a requirement to change some settings in the security tab of user accounts in Active Directory for a large group of people. I need to give Everyone Access to specific Read Settings under the Security tab of a user account.
Is there a better way to manage this than having to go into Active Directory > View > Advanced Features > Open User Account > Security Tab; then adding the check marks for each of the Permissions for Everyone to each of the users? This also needs to be applied to new user accounts moving forwards.
Edit:
The specific permissions are the advanced permissions, not just read. I need to add Authenticated Users to be able to: Read account restrictions, Read general information, Read logon information, read group information, read phone and mail options, read private information.
I tried to setup a new OU. But I don't have those advanced security settings under the new OU.

A: You should be able to use Delegation of Control to delegate the required READ permission(s) to the Everyone group on User objects. If you set it at the domain root it should be inherited by all child nodes in the domain, avoiding the need to manually set the permissions on existing objects or new objects..


text:
Q: Assign Some Text to particular line in UITextView Programmatically I create an instance of UITextView programmatically. I want to assign some text to particular line in UITextView programmatically. Here is my code to create UITextView.
UITextView *textView =[[UITextView alloc]init];
textView.frame=CGRectMake(0,0,282,210);
[textView setReturnKeyType:UIReturnKeyDone];
[self.view addSubview:textView];

For example I want to add some text to particular line (at the end of line 5).
Programmatically, how is it possible to do this?

A: UITextView *textView =[[UITextView alloc]init];
textView.frame=CGRectMake(0,0,282,210);
textView.text = @"xxxxxx";

...

A: You can't edit lines directly in the text view because the number of lines depends on the content size and the size of the font.
Check this question as a reference:
How to Read Number of lines in UITextView
You could do some calculation to determine where to insert the text, but I'm nor sure if that's the best way to go around. There is probably a better way to accomplish what you are trying to do.

A: you can use the following:
NSString *str=yourTextview.text;
[str stringByAppendingString:yourNewString];

Then add it to textview
yourTextView.text=str;

check it and let me know if any clarification you need