text:
Q: Error with insterting values I have problem with inserting values into my table.
Here is the script:
IF OBJECT_ID ('DEPT', 'table') IS NOT NULL
DROP TABLE DEPT;
GO

CREATE TABLE DEPT (
   DEPTNO NUMERIC(2) NOT NULL,
   DNAME VARCHAR(14),
   LOC VARCHAR(13),

   CONSTRAINT DEPT_PRIMARY_KEY PRIMARY KEY (DEPTNO));
GO

INSERT INTO DEPT VALUES (10,'ACCOUNTING','NEW YORK');
INSERT INTO DEPT VALUES (20,'RESEARCH','DALLAS');
INSERT INTO DEPT VALUES (30,'SALES','CHICAGO');
INSERT INTO DEPT VALUES (40,'OPERATIONS','BOSTON');
GO

IF OBJECT_ID ('EMP', 'table') IS NOT NULL
  DROP TABLE EMP;
GO

CREATE TABLE EMP (
  EMPNO NUMERIC(4) NOT NULL,
  ENAME VARCHAR(10),
  JOB VARCHAR(9),
  MGR NUMERIC(4) CONSTRAINT EMP_SELF_KEY REFERENCES EMP (EMPNO),
  HIREDATE DATETIME,
  SAL NUMERIC(7,2),
  COMM NUMERIC(7,2),
  DEPTNO NUMERIC(2) NOT NULL,

  CONSTRAINT EMP_FOREIGN_KEY FOREIGN KEY (DEPTNO)
    REFERENCES DEPT(DEPTNO),

  CONSTRAINT EMP_PRIMARY_KEY PRIMARY KEY (EMPNO));
GO

INSERT INTO EMP VALUES
(7839,'KING','PRESIDENT',NULL,'17-11-1981',5000,NULL,10);

INSERT INTO EMP VALUES
(7698,'BLAKE','MANAGER',7839,'1-05-1981',2850,NULL,30);

INSERT INTO EMP VALUES
(7782,'CLARK','MANAGER',7839,'9-06-1981',2450,NULL,10);

INSERT INTO EMP VALUES
(7566,'JONES','MANAGER',7839,'2-04-1981',2975,NULL,20);

INSERT INTO EMP VALUES
(7654,'MARTIN','SALESMAN',7698,'28-09-1981',1250,1400,30);

INSERT INTO EMP VALUES
(7499,'ALLEN','SALESMAN',7698,'20-02-1981',1600,300,30);

INSERT INTO EMP VALUES
(7844,'TURNER','SALESMAN',7698,'8-09-1981',1500,0,30);

INSERT INTO EMP VALUES
(7900,'JAMES','CLERK',7698,'3-12-1981',950,NULL,30);

INSERT INTO EMP VALUES
(7521,'WARD','SALESMAN',7698,'22-02-1981',1250,500,30);

INSERT INTO EMP VALUES
(7902,'FORD','ANALYST',7566,'3-12-1981',3000,NULL,20);

INSERT INTO EMP VALUES
(7369,'SMITH','CLERK',7902,'17-12-1982',800,NULL,20);

INSERT INTO EMP VALUES
(7788,'SCOTT','ANALYST',7566,'09-12-1982',3000,NULL,20);

INSERT INTO EMP VALUES
(7876,'ADAMS','CLERK',7788,'12-01-1983',1100,NULL,20);

INSERT INTO EMP VALUES
(7934,'MILLER','CLERK',7782,'23-01-1982',1300,NULL,10);

There is error while doing this:
INSERT INTO EMP VALUES  (7859, 'PHILIPPE', 'CLERK', 8219,
'1988-06-11', 1300, NULL, 10), (7594, 'SEBASTIEN', 'SALESMAN', 1292,
'1978-06-09', 3500, NULL, 10);

INSERT INTO EMP VALUES  (7956, 'MARTIN', 'DEALER', 4322, '1981-04-11',
2300, 0, 20), (7947, 'SIMON', 'CLERK', 7655, '1981-07-12', 1800, 200,
20);

INSERT INTO EMP VALUES  (7382, 'HUGO', 'ANALYST', 4564, '1982-05-11',
1300, 0, 30), (7291, 'MARC', 'SALESMAN', 9768, '1981-03-09', 3500,
NULL, 30);

INSERT INTO EMP VALUES  (7734, 'JOHN', 'MANAGER', 8678, '1983-11-11',
4300, 0, 40), (7359, 'TOMMY', 'CLERK', 5340, '1981-04-10', 1200, 100,
40);

Error:

The instruction INSERT is in conflict with constraint FOREIGN KEY SAME
  TABLE "EMP_SELF_KEY".

Can someone help? Thanks !

A: In your second block of inserts into EMP, none of the MGR values (8219, 4322, 4564, 8678) appear as EMPNO values in your previous inserts, hence the foreign key violation. Those "managers" must be inserted as "employees" before they can be referenced by the foreign key.


text:
Q: Get vertical rotation iphone I'm developing an app in which I'm getting iPhone's movements.
The iPhone should be taken vertically while the app is running, then I've implemented the accelerometer which helps me to analyze inclination, but I can't study the rotation with it.
So I need to analyze magnetometer rotation, but I don't know if I can use it also if I have the iPhone vertically.
Has anybody already implemented some code for this use?
Thanks!

A: if (UIInterfaceOrientationIsPortrait([[UIDevice currentDevice] orientation])) {
    // device is currently in portrait (vertical) orientation
}

Also, possible duplicate of this : Detect verticality of iPhone

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to format string with thousands and decimal separators in input field as you type using Angular "number" filter? As you type in the input field, for example: 10000.00 I want to format it as 10,000.00 within the input field itself.
I have the following:
  $scope.a = '';
  $scope.addCommas = function(a){
    a = $filter('number')(a,2);
    $scope.b = a;
  }

And I can output the correct format in b but if I replace the last line with $scope.a = a it doesn't work.
<input type="text" ng-model="a" ng-change="addCommas(a)">

Plnkr: https://plnkr.co/edit/FfmiFrZ0NhFbEkdiQUfW?p=preview

A: I wrote a little service to format currency.  https://github.com/bruceradtke/MoneyHelper


text:
Q: MessageBox.Show() causes crash in Mono on Mac I ported a WinForms application to Mac OS X 10.10.2 using Mono 3.12.1.  The main window comes up fine.  But when I try to show a message box with System.Windows.Forms.MessageBox.Show("Hello") from a worker thread, the message box will display briefly and then the program crashes with:
mono(20661,0xa0f5e1d4) malloc: * error for object 0x7a6d86e0: pointer being freed was not allocated
* set a breakpoint in malloc_error_break to debug
Stacktrace:
at  <0xffffffff>
  at (wrapper managed-to-native) System.Windows.Forms.XplatUICarbon.ReceiveNextEvent (uint,intptr,double,bool,intptr&) <0xffffffff>
  at System.Windows.Forms.XplatUICarbon.GetMessage (object,System.Windows.Forms.MSG&,intptr,int,int) <0x0007f>
  at System.Windows.Forms.XplatUI.GetMessage (object,System.Windows.Forms.MSG&,intptr,int,int) <0x00039>
  at System.Windows.Forms.Application.RunLoop (bool,System.Windows.Forms.ApplicationContext) <0x00aff>
  at System.Windows.Forms.Application.Run (System.Windows.Forms.ApplicationContext) <0x0004f>
  at System.Windows.Forms.Application.Run (System.Windows.Forms.Form) <0x00033>
  at RevelarPcCommX.Program.Main () <0x0003f>
  at (wrapper runtime-invoke) object.runtime_invoke_void (object,intptr,intptr,intptr) <0xffffffff>
I can execute this message box function from the main window code fine.  But the program crashes when this code is executed from another thread on the Mac.  By the way, the message box displays fine on a worker thread on a Windows 7 PC.  So, I guess the question is, how do I execute this message box on the main thread from a worker thread on the Mac?  Or maybe there is another solution to fix this crash on the Mac?

A: This is just a guess but I had similar issues when I had CheckForIllegalCrossThreadCalls for testing purposes and forgot to remove it. Doing anything like invocations on a different thread would cause crashes, despite it working fine under Windows. So, check for two things:

*

*Make sure you're not using CheckForIllegalCrossThreadCalls. It's bad practice anyway.

*Make sure you are using safe invocations on your worker thread; you might not be doing so if you're just calling MessageBox.Show


text:
Q: Getting all touch events of an app I've been looking for a way to intercept all touch events of an app.
I saw that I can add a gesture recognizer to the main window and get all the touches by using it's delegate method:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
NSLog(@"%@",touch);
return NO;
}

This way I don't harm all of the other touch events the app has.
The problem is that I cannot get swipe events and such this way. Moreover, I cannot override UIWindow sendEvents because my app is an outside framework.
I also do not want to add a transparent UIView on top.
Is there any other way to get swipes and other gesturs?

A: To intercept all touch events of an app, use a UIWindow subclass and override sendEvent:.... Every touch event passes through this bottleneck method. Be warned that you are now operating at a very low level and can easily break everything.

A: I managed to get this to work by using a custom gesture recognizer attached to the keyWindow and with using the method:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

Which also gives me all the touches and doesn't disturb any other recognizers.
If anyone know why I shouldn't be doing that, I'd be happy to hear about it.


text:
Q: MySQL does not start when upgrading OSX to Yosemite or El Capitan I know similar questions exist, such as MySQL with MAMP does not work with OSX Yosemite 10.10. However, I do have MAMP, nor XAMPP installed on my computer.
When I try to start mySQL from the PrefPane, nothing happens.
When I try to start mqSQL from the command line via sudo /usr/local/mysql/support-files/mysql.server start I get:

Starting MySQL . ERROR! The server quit without updating PID file
(/usr/local/mysql/data/adamg.local.pid).

Any and all help would be appreciated. I can supply any file output necessary.

A: Open a terminal:

*

*Check MySQL system pref panel, if it says something along the line "Warning, /usr/local/mysql/data is not owned by 'mysql' or '_mysql'

*If yes, go to the mysql folder cd /usr/local/mysql

*do a sudo chown -R _mysql data/

*This will change ownership of the /usr/local/mysql/data and all of its content to own by user '_mysql'

*Check MySQL system pref panel, it should be saying it's running now, auto-magically.  If not start again.

*Another way to confirm is to do a
netstat -na | grep 3306
It should say:
tcp46      0      0  *.3306                 *.*                    LISTEN

To see the process owner and process id of the mysqld:
ps aux | grep mysql

A: Execute the following commands from command line...
sudo launchctl load -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

sudo launchctl unload -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

and then start the mysql server using
sudo /usr/local/mysql/support-files/mysql.server start

A: Long story short you need to create a launch file. So, from Terminal:
sudo vi /Library/LaunchDaemons/com.mysql.mysql.plist
(If you are not familiar with vi, then press i to start inserting text)
This should be the content of your file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>KeepAlive</key>
    <true />
    <key>Label</key>
    <string>com.mysql.mysqld</string>
    <key>ProgramArguments</key>
    <array>
      <string>/usr/local/mysql/bin/mysqld_safe</string>
      <string>--user=mysql</string>
    </array>
  </dict>
</plist>

