text:
Q: BPEL, threads stucked on HashMap.getEntry? I am new to SOA, and currently we met a problem when using BPEL to do some XML transformation.
we have 3 SOA projects will do something like:

*

*Read input files from folder which is in text format

*Save file content in Database and put on AQ

*Read file id from AQ, load content from database, and transform to our internal XML format

*apply some business logic and transform content back to text format.

SOA proejct1 do step 1-2, project2 do step 3 and project3 to step4.
We are doing some load test with input 7000 files.
the problem we experienced is that the memory use of "Old Generation" keep accumulating, although major GC can reduce it, it still keep growing, until 100%. Then no new BEPL instance can be created, and we met transaction timeout.
after analyze heap dump, we get a result like below, it seems that BPELFactoryImpl hold a HashMap which more than 180M, and it will keep growing. so does anyone experienced something similar?
we use SOA version 12.1.3. this problem stopped us for weeks, please help, thanks a lot.
Image of heap analysis

A: Guys
Finally we got an answer on this, it was caused by a bug, as said by Oracle Support, we are waiting for the patch.
thanks for your attention.
It's a bug. You should raise an SR referring for: stuck threads on
    at java.util.HashMap.getEntry(HashMap.java:465)
 at java.util.HashMap.get(HashMap.java:417)
 at oracle.xml.parser.v2.XMLNode.setUserData(XMLNode.java:2137)
 at oracle.bpel.lang.v20.model.impl.ExtensibleElementImpl.doCreateElement(ExtensibleElementImpl.java:502)
 at oracle.dp.entity.impl.EmFacadeObjectImpl.getElement(EmFacadeObjectImpl.java:35)
 at oracle.bpel.lang.v20.model.impl.ExtensibleElementImpl.performDOMChange(ExtensibleElementImpl.java:707)
 at oracle.bpel.lang.v20.model.impl.ExtensibleElementImpl.doOnChange(ExtensibleElementImpl.java:636)
 at oracle.bpel.lang.v20.model.impl.ExtensibleElementImpl$DOMUpdater.notifyChanged(ExtensibleElementImpl.java:535)
 at oracle.dp.notify.impl.NotifierImpl.emNotify(NotifierImpl.java:39)
 at oracle.dp.entity.impl.EmHolderImpl.doNotifyOnSet(EmHolderImpl.java:53)
 at oracle.dp.entity.impl.EmHolderImpl.set(EmHolderImpl.java:47)
 at oracle.bpel.lang.v20.model.impl.CopyImpl.setTo(CopyImpl.java:115)
 at com.collaxa.cube.engine.ext.bpel.v2.wmp.BPEL2xCallWMP$CallArgument$1.evaluate(BPEL2xCallWMP.java:190)
 at com.collaxa.cube.engine.ext.bpel.v2.wmp.BPEL2xCallWMP.invokeMethod(BPEL2xCallWMP.java:103)
 at com.collaxa.cube.engine.ext.bpel.v2.wmp.BPEL2xCallWMP.__executeStatements(BPEL2xCallWMP.java:62)
 at com.collaxa.cube.engine.ext.bpel.common.wmp.BaseBPELActivityWMP.perform(BaseBPELActivityWMP.java:188)
 at com.collaxa.cube.engine.CubeEngine.performActivity(CubeEngine.java:2880)
 ....

Bug 20857627 (20867804) : Performance issue due to large number of threads stuck in HashMap.get