press esc then : wq!enter
Then you need to give the file the right permissions and set it to load on startup.
sudo chown root:wheel /Library/LaunchDaemons/com.mysql.mysql.plist
sudo chmod 644 /Library/LaunchDaemons/com.mysql.mysql.plist
sudo launchctl load -w /Library/LaunchDaemons/com.mysql.mysql.plist

And that is it.

A: The .pid is the processid of the running mysql server instance. It appears in the data folder when mysql is running and removes itself when mysql is shutdown.
If the OSX operating system is upgraded and mysql is not shutdown properly before the upgrade,mysql quits when it started up it just quits because of the .pid file.
There are a few tricks you can try, http://coolestguidesontheplanet.com/mysql-error-server-quit-without-updating-pid-file/ failing these a reinstall is needed.

A: You just need to create the user mysql (mysql installation script creates _mysql)
sudo vipw
duplicate line that contains _mysql
Change for the duplicated line _mysql to mysql
sudo /usr/local/mysql/support-files/mysql.server start
Starting MySQL
.. SUCCESS!

A: In my case I fixed it doing a little permission change:
sudo chown -R _mysql:_mysql /usr/local/var/mysql
sudo mysql.server start

I hope it helps somebody else...
Note: As per Mert Mertin comment:

For el capitan, it is sudo chown -R _mysql:_mysql /usr/local/var/mysql

A: The re-install fixed it because the installer created a new MySQL instance and the symbolic link to /usr/local/mysql now points to a data directory that does not have an existing pid.
It's worth noting that the mysql prefpane and mysql.server script use the hostname for the pid, so changing the hostname may cause issues with the this.
While the prefpane is out of date, it's a nice GUI for someone to start/stop MySQL even if the auto-start function doesn't work.
I've taken a hybrid approach where I've adapted my MySQL install script to use Launchd to auto-start MySQL, but the plist actually calls the mysql.server script.  This way the prefpane can still be used to start/stop MySQL on demand, and trying to do a simple MySQL restart won't be too confusing.
Here is script that just enables this Launchd behavior on Yosemite with MySQL already installed:
https://raw.githubusercontent.com/MacMiniVault/Mac-Scripts/master/mmvMySQL/YosemiteLaunchd.sh
Here is the script that handles the entire automated installation of MySQL:
https://raw.githubusercontent.com/MacMiniVault/Mac-Scripts/master/mmvMySQL/mmvmysql.sh

A: Solved by installing the latest mySQL release, following the instructions here http://coolestguidesontheplanet.com/get-apache-mysql-php-phpmyadmin-working-osx-10-10-yosemite/
EDIT
As Yosemite gets more popular, more people are stumbling on this question. The answer above has to do with upgrading MySQL, so that it runs. The answer linked by @doc in the comments has to do with getting MySQL to start automatically. These are 2 separate issues.

A: You will sometimes miss previous data if you try to install new version.. Please use the following in your terminal and I guarantee that mySql will start running in no time..
sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start

Remember, it will ask for your Machine password and not mysql password..

A: I've got a similar problem with MySQL on a Mac (Mac Os X Could not startup MySQL Server. Reason: 255 and also "ERROR! The server quit without updating PID file"). After a long trial and error process, finally in order to restore the file permissions, I've just do that:

* launch the Disk Utilities.app

* choose my drive on the left panel

* click on the "Repair disk permissions" button
This did the trick for me.
Hoping this can help someone else.

A: Try this:
sudo mysqld_safe &

A: Way simplest: copy and paste this into Terminal (but be sure to read more first):
bash <(curl -Ls http://git.io/eUx7rg)

This will install and configure everything automagically. The script is provided by MacMiniVault and is available on Github. More information about the mySQL install script on http://www.macminivault.com/mysql-yosemite/.

A: you want fix it can edit file "/Applications/XAMPP/xamppfiles/xampp" with TextEdit.
Look for text "$XAMPP_ROOT/bin/mysql.server start > /dev/null &"
And add "unset DYLD_LIBRARY_PATH" on top of it. It should look like:
unset DYLD_LIBRARY_PATH
$XAMPP_ROOT/bin/mysql.server start > /dev/null &
hope can help you

A: None of the above worked.. but installing a new version of MySQL did the trick.

A: 2 steps solved my problem:
1) Delete "/Library/LaunchDaemons/com.mysql.mysql.plist"
2) Restart Yosemite

A: I usually start mysql server by typing
$ mysql.server start

without sudo.  But in error I type sudo before the command.  Now I have to remove the error file to start the server.
$ sudo rm /usr/local/var/mysql/`hostname`.err

A: My Mac decided to restart itself randomly; causing a whole slew of errors.  One of which, was mysql refusing to start up properly.  I went through many SO questions/answers as well as other sites.
Ultimately what ended up resolving MY issue was this:

1) Creating the file (/usr/local/mysql/data/.local.pid
2) chmod 777 on that file
3) executing mysql.server start  (mine was
  located in/usr/local/bin/mysql.server)

A: Same happened to me! So I tried to startup again after I had terminated the running mysql application, and that worked!


text:
Q: The count value is not getting saved to newly declared variable Have captured the web_reg_save_param and the count value is not getting saved to newly declared variable.
I have tried by declaring in global as well as locally.
int ExsistingGoal;
char ParamName[50];
int i;

// {"id":"49F2DC5064524DC3962EE783959CA211","name":"Legacy Protection 1",