text:
Q: IEEEtran and natbib: forbid line break after [ in citation I am using a series of small hacks to use IEEEtran with natbib (I like \citeauthor and the like). In an eleven-page document, this produces identical-looking pdf output with and without \ifhack, with one exception: line breaks after "[".
Without the hack, I get
A [1],
[2]

With the hack, I get
A [1], [
2

What can I do to solve this? This is my MWE:
\documentclass{IEEEtran}
\newif\ifhack
\hacktrue
\ifhack
    \let\theoldbibliography\thebibliography
    \usepackage[numbers,sort&compress]{natbib}
    \let\thebibliography\theoldbibliography

    \makeatletter

    % https://tex.stackexchange.com/questions/47317/
    \def\NAT@def@citea{\def\@citea{\NAT@separator}}% removed \NAT@space

    \usepackage{etoolbox}
    \patchcmd{\NAT@citexnum}{--}{]--[}{}{}

    \makeatother

    \bibpunct{[}{]}{], [}{n}{}{,}
\else
    \usepackage{cite}

    % https://tex.stackexchange.com/questions/229126/
    \AtBeginDocument{\let\normalsfcodes\frenchspacing}
\fi

\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@article{a}
@article{b}
\end{filecontents}

\begin{document}
\parbox{1.2cm}{A \cite{a,b}}
\bibliographystyle{IEEEtran}
\bibliography{\jobname}
\end{document}

A: Replacing the call to \bibpunct by this fixed it for me:
\def\NAT@sep{], [}
\def\NAT@separator{\NAT@sep}% removed \NAT@penalty

redpajama_set_name: RedPajamaStackExchange


text:
Q: Receive events with Angular in order I have some trouble managing events in AngularJs.
In a service I dispatch events with the following line of code :
 $rootScope.$emit("FNH."+this.status, flowNodeHelper);

In a service "S1" I receive the event in the following way :
    $rootScope.$on('FNH.READY', function(event, flowNodeHelper) {
        flowNodeHelperService.setActive(flowNodeHelper);
    });
    $rootScope.$on('FNH.ACTIVE', function(event, flowNodeHelper) {
        flowNodeHelperService.setCompleting(flowNodeHelper);
    });
    $rootScope.$on('FNH.COMPLETING', function(event, flowNodeHelper) {
        flowNodeHelperService.setCompleted(flowNodeHelper);
    });
    $rootScope.$on('FNH.COMPLETED', function(event, flowNodeHelper) {
        flowNodeHelperService.setClose(flowNodeHelper);
    });

In a directive I receive event in the same way :
     $rootScope.$on('FNH.READY', function(event, flowNodeHelper) {
           console.log(flowNodeHelper + " status is ready");
      });
      $rootScope.$on('FNH.ACTIVE', function(event, flowNodeHelper) {
         console.log(flowNodeHelper + " status is  active");
      });
      $rootScope.$on('FNH.COMPLETING', function(event, flowNodeHelper) {
          console.log(flowNodeHelper + " status is completing");
      });
      ...

In my service "S1" when I receive event "FNH.READY", I call the flowNodeHelper.setCompleting() function which dispatch an event of type FNH.ACTIVE with $rootScope.$emit.
Same thing to go from ACTIVE status to COMPLETING status, etc. workflow is going on.
In "S1" I receive events in the good order READY, then ACTIVE, then COMPLETING, ...
But in my directive I receive them in the other order : COMPLETED then COMPLETING, then ACTIVE, then READY !!
How can I do to receive events in the same time in my "S1" service and in my directive please ?

A: Strange, it works if I do the following for each call to flowNodeHelperService in S1 :
$timeout(function() {
     flowNodeHelperService.setActive(flowNodeHelper);
}, 1);


text:
Q: PL/SQL Trigger exercise I have this question that I can see what it's asking but just can't wrap my head around how to write it specifically:
When a new tuple is inserted into the sales order detail, your trigger should insert a corresponding raw material tuple in the Inventory Report table for the Report date (i.e., beginning inventory level, consumption quantity, same-day order quantity, next-day order quantity)
Assumptions I gathered from the notes:
itemID = itemID from RAWMATERIALS table
reportDate = dueDate from SALESORDERS table
begInv = inventoryLevels from RAWMATERIALS table
consumpQty = itemID from FINISHEDGOODS * rmQuantity (raw material required to make each finished good) from FINISHED GOODS
orderNextDay = If consumpQty <= begInv then orderNextDay = consumpQty
                        orderSameDay = 0
orderSameDay = If consumpQty > begInv then  orderNextDay = begInv
                        orderSameDay = consumpQty - begInv
I thought the trigger might go something like:
CREATE OR REPLACE TRIGGER inv_report
BEFORE INSERT
ON SALESORDERDETAIL
FOR EACH ROW

DECLARE
item_id RAWMATERIALS.ITEMID%TYPE
reportDate SALESORDERS.DUEDATE%TYPE
begInv RAWMATERIALS.INVENTORYLEVEL%TYPE

And then I understand we would probably need to INSERT into INVENTORYREPORT table (which currently has no data in it) and maybe do an IF ELSEIF statement to satisfy the orderNextDay and orderSameDay columns but i'm still not familiar enough with PL/SQL to know exactly how to tackle this.
Can anyone help me out with this?  Thanks!

A: I'll try to find some time to write up some code for you on this, but my first recommendation is to NOT do this in a trigger. Instead, create a procedure "insert_so_detail" that inserts into the the SALESORDERDETAIL and then does the related insert into INVENTORYREPORT.
That procedure is then always called to insert into the S-O-D table. Executing DML inside triggers is a tricky thing to do because the database might decide it needs to restart the DML and then possibly do another insert into the I-R table. Check out this AskTOM thread for more details.
You are always better off putting your DML into PL/SQL package APIs, then only allow DML on the table through the API (grant execute on the package, do NOT grant insert or update or delete on the table directly to a user).


text:
Q: In spring boot, failing to insert data after checking whether that data pair exists in table, insertion will happen if that pair does not exist I've a table user_followers.It has two field user_id and following_id from user table. I'm supposed to insert user_id, following_id in this table after a check, if that pair already exists and status is inactive, then I'll just change the status which is working in my code. But if that pair does not exist, then insertion will happen.
table user_followers :
CREATE TABLE `user_followers` (
  `id` BIGINT(255) NOT NULL AUTO_INCREMENT,
  `user_id` BIGINT(100) NOT NULL,
  `following_id` BIGINT(100) NOT NULL,
  `status` ENUM('active','inactive') NOT NULL,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=latin1;

controller
@RequestMapping(value = "/add/follower", method = RequestMethod.POST)
    public JsonNode addFollower(HttpServletRequest httpServletRequest, @RequestBody String body) throws IOException {

        long startTime = System.currentTimeMillis();

        utility.printCallingUrl(httpServletRequest);

        JSONObject request = new JSONObject(body);
        JSONObject response = new JSONObject();

        String auth = httpServletRequest.getHeader("Authorization");
        String authentication = utility.getBasicAuth();

        if (auth.equals(authentication)) {
            try {
                UserFollowers userFollower = new UserFollowers();

                User user = userService.getUser(request.getLong("userId"));

                User following = userService.getUser(request.getLong("followingId"));

                userFollower = userFollowersService.getUserFollowerYYYY(user, following);

                if (userFollower == null) {
                    userFollower.setFollower(user);
                    userFollower.setFollowing(following);
                    userFollower.setStatus("active");
                    userFollower = userFollowersService.createUserFollowers(userFollower);

                    response = new JSONObject(utility.convertPOJOtoStringHiding(userFollower));

                } else if (userFollower != null && userFollower.getStatus().equals("inactive")) {
                    userFollower.setStatus("active");
                    userFollower = userFollowersService.updateUserFollower(userFollower);
                    response = new JSONObject(utility.convertPOJOtoStringHiding(userFollower));

                } else {
                    response = new JSONObject();
                }

            } catch (Exception e) {
                response = utility.createResponse(500, KeyWord.ERROR, e.toString());
                utility.showMessage(e.toString());
            }
        } else {
            response = utility.createResponse(500, KeyWord.ERROR, KeyWord.AUTHENTICATION);
        }

        return objectMapper.readTree(response.toString());
    }

service portion
public UserFollowers createUserFollowers(UserFollowers userFollowers) {
        return userFollowersRepository.save(userFollowers);
    }

repository portion
public UserFollowers getUserFollowerYYYY(User user, User following) {
        return userFollowersRepository.findByFollowerAndFollowing(user, following);
    }

That else if portion in controller is working fine, tested with data. not sure why
if (userFollower == null) {
                    userFollower.setFollower(user);
                    userFollower.setFollowing(following);
                    userFollower.setStatus("active");
                    userFollower = userFollowersService.createUserFollowers(userFollower);

                    response = new JSONObject(utility.convertPOJOtoStringHiding(userFollower));

                }

this portion is not working.

A: You need to initialize the userFollower object. In if condition you are checking whether it is null or not, and if it is null then you are setting values into it. But you cannot set values in null object. Below snippet must work for you:
if (userFollower == null) {
                userFollower = new UserFollowers();
                userFollower.setFollower(user);
                userFollower.setFollowing(following);
                userFollower.setStatus("active");
                userFollower = userFollowersService.createUserFollowers(userFollower);

                response = new JSONObject(utility.convertPOJOtoStringHiding(userFollower));

            }


text:
Q: How clear all notifications of notification bar in Android 7.1? I want clear all notifications of notification bar and had made a separated class that extends NotificationListenerService
package com.testando.teste;

import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;

public class NotificationListener extends NotificationListenerService {

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        cancelNotification(sbn.getKey());
    }
}

and my manifest file is like this:
<application>

<service android:name=".NotificationListener"
            android:enabled="true"
            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
            <intent-filter>
                <action android:name="android.service.notification.NotificationListenerService" />
            </intent-filter>
        </service>

 </application>

Then i want know why every time that a notification arrives, this not is removed?
Or then some one know some way of remove these notification without use of NotificationListenerService class, similar to "Clear All" button?

A: // Clears notification tray messages
    public static void clearNotifications(Context context) {
        try{
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.cancelAll();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

AndroidHive has a detail tutorial for Notifications with
Firebase Cloud Messaging
This tutorial is your reference.I hope this will help for you.


text:
Q: Green's Theorem with change of variables Evaluate $$\int_C F dr$$
$$ F =< x2, xy > $$
$$ C: x^2/4^2 + y^2/9 = 1 $$
With y ≥ 0 positively oriented.

For the circle
$$ u^2 + v^2 = 1 $$
$$ u=x/a $$
$$ v=y/b $$
$$ x=au $$
$$ y=bv $$
For the ellipse
$$ (x/a)^2 + (y/b)^2 = 1 $$
Computing the jacobian, I get 6. So, using greens theorem and switching to polar I get:
$$ \int \int (6rsinθ) rdrdθ $$
Just want someone to see if I've completed the changing of variables correctly. Computing integrals isn't all that difficult but I'm having a bit of trouble with the setup still.

A: $$F=(F_1(x,y),F_2(x,y))=(x^2,xy)$$
$$\oint\limits_{C}{F.dr}=\int{\int{\left( \frac{\partial {{F}_{2}}}{\partial x}-\frac{\partial {{F}_{1}}}{\partial y} \right)}}\,dA=\int\int y\,dA$$
let $x=2r\cos\theta$ and $y=3r\sin\theta$ we have
$$\left| \frac{\partial (x,y)}{\partial (r,\theta )} \right|=6r$$
and
$$\int\limits_{C}{F.dr}=\int_{0}^{2\pi}{\int_{0}^{1}} 18r^2\sin\theta\,drd\theta=\int_{0}^{2\pi}\sin \theta d\theta\times\int_{0}^{1}18r^2dr=0$$


text:
Q: FIX (quickfix) how to set which NIC/IP to use for the FIX session I am about to write a trading application using the FIX protocol (QuickFix for C++). The computer has 6 NIC card configured.  How do I let my FIX application (acting as an initiator in the case) to use one particular NIC card (IP address) of the all 6 available? The initiator setting only let me set the target host/port, not source IP/port.
And, how to let it use 2+ NIC cards simultaneously (for load balancing purpose) within the same application?
thank you

A: Initiator only needs to know of the IP address with which it needs to connect. How should a packet reach that IP is the job of the lower network layers and the kernel network stack.
Regarding 2+ NICs, that should be handled by the kernel routing table or the routers, which come along the way.

A: You can setup specific routes in your routing table.
Example:
route add -host  gw
Where  is IP address of the target machine to which you want to connect to.
 is the IP address of one of NIC you want to use.
Thus it will use that NIC card for quickfix session.
Hope this helps.


text:
Q: PHP theres some Impact using long text in a associative array? Im doing a database class in PHP and I want to make cache of the result of the querys in a associative array, My idea is to use the sql statment as the index of the cache array, its could be a good idea? or should I use a md5 from the sql?
class DB{
const HOST = 'localhost'; //Your Database Host!
const USER = 'user'; //Your Database Username!
const PASSWORD = 'pass'; //Your Database Password!
const DATABASE = 'database'; //Your Database Name!

private static $Instance;
private static $cache = array();

private function __construct(){
    self::$Instance = mysql_connect(self::HOST, self::USER, self::PASSWORD) or die("Could not connect to database server
Error:".mysql_error());
    mysql_select_db(self::DATABASE) or die("Could not connect to database
Error:".mysql_error());
    return self::$Instance;
}

public static function DB(){
    if(!isset(self::$Instance)){
      $c = __CLASS__;
      new $c();
    }
    return self::$Instance;
}

public static function QueryUnique($query){
    $query = "$query LIMIT 1";
    //$h = md5($query);
    $h = $query;
    if(isset(self::$cache[$h]))return self::$cache[$h];

    $result = mysql_query($query, self::DB());
    self::$cache[$h] = mysql_fetch_array($result);
    return self::$cache[$h];
}

}
Good Day

A: Before you get too far through your implementation, you should know that mysql does its own query caching and it has several major advantages over your implementation:

*

*The cache is shared among all PHP requests.

*Cached results are automatically cleaned up when the table data changes.

*The cache is limited to a certain memory size (rarely-used queries will be dropped out of the cache)

A: caching mysql data could be a little risky, it makes a lot of assumptions about things, however having said that a md5 checksum of the sql string is an good way of generating a id for your cache data, however you'll need to normalise the sql first, for example:
'select 1+2'
'select 1 + 2'
' select 1 +2'

each one will give a different checksum, you'll need to make sure any little differences between the same query are taken care of.

A: There shouldn't be a large impact, apart from a little extra memory usage, but compared to the result of the query, I don't think it will be a problem.
Associative arrays are ordered maps, so finding the right index shouldn't be affected too much by the total length of the string. The only downside would be that most strings start with the exact same text.
I wouldn't rely on just an MD5 hash for your queries. It's possible (if unlikely) that a hash collision would occur, and it would select a completely different query result. It might be an acceptable risk for your application however.
Personally, I wouldn't do this at the query level at all. The cacheability usually depends on the type of data returned. If you cache at this level, your application would be completely agnostic of what it is caching.

A: A hash (md5, sha1) will eat less memory space.

A: If the query is quite long, I'd go for using some kind of hash (like md5) :

*

*it will probably use a bit less memory (not that relevant, I suppose)

*it will allow you to store that in some other kind of cache, like file or APC or memcached or whatever without having to change the index.

Considering the low risks of collisions with md5, it doesn't seem "dangerous" to do that.
The only problem I see is it might get harder for you to find your cached data when debugging, be it with var_dump or any kind of "real" debugger :-(


text:
Q: Simple Transformation of data with AWK I have some data in this kind of format;-
Type,Fac1,Fac2,Fac3
1,0.1,0.1,0.1
2,0.2,0.2,0.2
3,0.3,0.3,0.3

Using AWK, I need to transform the data so that it looks like this;-
Type
1,Fac1,0.1
1,Fac2,0.1
1,Fac3,0.1
2,Fac1,0.2
2,Fac2,0.2
2,Fac3,0.2
3,Fac1,0.3
3,Fac2,0.3
3,Fac3,0.3

In other words a kind of "pivot" action that transforms from the horizontal to the vertical.
So I tried this:
awk -F ',' '{for (i=2;i<=NF;i++) { if (i==2) {print $1"," $i } else print $1"," $i}}'

A: $ cat tst.awk
BEGIN { FS=OFS="," }
NR==1 {
    print $1
    split($0,tags)
    next
}
{
    for (i=2; i<=NF; i++) {
        print $1, tags[i], $i
    }
}

$ awk -f tst.awk file
Type
1,Fac1,0.1
1,Fac2,0.1
1,Fac3,0.1
2,Fac1,0.2
2,Fac2,0.2
2,Fac3,0.2
3,Fac1,0.3
3,Fac2,0.3
3,Fac3,0.3

A: With perland splitting lines on comma
perl -sF, -lane '
  $.==1 && do{
    print shift @F;
    @h = @F; next;
  };
  my $i;
  print $F[0], splice(@F,1,1), $h[$i++] while @F > 1;
' -- -,=, file

Output:-
Type
1,0.1,Fac1
1,0.1,Fac2
1,0.1,Fac3
2,0.2,Fac1
2,0.2,Fac2
2,0.2,Fac3
3,0.3,Fac1
3,0.3,Fac2
3,0.3,Fac3

With Python and list comprehension in conjunction with the itertools module
python3 -c 'import itertools as it, sys
ifile = sys.argv[1]
fs,rs = ",","\n"
ofs,ors = fs,rs
with open(ifile) as f:
  for nr,l in enumerate(f,1):
    L = l.rstrip(rs).split(fs)
    if nr == 1:
      print(L.pop(0))
      H = L
    else:
      print(*[ofs.join([a,*b])
      for a,b in zip(it.repeat(L.pop(0)),zip(L,H))],sep=ors)
' file

GNU sed in extended regex mode:-
sed -Ee '
  1{
    s/,/\n/;P
    s/.*\n//
    h;d
  }
  /\n/!G
  s/,/&\n/2
  s/^(([^,]*,).*)\n(.*\n)([^,]*),/\1\4\n\2\3/
  /\n.*\n/!s/\n/,/
  P;D
' file


text:
Q: Is it possible to use ReportViewer with ASP.NET MVC? I'm trying to use ReportViewer (it must be ReportViewer!) with Asp.NET MVC. Is it possible?
Thanks!!!

A: You can use a webform for that or use the SOAP functionality

A: Report Viewer requires view state, and you do not have that in ASP.Net MVC.
There are two ways to do this.

*

*Have one page on you site that is a normal web page and use that to display the report viewer.

*Let your asp.net MVC page call your report server and then stream out the Http response to the client (we use this for PDF reports)

A: Any control that does not use ViewState or require runat=server can be used in ASP.NET MVC without problems.
The construction of ASP.NET MVC allows report writing in a view to be a relatively straightforward proposition.

A: You will want to put the report viewer on a Web Form.  Check out the second section on this page.
http://www.packtpub.com/article/mixing-asp.net-webforms-and-asp.net-mvc


text:
Q: How to connect to a fixed IP address device with a different network portion than my local network? My Actiontec WCB3000N has a fixed IP of 192.168.99.254 (or, at least, that's what it says on the side of the device). My LAN is 192.168.68.0 and when I try to direct my browser to 192.168.99.254, it times out. When I ping, I get "Destination Net Unreachable". I suspect the reason is that my routing table directs traffic to my gateway (router) for anything other than 192.168.68.0:
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.68.1    0.0.0.0         UG    100    0        0 eth0
192.168.68.0    0.0.0.0         255.255.255.0   U     100    0        0 eth0

Is there a configuration change I could make to allow me to connect to 192.168.99.254?

A: The documentation for your extender says

The default IP address for the WCB3000N is 192.168.99.254 when it is
not connected to a router with a DHCP server. If it is connected to a
router the IP address will be assigned to the WCB3000N using DHCP. If
you are having issues accessing configuration page or GUI please
contact Technical Support.

From https://actiontecsupport.zendesk.com/hc/en-us/articles/115000504846-How-do-I-access-the-configuration-page-or-GUI-of-the-device-
Using this you should be able to (a) get an IP and (b) manage the device.


text:
Q: How can I cluster a graph in Python? Let G be a graph. So G is a set of nodes and set of links. I need to find a fast way to partition the graph. The graph I am now working has only 120*160 nodes, but I might soon be working on an equivalent problem, in another context (not medicine, but website development), with millions of nodes.
So, what I did was to store all the links into a graph matrix:
M=numpy.mat(numpy.zeros((len(data.keys()),len(data.keys()))))

Now M holds a 1 in position s,t, if node s is connected to node t. I make sure M is symmetrical M[s,t]=M[t,s] and each node links to itself M[s,s]=1.
If I remember well if I multiply M with M, the results is a matrix that represents the graph that connects vertexes that are reached on through two steps.
So I keep on multplying M with itself, until the number of zeros in the matrix do not decrease any longer. Now I have the list of the connected components.
And now I need to cluster this matrix.
Up to now I am pretty satisfied with the algorithm. I think it is easy, elegant, and reasonably fast. I am having trouble with this part.
Essentially I need to split this graph into its connected components.
I can go through all the nodes, and see what are they connected to.
But what about sorting the matrix reordering the lines. But I don't know if it is possible to do it.
What follows is the code so far:
def findzeros(M):
    nZeros=0
    for t in M.flat:
        if not t:
            nZeros+=1
    return nZeros

M=numpy.mat(numpy.zeros((len(data.keys()),len(data.keys()))))
for s in data.keys():
    MatrixCells[s,s]=1
    for t in data.keys():
        if t<s:
            if (scipy.corrcoef(data[t],data[s])[0,1])>threashold:
                M[s,t]=1
                M[t,s]=1

nZeros=findzeros(M)
M2=M*M
nZeros2=findzeros(M2)

while (nZeros-nZeros2):
    nZeros=nZeros2
    M=M2
    M2=M*M
    nZeros2=findzeros(M2)

Edit:
It has been suggested that I use SVD decomposition. Here is a simple example of the problem on a 5x5 graph. We shall use this since with the 19200x19200 square matrix is not that easy to see the clusters.
import numpy
import scipy

M=numpy.mat(numpy.zeros((5,5)))

M[1,3]=1
M[3,1]=1
M[1,1]=1
M[2,2]=1
M[3,3]=1
M[4,4]=1
M[0,0]=1

print M

u,s,vh = numpy.linalg.linalg.svd(M)
print u
print s
print vh

Essentially there are 4 clusters here: (0),(1,3),(2),(4)
But I still don't see how the svn can help in this context.

A: In SciPy you can use sparse matrices. Also note, that there are more efficient ways of multiplying matrix by itself. Anyway, what you're trying to do can by done by SVD decomposition.
Introduction with useful links.

A: There's also graph_tool and networkit that have efficient routines for connected components, and both store the network efficiently. If you're going to work with millions of nodes, networkx will likely not be sufficient (it's pure python afaik). Both those tools are written in C++ so can handle analysis of large graphs with reasonable run times.
As Phil points out, your method will have horribly long compute times for large graphs (we're talking days, weeks, months...), and your representation for a graph of a million nodes will need something like a million gigabytes of memory!

A: Finding an optimal graph partition is an NP-hard problem, so whatever the algorithm, it is going to be an approximation or a heuristic. Not surprisingly, different clustering algorithms produce (wildly) different results.
Python implementation of Newman's modularity algorithm:
modularity
Also: MCL, MCODE, CFinder, NeMo, clusterONE

A: Here's some naive implementation, which finds the connected components using depth first search, i wrote some time ago. Although it's very simple, it scales well to ten thousands of vertices and edges...

import sys
from operator import gt, lt

class Graph(object):
    def __init__(self):
        self.nodes = set()
        self.edges = {}
        self.cluster_lookup = {}
        self.no_link = {}

    def add_edge(self, n1, n2, w):
        self.nodes.add(n1)
        self.nodes.add(n2)
        self.edges.setdefault(n1, {}).update({n2: w})
        self.edges.setdefault(n2, {}).update({n1: w})

    def connected_components(self, threshold=0.9, op=lt):
        nodes = set(self.nodes)
        components, visited = [], set()
        while len(nodes) > 0:
            connected, visited = self.dfs(nodes.pop(), visited, threshold, op)
            connected = set(connected)
            for node in connected:
                if node in nodes:
                    nodes.remove(node)

            subgraph = Graph()
            subgraph.nodes = connected
            subgraph.no_link = self.no_link
            for s in subgraph.nodes:
                for k, v in self.edges.get(s, {}).iteritems():
                    if k in subgraph.nodes:
                        subgraph.edges.setdefault(s, {}).update({k: v})
                if s in self.cluster_lookup:
                    subgraph.cluster_lookup[s] = self.cluster_lookup[s]

            components.append(subgraph)
        return components

    def dfs(self, v, visited, threshold, op=lt, first=None):
        aux = [v]
        visited.add(v)
        if first is None:
            first = v
        for i in (n for n, w in self.edges.get(v, {}).iteritems()
                  if op(w, threshold) and n not in visited):
            x, y = self.dfs(i, visited, threshold, op, first)
            aux.extend(x)
            visited = visited.union(y)
        return aux, visited

def main(args):
    graph = Graph()
    # first component
    graph.add_edge(0, 1, 1.0)
    graph.add_edge(1, 2, 1.0)
    graph.add_edge(2, 0, 1.0)

    # second component
    graph.add_edge(3, 4, 1.0)
    graph.add_edge(4, 5, 1.0)
    graph.add_edge(5, 3, 1.0)

    first, second = graph.connected_components(op=gt)
    print first.nodes
    print second.nodes

if __name__ == '__main__':
    main(sys.argv)

A: As others have pointed out, no need to reinvent the wheel. A lot of thought has been put into optimal clustering techniques. Here is one well-known clustering program.

A: Why not use a real graph library, like Python-Graph? It has a function to determine connected components (though no example is provided). I'd imagine a dedicated library is going to be faster than whatever ad-hoc graph code you've cooked up.
EDIT: NetworkX seems like it might be a better choice than python-graph; its documentation (here for the connected components function) certainly is.

A: Looks like there is a library PyMetis, which will partition your graph for you, given a list of links. It should be fairly easy to extract the list of links from your graph by passing it your original list of linked nodes (not the matrix-multiply-derived one).
Repeatedly performing M' = MM will not be efficient for large orders of M. A full matrix-multiply for matrices of order N will cost N multiplications and N-1 additions per element, of which there are N2, that is O(N3) operations. If you are scaling that to "millions of nodes", that would be O(1018) operations per matrix-matrix multiplication, of which you want to do several.
In short, you don't want to do it this way. The SVD suggestion from Vartec would be the only appropriate choice there. Your best option is just to use PyMetis, and not try to reinvent graph-partitioning.

A: The SVD algorithm is not applicable here, but otherwise Phil H is correct.


text:
Q: Why I can't run any docker commands inside my Jenkins Docker container? In my EC2 instance, I created a docker image from a running Jenkins container to get the existing jobs to the new image. Then I ran the new image with a different port mapping. Then when I enter inside the new container and ran docker ps. But i got an error like below
root@6151a7f83e0f:/# docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
root@6151a7f83e0f:/#

Then I tried to start docker inside the new container with this sudo service docker start. But I received below error,
etc/init.d/docker: 96: ulimit: error setting limit (Operation not permitted)

What am I missing here?
FYI, above commands are working fine in the old container. FYI, the whole purpose of this work is to migrate Jenkins from one instance to another without creating a fresh Jenkins container.

A: Check whether the old container is running with a different user other than the root. Normally Jenkins will create a new user called Jenkins. If so switch to the correct user from root and try to execute the commands.
Update: I assume you created the image from a running EC2 instance without rebooting. There can be issues if you do so. AWS page has a Warning for this. Check the below.


text:
Q: Ember disabled button I'm having an issue with embers bind-attr on the 'disabled' attribute on a button. Basically I can't get it to not disable my button.
isCancelled is a boolean in my model, according to this it should make 'disabled' appear and disappear inside the rendered tag.
Button looks like:
<button {{action "cancel" provisioning}} {{bind-attr disabled="isCancelled"}}>

It always renders the 'disabled' attribute.
I made a simple check to debug it. It looks like this:
isCancelled: {{isCancelled}}

It renders like: isCancelled: false
I'm using Ember 1.12.0

A: The problem is that if isCancelled is false, it will still render the disabled tag.
Make sure isCancelled is either TRUE or NULL. Only when it is null, 'disabled' won't be rendered

A: The bind-attr syntax is deprecated:
<button {{action "cancel" provisioning}} disabled={{isCancelled}}>

And in your case you are passing a string not the isCancelled property therefore it is always true,  {{bind-attr disabled=isCancelled}}> would work.


text:
Q: Godaddy SSL Certificates Install in NGINX Server | Failing I have requested SSL Certificate from GoDaddy, I got Private Key & CSR file, which downloaded as TEXT format.

I have modified file extensions as follows
**Original File Names**
firstcsrfile.txt
firstprivatekey.txt

**After Renaming File Names**
firstcsrfile.csr
firstprivatekey.key

domain.com.chained with below files downloaded from GoDaddy by selecting other option

From above files

*

*1fbfa674f5fe68aa.crt to domain.com.crt

*gd_bundle-g2-g1.crt to intermediate.crt

cat domain.com.crt intermediate.crt > domain.com.chained.crt

My nginx.conf file
worker_processes 4;

events { worker_connections 1024; }

http {
    server {
        listen 443 ssl;
        server_name _;

        ssl_certificate     /etc/nginx/ssl/domain.com.chained.crt;
        ssl_certificate_key /etc/nginx/ssl/firstprivatekey.key;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        add_header Strict-Transport-Security max-age=15768000;

        include /etc/nginx/mime.types;

        location / {
            root  /usr/share/nginx/html;
        }
    }
}

I have tried multiple times with various approaches but always same error
2022/10/24 13:51:20 [emerg] 1#1: SSL_CTX_use_PrivateKey("/etc/nginx/ssl/firstprivatekey.key") failed (SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch)
nginx: [emerg] SSL_CTX_use_PrivateKey("/etc/nginx/ssl/firstprivatekey.key") failed (SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch)

I have followed few blogs from Godaddy and some random blogs
https://blog.yudiz.com/install-ssl-certificate-with-nginx/
Since last 6-7 days struggled a lot, and where I am doing mistakes not sure !!.


text:
Q: OpenStreetMap and floorplan image interaction and coordinate conversion Premise: I need to build this feature for an open source application.
I want to allow users to upload images of floorplans and specify coordinates of objects on these floorplans.
In a specific common use case, users will need to be able to convert floorplan coordinates to geographic (latitude & longitude) coordinates, with good enough precision (not rocket science, but either not totally wrong).
The question is: on a high level, how can I accomplish this?
What kind of existing educational resources can I find about this subject?
My idea is to let users place/rotate/adapt the floorplan images on the geographic map, so that floorplan coordinates can be converted to geographic coordinates in some way.
The only good javascript open source project I found that deals with floorplan is d3-floorplan.
Any other suggestion will be very useful.
PS: I know it's a broad question, but I know of no other good place to ask this question than here on SO, I think this kind of question has a good value for people that will find this kind of information from future searches.

A: What you can do is to pick similar points to the not aligned image / floorplan and on a geographic aligned map (aka 'passpoints'). The processing with n passpoints is usually done at server side and the client downloads the resulting aligned plan as WMS / TMS layer to Leaflet or OL3 JS.
Some existing services: https://wiki.openstreetmap.org/wiki/Vertical_Aerial_Photographs
P.S: Be aware, that this covers legal aspects, too. So are you allowed to clone the georeference and does it fit well enough etc...


text:
Q: Presenting a modal view from a UITabBarController I checked the various answers here and could not find one which works. I have a regular TabBarController based application. I want to show a login screen at launch. What I did was

*

*Subclassed UITabBarController and implemented the following in the viewDidAppear:
LoginViewController *controller = (LoginViewController *)[[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"LoginVC"];
[self presentViewController:controller animated:YES completion:nil];
Once this runs there are 2 things happening :
1. The login view never shows up
2. The log has this : Warning: Attempt to present  on  whose view is not in the window hierarchy!
What am I missing?

A: rdelmar answer fixed the warning, that is do the presentation in the viewDidAppear. Thanks!


text:
Q: Get instance variable from previous request in rails I have an instance controller containing data which i need to filter in a separate function within the same controller. From what I've read this seems to be impossible, since the lifespan of an instance variable is only in the request. So in what way can i get a hold of the data in the instance controller which was served in the previous request? I know that you can use hidden fields and store it in session but there has to be a better way?

A: Use flash?
http://guides.rubyonrails.org/action_controller_overview.html#the-flash
flash[:my_object] = json_object

I don't think it is good for complete objects but maybe store the entire object in your DB and falsh the id. Or just flash some key parameters.


text:
Q: Como fazer uma pesquisa pelo input text do html? Quero fazer algo tal como o Google, onde você começa a digitar e vai aparecendo a lista de opções de acordo com o que você inseriu, onde estas opções já estão cadastradas no banco de dados...
EXEMPLO:
Um sistema de lanchonete, onde começa a digitar "COX" e já apareça todas as opções que começam com estas letras, como 'coxinha', 'coxinha de frango', 'coxinha de frango com catupiri' e afins...
Ou até mesmo digitando apenas a ID da opção que a pessoa deseja e já cai no produto..
O que é necessário? Como fazer isso?

A: Tens de ter um input com id='search_input', por exemplo, onde possas digitar o nome ou ID do produto.
 Depois tens uma table onde estão todos os produtos e seus respectivos ID's, neste caso dei um id='tabela-produtos' à tabela.
$('#search_input').bind('keyup click change',function(){
    search = $(this).val().toLowerCase();
    var re = new RegExp(search, 'g');

    $('#tabela-produtos tbody tr').each(function(){
        $(this).hide();
        target = $(this).find('td').text().toLowerCase();
        if(target.match(re) || target.match('^' + search)){
            $(this).show();
        }
    });
});

Neste caso, o código vai buscar o valor que introduzes no input, converte as maiúsculas para minúsculas (se for o caso), depois vai correr cada tr da tabela dos produtos e procurar em cada td uma correspondência para o valor/texto que introduziste no input.
Ao correr cada tr, estes são escondidos e só são mostrados os que tiverem correspondência com o valor do input.


text:
Q: Discrete singularities of $C^k$-functions. I'm stacked in the following problem: suppose $f:M\rightarrow N$ is a $C^k$ map between $C^k$-manifolds, such that $\dim M=\dim N=n>1$; if the singularities of $f$ are isolated, then the map is open.
I've tried to use the fact that in the complement of the singularities $f$ is a submersion, hence is an open map, but I don't know how to extend this to the whole function.
Thank you!


text:
Q: What is the analytics.js equivalent of _trackPageview found in ga.js Using the previous version of google analytics (ga.js) you can track a virtual page view using the _trackPageview method to record when something is downloaded or some other metric if desired.  Using the new analytics.js what is the syntax to track a virtual page view?

A: Just as you use the standard _trackPageview method for ga.js, in analytics.js also you can track virtual pageview by using the standard function.
Assume you have arleady initialised your analytics tracking code as below:
function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXXX-X', 'name as seen in GA tracking code');

Now inside any function block in your page, where you want to track a virtual page view , call the send pageview with the suitable name and title you want for the virtual page:
ga('send', 'pageview', {
  'page': '/usersignup',
  'title': 'user signup'
});


text:
Q: Jira Integration for Jenkins new create issue firstly i have tried to new create issue in Jira from Jenkins. But it is not successful. i spent to 3 days for how i can solve this issue.
when i completed integration between jira and jenkins site. There is one
link  http://jirasite.com/rest/api/2 .... in in Jira Integration for Jenkins monitor (under the manage jenkins)
But i deleted it. now i couldn't create again link in jenkins. There is below warning.
Jira Integration for Jenkins
Jira Sites cannot be added directly here in Jenkins, this Jenkins instance needs to be configure in Jira.
No Jira Sites available.
I got this below error message after jenkins job build fail for jira create

Build step 'Execute shell' marked build as failure
ERROR: Build step failed with exception
java.lang.NullPointerException
 at hudson.plugins.jira.JiraSession.createIssue(JiraSession.java:412)
 at hudson.plugins.jira.JiraCreateIssueNotifier.createJiraIssue(JiraCreateIssueNotifier.java:202)
 at hudson.plugins.jira.JiraCreateIssueNotifier.currentBuildResultFailure(JiraCreateIssueNotifier.java:357)
 at hudson.plugins.jira.JiraCreateIssueNotifier.perform(JiraCreateIssueNotifier.java:157)
 at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:45)
 at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:744)
 at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:690)
 at hudson.model.Build$BuildExecution.post2(Build.java:186)
 at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:635)
 at hudson.model.Run.execute(Run.java:1840)
 at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
 at hudson.model.ResourceController.execute(ResourceController.java:97)
 at hudson.model.Executor.run(Executor.java:429)
Build step 'JIRA: Create issue' marked build as failure
Finished: FAILURE

How I can solve this issue?
Thanks,

A: Please check the Jira configuration by clicking on validate settings. some values like component, issue type is might be missing, i faced same issue and found the value of issue type and issue priority was reset. i hope this might help you.


text:
Q: way to automate git repositories cloning I have to clone several repositories on the VM-s and then building software on them.
I have pretty nice build script but there is one issue. Before build, several repos should be cloned, and after some security updates, I am not allowed to add my public key to git server and also only supported protocol is ssh.
The cloning command looks like follow:
git clone ssh://userA@git-ger-XXX.com:YYYY/repoB

but there are plenty of them and passing password after each of them is really annoying and time-consuming.
What I am trying to do is to pass automatically password to clone command.
I was trying add userA:passwordA@git-ger.... but it works only for HTTPS, not ssh. I know that I have to switch to some automatic tools like ansible to make automatic deployment but it took me a lot of time to rewrite whole building process.
My question is how I can automatically pass a password to clone repo, without changing anything on the server. Ideally, would be to do this from bash level.
I was trying reading lines after typing git clone but it also didn't work for me.
Any help will be appreciated

A: IMO the best solution is using a custom GIT_ASKPASS helper and deliver the password as another environment variable. So for example, create a file git-askpass-helper.sh as:
#!/bin/sh
exec echo "$GIT_PASSWORD"

and then run git clone https://username@hostname/repo with environment variables GIT_ASKPASS=/path/to/git-askpass-helper.sh and GIT_PASSWORD=nuclearlaunchcodes.


text:
Q: Entity Framework 6 uses an UPDATE when it should be using a DELETE when deleting from a bound DataGridView I have a DataGridView bound to a BindingSource that is bound to DataMember tbl_Distribution_Orders_Restriction of DataSource bs_tbl_Series_Manufacturer, which is itself a BindingSource that has a DataSource linked to an entity, ForeNET.tbl_Series_Manufacturer.  The DataGridView in question displays only records related to the current record of bs_tbl_Series_Manufacturer.
tbl_Distribution_Orders_Restriction has the following definition:
CREATE TABLE [Fore].[tbl_Distribution_Orders_Restriction](
    [GM_ORDER_NBR] [varchar](50) NOT NULL,
    [Include] [bit] NOT NULL,
    [AUS_SRS_CD] [varchar](2) NULL,
    [ManufacturerID] [tinyint] NULL,
    [CNTLG_DLR_CD] [varchar](6) NULL,
    [FAWCode] [varchar](15) NULL,
 CONSTRAINT [PK_tbl_Distribution_Orders_Restriction_1] PRIMARY KEY CLUSTERED
([GM_ORDER_NBR] ASC) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [Fore].[tbl_Distribution_Orders_Restriction]  WITH CHECK ADD  CONSTRAINT [FK_tbl_Distribution_Orders_Restriction_tbl_Dealer] FOREIGN KEY([CNTLG_DLR_CD])
REFERENCES [Fore].[tbl_Dealer] ([cntlg_dlr_cde])

ALTER TABLE [Fore].[tbl_Distribution_Orders_Restriction] CHECK CONSTRAINT [FK_tbl_Distribution_Orders_Restriction_tbl_Dealer]

ALTER TABLE [Fore].[tbl_Distribution_Orders_Restriction]  WITH CHECK ADD  CONSTRAINT [FK_tbl_Distribution_Orders_Restriction_tbl_ModelCodes] FOREIGN KEY([FAWCode])
REFERENCES [Fore].[tbl_ModelCodes] ([FAWCode])

ALTER TABLE [Fore].[tbl_Distribution_Orders_Restriction] CHECK CONSTRAINT [FK_tbl_Distribution_Orders_Restriction_tbl_ModelCodes]

ALTER TABLE [Fore].[tbl_Distribution_Orders_Restriction]  WITH CHECK ADD  CONSTRAINT [FK_tbl_Distribution_Orders_Restriction_tbl_Series_Manufacturer] FOREIGN KEY([AUS_SRS_CD], [ManufacturerID])
REFERENCES [Fore].[tbl_Series_Manufacturer] ([aus_series_cde], [ManufacturerID])

ALTER TABLE [Fore].[tbl_Distribution_Orders_Restriction] CHECK CONSTRAINT [FK_tbl_Distribution_Orders_Restriction_tbl_Series_Manufacturer]

ALTER TABLE [Fore].[tbl_Distribution_Orders_Restriction] ADD  CONSTRAINT [DF_tbl_Distribution_Orders_Restriction_Include]  DEFAULT ((0)) FOR [Include]

CREATE TRIGGER [Fore].[trg_I_tbl_Distribution_Orders_Restriction]
   ON  [Fore].[tbl_Distribution_Orders_Restriction]
   INSTEAD OF INSERT
AS
BEGIN
    SET NOCOUNT ON
    INSERT INTO Fore.tbl_Distribution_Orders_Restriction (GM_ORDER_NBR, [Include], AUS_SRS_CD, ManufacturerID, CNTLG_DLR_CD, FAWCode)
    SELECT      inserted.GM_ORDER_NBR, inserted.Include, Fore.qry_SOM_OrderInfo.AUS_SRS_CD, Fore.tbl_ModelCodes.ManufacturerID,
                      Fore.qry_SOM_OrderInfo.CNTLG_DLR_CD, Fore.qry_SOM_OrderInfo.FAWCode
    FROM        inserted INNER JOIN
                      Fore.qry_SOM_OrderInfo WITH (NOEXPAND) ON inserted.GM_ORDER_NBR = Fore.qry_SOM_OrderInfo.GM_ORDER_NBR INNER JOIN
                      Fore.tbl_ModelCodes ON Fore.qry_SOM_OrderInfo.FAWCode = Fore.tbl_ModelCodes.FAWCode
END

CREATE TRIGGER [Fore].[trg_U_tbl_Distribution_Orders_Restriction]
   ON  [Fore].[tbl_Distribution_Orders_Restriction]
   INSTEAD OF UPDATE
AS
BEGIN
    SET NOCOUNT ON
        DELETE Fore.tbl_Distribution_Orders_Restriction
    FROM deleted INNER JOIN Fore.tbl_Distribution_Orders_Restriction ON Fore.tbl_Distribution_Orders_Restriction.GM_ORDER_NBR=deleted.GM_ORDER_NBR AND Fore.tbl_Distribution_Orders_Restriction.[Include]=deleted.[Include]
INSERT INTO Fore.tbl_Distribution_Orders_Restriction (GM_ORDER_NBR, [Include], AUS_SRS_CD, ManufacturerID, CNTLG_DLR_CD, FAWCode)
    SELECT  inserted.GM_ORDER_NBR, inserted.Include, qry_SOM_OrderInfo.AUS_SRS_CD, Fore.tbl_ModelCodes.ManufacturerID, Fore.qry_SOM_OrderInfo.CNTLG_DLR_CD, Fore.qry_SOM_OrderInfo.FAWCode
    FROM    inserted INNER JOIN Fore.qry_SOM_OrderInfo WITH (NOEXPAND)
                ON inserted.GM_ORDER_NBR = Fore.qry_SOM_OrderInfo.GM_ORDER_NBR INNER JOIN
                      Fore.tbl_ModelCodes ON Fore.qry_SOM_OrderInfo.FAWCode = Fore.tbl_ModelCodes.FAWCode
END

My problem is this:
When I delete a row from the DataGridView, the row disappears as expected.  At that point, my event code calls Context.SaveChanges()  However, the row is not deleted from the database, and the next time I open the form, all the records that I thought I had deleted are still there.  No error messages are displayed at any point.
I bound Context.Database.Log to the debug window, and found that when I perform a delete through the DataGridView, results similar to the following log output are being generated on executing Context.SaveChanges():
UPDATE [Fore].[tbl_Distribution_Orders_Restriction]
SET [AUS_SRS_CD] = NULL, [ManufacturerID] = NULL
WHERE ([GM_ORDER_NBR] = @0)

-- @0: '6W2CAA' (Type = AnsiString, Size = 50)

-- Executing at 12/02/2014 8:15:51 AM +11:00

-- Completed in 142 ms with result: 1

The end result of this SQL statement is that no changes at all are made to the '6W2CAA' record in [Fore].[tbl_Distribution_Orders_Restriction], since that table has triggers that populate fields [AUS_SRS_CD] and [ManufacturerID] (amongst others) based on the [GM_ORDER_NBR] value, the former fields existing only to obviate the need for an unacceptably slow stored procedure that must look up these values from a number of other tables - it is more acceptable for the lookup load to be shifted to the SQL Server on insert/update.
However, even if these triggers did not exist, in the event of a user deleting then inserting records with the same [GM_ORDER_NBR] value, an error would occur since a record with the same (primary key) [GM_ORDER_NBR] value would still exist, albeit with NULL [AUS_SRS_CD] and [ManufacturerID] values.
I would have expected that the SQL statement executed by Entity Framework after a delete from the DataGridView would be more like: DELETE FROM [Fore].[tbl_Distribution_Orders_Restriction] WHERE ([GM_ORDER_NBR] = @0)
When I .Remove an entity in event code, followed by .SaveChanges, the invalid UPDATE still occurs first, followed by a DELETE.
How can I get Entity Framework to execute the correct DELETE SQL statement in response to a DataGridView deletion, instead of (rather than in addition to) a wholly inappropriate UPDATE?

A: Entity Framework does not issue "Delete" for relations, your DataGridView is bound to an Entity Collection not an Entity Set.
When an entity is removed from EntityCollection, Entity Framework will only delete its association or relation which is identified by a foreign Key. Entity Framework does not know whether to delete it from database or not.
Consider an entity with multiple foreign keys.
 Table Products
    PK ProductID
    FK CategoryID (nullable)
    FK VendorID (nullable)

Assuming Product is related to Category table and Vendors table. Now when you are removing a product from one category, it is not necessary that it should be deleted from table itself. Because some products may have category and some may not have, similarly some may have vendors defined and some may not.
This is the reason EF does not delete actual record, instead it just sets its foreign key column to null. Which removes an entity from its associated related table, but entity is still present.
If foreign keys are not nullable, then old version of EF used to throw an error. I don't know about the new one yet.
Theoretically, in case of nullable foreign keys, Child Entity can exist without its parent, and in case of non nullable foreign keys, Child Entity can not exist without its parent, in this case relation should be defined correctly. And I had overriden a SaveChanges method to identify non nullable foreign keys and delete the record accordingly if it's associated parent is set to null.
Answer
You can bind DGV to Entity Set of tbl_Distribution_Orders_Restriction and set Condition/Predicate for ForeginKey = Manufacturer DGV's SelectedItem.PrimaryKey

A: Akash Kava's answer was enlightening in its revelation that in situations such as the one I described, a record is unlinked, not deleted on "delete".  However, his "answer" was quite inadequate in that, yes, you can "bind DGV to Entity Set of tbl_Distribution_Orders_Restriction and set Condition/Predicate for ForeginKey = Manufacturer DGV's SelectedItem.PrimaryKey", however, in doing so, you lose the EF tracking and the ability to make changes to the underlying DB's data altogether.
However, Akash Kava's answer was a useful start, so I haven't simply downvoted it.
The solution I found was:
Load the data for tbl_Distribution_Orders_Restriction, and filter it to an ObservableCollection that is bound to the BindingSource, then add a handler for the ObservableCollection's  CollectionChanged event, in which the ObservableCollection's changes are propagated back to the source, from where they will be propagated back to the database on m_Context.SaveChanges:
Dim m_oc_tDSR = New ObjectModel.ObservableCollection(Of tbl_Distribution_Stock_Restriction)(From tDSR As tbl_Distribution_Stock_Restriction In m_Context.tbl_Distribution_Stock_Restriction.Local
                                                                                Where tDSR.AUS_SRS_CD = m_CurrentSeries And tDSR.ManufacturerID = m_CurrentManufacturer
                                                                                Select tDSR)
bs_tbl_Distribution_Stock_Restriction.DataSource = m_oc_tDSR
bs_tbl_Distribution_Stock_Restriction.ResetBindings(False)
AddHandler m_oc_tDSR.CollectionChanged, AddressOf m_oc_tDSR_CollectionChanged

Where the definition for m_oc_tDSR_CollectionChanged is (in essence):
Private Sub m_oc_tDOR_CollectionChanged(sender As Object, e As System.Collections.Specialized.NotifyCollectionChangedEventArgs)
    Select Case e.Action
        Case Specialized.NotifyCollectionChangedAction.Add
            For Each tDOR As tbl_Distribution_Orders_Restriction In e.NewItems
                m_Context.tbl_Distribution_Orders_Restriction.Add(tDOR)
            Next
        Case Specialized.NotifyCollectionChangedAction.Remove
            For Each tDOR As tbl_Distribution_Orders_Restriction In e.OldItems
                Try
                    m_Context.tbl_Distribution_Orders_Restriction.Remove(tDOR)
                Catch ex As InvalidOperationException
                End Try
            Next
        Case Specialized.NotifyCollectionChangedAction.Replace
            For CtrA As Long = 0 To e.OldItems.Count - 1
                m_Context.tbl_Distribution_Orders_Restriction.Remove(DirectCast(e.OldItems, tbl_Distribution_Orders_Restriction))
                m_Context.tbl_Distribution_Orders_Restriction.Add(DirectCast(e.NewItems, tbl_Distribution_Orders_Restriction))
            Next
    End Select
End Sub

This allows a filtered entity set that is still tracked.


text:
Q: How can I prevent extra characters at the end of my string in Regex? Background
I'm working on a Javascript application where users have to use a specific email domain to sign up (Either @a.com or @b.com. Anything else gets rejected).
I've created a regex string that makes sure the user doesn't do @a.com with nothing in front of it and limits users to only @a.com and @b.com. The last step is to make sure the user doesn't add extra characters to the end of @a.com by doing something like @a.com.gmail.com
This is the regex I currently have:
\b[a-zA-Z0-9\.]*@(a.com|b.com)
Question
What can I use at the end to prevent anything from being added after a.com or b.com? I'm very novice at regex and have no idea where to start.

A: To solve your problem add $ to the regex's end. $ means your match should be at the strings' end.
Also you can reduce (a.com|b.com) to [ab]\.com. Look I've also escaped the dot
The character class [ab] means one of its characters should be matched.
Check this demo.
As stated in the comments, be sure to use the (m)ultiline flag, this way the regex engine will threat each line as a separate string.


text:
Q: Fluid key input? (constant stream of key input) in Javascript

window.onload = function() {
  canv = document.getElementById("gc");
  canv.width = 500;
  canv.height = 300;
  ctx = canv.getContext("2d");
  document.addEventListener("keydown", keyDown);
  setInterval(game, 10);
}

function Paddle(x, y) {
  this.x = x;
  this.y = y;
  this.l = 50;
  this.score = 0;
}

function Ball(x, y, xv, yv) {
  this.x = x;
  this.y = y;
  this.xv = xv;
  this.yv = yv;
  this.s = 5;
  this.update = function() {
    this.x += this.xv;
    this.y += this.yv;
  }
}

function drawLine(x1, y1, x2, y2) {
  ctx.beginPath();
  ctx.moveTo(x1, y1)
  ctx.lineTo(x2, y2)
  ctx.stroke();
  ctx.closePath();
}

function random(min, max) {
  var i = 0;
  while (!i) {
    i = Math.floor(Math.random() * (max - min + 1) + min);
  }
  return i;
}

p1 = new Paddle(10, 125);
p2 = new Paddle(490, 125);
b = new Ball(250, 150, random(-2, 2), random(-2, 2));

function game() {
  b.update();
  if (p1.y < 0)
    p1.y = 0;
  else if (p1.y + p1.l > canv.height)
    p1.y = canv.height - p1.l;
  if (p2.y < 0)
    p2.y = 0;
  else if (p2.y + p2.l > canv.height)
    p2.y = canv.height - p2.l;
  if (b.y < 0 || b.y > canv.height)
    b.yv = -b.yv;
  if (b.x < 0) {
    p2.score++;
    b = new Ball(30, 150, random(0, 2), random(-2, 2));
  } else if (b.x > canv.width) {
    p1.score++;
    b = new Ball(canv.width - 30, 150, random(-2, 0), random(-2, 2));
  }
  if ((b.x == p1.x && b.y > p1.y && b.y + b.s < p1.y + p1.l) ||
    b.x + b.s == p2.x && b.y > p2.y && b.y + b.s < p2.y + p2.l)
    b.xv = -b.xv;
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, canv.width, canv.height);
  ctx.strokeStyle = "white";
  drawLine(p1.x, p1.y, p1.x, p1.y + p1.l);
  drawLine(p2.x, p2.y, p2.x, p2.y + p2.l);
  ctx.fillStyle = "white";
  ctx.fillRect(b.x, b.y, b.s, b.s);
  ctx.font = "30px sans serif";
  ctx.fillText(p1.score, 200, 50);
  ctx.fillText(p2.score, 300, 50);
}

function keyDown(evt) {
  switch (evt.keyCode) {
    case 83:
      p1.y += 10;
      break;
    case 87:
      p1.y -= 10;
      break;
    case 40:
      p2.y += 10;
      break;
    case 38:
      p2.y -= 10;
      break;
  }
}
<canvas id="gc"></canvas>

In this rudimentary Pong program, I use document.addEventListener("keydown", keyDown); to control the movement of the paddles. But, the function is not being called at a consistent rate (the movement is not fluid). The first press is registered, then a slight pause, and THEN it moves fluidly. (Similar to if you hold a letter key down, it types one letter. If you continue holding it, it continues to type letters, but not before a slight pause? Not sure if I'm being clear here...)
Is there a way to have consistent input/function calls using the "keydown" event listener?

A: You can smooth out the effect of your OS keyboard repeat rate by setting the value of a variable on keydown, and clearing it on keyup. For example:
let direction = null;

document.addEventListener("keydown", function (evt) {
  switch (evt.keyCode) {
    case 83:
      direction = "down";
      break;
    case 87:
      direction = "up";
      break;
    case 40:
      direction = "down";
      break;
    case 38:
      direction = "up";
      break;
    default:
      direction = null;
  }
});

document.addEventListener("keyup", function (evt) {
  direction = null;
})

Check the state of this variable on each iteration of your game loop. Most HTML5 games use requestAnimationFrame for that.


text:
Q: Comparing Two Uneven List Tuples I am trying to compare to list tuples and subtract the second value pair ONLY if the first value matches. After this subtraction is done, I would like to keep the tuples that were not in the list. In this case, I would keep ('2574529422', 1).
The code below that I tried returns an empty list. I don't know why it's not working, if allc[0] should be in stmt[0] when it's iterating??
I tried:
a = [(allc[0], stmt[1]-allc[1]) for allc,stmt in zip_longest(self.allocation_results, self.statement_results)
             if allc[0] in stmt[0]]

input:
List 1

[('0856547518', 2), ('1292058151', 5), ('2574529422', 3)]

List 2

[('0856547518', 1), ('1292058151', 3), ('2574529422', 1), ('123456789', 1)]

Expected output:
[('0856547518', 1), ('1292058151', 2), ('2574529422', 2), ('2574529422', 1)]

A: If the first values of each of your tuples is unique as in your example, you can use them as dictionaries in a list comprehension to get your result:
l1 = [('0856547518', 2), ('1292058151', 5), ('2574529422', 3)]
l2 = [('0856547518', 1), ('1292058151', 3), ('2574529422', 1), ('123456789', 1)]

>>> [(k, dict(l1)[k]-dict(l2)[k]) if k in dict(l1) else (k, dict(l2)[k]) for k in dict(l2)]
[('0856547518', 1), ('1292058151', 2), ('2574529422', 2), ('123456789', 1)]

A: I had to rearrange a few things to get this to work.
I suspect you had some errors you didn't report.
from itertools import zip_longest

ar = [('0856547518', 2), ('1292058151', 5), ('2574529422', 3)]
sr = [('0856547518', 1), ('1292058151', 3), ('2574529422', 1), ('2574529422', 1)]

def check(allc, stmt):
    if allc is None:
        return True
    return allc[0] == stmt[0]

def make_tuple(allc, stmt):
    if allc is None:
        return stmt
    return allc[0], allc[1] - stmt[1]

a = [make_tuple(allc, stmt) for allc,stmt in zip_longest(ar, sr) if check(allc, stmt)]

print(a)

Output as required


text:
Q: pause/resume activity started from another activity in android I have an activity say A from which I am starting an activity say B through startActivity().
How do I pause/resume activity B from activity A?

A:
How do I pause/resume activity B from activity A?

You can't, sorry. Most likely, no code from Activity A is even running while Activity B is on-screen.

A: It's a little difficult to determine what you're asking for. If you simply want to end Activity A and go back to Activity B, then you would call finish() to kill Activity A, or even just use the Back button to end it and go back...
onPause() and onResume are part of an Activity's life cycle. They are called by the Android framework and should never be called explicitly.


text:
Q: insert into one table from another table using join update or insert SQL server I currently have two tables as seen in the pictures below.
The first table is called bottle:

The second table is called cases:

I am trying to insert into the bottles table where case_id = 0 the values seen in the cases table (ie case_id=100, 100, 103, 103 etc..). They are two separate tables and I am trying to join them without creating NULL values.
Please let me know if I need to use insert, join, or update. I would manually do it however these data points are coming live from a PLC and there will be many more than just all the data points seen below.

A: There is no explicit join column with which to perform the UPDATE you want.  But we can create one by joining on the row number value from each table, using a certain order.  In the query below, I order the row number in the bottle table using the bottle_id, and the row number in the cases table using the case_id.
UPDATE t1
SET t1.case_id = t2.case_id
FROM
(
    SELECT t.*, ROW_NUMBER() OVER (ORDER BY bottle_id) rowId
    FROM bottle t
) t1
INNER JOIN
(
    SELECT t.*, ROW_NUMBER() OVER (ORDER BY case_id) rowId
    cases t
) t2
    ON t1.rowId = t2.rowId

This should give output in bottle looking like this (some columns omitted):
bottle_id      case_id
1              100
2              100
3              103
4              103
5              104
6              104
7              105
8              105


text:
Q: Equavalent operation of mathematica in python Suppose that:
h=[1,2,3]

There is operation N[expr] in Mathematica that gives us:
N[h[0]]=1, N[h[1]]=2, N[h[2]]=3

and for example N[h[6]]=0, is something like this in Python?

A: N[expr] in mathematica gives you the numeric value oft an expression. This makes sense in mathematica, which dos symbolic math.
In Python you normally don't have symbolic expressions (unless using specialized libraries such as sympy).
You can convert objects to integers using int. For example, int(2), int('2'), or int(2.6) result in the value 2.
Or you can convert to floating point using float.

A: Accesing out-of-bound value in Python using [..] operator in Python raises IndexError.
>>> h = [1, 2, 3]
>>> h[0]
1
>>> h[6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

By catching IndexError, you can have similiar operation using a custom function:
>>> def N(sequence, index, fallback=0):
...     try:
...         return sequence[index]
...     except IndexError:
...         return fallback
...
>>> h = [1, 2, 3]
>>> N(h, 0)
1
>>> N(h, 1)
2
>>> N(h, 2)
3
>>> N(h, 6)
0
>>>
>>> N(h, 6, 9)  # different fallback value other than 0
9


text:
Q: REST Assured don't log response body I have method:
<https://uri:8080/getVer>

This method returns info about version of app. Like that:
1.39.1

It is text- not xml, not json, not html.
When I try to use this method in REST Assured:
        RestAssured.given()
            .log().uri()
            .baseUri("https://uri:8080/")
            .relaxedHTTPSValidation()
            .get("getVer")
            .then()
            .log().all();

I do not recived a response body:
Logs from process:

Request URI:  https://uri:8080/getVer

HTTP/1.1 200
Content-Length: 6
X-Flow-Trace-Id: someTraceId
Content-Type: application/json;charset=UTF-8
Date: Thu, 30 Dec 2021 19:27:03 GMT
Set-Cookie: some_cookie; path=/; Httponly; Secure
Server: some app server

Process finished with exit code 0

Why i am not received response body? When I try to go to this link on my browser, I recieved a value.
It is an example from Postman

A: Try this:
RestAssured.given()
            .log().uri()
            .baseUri("https://uri:8080/")
            .relaxedHTTPSValidation()
            .get("getVer")
            .then()
            .log().all()
            .extract()
            .response();


text:
Q: md5sum prepends '\' to the checksum Why md5sum is prepending "\" in front of the checksum when finding the checksum of a file with "\" in the name?
$ md5sum /tmp/test\\test
\d41d8cd98f00b204e9800998ecf8427e  /tmp/test\\test

The same is noted for every other utility.

A: This is documented, for Coreutils' md5sum:

If file contains a backslash or newline, the line is started with a backslash, and each problematic character in the file name is escaped with a backslash, making the output unambiguous even in the presence of arbitrary file names.

(file is the filename, not the file's contents).
b2sum, sha1sum, and the various SHA-2 tools behave in the same way as md5sum. sum and cksum don't; sum is only provided for backwards-compatibility (and its ancestors don't produce quoted output), and cksum is specified by POSIX and doesn't allow this type of output.
This behaviour was introduced in November 2015 and released in version 8.25 (January 2016), with the following NEWS entry:

md5sum now ensures a single line per file for status on standard output, by using a '\' at the start of the line, and replacing any newlines with '\n'. This also affects sha1sum, sha224sum, sha256sum, sha384sum and sha512sum.

The backslash at the start of the line serves as a flag: escapes in filenames are only processed if the line starts with a backslash. (Unescaping can't be the default behaviour: it would break sums generated with older versions of Coreutils containing \\ or \n in the stored filenames.)

A: Stephen Kitt's answer covers the what and I will try to cover why this change was implemented. First, someone observed that a filename containing newlines1 could result in ambiguous output. For example, consider this output:
d41d8cd98f00b204e9800998ecf8427e  foo
25af89c92254a806b2e93fffd8ac1814  bar

Does this mean there were two files foo and bar, or only one file whose filename is "foo\n25af89c92254a806b2e93fffd8ac1814  bar"? Granted, this latter possibility is highly unlikely, but it is possible. To resolve the ambiguity the developers chose to escape newlines with a backslash (\). The output then becomes distinguishable. However, then there is a further ambiguity:
764efa883dda1e11db47671c4a3bbd9e  foo\nbar

Does this file's name contain a newline, or a backslash followed by an n? To resolve this we need to escape backslashes too, so that the latter case becomes:
764efa883dda1e11db47671c4a3bbd9e  foo\\nbar

Finally, they elected to prepend each output line which contains such escapes with a \\ to make it easy for a parser to detect whether escaping has been done. Presumably this was done to allow parsers to handle output both from escaping versions of md5sum and from non-escaping versions (non-GNU). The flag also means that "costly" un-escaping does not need to be done when not necessary. You can see an example of this parsing in action in md5sum.c itself (line 382 in the linked version).

1 By newline I mean the character \n which is sometimes also specifically referred to as a linefeed or LF; see md5sum.c.


text:
Q: Login to a Remote Service (ruby based) from iPhone Ok here's my problem in a nutshell I've built a web service from ruby on rails. I'm using restful_authentication to create and run the login but I'm also building an iPhone application to access my web service but I can't quite figure it out. I was wondering if anyone could help me figure out a place to begin.

A: Are you asking from the iphone side or the rails side?
For Rails, I think you should either use the basic_authentication features of restful_authentication to take in a username password and authorize your request, or follow this article: http://www.compulsivoco.com/2009/05/rails-api-authentication-using-restful-authentication/ which lets you login via an API Key
def login_from_api_key
  self.current_user = User.find_by_api_key(params[:api_key]) unless params[:api_key].empty?
end

def current_user
  @current_user ||= (login_from_session || login_from_api_key || login_from_basic_auth || login_from_cookie) unless @current_user == false
end

The iPhone side is simpler if you use the api_key; just append it to your http headers and you'll be good to go.


text:
Q: Flutter making bad Hero animation I have implemented a Hero animation between 2 screens. The problem is that it's not showing the animation properly. Putting yellow lines under the word as you can see in the picture
Example of what I mean
  child: InkWell(
    onTap: (){
      Navigator.push(context, MaterialPageRoute(builder: (context) => CityScreen(widget.city)));
    },
    child: Row(
      children: [
        Padding(
          padding: const EdgeInsets.all(15.0),
          child: Hero(
            tag: widget.city.name + 'img',
            child: Container(
              child: Image(
                width: 100,
                height: 100,
                image: AssetImage('images/oussama.jpg'),
              ),
            ),
          ),
        ),

The other screen there is:
  child: Scaffold(
    body: NestedScrollView(
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return <Widget>[
          SliverAppBar(
            expandedHeight: 300.0,
            floating: false,
            pinned: true,
            flexibleSpace: Center(
              child: FlexibleSpaceBar(
                  centerTitle: true,
                  title: Hero(
                    tag: widget.city.name,
                    child: Container(
                      child: Text(widget.city.name,
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 30,
                            fontWeight: FontWeight.bold,
                          ),
                      ),
                    ),
                  ),
                  background: Hero(
                    tag: widget.city.name + 'img',
                    child: Container(
                      child: Image(
                        image: AssetImage('images/oussama.jpg'),
                      ),
                    ),
                  ),
              ),
            ),
          ),
        ];
      },

A: Try wrapping your root widget in a Scaffold.


text:
Q: Getting error while running dbca command as oracle user on linux, please help me on this could someone please help me on the below error to get ride of it:
[oracle@localhost ~]$ dbca
UnsatisfiedLinkError exception loading native library: njni11
java.lang.UnsatisfiedLinkError: /u01/app/oracle/product/11.2.0/db_home/lib/libnjni11.so: libaio.so.1: cannot open shared object file: No such file or directory
Exception in thread "main" java.lang.UnsatisfiedLinkError: get
        at oracle.net.common.NetGetEnv.get(Native Method)
        at oracle.net.config.Config.getNetDir(Unknown Source)
        at oracle.net.config.Config.initConfig(Unknown Source)
        at oracle.net.config.Config.<init>(Unknown Source)
        at oracle.sysman.assistants.util.NetworkUtils.<init>(NetworkUtils.java:286)
        at oracle.sysman.assistants.util.step.StepContext.<init>(StepContext.java:332)
        at oracle.sysman.assistants.dbca.backend.Host.<init>(Host.java:811)
        at oracle.sysman.assistants.dbca.ui.UIHost.<init>(UIHost.java:258)
        at oracle.sysman.assistants.dbca.ui.InteractiveHost.<init>(InteractiveHost.java:54)
        at oracle.sysman.assistants.dbca.Dbca.getHost(Dbca.java:164)
        at oracle.sysman.assistants.dbca.Dbca.execute(Dbca.java:112)
        at oracle.sysman.assistants.dbca.Dbca.main(Dbca.java:180)
[oracle@localhost ~]$

A: Start with (use the appropriate install syntax for your distro)
sudo apt-get install libaio1

and if that doesn't do the trick, do
sudo apt-get install libaio libaio-dev

Paul...

A: You maybe have several Oracle home in your server.
Check your path environment: ORACLE_HOME/bin should be in first position.

A: search " libaio.so.1" file in directory,
copy it or move to your path mentioned in error, as /u01/app/oracle/product/11.2.0/db_home/lib/
and this worked for me

A: I Have also faced this error and finally able to resolve. It will occur only if prerequisite have not been met.
Below are the two cases:

*

*Oracle binaries which you have downloaded is not supported by the OS.

*You have not installed the suggested oracle RPM packages.

In my case I was getting this error because of the missing oracle 11g RPM's.
Below are the list of suggested oracle 11g and 12c packages. Just crossverify once and try installing from fresh.
https://www.orahow.com/2018/07/dbca-unsatisfiedlinkerror-exception.html


text:
Q: How to parse a weirdly formatted data file? How to read a weirdly formatted data file?
For example if there are different types of seperators (, : |) all used together?
Looking at a dataframe example, something along these lines:

A: A monstrous response to the monstrous data. First, split each column containing k:v pairs and convert them to pandas Series. Combine the results for all three "Other" columns into one dataframe:
others = pd.concat(data[x].str.split(':').apply(pd.Series)
                   for x in ('Other1', 'Other2', 'Other3')).dropna(how='all')

#                  0                  1
#0          Hospital   Awesome Hospital
#1           Hobbies            Cooking
#2          Hospital   Awesome Hospital
#0       Maiden Name              Rubin
#1  Hobby Experience           10 years
#2       Maiden Name            Simpson
#0               DOB         2015/04/09
#2               DOB         2015/04/16

Do some index manipulations (we want the keys to become column names):
others = others.reset_index().set_index(['index',0]).unstack()
#                 1
#0              DOB   Hobbies Hobby Experience           Hospital Maiden Name
#index
#0       2015/04/09      None             None   Awesome Hospital       Rubin
#1             None   Cooking         10 years               None        None
#2       2015/04/16      None             None   Awesome Hospital     Simpson

Remove the hierarchical column index produced by unstack():
others.columns = others.columns.get_level_values(0)

Put the pieces together again:
pd.concat([data[["Full Name","Town"]], others], axis=1)

A: parse has a nice interface and might be good option for pulling data such as this out:
>>> import parse
>>> format_spec='{}: {}'
>>> string='Hobbies: Cooking'
>>> parse.parse(format_spec, string).fixed
('Hobbies', 'Cooking')

Use compile if you will parse the same spec over and over:
>>> other_parser = parse.compile(format_spec)
>>> other_parser.parse(string).fixed
('Hobbies', 'Cooking')
>>> other_parser.parse('Maiden Name: Rubin').fixed
('Maiden Name', 'Rubin')

The fixed property returns the parsed arguments as a tuple. Using these tuples we can just create a bunch of dictionaries, feed them into pd.DataFrame, and merge with the first df:
import parse
import pandas as pd

# slice first two columns from original dataframe
first_df = pd.read_csv(filepath, sep='t').ix[:,0:2]

# make the parser
other_parser = parse.compile('{}: {}')

# parse remaining columns to a new dataframe
with open(filepath) as f:
    # a generator of dict objects is fed into DataFrame
    # the dict keys are column names
    others_df = pd.DataFrame(dict(other_parser.parse(substr).fixed for substr in line.split('\t')[2:]) for line in f)

# merge on the indexes
df = pd.merge(first_df, others_df, left_index=True, right_index=True)


text:
Q: Ubuntu: Freeing up ports? I have tried to install cassandra on my Ubuntu test environment, but what happens when I try to start it is that I get the following error:
java.net.BindException: Address already in use

I have tried port 3072, 10032 and 8080 in the config, but it doesn't change. Still the same error.
So what can I do - can I free up the port number I want to use to let Cassandra take it?
Thanks

A: run netstat -ntlp to check what applications are using the ports then determine if you need them or not.


text:
Q: How to find the area bounded by $y=\ln\left(x\right)$ and $y=e+1-x$, and the $x$ axis? Given $\int \int dxdy$, I want to find the area bounded by $y=\ln\left(x\right)$ and $y=e+1-x$, and the $x$ axis.
I think the limits of integral in $y$ axis are from $y=\ln\left(x\right)$ to $y=e+1-x$ so $\int \limits_{y=\ln\left(x\right)}^{e+1-x}dy\int \:dx$, but I don't know how to find the limits of the integral in $x$ axis since the area bounded by $x$ axis? Please give me a clue to solve this problem.

A: In this case it is convenient to use inverse representation of the curves,
$x=\mathrm{e}^y,\ x=\mathrm{e}+1-y$:

$$ \int_0^1 \int_{\mathrm{e}^y}^{\mathrm{e}+1-y} dx dy=\frac{3}{2}$$.

A: HINT:
y = ln(x), y = e+1-x
I would say, can guess the solution x = e, y = 1. Other real solution is not.


text:
Q: C - Unsigned long long to double on 32-bit machine Hi I have two questions:

*

*uint64_t vs double, which has a higher range limit for covering positive numbers?

*How to convert double into uint64_t if only the whole number part of double is needed.
Direct casting apparently doesn't work due to how double is defined.
Sorry for any confusion, I'm talking about the 64bit double in C on a 32bit machine.
As for an example:
//operation for convertion I used:
double sampleRate = (
                      (union { double i; uint64_t sampleRate; })
                      { .i = r23u.outputSampleRate}
                    ).sampleRate;

//the following are printouts on command line
//         double                               uint64_t
//printed by   %.16llx                           %.16llx
outputSampleRate  0x41886a0000000000      0x41886a0000000000 sampleRate

//printed by   %f                                    %llu
outputSampleRate  51200000.000000        4722140757530509312 sampleRate

So the two numbers remain the same bit pattern but when print out as decimals, the uint64_t is totally wrong.
Thank you.

A:
uint64_t vs double, which has a higher range limit for covering positive numbers?

uint64_t, where supported, has 64 value bits, no padding bits, and no sign bit.  It can represent all integers between 0 and 264 - 1, inclusive.
Substantially all modern C implementations represent double in IEEE-754 64-bit binary format, but C does not require nor even endorse that format.  It is so common, however, that it is fairly safe to assume that format, and maybe to just put in some compile-time checks against the macros defining FP characteristics.  I will assume for the balance of this answer that the C implementation indeed does use that representation.
IEEE-754 binary double precision provides 53 bits of mantissa, therefore it can represent all integers between 0 and 253 - 1.  It is a floating-point format, however, with an 11-bit binary exponent.  The largest number it can represent is (253 - 1) * 21023, or nearly 21077.  In this sense, double has a much greater range than uint64_t, but the vast majority of integers between 0 and its maximum value cannot be represented exactly as doubles, including almost all of the numbers that can be represented exactly by uint64_t.

How to convert double into uint64_t if only the whole number part of double is needed

You can simply assign (conversion is implicit), or you can explicitly cast if you want to make it clear that a conversion takes place:
double my_double = 1.2345678e48;
uint64_t my_uint;
uint64_t my_other_uint;

my_uint = my_double;
my_other_uint = (uint64_t) my_double;

Any fractional part of the double's value will be truncated.  The integer part will be preserved exactly if it is representable as a uint64_t; otherwise, the behavior is undefined.
The code you presented uses a union to overlay storage of a double and a uint64_t.  That's not inherently wrong, but it's not a useful technique for converting between the two types.  Casts are C's mechanism for all non-implicit value conversions.

A: double can hold substantially larger numbers than uint64_t, as the value range for 8 bytes IEEE 754 is 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative) [taken from here][more detailed explanation]. However if you do addition of small values in that range, you will be in for a surprise, because at some point the precision will not be able to represent e.g. an addition of 1 and will round down to the lower value, essentially making a loop steadily incremented by 1 non-terminating.
This code for example:
#include <stdio.h>
2 int main()
3 {
4     for (double i = 100000000000000000000000000000000.0; i < 1000000000000000000000000000000000000000000000000.0; ++i)
5         printf("%lf\n", i);
6     return 0;
7 }

gives me a constant output of 100000000000000005366162204393472.000000. That's also why we have nextafter and nexttoward functions in math.h. You can also find ceil and floor functions there, which, in theory, will allow you to solve your second problem: removing the fraction part.
However, if you really need to hold large numbers you should look at bigint implementations instead, e.g. GMP. Bigints were designed to do operations on very large integers, and operations like an addition of one will truly increment the number even for very large values.


text:
Q: Using Keys as Variables in Python There is probably a term for what I'm attempting to do, but it escapes me.  I'm using peewee to set some values in a class, and want to iterate through a list of keys and values to generate the command to store the values.
Not all 'collections' contain each of the values within the class, so I want to just include the ones that are contained within my data set.  This is how far I've made it:
for value in result['response']['docs']:
    for keys in value:
        print keys, value[keys]   # keys are "identifier, title, language'

#for value in result['response']['docs']:
#   collection =  Collection(
#       identifier = value['identifier'],
#       title = value['title'],
#       language = value['language'],
#       mediatype = value['mediatype'],
#       description = value['description'],
#       subject = value['subject'],
#       collection = value['collection'],
#       avg_rating = value['avg_rating'],
#       downloads = value['downloads'],
#       num_reviews = value['num_reviews'],
#       creator = value['creator'],
#       format = value['format'],
#       licenseurl = value['licenseurl'],
#       publisher = value['publisher'],
#       uploader = value['uploader'],
#       source = value['source'],
#       type = value['type'],
#       volume = value['volume']
#       )
#   collection.save()

A: for value in result['response']['docs']:
    Collection(**value).save()

See this question for an explanation on how **kwargs work.

A: Are you talking about how to find out whether a key is in a dict or not?
>>> somedict = {'firstname': 'Samuel', 'lastname': 'Sample'}

>>> if somedict.get('firstname'):
>>>    print somedict['firstname']
Samuel

>>> print somedict.get('address', 'no address given'):
no address given

If there is a different problem you'd like to solve, please clarify your question.


text:
Q: How to compare a set of values in visual basic   If Target.Column = 6 Then
  End If

I would like the If code to be execute if the Column is 6 or 8 or 10. How should I modify the above code

A: You could use a case statement
CASE Statement (VBA)
See the section
You can also comma delimit values. For example:

Select Case LNumber
    Case 1, 2
       LRegionName = "North"
    Case 3, 4, 5
       LRegionName = "South"
    Case 6
       LRegionName = "East"
    Case 7, 11
       LRegionName = "West"
 End Select

A: This is more specifically what you asked:
If Target.Column = 6 OR Target.Column = 8 OR Target.Column = 10 Then
'Code for if a match is found.
else
'Code for when a match isn't found.
End If

Or as astander displayed:
Select Case Target.Column
Case 6, 8, 10
'Code for if a match is found.
Case Else
'Code for when a match isn't found.
End Select

Or even another way:
With Target
If .Column = 6 Or .Column = 8 OR .Column = 10 then
'Code for if a match is found.
else
'Code for when a match isn't found.
End If
End with


text:
Q: Unable to dereference vector iterators I don't understand what the problem with this function is, I've done something very similar to this in the past and it worked fine, but now when I try to run this function I get the error
"Unable to dereference vector iterator"

It comes on the line curr->setName(new_name); which makes sense since that's where its being dereferenced.  Also just to be clear all the functions and classes used in this method work fine on their own, I'm just not inserting them for the sake of space.
void System::modify(PC a){
    char x;
    curr = find(begin(comps), end(comps), a);

    cout << "What would you like to modify:" << endl;
    cout << "a - Name" << endl;
    cout << "b - IP" << endl;
    cout << "c - Password" << endl;

    cin >> x;
    if(x == 'a'){
        string new_name;
        cout << "What would you like to rename the computer to: ";
        cin >> new_name;
        curr->setName(new_name);
    }

    if(x == 'b'){
        string new_IP;
        cout << "What would you like the new IP address to be: ";
        cin >> new_IP;
        curr->setIP(new_IP);
    }

    if(x == 'c'){
        curr->setNewPass();
    }

    else{
        cout << "Choice is not valid" << endl;
        return;
    }
}

A: You need to modify your function - it should check, whether find() has found something at all:
void System::modify(PC a){
    char x;
    curr = find(begin(comps), end(comps), a);

    if(curr == end(comps))
    {
        cout << "Specified PC was not found!" << endl;
        return;
    }

    //...
}

Documentation page for find() says:

Return value
An iterator to the first element in the range that compares equal to val. If no elements match, the function returns last.

Where last in this case is end(comps).

A: It seems that value a was not found in this statement
curr = find(begin(comps), end(comps), a);

and curr is equal to end(comps) .
You should check that the search was successfull.
For example
if ( ( curr = find(begin(comps), end(comps), a) ) != end(comps) )
{
    // the search was successfull
}

A: it's not clear how the PC could be compared. But it seems that find function returns end(comps), that means that there is no "PC a" in the list/vector/whatever. You should check that PC a has been found by
if(curr!=end(comps)) {
// do whatever you wont with corr
}
else {
//nothing has been found
}


text:
Q: How to I do add a function as a variable into a link url as a tweet for twitter? Ok so I made a random quote generator which works fine. I now want to take the randomly generated quote and make it a tweet. I know how to make text a tweet. My problem is taking the function that generates the random quote and adding to the url to tweet here is my code:

Random Quote Generator

Star Wars Quotes

               <button class="btn btn-default" type="submit">New Quote</button>

"Placeholder Quote"

Placheolder Author

          Use the Force to Tweet

    $(document).ready(function() { //random quote works fine
       function pickQuote() {
          var quotes = ["It's a trap!", "Mmm. Lost a planet, Master Obi-Wan has. How embarrassing.", "I find your lack of faith disturbing"];
          var author = ["-Admiral Akbar", "-Yoda", "-Darth Vader"];

          var randomNum = Math.floor((Math.random() * quotes.length));

          var randomQuote = quotes[randomNum];

          var randomAuthor = author[randomNum];

        $(".quote").text(randomQuote);
        $(".author").text(randomAuthor);
      }

      $(".btn").on("click", function() {
         pickQuote();
      });

  //this is where the tweet magic is supposed to happen
  var a = pickQuote();
  function getTweet(){
      return "http://twitter.com/home/?status=" + a;
  }

});

Please any help would be greatly appreciated.

A:

        var pickQuote = function () {
           var quotes = ["It's a trap!", "Mmm. Lost a planet, Master Obi-Wan has. How embarrassing.", "I find your lack of faith disturbing"];
           var author = ["-Admiral Akbar", "-Yoda", "-Darth Vader"];

           var randomNum = Math.floor((Math.random() * quotes.length));

           var randomQuote = quotes[randomNum];

           var randomAuthor = author[randomNum];

           $(".quote").text(randomQuote);
           $(".author").text(randomAuthor);
           return randomQuote + " " + randomAuthor;
       }

       var getTweet = function () {
           var a = pickQuote();
           var url = "http://twitter.com/home/?status=" + a;
           console.log(url);
           return url;
       }

       $(document).ready(function() {
          $(".btn").on("click", function () {
          pickQuote();
          });
       });

Placeholder Quote

Placheolder Author

          Use the Force to Tweet

A:

.button {
    background-color: white;
    color: black;
    border: 2px solid #555555;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    -webkit-transition-duration: 0.4s;
    /* Safari */

    transition-duration: 0.4s;
    cursor: pointer;
    height: 30%;
    vertical-align: top;text-align: left;
}
.button:hover {
    background-color: #555555;
    color: white;
}
#grid {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ffffff;
    display: flex;
    flex: 1;
}
#gridli {
    width: 24%;
    margin-left: 0.5%;
    margin-right: 0.5%;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

      <form action="http://google.com">
         <button class="button" type="submit"  />
         Computers, printers, mobile phones and the widgets that accompany them account for the emission of about two per cent of the estimated total of emissions from human activity. And that is the same as the aviation industry’s contribution. 25 per cent of the emissions in question are generated by the manufacture of computers. The rest come from their use.
         </button>
      </form>

      <form action="http://google.com" style="float: left">
         <button class="button" type="submit"  />
         Computers can be used to reduce emissions produced by other industries, up to 7.8 billion tonnes by 2020, or five times ICT’s own footprint. Computers can make industries more efficient and less wasteful of power and fuel.
         </button>
      </form>

      <form action="http://google.com" style="float: left">
         <button class="button" type="submit"  />
         The use of computers has led to both positive and negative impacts on the climate change of our planet. Computers can help make some processes more efficient and save energy while the use and manufacture of computers contributes to the increased use of energy which leads to global warming. This website helps you to look at the positives and negatives of computing and climate change.

         </button>
      </form>

      <form action="http://google.com" style="float: left">
         <button class="button" type="submit"  />

 Saving Energy

            There are many ways in which computers can help cut down on our use of energy. Computers are steadily improving the amount of energy that they use with the smaller computers producing less CO2 than larger desktop computers.
         </button>
      </form>


text:
Q: É possível alterar CSS de um iframe? Tenho o seguinte iframe do Google Calendar incorporado:
<iframe src="https://calendar.google.com/calendar/embed?showNav=0&showPrint=0&showCalendars=0&showTz=0&height=600&wkst=1&bgcolor=%23ffffff&src=exemplo.com;color=%23182C57&ctz=America%2FSao_Paulo" style="border-width:0;" width="100%" height="600" frameborder="0" scrolling="no"></iframe>

Estou puxando esse iframe de uma agenda do Google, a pergunta é: Consigo alterar o CSS desse iframe?
Preciso alterar cores, fontes, etc. Gostaria de saber se existe alguma possibilidade de fazer isso, ou se alguém conhece outra forma de fazer essas edições no Google Calendar.

A: Até onde eu saiba, somente tendo acesso ao DOM usando js ex:
var estilo = document.createElement('link');
estilo.rel = 'stylesheet';
estilo.type = 'text/css';
estilo.href = 'caminho/estilo.css';
seuIframe.getElementsByTagName('head')[0].appendChild(estilo);


text:
Q: pip3 dateparser gives error with gcc I run Mac High Sierra and got python3 via brew. I wanted to pip3 dateparser, but got this error:
command 'gcc' failed with exit status 1

I followed a hint from https://github.com/maciejkula/glove-python/issues/55 (panaali commented on Nov 12, 2017) and did the following change:
brew install gcc

and then export gcc into CC like:
export CC=/usr/local/Cellar/gcc/8.3.0/bin/g++-8

But then I got the new error
self->locale_info = re_alloc(sizeof(RE_LocaleInfo));
                                 ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
    error: command '/usr/local/Cellar/gcc/8.3.0/bin/g++-8' failed with exit status 1

Afterwards I downloaded dateparser manually and wanted it to set up via:
git clone https://github.com/scrapinghub/dateparser.git
cd dateparser
python setup.py install

but this gives me the same error:
regex_3/_regex.c:26401:37: error: invalid conversion from 'void*' to
'RE_LocaleInfo*' [-fpermissive]
         self->locale_info = re_alloc(sizeof(RE_LocaleInfo));
                             ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~ error: Setup script exited with error: command
'/usr/local/Cellar/gcc/8.3.0/bin/g++-8' failed with exit status 1

A: I encountered the same issue doing pip install dateparser.
Fix: use xcode-select --install to install command line developer tools.


text:
Q: Custom Item Frame Paintings I really have to make an item frame painting, take a screenshot, and post it to Imgur and Pinterest. Is there a way to make an item frame painting did in the following image (Of course there is)?

A: The real solution: Build with colored blocks in a big area and make in-game maps of that area.
A better solution for you: Make a screenshot of an empty wall and then use an image editing program to put the image in that place.