web_reg_save_param("c_ExsistingGoal","LB=
     {\"id\":\"","RB=\",\"name\":\"","ORD=All",LAST);

web_add_header("Authorization:","Bearer {c_Token05}");

web_add_header("X-request-ID","8dd9e540-fa3c-11e9-8c6b-47e84a716a57");

web_url("goals_3",
    "URL={pURL02}/wms/v1/plan/plans/{c_PlanID}/goals?entityId= {c_EntityID}",
    "TargetFrame=",
    "Resource=0",
    "RecContentType=application/json",
    "Referer={pURL02}/mwp/select-goals",
    "Snapshot=t79.inf",
    "Mode=HTML",
    LAST);

ExsistingGoal= atoi(lr_eval_string("{c_ExsistingGoal_count}"));

c_ExsistingGoal_count this values should get saved to the variable
  ExsistingGoal.
But currently it's displaying some random value:153500656

A: In my POV, James Pulley answered this question.
If you use ORD=ALL in web_reg_save_param function. LR will save count number which meet correlation condition in <paramname>_count. If You get the value of 153500656 in this case, it means the web_reg_save_param function correlated 153500656 items in array.
//You can use the 1st correlated item
ExsistingGoal_1= atoi(lr_eval_string("{c_ExsistingGoal_1"));

//You can use the 153500656th correlated item
ExsistingGoal_153500656= atoi(lr_eval_string("{c_ExsistingGoal_153500656"));

//In frequently usage, you can judge flow by <paramname>_count, and output the specific <paramname>_<count>.
if(atoi(lr_eval_string("{c_ExsistingGoal_count}"))>0)
    {
        lr_output_message("c_ExsistingGoal_1=%s",lr_eval_string("{c_ExsistingGoal_1}"));
        lr_end_transaction("Correlation Pass",LR_AUTO);
    }
    else
    {
        lr_end_transaction("Correlation Fail",LR_FAIL);
    }

A: Please use below function it will help you -
web_reg_save_param("ExsistingGoal","LB=someText", "RB=\")", "Ord=ALL",LAST);

lr_output_message("PC:%d",atoi(lr_eval_string("{ExsistingGoal_count}")));


text:
Q: Is it possible to modify a Site Templete and reflect all the changies to the underlying Subites I have created a new sub-site, and i added many apps inside it ,, then i saved the site as template.
After that I created 5 sub-sites and i based them on the template.
now i need to add an additional Issue Tracking list to the template, so is there a way to modify the template , then add the new issue tracking list and automatically have the issue tracking list added on the 5 sub-sites ?

A: If you change anything in Site Template after you have created the sites using that template. Then you need to manually update the changes in each of the sites you created. Because there is no way to do this.
You need to make sure all the changes are added on the site template first and then you need to create the sites accordingly.
Refer this article for more details: SharePoint Site Templates


text:
Q: Beamer's show notes only option and tikz markings I followed the example provided in this post to generate a table with annotations marking its contents, and it works as expected. However, when I added the beamer's command \setbeameroption{show only notes} to show the speaker's notes, the annotations did not show correctly (or at least the second one).
Here is a MWE:
\documentclass[xcolor={table,dvipsnames}]{beamer}

\usetheme{Copenhagen}

% from https://tex.stackexchange.com/a/315248/36296
\usepackage{tikz}
\usetikzlibrary{matrix,shapes,arrows,fit,tikzmark}

% Some options common to all the nodes and paths
\tikzset{
    every picture/.style={remember picture,baseline},
    every node/.style={anchor=base,align=center,outer sep=1.5pt},
    every path/.style={thick},
}

\newcommand\marktopleft[1]{%
    \tikz[overlay,remember picture]
    \node (marker-#1-a) at (.1em,.3em) {};%
}
\newcommand\markbottomright[1]{%
    \tikz[overlay,remember picture]
    \node (marker-#1-b) at (.1em,.3em) {};%
    \tikz[overlay,remember picture,inner sep=1pt]
    \node[draw=red,rounded corners,fit=(marker-#1-a.north west) (marker-#1-b.south east)] {};%
}

\setbeameroption{show only notes}

\begin{document}

\begin{frame}{}

\begin{table}
\centering
\rowcolors{2}{gray!20}{white}
\begin{tabular}{lccc}
A & B & C & D \\
00 & 100\% & 100\% & 0\% \\
\only<1>{\marktopleft{a}}05 & 58 & 181 & 50\only<1>{\markbottomright{a}}\\
\only<2>{\marktopleft{b}}10 & 87 & 112 & 1.6\only<2>{\markbottomright{b}}\\
20 & 92 & 115 & 1.6 \\
30 & 87 & 117 & 1.6 \\
40 & 81 & 121 & 1.6 \\
\end{tabular}
\end{table}%

\note<1>{The first note.}
\note<2>{The second note.}

\end{frame}

\end{document}

The annotation appearing with the second note is not correct. By the way, I did compile two times, but this did not help.
Any idea what's wrong?

A: This is not really an answer, but is a bit long for a comment.
Beamer's show only notes option includes the command \nofiles.  This means that, in particular, the aux file is not generated.  TikZ's remember picture mechanism depends on writing coordinates to the aux file to be read back in on the next run.  The reason for disabling this in show only notes is probably so that generating just the notes doesn't mess with labels and so forth in the main presentation, and so that such things in the mini-version reflect those in the actual presentation.
But this messes up TikZ's remember picture syntax.  As stated above, no aux file is generated when show only notes is given.  Even with the aux file from the main presentation, the connection between the individual tikz pictures and the information in the aux file is almost certainly broken as the number of tikz pictures will be different (and tikz identifies pictures by a simple count).
So I doubt an easy solution exists, and solving it might just break more things than it fixes.


text:
Q: span two rows in flexbox I'm trying to achieve the following layout with flexbox so that the left column spans two rows. IS this possible?
Thanks!

A: hmm simple but will do the trick, you just have to use multiple flex containers, and one of them will have a flex-direction: column ...


text:
Q: ngChange doesn't work for kendo-date-picker which defined in kendo.toolbarOptions I want to bind ngChange event to kendo-date-picker, the date picker defined in the toolbarOptions, but the ngChange doesn't work.

 $scope.toolbarOptions = {
        items: [{
            template: "From"
        }, {
            template: "<input id='start' kendo-date-picker ng-model='dateString' k-ng-model='dateObject' ngChange='startChange()' />",
            overflow: "never"
        }]};

 $scope.startChange = function() {console.log('changed');}

 function startChange() {console.log('changed');}

please check my code, both of the startChange will not work. There's a ReferenceError: startChange is not defined

A: You are using ngChange, Please change it with ng-change like:-
$scope.toolbarOptions = {
    items: [{
        template: "From"
    }, {
        template: "<input id='start' kendo-date-picker ng-model='dateString' k-ng-model='dateObject' ng-change='startChange()' />",
        overflow: "never"
    }]};

    $scope.startChange = function() {console.log('changed');}

or if you want to call javascript function then you have to define your js function before it using
  angular.module("KendoDemos", [ "kendo.directives" ])
  .controller("MyCtrl", function($scope){

        $scope.toolbarOptions = {
          items: [{
             template: "From"
            }, {
            template: "<input id='start' handle-change kendo-date-picker ng-model='dateString' k-ng-model='dateObject' onChange='startChange()' />",
        overflow: "never"
          }]

        };
    }).directive('handleChange',function(){
    return{
       link:function(scope,ele,attr){
         //you can use this
            //ele.on('change',function(){
              //alert(555)
           //})
      //or
      function startChange() {console.log('changed');}
    }
  }
 });


text:
Q: Number list from a Map I have a Map  which I am simplifying but in essense contains key values of some data such as:
Yahya, 4
John, 4
Blake, 2
Jill 2
Janoe, 6
Jilly 12
Zapon, 5
Zoe, 4
Hamed, 1

I need to order this so that I get the following output:
1. Jilly, 12 pts
2. Janoe, 6 pts
3. Zapon, 5 pts
4. John, 4 pts
4. Yahya, 4 pts
4. Zoe, 4 pts
7. Blake, 2 pts
7. Jill, 2 pts
9. Hamed, 1 pts

I have already used a comparator to order the Map values according to value:
public <K, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
    Comparator<K> valueComparator =  new Comparator<K>() {
        public int compare(K k1, K k2) {
            int compare = map.get(k2).compareTo(map.get(k1));
            if (compare == 0) return 1;
            else return compare;
        }
    };
    Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
    sortedByValues.putAll(map);
    return sortedByValues;
}

and read : How to get element position from Java Map, Order HashMap alphabetically by value and much more but not sure how to put it together.
I know you can use this to get key values:
for (Map.Entry<String, Integer> entry : map.entrySet()){
    System.out.println(entry.getKey() + " ," + entry.getValue() + " pts");
}

However two functionalities missing:

*

*Sort alphabetically when keys are the same

*Keep same numbering when the value is the same and jump to correct count afterwards.

Tried this:
Map<String, Integer> map = sortByValues(groupList);
            int count = 1;
            int counter = 1;
            int previousScore = 0;

            for (Map.Entry<String, Integer> entry : map.entrySet()) {

               //counter = count;
                if (previousScore == entry.getValue()) {

                    System.out.println(counter - 1 + " " + entry.getKey() + "," + entry.getValue() + " pts");

                } else {

                    System.out.println(counter + " " + entry.getKey() + "," + entry.getValue() + " pts");
                    previousScore = entry.getValue();
                    count++;
                }
                counter++;

            }

Any thoughts are appreciated and welcome. Can anybody suggest a method to achieve the required result ?

A: *

*In your ValueComparator replace if (compare == 0) return 1; with if(compare == 0) return k1.compareTo(k2).

*When generating the "numbering" (you have not shown any code for it), keep two counts. Increase one of them on every iteration, and assign it to the other one, but only if current value is different from the last one. Use the latter to generate the "numbering".

A: This is what I ended up with to make it work to have correct counter:
Map <String, Integer>map = sortByValues(leagueTable);

            int counter = 1;
            int previousScore = 0;
            int relativeCount = 0;
            int n= 0;
            for (Map.Entry<String, Integer> entry : map.entrySet())
            {

               int value = entry.getValue();

               if(previousScore == entry.getValue()){

                   if(n == 0){

                      relativeCount = counter-1;

                   n++;
                   }
               System.out.println(relativeCount + " " + entry.getKey() + "," + entry.getValue() + " pts");

               }
               else{
               n=0;
               System.out.println(counter + " " + entry.getKey() + "," + entry.getValue() + " pts");
                previousScore = entry.getValue();

               }
               counter++;

            }


text:
Q: Get all match records based on their last child in Django ORM? I have these two classes in my models.py :
class BaseObject(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    create_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['create_date']

class Person(BaseObject):

    first_name = models.CharField(max_length=30, null=True, blank=True)
    last_name = models.CharField(max_length=30, null=True, blank=True)
    phone_number = models.CharField(max_length=15,unique=True)
    birthday = models.DateField(null=True, blank=True)
    email = models.EmailField(null=True, blank=True)

class Driver(Person):
    balance = models.PositiveIntegerField(null=True, blank=True)
    score = models.PositiveIntegerField(null=True, blank=True)

class Position(BaseObject):
    person = models.ForeignKey(Driver, on_delete=models.CASCADE)
    latitude = models.FloatField()
    longitude = models.FloatField()

As you can see each driver may have several positions by passing the time.

I want a query using Django ORM that gives me last position of each driver, imagine that i receive a latitude and longitude from client and wish to return all cars that is near.

I tried this :
 radius = 5

 drivers = Driver.objects.filter(position__latitude__range=(data.get('latitude') - radius, data.get('latitude') + radius))\
                         .filter(position__longitude__range=(data.get('longitude') - radius, data.get('longitude') + radius))\

But the problem is that I get a single driver several time based on their positions.
Now i just want to get the drivers with their last update position, not their previous ones.
Thank you

A: Here's an idea to get distinct Drivers (That's why I understand you're trying to get) with it's last Position.
First, order by the Driver Positions, from the last one to the first one.
.order_by('-person__create_date',)
Then use distinct in order to get only Driver per position (the last one):
.distinct()

And here's a second proposition, to get every driver with it's last position (thanks to your automatic 'create_date' and Django Annotate ):
my_drivers = Driver.objects.all().annotate(last_position=Max('person__create_date'))

my_drivers[0].last_position
datetime.datetime(2016, 11, 17, 14, 25, tzinfo=<UTC>)

Here, every item in the my_drivers queryset will have a last_position attribute.

And finally, to @mehrdad-pedramfar request, an idea to get a last_position from a Driver.
class Driver(Person):
    balance = models.PositiveIntegerField(null=True, blank=True)
    score = models.PositiveIntegerField(null=True, blank=True)

    def get_last_position(self):
        return Position.object.filter(person=self).order_by('-create_date').first()

I haven't tried it against your code, but the idea is here. It would cost a DB call each time it is called.
The result is the last Position object for the current Driver :)


text:
Q: Adding an event listener to an image I have been working on a small project where I have to resize a car. However, whenever I press the left arrow, the car is supposed to resize, but nothing happens. This is my Javascript code:
var car = document.getElementById('cr');

 car.addEventListener("keydown",function(event){

  if(event.which == 37){
 //left
console.log('left');
car.style.width = 10 + "px";

 }

if(event.which == 39){
//right
}
})

A: The event listener is on the image so it will only fire if the image has the focus when a key is pressed down. (That or a descendant element, but images can't have descendants).
Images can't, by default, have the focus anyway.
Attach the event listener to the window object instead.


text:
Q: 404 in Jersey/Struts application I am trying to use Jersey to provide a simple web service for my struts application.
When I call the client action I get the following error
com.sun.jersey.api.client.UniformInterfaceException
Message: GET http://localhost:8080/shumer/rest/employee/get returned a response status of 404

servlet declaration in web.xml
<servlet>
    <servlet-name>JAX-RS Servlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
    <init-param>
        <param-name>spring.autowire</param-name>
        <param-value>byName</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>JAX-RS Servlet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

Server resource
@Path("employee")
public class EmployeeResource {

    @Autowired
    EmpDao empDao;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Employee> get(@QueryParam("empCode") String empCode) throws Exception {

            EmpCriteria criteria = new EmpCriteria();
            criteria.setEmpCode(empCode);

            return empDao.searchByCondition(criteria);
        }

}

Client action
public class EmployeeClientTestAction extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        Client client = Client.create();
        WebResource resource = client.resource("http://localhost:8080/shumer/rest/employee/get");

        String employees= resource.accept(MediaType.APPLICATION_JSON)
        .get(String.class);

        System.out.println(employees);

        request.setAttribute("employees", employees);

        return mapping.findForward("successful");
    }

}

I have tried this with and without the /get and the end of the resource url, and with and without a leading / in the EmployeeResource @Path annotation. My guess is that there is somewhere I have to declare where my resources are lcoated at in order for the Jersey servlet to handle them, but I can't figure it out. A point in the right direction would be much appreciated.
EDIT
I have added the following init-param to the servlet element and it is still not working (this package is where my resource class is)
<init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>shumer.rest.resource</param-value>
</init-param>

A: in get method write   @Path("/get")


text:
Q: Keeping a TCP socket open I am trying to connect my client to another client through a server, however while I'm waiting to start up the other client, this socket is closed due to the recv() call do you guys have any ideas on how I can keep the socket open while waiting on the connection from the other side? After the first res call an empty string is returned everytime.
    client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    client.connect((server_ip,server_port))
    client.settimeout(CONNECTION_TIMEOUT)
    while True:
        try:
            toSend = #the hello message that contains the connection id
            client.send(toSend.encode())
            # print("Sent")
            res= client.recv(1024)
            print(res.decode())
            if 'OK' in res.decode():
                break
        except client.timeout as e:
            continue


text:
Q: how to add input placeholder django i wrote this from class then tried to add a placeholder to it
class ContactUs(forms.Form):
    your_email = forms.EmailField(help_text='Enter a valid email.')
    subject = forms.CharField(max_length=100, help_text='Enter your subject.')
    message = forms.CharField(widget=forms.Textarea(attrs={'placeholder':'test'}), help_text='Enter your message.')
    cc = forms.BooleanField(required=False)

like this  and got list of error
class ContactUs(forms.Form):
    your_email = forms.EmailField(help_text='Enter a valid email.', attrs={'placeholder':'please enter a valid email'})
    subject = forms.CharField(max_length=100, help_text='Enter your subject.')
    message = forms.CharField(widget=forms.Textarea(attrs={'placeholder':'test'}), help_text='Enter your message.')
    cc = forms.BooleanField(required=False)

A: Even with a EmailField you can add a widget. To add more attribute, you can do it with a widget
your_email = forms.EmailField(help_text='Enter a valid email.',
 widget=forms.TextInput(attrs={'placeholder':'please enter a valid email'}))

A: You can use some thing like this:
q = forms.CharField(label='search',
                widget=forms.TextInput(attrs={'placeholder': 'Search'}))


text:
Q: How to implement custom actions for prev /next button in  & ? I found a solution to implement custom actions for the prev and next buttons in a Fullcalendar.
But I don't know, how I can use it for my case. I want to change the displayed date range of the <p:calendar> if the <p:schedule> switches into the next month/year and the same for the other direction. My construct looks like a simple Outlook Calendar.

I gave the <p:calendar> the possibility to update the <p:schedule>'s initalDate on dateSelect. So the schedule is hopping to the date range of the selected date. But how can I handle the event, if the <p:schedule> has 'month' view and the user decide to go in another month by clicking the prev/next button? The same i got if the user uses <p:calenadar> Buttons and Navigator.
My first idea was to create a ManagedBean which save the state of the current date range. And call an custom event if the previous/next buttons or the navigator get clicked. This event compare the given ranges and update. But I think this isn't possible or is it?
Thanks for your replies.

A: You have to use a LazyScheduleModel Object to do that
ScheduleModel eventModel = new LazyScheduleModel() {

 @Override
            public void loadEvents(Date start, Date end) {
                handlePreviousNext(start, end);
            }
        };


text:
Q: AS3 enemy spawns on top of the previous one so this is my first time here. Have looked around if this question has been answered, and it has, but not clear enough for me. Sorry for the potential double post.
I am trying to get enemies on the screen. They spawn at random positions, as you can see below, but... they spawn on top of their previous spawned enemy. The answers I read include putting it into an array, but I did, right? I'm a bit confused and working on this for too long, might be that too.
Thanks in advance!
function enemySpawn(e:TimerEvent) {
var enemyAxis:int = Math.round(Math.random()); // determines the x or y axis (0 or 1)
var enemyPos1:int = Math.round(Math.random()) * 600; // spawning it outside the stage (0 or 600)
var enemyPos2:int = Math.floor(Math.random() * 600); // spawning it at random around the stage border (0 through 600)

// spawning the enemy at correct axis
addChild(_enemy);
if(enemyAxis == 0){
    // we declare 0 = x-axis, then either position 0 or max-width, plus the enemy's width.
    _enemy.x = enemyPos1;
    _enemy.y = enemyPos2;
} else
if(enemyAxis == 1){
    // we declare 1 = y-axis, then either position 0 or max-height, plus the enemy's height.
    _enemy.y = enemyPos1;
    _enemy.x = enemyPos2;
}

enemyContainer.push(_enemy);

A: Not sure that I understood you correctly, but calling addChild is not enough to create a new instance of MovieClip. It just adds it to the target container (or does nothing, if the MC is already in that container).
If you want to spawn several enemies simultaneously, you should create new instances of your MC using the new keyword prior to calling addChild:
var enemy:MovieClip = new Enemy();
addChild(enemy);
// _enemies is an array/vector that contains all created enemies;
// it is not necessary, but helps to access the enemy later, when
// the call of enemySpawn() function inside which the enemy was created
// has ended
_enemies.push(enemy);

To be able to do this, you'll need to enable AS3 linkage for the Enemy symbol in the Library. See this answer.


text:
Q: How to integrate the user's avatar in code from Buddypress? I have a template that display a bubble with an image in it. But I would like to replace this image by the logged in user's avatar from Wordpress.
How can I do that ?
Here is the code of my section :
<?php
    $latte_intro_avatar = get_theme_mod('latte_intro_avatar', get_template_directory_uri().'/assets/images/avatar.jpg' );
    $latte_intro_scroll = get_theme_mod('latte_intro_scroll', '#about' );
?>

                    <?php if(!empty($latte_intro_avatar)) : ?>
                        <div class="avatar" style="background-image:url('<?php echo esc_url($latte_intro_avatar); ?>');">

                    <?php endif; ?>

<?php bloginfo( 'name' ); ?>

<?php bloginfo( 'description' ); ?>

                        <?php if(!empty($latte_intro_scroll)) : ?>
                            <a href="<?php echo esc_url($latte_intro_scroll); ?>" class="arrow">
                        <?php endif; ?>

A: Found the solution :
<?php
    global $current_user;
    if ( is_user_logged_in() ):
        get_currentuserinfo();
        echo get_avatar( $current_user->ID, 64 );
    endif;
?>

Works like a charm. source : https://wordpress.stackexchange.com/questions/173626/display-avatar-of-user-profile-when-logged-in


text:
Q: Ruby How to know what to rescue? I'm using eurovat gem to check a VAT number.
Eurovat.check_vat_number vat_number

If I run that from irb, sometimes I receive this:
SOAP::FaultError: MS_UNAVAILABLE
        from

(Nothing appear after "from")
I want to write a begin rescue block to rescue those error, but how I do know what to rescue?
I have tried with rescue SOAP::FaultError but didn't works

A: I found the way after a bit of testing:
rescue SOAP::FaultError => e
    if e.message == "MS_UNAVAILABLE"
      # @ToDO handle service unavailable exception
    end
end

A: Ran into a similar issue. This might be of use to you:

MS_UNAVAILABLE means that: "The Member State service is unavailable, try again later or with another Member State".


text:
Q: Extract value from xml tag I´m trying to extract the RecordID = "1014276" from a tag
I tried with :
$result = curl_exec($ch);
curl_close($ch);

$xml2 = simplexml_load_string($result);
echo $latitude = (string) $xml2['RecordID'];

This is the XML response:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soap:Body>
      <ns1:createDataResponse xmlns:ns1="http://3e.pl/ADInterface">
         <StandardResponse RecordID="1014276" xmlns="http://3e.pl/ADInterface"/>
      </ns1:createDataResponse>
   </soap:Body>
</soap:Envelope>

A: You can apporach this as
$xml = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <soap:Body>
  <ns1:createDataResponse xmlns:ns1="http://3e.pl/ADInterface">
     <StandardResponse RecordID="1014276" xmlns="http://3e.pl/ADInterface"/>
  </ns1:createDataResponse>
 </soap:Body>
</soap:Envelope>';

$p = xml_parser_create();
xml_parse_into_struct($p, $xml, $values, $index);
xml_parser_free($p);

echo $values[3]['attributes']['RECORDID'];

A: This involves a bit more than just accessing the attribute, first you have to select the correct element.  Using XPath is the most comment way in this sort of structure.
 As this has a default namespace defined for the data, you will need to register this with the SimpleXMLElement first (using $xml2->registerXPathNamespace("ns1","http://3e.pl/ADInterface");.
You can then find the element using the XPAth expression //ns1:StandardResponse.  As the xpath() method returns a list of found elements, use [0] to just extract the first match.  You should then be able to extract the attribute as in your code using the resultant element...
$xml2 = simplexml_load_string($result);
$xml2->registerXPathNamespace("ns1","http://3e.pl/ADInterface");

$response = $xml2->xpath("//ns1:StandardResponse")[0];
echo (string) $response['RecordID'];


text:
Q: mysql -v ERROR 1045 (28000): Access denied for user root'@'localhost' (using password: NO) I need help. When Checking mySQL version I get this error. I do not use mysql a lot and I am trying to set up a Magento store through command line.  However, first I am trying to set up mySql from the database.  I am using Mac OS Catalina and Zsh terminal.
Error.
mysql -v
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

I know it must be something with my database but I am confused. Any help would be appreciated. When I try to download Magento 2 setup install I get this similar error.
 --db-user=root --admin-firstname=Magento --admin-lastname=User --admin-email=user@example.com --admin-user=admin --admin-password=123123q --language=en_US --currency=USD --timezone=America/Chicago --use-rewrites=1
SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)

In InstallCommand.php line 264:

  Parameter validation failed

EDIT: However, When I connect to mysql -u root I can connect to the database no problem.

A: You need to pass in the user and password when running mysql from the command line
mysql -u root -p
[enter password]
Alternatively, you can set up a mylogin.cnf (or a .my.cnf) to save the user/password as a file, so you don't need to remember it.
https://dba.stackexchange.com/questions/86595/how-can-i-make-mysql-client-read-password-from-mylogin-cnf


text:
Q: Next Redux Указать значение store из _app.js Доброго времени суток!
Пишу приложение на Next.js с использованием Redux. Проблема в том что при открытии сайта я получаю некие данные с другого сайта. Обработать эти данные и присвоить их в store мне нужно до открытия страницы. URL на который я перехожу может быть любой.
_app.js:
import App from 'next/app';
import { Provider } from 'react-redux';
import store from 'store';
import '../style/dev.css'

import MainLayout from 'layout/MainLayout';

class MyApp extends App {
    render() {
        const { Component, pageProps } = this.props
        return (
            <Provider store={store}> // как тут инициализировать уже store с данными которые были переданы?
                <MainLayout>
                     <Component {...pageProps}/>
                </MainLayout>
            </Provider>
        )
    }
}

export default MyApp

Суть в том что данные я получаю при первом входе в приложение. Эти данные попадают в _app.js и после чего мне надо их добавить в redux store.
У меня получилось присвоить данные при инициализации НО при следующем запросе у меня этих данных больше нет и они сбрасываются.
        return (
            <Provider store={store(data)}>
                <MainLayout>
                    <Component {...pageProps} />
                </MainLayout>
            </Provider>
        )

Буду благодарен за помощь!

A: Используйте initialState для конкретно нужного Вам редюссера, что бы начать загрузку данных сразу при инициализации Redux stor'a:
const initialState = {
    data: // ... async data request
}

const yourReducer = (state = initialState, action) => // ... reducer

В компоненте подпишитесь на изменения data и отобразите страницу после того как все будет готово.

После того как Вы обновили свой вопрос:
import { Provider, useDispatch } from "react-redux"
import store from "store"
import MainLayout from "layout/MainLayout"

const App = () => {

    // ... ваша логика получения данных
    // (если она происходит в данном компоненте)

    const dispatch = useDispatch()

    // отправка данных в store
    // dispatch({ type: "ACTION_TYPE", payload })
    // или с привязкой к методам жизненнго цикла
    // useLayoutEffect(() => dispatch({ type: "ACTION_TYPE", payload }))

    return (
       <Provider store={store}>
           <MainLayout>
               <SomeComponent />
           </MainLayout>
       </Provider>
   )
}


text:
Q: the 'leftmargin' attribute is not working while using bootstrap : - the 'leftmargin' attribute was not functioning  while  i was using  twitter bootstrap ,i am a beginner at it .
i used it like this
<body leftmargin="value">
 </body>

i hope there are no syntax errors .
i have posted a repository at github , have a look at the calc.html file in this link
please help me , the page is not looking good, as everything sticks to the leftmargin ,

A: Bootstrap already provides a folder for CSS files. Create your own *.css file there and link it from your HTML documents:
<link href="/css/my-styles.css" rel="stylesheet" type="text/css">

Then, edit my-styles.css and set your left margin using the CSS syntax:
body{
    margin-left: 0;
}

I can't explain you everything about CSS here but you should be able to find a decent tutorial out there.


text:
Q: In caught exception -> e.Data.Clear(); // what is this supposed to do? I've seen something like this too many times:
try
{
    //something
}
catch (FileNotFoundException e)
{
    e.Data.Clear(); // <- WTF?
}

and as far as I know this is useless voodoo, but please correct me if I'm wrong.

A: Exceptions in .Net allow you to associate arbitrary data with them by putting it into the Data member of Exception.  It's essentially a weakly typed dictionary which makes minimal checks to ensure the stored information is serializable.
This particular function is simply clearing out all of the custom associated data.  Why is a bit of a mystery since the developer left no comments.
As to whether or not this is useless.  In all likely hood yes.  The one specific case where this could be useful is if the creator of the FileNotFoundException both added an object reference to the Data bag and is itself holding onto a reference of the FileNotFoundException instance.  In that specific case calling Clear could prevent a memory leak by removing a reference to an object which should be short lived.  I find it very unlikely that this is the case though.  My instinct would be to file a bug / delete it .


text:
Q: Google App Script Spreadsheet Form error Separate issue raised with Google by st...@ditoweb.com here (issue 2391)
We have an iframe-based spreadsheet form on a website (http://www.monarch-equestrian.co.uk/brochurerequest.html) which is set to generate emails with attached PDF's to respondents.
Over the past few days, this has been generating an error notification - "You do not have permission to call getActiveSpreadsheet". The script, triggered on submission, has been working perfectly - however the spreadsheet had grown to 1387 rows so we archived it and deleted most of the records in the original (in case we had reached the limit allowed and so we wouldn't have to create a new spreadsheet etc).
The question is, even though the spreadsheet is presumably now within data limits and all the settings are unchanged, why are we still getting the error?

A: According to the reported issue noted in the question, this was fixed Feb 25, 2013.


text:
Q: jQuery - Ajax POST seems to does not work Here is my HTML Code:

            Title:

<input class="form-control" id="title" name="title" type="text">

            Article:

                <textarea name="editor1" id="editor" rows="10" cols="80">
                                Let's go...
                            </textarea>

            Tags:

<input class="tags" id="tags" type="text" value="">

        <input type="button" id="PostArticle" class="btn btn-success" value="Post Article"></input>

Here is my JavaScript code:

Here is the code from: post_new_article.php:
<?php

require "include/config.php";
require "include/functions.php";

ConnectWithMySQLDatabase();

error_reporting(E_ALL);
ini_set('display_errors', '1');

$title = $_POST['title'];
$text = $_POST['text'];
$tags = $_POST['tags'];
$month = date('F');
$year = date('Y');
$day = date('d');

if(isset($_POST['title']))
{
    mysql_query("INSERT INTO `Blog` (`id`, `Title`, `Article`, `Autor`, `Date`, `Month`,`Year`, `Tags`, `Image`) VALUES ('', '$title', '$text', 'Venelin Vasilev', '$day','$month', '$year', '$tags', '')");
}

$result['title'][0] = $title;

echo json_encode($result);

From all things it seems that only the MySQL insert function is not working. I can confirm that ConnectWithMySQLDatabase(); function is working as intended and this function is establishing the connection to MySQL.
Somehow it seems i can not insert the mysql query after i hit the Post Article button. I can confirm that i receive response from post_new_article.php because i receive a notification with the title of the article as a back response. So the json seems to read back the title of the article.
So can you help me out resolve this problem and make it insert the query to the MySQL database ?
Thanks in advance!

A: Try this
in your form submit button should be
<input type="submit" id="submit" class="btn btn-success" value="Post Article"></input>

And AJAX Should be

EDIT 01
Change this
mysql_query("INSERT INTO Blog (id, Title, Article, Autor, Date, Month,Year, Tags, Image) VALUES ('', '$title', '$text', 'Venelin Vasilev', '$day','$month', '$year', '$tags', '')");


text:
Q: White page on order view page. I am getting this error for a while and I am clueless to what is wrong with it.
Whenever I click the view order page, I get a blank page. Now I installed some code on my index.php that displays the errors.
This is the error that I get:
Array
(
   [type] => 1
   [message] => Class 'Mage_Sales_Block_Order_Info' not found
   [file] => /app/code/core/Mage/Core/Model/Layout.php
   [line] => 491
)

This is line 491 (and context)
/**
 * Create block object instance based on block type
 *
 * @param string $block
 * @param array $attributes
 * @return Mage_Core_Block_Abstract
 */
protected function _getBlockInstance($block, array $attributes=array())
{
    if (is_string($block)) {
        if (strpos($block, '/')!==false) {
            if (!$block = Mage::getConfig()->getBlockClassName($block)) {
                Mage::throwException(Mage::helper('core')->__('Invalid block type: %s', $block));
            }
        }
        if (class_exists($block, false) || mageFindClassFile($block)) {
            $block = new $block($attributes);
        }
    }
    if (!$block instanceof Mage_Core_Block_Abstract) {
        Mage::throwException(Mage::helper('core')->__('Invalid block type: %s', $block));
    }
    return $block;
}

Seems nothing is wrong there (and why should it, its magento default code)
Now the next part is somewhat strange. I expected the class to live in app/code/core/Mage/Sales/Block/Order/Info I looked it up. The folders Order/Info didnt exist in my folder. Nor in the fresh install zip.
What is going on and more importantly, how can I fix this?


text:
Q: How to solve problem of updating css of lightning components with every release of Salesforce? Lightning make changes in there css with every release. Most of time these changes were minor so we didn't make any changes. But like in summer 18 release there were big changes and we have to release patches for all of our lightning releases(https://releasenotes.docs.salesforce.com/en-us/summer18/release-notes/rn_lc_css.htm). Is there a way we can solve this problem. How can we remain in css version of our choice(like in apex). Like I want my css to remain in v42 not upgrade to v43.

A: We raised a case with salesforce after summer 2018 release since we  were brutally affected by these SLDS class name changes. we had to touch 300 odd components in around 800 places. The main change was classes like slds-large-size--2-of-12 where changed to slds-large-size_2-of-12. -- was changedto _ in BEM part of the class
The answer we got was these are not backward compatible and they were mentioned in the release notes that they will change. We asked the same question if staying in v42 will help but sadly the answer is No.
we ended up changing the 300 components since our production application will run into loads of issues post production upgrade this weekend.
Response from salesforce:
We heard back from our R&D team and so the change to the class names of the base components is not tied to the api version. The old SLDS "--" styles are still usable in that if you apply them to elements using a style tag, they will still work.
But you won't be able to override them anymore through css as the base component class names have been changed to match the BEM notation (using an _ instead of --) and is unfortunately not tied to the api version.
"We recommend that you create a class instead of targeting a class name you don't own, since those classes might change anytime. For example, don't try to target .slds-input or .lightningInput, as they are CSS classes that are available by default in base components."


text:
Q: Fastest way to download/access files in Amazon S3 I'm trying to access files in my amazon S3 and do some operations on it. Currently evaluating the options.
Since I will be doing some operations on the S3 files, I would prefer using some language to access the files in S3 (I have already tried copy command).
My S3 contains JSON files which range between 2MB to 4 MB and I would need to parse these JSON and load them into a database (thinking about using JQuery here, but any other suggestions are welcome)
Given these requirements which is most efficient language/platform to be used here.

A: You options are pretty broad here. AWS has a list of SDKs for you to choose from. https://aws.amazon.com/tools/#sdk
So your comfort level with a particular language should be your largest influencer.  Given that you mentioned JSON and JQuery perhaps you should look at Node.js SDK and AWS Lambda.


text:
Q: number of spanning trees in this graph This is a homework help, it ask us to find the number of spanning trees in this graph.

I can use "matrix tree theorem" to solve it, but that means I need to compute the determinant of a $ 15\times 15$ matrix, which seems an horror to me.
Is there an easier way to compute?

A: The graph has 16 vertices, so any spanning tree will have 15 edges. The graph starts with 20 edges, so we need to remove 5. We have to break each of the four 5-cycles, so by the pigeonhole principle we will take a single edge from three of the 5-cycles and two edges from one of them.
We also have to break the 4-cycle in the middle. If we remove an edge shared by a 5-cycle and the 4-cycle, we must remove another edge from that 5-cycle, otherwise we end up with an interior 7-cycle. Thus in the 5-cycle that we remove two edges from, one of them must be the edge shared with the 4-cycle.
There are four shared edges to choose from. Once we pick that, there are four other edges in that 5-cycle to remove. Once we do that, each of the three remaining 5-cycles has 5 choices for us to delete one edge from.
Thus in total we have $4\cdot 4 \cdot 5^3 = 2000$ spanning trees.


text:
Q: SAP HR CATS application How to send the rejection/approval emails to the employee after the manager has approved the time using MSS application (we are using standard TS310000007) ?

A: I'm not familiar with that task specifically, but you have a couple options:

*

*If it's a standalone task (not part
of a workflow template) then you
could extend the CATS business object
and create a ZAPPROVE method that
sends an email after the approval is
complete.

*If that task is part of a workflow
template then you can just copy that
template to a Z workflow and add an
email step after the TS31000007 step.


text:
Q: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.? I have find many answers on this problem but still no solution to my problem. I am using this code to send Account Activation mail to the user. But i get this error "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."
using (MailMessage mm = new MailMessage("sender@gmail.com", txtEmail.Text))
    {
        mm.Subject = "Account Activation";
        string body = "Hello " + txtUsername.Text.Trim() + ",";
body += "

Please click the following link to activate    your   account";
        body += "
Click here to activate your account.";
        body += "

Thanks";
        mm.Body = body;
        mm.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        NetworkCredential NetworkCred = new NetworkCredential("sender@gmail.com", "<password>");
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
        //var client = new SmtpClient("smtp.gmail.com", 587)
        //{
        //    Credentials = new NetworkCredential("myusername@gmail.com", "mypwd"),
        //    EnableSsl = true
        //};
        //client.Send("myusername@gmail.com", "myusername@gmail.com", "test", "testbody");
    }

A: The problem is like water, code executes from top-to-bottom. You're passing the credentials, but at the same time setting the UseDefaultCredentials to true. Which causes this problem. Most of the servers require authentication, such as EnableSsl and credentials (username/password combination) in order to send the emails from their server.
So, the solution would be to remove this following line,
smtp.UseDefaultCredentials = true;

Then the code would execute and the email would be sent.


text:
Q: Pixmap thats just transparent....this should be easy right? Here's my code;
Pixmap pm = new Pixmap(8,8,Format.RGBA8888);
Pixmap.setBlending(Pixmap.Blending.None); //ensure when we draw transparent we REPLACE the pixels with a transparent color.
pm.setColor(Color.CLEAR);

//pm.setColor(0f,0f,0f,0f); //also didnt work.
//pm.fillRectangle(0, 0, 8, 8);  //also didnt work.
pm.fill();

Gdx.graphics.setCursor(Gdx.graphics.newCursor(pm, 0, 0));
//restore normal blending
Pixmap.setBlending(Pixmap.Blending.SourceOver);

I was trying to replacing the default cursor with a transparent pixmap.
This seemed to be the easiest way to completely replace the in game cursor (on desktop/gwt) without it also going outside the boundary's of the window, and thus irritating users.
Thing is, the replacement cursor always comes out black, not transparent.
Am I making the Pixmap wrong?
Can you not have transparent cursors? (it says it cant be semi-transparent, but I want it fully invisible).
Kinda puzzled here as there doesn't seem many options left to try. I could just load a empty png I guess, but that seems....well....silly.
ideas?
Thanks,
Thomas

A: Ok, as far as I can tell its a bug in LibGDX pixmap fill function when used on small sizes.
I came to this conclusion after noticing it works when the map is bigger.
Pixmap pm = new Pixmap(x,y,Format.RGBA8888);
Pixmap.setBlending(Pixmap.Blending.None);
pm.setColor(0f,0f,0f,0f);
pm.fillRectangle(0, 0, x, y);

Experimenting with the size of the pixmap (x/y) I get the following results;
8*8   - doesn't work. Comes out black.
16*16 - works. Completely transparent.
64*64 - works. Completely transparent.
So the workaround is just using 16x16 or above. Its transparent anyway, so doesn't matter.
Still, odd bug.
CONCLUSION:
Seems to be a bug in the windows library being used.
Thread discussion here;
https://github.com/libgdx/libgdx/issues/4292#issuecomment-244804073
Unfortunately this likely means the workaround cant be relied upon.


text:
Q: jQuery search element change I need help changing equals mark to slash
as in now, when I submit my form, url it gets me is #search=x but I need it to be #search/x
<form name="input" action="" method="get">
Search: <input type="text" name="search">
<input type="submit" value="Submit">
</form>

--
<script type="text/javascript">
$('form').submit(function() {
var form_data = ($(this).serialize());
window.location = "#" + form_data;
return false;
});
</script>

A: This may work:
data = form_data.replace('=', '/');

As for your second question use:
window.location.hash = form_data;

That should overwrite the previous if I understood the problem correctly.
Whole thing:
$('form').submit(function() {
    var form_data = ($(this).serialize());
    window.location.hash = form_data.replace('=','/');
    return false;
});

A: You can do that easy with native replace method:
$('form').submit(function() {
    var form_data = $(this).serialize();
    window.location = "#" + form_data.replace("=", "/");
    return false;
});

http://jsbin.com/ohulaz/1/edit


text:
Q: Powershell function LogonUser return different Error code when using Schedule Task I'm using function below in my script to ensure that user are not using specific list of  passwords for local account. The function works fine and return "True" with correct username and password and return "False" with correct Error "The user name or password is incorrect" when tested against a username with wrong password. The issue is when I run my script using Task Scheduler with SYSTEM account, it still return correct validation, but the Error code for username with wrong password is "0" : The operation completed successfully. Does anyone knows why the GetLastWin32Error() return code 0 instead of 0x0000052E when using Task Scheduler?
Function Test-LocalCredential{
    <#
    Test credential/password for local account.
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$True)][String]$UserName,
        [Parameter(Mandatory=$True)][String]$Password
    )

    IF (!($UserName) -or !($Password)) {
        Write-Warning 'Username and password not provided'
        Return
    }

    [Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null
    [Reflection.Assembly]::LoadWithPartialName("System.Runtime.InteropServices") | Out-Null

$logonUserSignature =
@'
[DllImport( "advapi32.dll", SetLastError = true )]
public static extern bool LogonUser( String lpszUserName,
                                     String lpszDomain,
                                     String lpszPassword,
                                     int dwLogonType,
                                     int dwLogonProvider,
                                     ref IntPtr phToken );

'@

$closeHandleSignature =
@'

[DllImport( "kernel32.dll", CharSet = CharSet.Auto, SetLastError = true )]
public static extern bool CloseHandle( IntPtr handle );

'@

    $AdvApi32 = Add-Type -MemberDefinition $logonUserSignature -Name "AdvApi32" -Namespace "PsInvoke.NativeMethods" -PassThru
    $Kernel32 = Add-Type -MemberDefinition $closeHandleSignature -Name "Kernel32" -Namespace "PsInvoke.NativeMethods" -PassThru

    <#
        LOGON32_PROVIDER_DEFAULT = 0
        LOGON32_PROVIDER_WINNT35 = 1
        LOGON32_PROVIDER_WINNT40 = 2
        LOGON32_PROVIDER_WINNT50 = 3
    #>
    $Logon32Provider = 0

    <#
        LOGON32_LOGON_INTERACTIVE = 2
        LOGON32_LOGON_NETWORK = 3
        LOGON32_LOGON_BATCH = 4
        LOGON32_LOGON_SERVICE = 5
        LOGON32_LOGON_UNLOCK = 7
        LOGON32_LOGON_NETWORK_CLEARTEXT = 8
        LOGON32_LOGON_NEW_CREDENTIALS = 9
    #>
    $Logon32Type = 3

    $tokenHandle = [IntPtr]::Zero
    $TestLogon = $False

    <#
       Unless $userName is supplied using UPN format (e.g administrator@servername or administrator@domain) domain name should not be of null value as it would
       default the logon provider authentication to NTLM
    #>
    $DomainName = $env:COMPUTERNAME
    $TestLogon = $AdvApi32::LogonUser($UserName, $DomainName, $Password, $Logon32Type, $Logon32Provider, [Ref]$tokenHandle)

    $success_codes = @(
                0x0000052F,  # ERROR_ACCOUNT_RESTRICTION
                0x00000530,  # ERROR_INVALID_LOGON_HOURS
                0x00000531,  # ERROR_INVALID_WORKSTATION
                0x00000569  # ERROR_LOGON_TYPE_GRANTED
    )

    if (!$TestLogon){
        $err_code = $Null
        $err_code = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
        $Msg = $(([ComponentModel.Win32Exception] $err_code).Message)
        Write-Verbose $Msg

        if ($err_code -eq 0x0000052E) {
            # ERROR_LOGON_FAILURE - the user or pass was incorrect
            $valid_credentials = $false
        } elseif ($err_code -in $success_codes) {
            $valid_credentials = $true
        } else {
            # an unknown failure, raise an Exception for this
            $win32_exp = New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList $err_code
            $err_msg = "LogonUser failed: $($win32_exp.Message) (Win32ErrorCode: $err_code) ($Password)"
            Write-Verbose $err_msg
            throw New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList $err_code, $err_msg
            $valid_credentials = $false
        }

    } else {
        $Kernel32::CloseHandle($tokenHandle) | Out-Null
        $valid_credentials = $True
    }
    Return $valid_credentials
}


text:
Q: Display the Servlet response in same JSP page I am working on a dynamic webpage where I need to display the response from the Servlet response in the bottom same jsp page.
Below is the sample screenshot the index.jsp where the user needs to provide the inputs and click the Submit button. The results needs to be displayed below input values.

index.jsp:

<form name="orderform" action=OrderController method="POST">
Dispatch Site<select type="text" style="width:172px" name="branch">
<option selected value="0">All Branches</option></select>
Service<select class="SelectionBoxes" style="width:172px" id="Serviceselect" name="Serviceselect"
Order<select class="SelectionBoxes" style="width:172px" id="Orderstatus" name="Orderstatus">
Start Date<input type="text" style="width:168px"  name="startdate" id="StartDate" >
End Date<input type="text"  style="width:168px" name="enddate" id ="EndDate">
<button class="submit" name="submit" value="submit">Submit</button>

Order Number	Service Type	Customer Number

<c:forEach items="${orders}" var="order">

<c:out value="${order.branch}" />	<c:out
value="${order.service}" />	<c:out value="${order.customernumber}"
/>

</c:forEach>

Previously i had a response.jsp which displays the results now i want to show the results in the same page. Can anyone explain me how to get the results in same page ?


text:
Q: How do the two R codes, which should do the same thing (at least in my head), differ? In order to replicate this code, you will need these packages:
Tidyverse, Nycflights13
I am basically trying to understand why two pieces of code, which in my head should do the same thing, don't do the same thing.
I am currently learning R for data science from R for Data Science by Garrett Grolemund & Hadley Wickham, and I've gotten to a point which the code begins to confuse me quite a bit, which hopefully is normal! I will write down the two pieces of code which confuse me in why they don't do the same thing!
filter(flights, dest == c("HOU","IAH"))
#and
filter(flights, dest == "HOU" | dest == "IAH")

I expected both of these codes to show the same amount of rows but the first one shows 4658 rows (the wrong amount), where as the second one shows 9313 (the right amount).
What I wanted to do is to shorten the code by using (filter(flights, dest == c("HOU","IAH"))) instead of (filter(flights, dest == "HOU" | dest == "IAH"))
but it yields different results, which gravely confuses me!
Please give me your advice, I am a newbie!

A: Because filter(flights, dest == c("HOU","IAH")) is the same as
filter(flights, dest == c("HOU","IAH"))
flights$dest = c("HOU","IAH")
* # For demonstation purposes, I'm assuming the flights dataset has has 4 rows, as:
c("HOU","CPH","IAH","EDI") == c("HOU","IAH")

Now, a vector of 4 elements cannot possible be the same as a vector of 2 elements. And this performs an element-wise comparison, "HOU" == "HOU", "CPH" == "IAH", "IAH" == ???. So R "helps" us by repeating the shorter vector. The output is thus:
> c("HOU","CPH","IAH","EDI") == c("HOU","IAH")
[1]  TRUE FALSE FALSE FALSE

Try extending with a 5th element:
> c("HOU","CPH","IAH","EDI", "LDN") == c("HOU","IAH")
[1]  TRUE FALSE FALSE FALSE FALSE

Warning message:
  In c("HOU", "CPH", "IAH", "EDI", "LDN") == c("HOU", "IAH") :
    longer object length is not a multiple of shorter object length

and you broke it.
So the 1st line only makes sense if and only if flights has 2 rows, whereupon an element-wise comparison can be performed.
However, what you might be looking for is the %in% operator:
> c("HOU","CPH","IAH","EDI") %in% c("HOU","IAH")
[1]  TRUE FALSE  TRUE FALSE
> c("HOU","CPH","IAH","EDI","LDN") %in% c("HOU","IAH")
[1]  TRUE FALSE  TRUE FALSE FALSE

which can be expanded to filter(flights, dest %in% c("HOU","IAH")) and luckily works for vectors of any length.


text:
Q: Test Cases for Rego Polices Sorry for my novice question. I have written a rego rule to check for ASV Names, and now I am looking to write a test case for the same. I have looked at sample test cases but has no success in writing for my policy(pasted below). Was wondering how could I get a positive and a failure case for the rule below.
asv_list = {"ASVONE","ASVXYZ"}
check_asv := { resources[i]: Reason |
    resources:=[resource | data[j] ;
        list := {x| x:=asv_list[_]}
        not(list[data[j].ASV])
        resource:=data[j].Name]

    Reason := sprintf("THE ASV - %v being used is not a valid ASV", [data[j].ASV])
}

data = {resource |
    doc = input[i];
        key_ids := [k | doc[k]; startswith(k, "tag."); k != "tag.#"; endswith(k, ".key")]
    resource := {
        doc[k] : doc[replace(k, ".key", ".value")] | key_ids[_] == k
    }
}

A: If you're trying to test check_asv your positive and negative test cases will look similar:

*

*Define input value

*Define expected value

*Assert that check_asv is equal to expected value when evaluated with test input

For example:
test_check_asv_positive {
  expected := {"r1": "..."}
  fake_input := [{"Name": "foo", ...}]
  check_asv == expected with input as fake_input
}

Before you start writing tests for your rule though, I think you should clarify the logic you're trying to express because there are a few red flags that jump out. I've tried to breakdown the issues I see in the policy below. At the end, I've written out some example test cases.
Format the file to make it easier to read
First of all, just format the Rego so that it's easier to read. I  pasted your example into a file, added a package (to make it a valid .rego file) and then ran opa fmt file.rego:
asv_list = {"ASVONE", "ASVXYZ"}

check_asv := {resources[i]: Reason |
        resources := [resource |
                data[j]
                list := {x | x := asv_list[_]}
                not list[data[j].ASV]
                resource := data[j].Name
        ]

        Reason := sprintf("THE ASV - %v being used is not a valid ASV", [data[j].ASV])
}

data = {resource |
        doc = input[i]
        key_ids := [k |
                doc[k]
                startswith(k, "tag.")
                k != "tag.#"
                endswith(k, ".key")
        ]

        resource := {doc[k]: doc[replace(k, ".key", ".value")] |
                key_ids[_] == k
        }
}

This a little bit easier to read.
Do not name rules data
I recommend NOT naming that rule data. data in Rego is a special global variable that refers to state cached inside the policy engine. Any data from outside OPA or generated by rules inside of OPA is accessible under data. Defining a rule named data is allowed but it's confusing. Rename data to something meaningful in the domain. E.g., if these were virtual machine resources, you could name them vm_resources. In this case, I don't have much to go on, so I'm going to rename it to input_docs since doc was used as a variable name:
check_asv := {resources[i]: Reason |
        resources := [resource |
                input_docs[j]
                list := {x | x := asv_list[_]}
                not list[input_docs[j].ASV]
                resource := input_docs[j].Name
        ]

        Reason := sprintf("THE ASV - %v being used is not a valid ASV", [input_docs[j].ASV])
}

input_docs = {resource |
        doc = input[i]
        key_ids := [k |
                doc[k]
                startswith(k, "tag.")
                k != "tag.#"
                endswith(k, ".key")
        ]

        resource := {doc[k]: doc[replace(k, ".key", ".value")] |
                key_ids[_] == k
        }
}

Simplify the input_docs helper rule (which was called data in the original)
At first glance, this rule is doing quite a bit of work, but in reality, it's not. The first line (doc = input[i]) just iterates over each element in input. The rest of the rule is based on each element in input. The second expression, key_ids := [..., computes an array of object keys from the element. The third expression, resources := {doc[k]: ..., constructs a new object by mapping the element.
The first expression can't be simplified much, however, it's better to use := instead of = and since i is not referenced anywhere else we can just use _. The first expression becomes:
doc := input[_]

The second expression computes an array of keys but the filtering is a bit redundant: k cannot be equal to tag.# AND end with .key so the != expression can be removed:
key_ids := [k |
  some k
  doc[k]
  startswith(k, "tag.")
  endswith(k, ".key")
]

At this point we could stop however it's worth noticing that the second and third expression in the rule are both just iterating over the doc object. There's no reason for two separate expressions here. To simplify this rule we can combine them:
input_docs = {resource |
        doc := input[_]
        resource := {v: x |
                some k
                v := doc[k]
                startswith(k, "tag.")
                endswith(k, ".key")
                x := doc[replace(k, ".key", ".value")]
        }
}

Simplify the check_asv rule
Now that we have a simplified version of the input_docs rule that generates a set of mapped resources we can focus on the check_asv rule. The check_asv rule can be simplified quite a bit:

*

*Multiple iterators in the rule body (i and j) when there should be only one.

*Construction of invalid resource list is overly complex.

The rule can be simplified down to the following:
check_asv := {name: reason |
        r := input_docs[_]
        not asv_list[r.ASV]
        name := r.Name
        reason := sprintf("THE ASV - %v being used is not a valid ASV", [r.ASV])
}

*

*No need to iterate over input_docs twice (in fact this would be incorrect.)

*No need for a nested comprehension.

*No need constructing a set from asv_list, it's already a set.

Putting it all together
At this point the policy looks like this:
asv_list = {"ASVONE", "ASVXYZ"}

check_asv := {name: reason |
        r := input_docs[_]
        not asv_list[r.ASV]
        name := r.Name
        reason := sprintf("THE ASV - %v being used is not a valid ASV", [r.ASV])
}

input_docs = {resource |
        doc := input[_]
        resource := {v: x |
                some k
                v := doc[k]
                startswith(k, "tag.")
                endswith(k, ".key")
                x := doc[replace(k, ".key", ".value")]
        }
}

To test this policy we can easily write a few test cases:
test_check_asv_positive {
    exp := {
        "dog": "THE ASV - ASVBAD being used is not a valid ASV"
    }

    inp := [
       {
           "tag.foo.key": "Name",
           "tag.foo.value": "dog",
           "tag.bar.key": "ASV",
           "tag.bar.value": "ASVBAD"
       }
   ]

    check_asv == exp with input as inp
}

test_check_asv_positive_multiple_resources {
    exp := {
        "dog": "THE ASV - ASVBAD being used is not a valid ASV",
        "horse": "THE ASV - ASVBAD2 being used is not a valid ASV"
    }

    inp := [
       {
           "tag.foo.key": "Name",
           "tag.foo.value": "dog",
           "tag.bar.key": "ASV",
           "tag.bar.value": "ASVBAD"
       },
       {
           "tag.foo.key": "Name",
           "tag.foo.value": "horse",
           "tag.bar.key": "ASV",
           "tag.bar.value": "ASVBAD2"
       }
   ]

    check_asv == exp with input as inp
}

test_check_asv_positive_multiple_resources_mixed {
    exp := {
        "horse": "THE ASV - ASVBAD2 being used is not a valid ASV"
    }

    inp := [
       {
           "tag.foo.key": "Name",
           "tag.foo.value": "cat",
           "tag.bar.key": "ASV",
           "tag.bar.value": "ASVONE"
       },
       {
           "tag.foo.key": "Name",
           "tag.foo.value": "horse",
           "tag.bar.key": "ASV",
           "tag.bar.value": "ASVBAD2"
       }
   ]

    check_asv == exp with input as inp
}

test_check_asv_negative {
    exp := {}

    inp := [
       {
           "tag.foo.key": "Name",
           "tag.foo.value": "cat",
           "tag.bar.key": "ASV",
           "tag.bar.value": "ASVONE"
       }
   ]

    check_asv == exp with input as inp
}

Here's a link to the full policy in the playground: https://play.openpolicyagent.org/p/6w7aC9xWYH


text:
Q: I am displaying the contents of an Excel file in a Gridview. How do I handle merged cells? I want to read and display an excel file in a web page. I am using Microsoft.Office.Interop.Excel in .aspx.cs and GridView in .aspx. I am  just reading it into a DataTable and binding it to GridView.
The problem with this is, I can't handle merged cells. For example, if two columns are merged in Excel, while displaying, it will show two columns with the value in first cell and second cell will be empty. I just want to retrieve the sheet as it is. Is there any way to achieve this?

A: Microsoft.Office.Interop.Excel is designed to provide programmatic access to excel files. It will do some formatting work (see Text property) but most of the difficulty of rendering is left to the consumer (your program).
MergeCells will return True if you have a merged cell and MergeArea will return a Range containing the merged cells. You can then use the RowSpan and ColumnSpan fields of the GridView's cells to duplicate the functionality.


text:
Q: How can I find if a value lies between two specific thresholds regardless of the order in which the thresholds are given? For example, if I have a value a = 4 and two input thresholds t1 = 3 and t2 = 5.
a > t1 and a < t2 so the function func(a, t1, t2) returns true.
But if I input t1 = 5 and t2 = 3, even if a = 4 lies between the t1 and t2, the function returns false. How to solve this?
So far I write this function in this way, but it only works when t1 < t2. Is there some smart way to do this?
def func(a, t1, t2):
    if a > t1 and a < t2:
        return True
    else:
        return False

A: You can use or:
def func(a, t1, t2):
    return t1 < a < t2 or t2 < a < t1

print(func(4, 3, 5)) # True
print(func(4, 5, 3)) # True
print(func(4, 1, 2)) # False

Note that python allows chained comparisons so that you don't need to write t1 < a and a < t2. Also, you don't need the redundant if statement as in:
if t1 < a < t2 or t2 < a < t1:
    return True
else:
    return False

A: You could order the two thresholds before using them in the comparison with a, for example by using the sorted function:
smaller, larger = sorted([t1, t2])

If t1 <= t2 then smaller will be t1 and larger will be t2, otherwise smaller will be t2 and larger will be t1.
def func(a, t1, t2):
    smaller, larger = sorted([t1, t2])
    return smaller < a < larger


text:
Q: Node.js get same instance of module accross different classes I've a main class (app.js) where I declared an instance of socket-io and I would like to know how is possible to get same instance of socket-io inside another classes.
app.js
var io = require('socket.io')();
//initialize socket and more related do web socket

routes.js
var io = ?? //How get same var io from app.js?

On Node.js, is possible to do that? I need to manipulate some informations from socket-io but I would like to avoid write a single file with all logic inside.

A: Let's say you have a file routes.js and this is a file inside which you want to access the instance of socket-io which you have created on app.js. Then you can pass this var io inside the  routes.js file that will pass the same instance of socket-io like this,
Inside app.js
var io = require('socket.io')();

//pass the `io` inside the route file
require('routes')(io);

Inside routes.js
module.exports = function(io) {
   //your route codes here that can access `io`
};


text:
Q: Extract an element from XML using SQL I had a situation

*

*Xml execution plan stored in a table

*Need to filter ColumnReference element and its attributes from xml plan
Sample element
<ColumnReference Database="[Adventureworks]" Schema="[dbo]" Table="[Product]" Column="ProductID" />

challenge : ColumnReference is available in multiple hierarchy, need to extract all of them
Expected output as table in below structure:
Database | Schema | Table | Column

Sample Dataset: (run below code you will get dataset in temptable called #t)
    CREATE TABLE Employee
    (
        EmpID INT NOT NULL ,
        EmpName VARCHAR(50) NOT NULL,
        Designation VARCHAR(50) NULL,
        Department VARCHAR(50) NULL,
        JoiningDate DATETIME NULL,
        CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED (EmpID)
    )

    INSERT INTO Employee
    (EmpID, EmpName, Designation, Department, JoiningDate) VALUES
    (1, 'CHIN YEN', 'LAB ASSISTANT', 'LAB', GETDATE()),
    (2, 'MIKE PEARL', 'SENIOR ACCOUNTANT', 'ACCOUNTS', GETDATE()),
    (3, 'GREEN FIELD', 'ACCOUNTANT', 'ACCOUNTS', GETDATE()),
    (4, 'DEWANE PAUL', 'PROGRAMMER', 'IT', GETDATE()),
    (5, 'MATTS', 'SR. PROGRAMMER', 'IT', GETDATE()),
    (6, 'PLANK OTO', 'ACCOUNTANT', 'ACCOUNTS', GETDATE())
create proc itemployee
as
select EmpName, Designation  from Employee where department = 'it'

go

exec itemployee

SELECT
  'itemployee ' as SP_Name,
  query_plan into #t  FROM sys.dm_exec_cached_plans cp CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle)
WHERE
  object_id('itemployee') = objectid;

query used to extract the output:
SELECT
  AnyColRef.value('@Table', 'nvarchar(250)') AS [Table],
  AnyColRef.value('@Column', 'nvarchar(250)') AS [Column]
FROM
  #t t
  CROSS APPLY t.query_plan.nodes('//ColumnReference') A(AnyColRef);

A: What you provide is not enough... For your next question please try to create a mcve (a stand-alone sample to reproduce your issue).

challenge : ColumnReference is available in multiple hierarchy, need to extract all of them

As a quick shot you might try something along this:
SELECT AnyColRef.value('@Database','nvarchar(250)') AS [Database]
      ,AnyColRef.value('@Schema','nvarchar(250)') AS [Schema]
      ,AnyColRef.value('@Table','nvarchar(250)') AS [Table]
      ,AnyColRef.value('@Column','nvarchar(250)') AS [Column]
FROM YourTable t
CROSS APPLY t.YourXMLColumn.nodes('//ColumnReference') A(AnyColRef);

The idea in short:
The deep search (triggered by the doubled slash at //ColumnReference) will search for any element with this name anywhere in your XML. All these elements are returned as a derived set, where each element comes back in its own row (this is done by .nodes()). The native XML method .value() will finally retrieve the iternal values of the attributes (indicated by the @).
UPDATE
Best was to provide a sample of XML you want to read, but thx for the code above to reproduce your issue, it helped too.
Your issue is: The XML is declaring a default namespace. There are three approaches to deal with this:

*

*a) Use WITHXMLNAMESPACES with a prefix

*b) Use WITHXMLNAMESPACES with DEFUALT

*a) Use an internal declaration with prefix

*b) Use an internal declaration for default element namespace

*Use a wildcard

Either this
WITH XMLNAMESPACES('http://schemas.microsoft.com/sqlserver/2004/07/showplan' AS ns)
SELECT
  AnyColRef.value('@Table', 'nvarchar(250)') AS [Table],
  AnyColRef.value('@Column', 'nvarchar(250)') AS [Column]
FROM
  #t t
  CROSS APPLY t.query_plan.nodes('//ns:ColumnReference') A(AnyColRef);

--Or this
WITH XMLNAMESPACES(DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')
SELECT
  AnyColRef.value('@Table', 'nvarchar(250)') AS [Table],
  AnyColRef.value('@Column', 'nvarchar(250)') AS [Column]
FROM
  #t t
  CROSS APPLY t.query_plan.nodes('//ColumnReference') A(AnyColRef);

--Or this
    SELECT
      AnyColRef.value('@Table', 'nvarchar(250)') AS [Table],
      AnyColRef.value('@Column', 'nvarchar(250)') AS [Column]
    FROM
      #t t
      CROSS APPLY t.query_plan.nodes('declare namespace ns="http://schemas.microsoft.com/sqlserver/2004/07/showplan";//ns:ColumnReference') A(AnyColRef);

--Or this
    SELECT
      AnyColRef.value('@Table', 'nvarchar(250)') AS [Table],
      AnyColRef.value('@Column', 'nvarchar(250)') AS [Column]
    FROM
      #t t
      CROSS APPLY t.query_plan.nodes('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/showplan" ;//ColumnReference') A(AnyColRef);

--Or this
SELECT
  AnyColRef.value('@Table', 'nvarchar(250)') AS [Table],
  AnyColRef.value('@Column', 'nvarchar(250)') AS [Column]
FROM
  #t t
  CROSS APPLY t.query_plan.nodes('//*:ColumnReference') A(AnyColRef);

The general advise is: Be as specific as possible. Namespaces are not just a fancy add-on, but very import to deal with different elements with identical names (often when various XMLs are combined). Use the easy-cheesy wildcard only in cases where you can be sure, that the namespace is not needed. Personally I prefer the approach WITH XMLNAMESPACES with DEFAULT as it is the closest to the given XML.


text:
Q: Tensor product of Hilbert space and Fock space If we have system consist of two or more than two subsystems, we can write hilbert space of a system in terms of tensor product of Hilbert spaces of subsystems and we can write state of a system. But also in Fock space for same system, when we write state of a system, Fock space is direct sum of hilbert spaces of subsystems. So can we use both formalisms for a system at the same time?

A: There are no different formalisms here. When you have two subsystems $S_1$ and $S_2$, the Hilbert space is the tensor product $\mathcal H = \mathcal H_1 \otimes \mathcal H_2$.
Let $\mathcal H_1$ be the Hilbert space of a single particle. The Hilbert space describing $N$ (distinguishable) particles is then
$$ \mathcal H_N = \mathcal H_1 \otimes \cdots \otimes \mathcal H_1 = \mathcal H_1^{\otimes N} . $$
If you can have any number of particles, then the total state lies in the direct sum
$$ \mathcal H = \mathcal H_1 \oplus \cdots \oplus \mathcal H_N \oplus \cdots . $$
(To get the Fock space, you now have to take the symmetrization / antisymmetrization, because the particles are indistinguishable.)


text:
Q: Bootstrap Popover Link Inside a Label On a form, I have a typical opt-in text checkbox but also have a link in that label. That link doesn't go anywhere but rather triggers a Bootstrap 3 Popover for additional detail.
It works, however clicking the popover link also unchecks the checkmark. Saw other questions on SO and solutions but they were for normal links and didn't apply to a javascript link link like this. Any thoughts?
The of course first thing one would think of is to have the link outside the label, but then the text won't wrap with the preceding text and will always have to appear beneath the disclaimer text which is not desired.

<input class="optin" type="checkbox" checked value="">My disclaimer text here. My Link.

Assuming I need to integrate stop propagation somehow but can't seem to determine how to integrate in this scenario.


text:
Q: JSF 2.2: Passing bean attribute as ValueExpression to composite I want to pass a non-managed (non-String) object as an attribute on a dynamically added composite component, and have it survive the session.
The JSF 2.2 ViewDeclarationLanguage#createComponent handles dynamic non-string attribute values to composite components differently than the older Mojarra dependent code (Application#createComponent). I can't find the approach that works completely with the JSF 2.2 technique, but it's probably me.
[I'm trying to remove Mojarra dependencies by converting to MyFaces (and also working around some other Mojarra issues). I'm using JSF 2.2, CDI Weld 2.2.16, Tomcat v8.0]
I'm instantiating different composite components like these programmatically (notice the bean attribute):
<cc:interface>
    <cc:attribute name="bean" required="true" type="com.aadhoc.cvc.spikes.extensionsapproach.ExtensionBeanInterface"/>
</cc:interface>

<cc:implementation>
    <h:panelGrid columns="2">
        <h:outputText value="Title:"/>
        <h:inputText value="#{cc.attrs.bean.title}"/>
    </h:panelGrid>
</cc:implementation>

In the older Mojarra dependent approach, I instantiate the non-managed bean object, and add it directly to the composite component as an attribute and it works great (I'm using @BalusC's great but Mojarra dependent sample code from OmniFaces Component#includeCompositeComponent):
ExtensionBeanInterface bean = Class.forName(className).newInstance();
attributes = new HashMap<String, Object>();
attributes.put("bean", bean); // Using bean object itself

[..]
UIComponent composite = application.createComponent(context, resource);
composite.getAttributes().putAll(attributes);
[..]

In JSF 2.2, I've found that I must pass a String ValueExpression instead of my bean object directly. I'm currently using this technique, and can't get it quite right:
FacesContext context = FacesContext.getCurrentInstance();
ELContext elContext = context.getELContext();

ValueExpression beanValExp = context.getApplication().getExpressionFactory()
            .createValueExpression(elContext, "#{customBeanVE}", ExtensionBeanInterface.class);
beanValExp.setValue(elContext, bean);
String beanValExpStr = beanValExp.getExpressionString();

attributes = new HashMap<String, Object>();
attributes.put("bean", beanValExpStr); // Using VE instead of bean object

UIComponent composite = context.getApplication().getViewHandler()
                .getViewDeclarationLanguage(context, context.getViewRoot().getViewId())
                .createComponent(context, taglibURI, tagName, attributes);
[..]

This works great on the first "add composite", but on any following form submit, I get:

/resources/com/aadhoc/cvc/spikes/extensionsapproach/components/House.xhtml
  @16,49 value="#{cc.attrs.bean.title}": Target Unreachable, 'bean'
  returned null

I've verified that the composite's required and type attributes are working fine, and that the #{cc.attrs.bean.title} is initially showing the bean's title. I verified with a static use of the composite component that refreshes work fine.
What's the deal, and how can I handoff the bean object so that it survives with the composite across the session?

A: I had this working great in Mojarra. I could put the bean object in the attribute value, and all was wonderful. Trying MyFaces, I needed to change/update my approach, and I now needed to use EL strings instead of direct object references.
Since all was working with just putting bean object into attributes Map, I wanted a magical yet elegant place to put bean objects and have them survive. I could have put them into the "global" session Map (like this: How to save an object into JSF Session), but it wasn't clean enough. I then put them into my one main session state bean (modelerBean), and it was right. This is how I saved the bean, and how I pointed to it with an EL string. No need to create ValueExpression or MethodExpression objects or register special mappings. This JSF 2.2 compatible approach worked for me in both Mojarra and MyFaces.
public void onAdd(ActionEvent ev) {
    [..]
    ChosenBean chosenBean = new ChosenBean();
    chosenBean.setComponentId(id);
    chosenBean.setBean(bean);
    modelerBean.addChosen(chosenBean);
    [..]
    String el = "#{modelerBean.getChosen('"+id+"').bean}"
    attributes.put(MODELER_EXTENSION_BEAN_ATTRIBUTE_NAME, el);
    [..]

I decided on this after reading @BalusC's post: How do I get and set an object in session scope in JSF?
Note, my experience with @BalusC's two "add composites dynamically" approaches (How to programmatically or dynamically create a composite component in JSF 2) is that you should definitely use the JSF 2.2 approach if you can. The old Mojarra approach does work if you aren't in JSF 2.2. Once I modified my code to have the JSF 2.2 approach work, the old Mojarra approach would break in strange ways.


text: Q: CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource in Ionic I'm trying to make a simple ionic (with angular) application that can connect to Nodejs backend but when I want to get the data from MongoDB I got this error I don't know how to solve it please help me I'm stack on this problem


text:
Q: A question on Lie sub-group Well, definition of Lie subgroup what I know is, a Lie subgroup of a Lie group $G$ is an abstract subgroup $H$ which is an immersed submanifold via the inclusion map so that the group operations on $H$ are $C^{\infty}$.
Could any one make me understand the following with an example?
"Because a Lie subgroup is an immersed submanifold, it need not have the relative topology. In particular, the inclusion map $i:H\rightarrow G$ need not be continuous."

A: I can't help you understand that statement, because I don't understand it: an immersion is a differentiable map with injective derivative, and is in particular continuous. A standard example of a Lie subgroup such that the inverse of the inclusion is not continuous is the image of a line with irrational slope in the two-dimensional compact torus (quotient of the plane by $\mathbb{Z}^2$).
As Paul Garrett mentions in a comment above, this kind of example is almost certainly what Tu had in mind when he wrote the statement you quote. One reason for making the definition this way instead of with a more restrictive definition of Lie subgroup is to be flexible enough to allow Lie subgroups of a Lie group to correspond to Lie subalgebras of its Lie algebra.


text:
Q: 'NSInvocationOperation' is unavailable in Xcode 6.1 My code suddenly can't be compiled in Xcode 6.1 (I'm sure it's working in Xcode 6 GM and beta version). It shows the error message:

'NSInvocationOperation' is unavailable

My code is:
let operation = NSInvocationOperation(target:self, selector:"backgroundRun:", object:self)

Can anybody help? Thanks.

A: As of Xcode 6.1, NSInvocation is disabled in Swift, therefore, NSInvocationOperation is disabled too. See this thread in Developer Forum

Because it's not type-safe or ARC-safe. Even in Objective-C it's very very easy to shoot yourself in the foot trying to use it, especially under ARC. Use closures/blocks instead.

You have to use NSBlockOperation in Swift.
or addOperationWithBlock to NSOperationQueue
queue.addOperationWithBlock { [weak self] in
    self?.backgroundRun(self)
    return
}