text:
Q: Как последовательно сложить число с каждым элементом списка? from random import randint
count = int( input ( 'Введите количетсво элементов массива: ' ) )
a = []
for i in range( count  ):
    a.append( randint(0, 5) )#крч тут заполнил список
print('Список: ', a )
for i in range(count - 1):
    if a[i] == a[i + range(1, count)]:
        print('Да, есть одинаковые числа',a[i])
    else:
        print('Одинаковых чисел нет(((')

Вот заполнен список. Должен работать он так: если первый элемент (i) равен либо 2 элементу(i+1) либо 3 элементу(i+2) ...и так далее, пока список не закончится. Только вот нельзя складывать число и  функцию range(). Что делать?
Можно бы что-то типо этого, но опять ошибка:
from random import randint
count = int( input ( 'Введите количетсво элементов массива: ' ) )
a = []
for i in range( count  ):
    a.append( randint(0, 5) )#крч тут заполнил список
print('Список: ', a )
for i in range(count - 1):
    if a[i] == a[i + g for g in range(1,count)]:
        print('Да, есть одинаковые числа',a[i])
    else:
        print('Одинаковых чисел нет(((')

A: попробуйте так:
from random import randint

count = int(input('Введите количетсво элементов массива: '))
a = []

for i in range(count):
    a.append(randint(0, 5))                     #крч тут заполнил список

print('Список: ', a )

for i in range(count - 1):
#    if a[i] == a[i + range(1, count)]:
    if a[i] in a[i+1:]:
        print('Да, есть одинаковые числа', a[i], i)
    else:
        print('Одинаковых чисел нет(((')


text:
Q: Select multiple columns from subquery - Connect by I have a table which manages folder structure. Hence it has a parent-child relationship.  We trigger a query to sum all documents in the complete heirarchy:
   SELECT  folder_name name,
      document_count,
      (SELECT SUM(e2.document_count)
        FROM       folder_mapping e2      START WITH e2.folder_mapping_id       = e1.folder_mapping_id CONNECT BY prior e2.folder_mapping_id = e2.parent_folder_mapping_id
      )
      sum_sal
    FROM
      folder_mapping e1

Now I have a requirement to calculate the sum of one more column
    SELECT  folder_name name,
      document_count,
      (SELECT SUM(e2.document_count), **sum(e2.folder_count)**

        FROM       folder_mapping e2      START WITH e2.folder_mapping_id       = e1.folder_mapping_id CONNECT BY prior e2.folder_mapping_id = e2.parent_folder_mapping_id
      )
      sum_sal
    FROM
      folder_mapping e1

This query throws error:>ORA-00913: too many values.
But what can be done to achieve the same?
Database structure with data:

Intended output:

Query with help of JSapkota
SELECT
  fm.folder_mapping_id,
  fm_main.folder_name,
  fm.Total_Doc_Count,
  fm.Total_Folder_Count,
  --  fm.shared_flag
  DECODE(fm.shared_flag, fm_main.shared_flag
  ||'', (DECODE(fm.shared_flag, '0', 'Not Shared', '1', 'Fully Shared',
  'Partially Shared')), 'Partially Shared') shared_flag
FROM
  (
    SELECT
      folder_mapping_id,
      SUM(document_count) Total_Doc_Count,
      SUM(folder_count) Total_Folder_Count,
      SUM(SHARED_FLAG) SHARED_FLAG,
      SUM(attachment_flag) attachment_flag
    FROM
      (
        SELECT
          CONNECT_BY_ROOT folder_mapping_id AS folder_mapping_id,
          document_count,
          folder_count,
          SHARED_FLAG,
          attachment_flag
        FROM
          (
            SELECT
              *
            FROM
              folder_mapping
            WHERE
              organization_id='Org_498'
          )
          --where organization_id='Org_498'
          CONNECT BY PRIOR folder_mapping_id = parent_folder_mapping_id
      )
    GROUP BY
      folder_mapping_id
  )
  fm,
  (
    SELECT
      folder_mapping_id,
      document_count,
      folder_name,
      folder_count,
      SHARED_FLAG
    FROM
      folder_mapping
    WHERE
      organization_id='Org_498'
  )
  fm_main
WHERE
  fm_main.folder_mapping_id = fm.folder_mapping_id
ORDER BY
  fm.folder_mapping_id;

With input as follows:

Current output is:

The output is pretty much OK except the fact that we want root9 to be displayed as fully shared since it is a subfolder of root8 which is fully shared.
Convention followed for shared flag
 --0 - not  shared
 --1 - fully shared
 --2 - partially shared
In case a folder is fully shared its subfolders are fully shared as well.
In case a folder is partially shared or fully shared its parent is partially shared.
Insert queries:
Insert into     FOLDER_MAPPING (FOLDER_MAPPING_ID,FOLDER_NAME,FOLDER_FILENET_ID,PARENT_FOLDER_MAPPING_ID,FOLDER_COUNT,DOCUMENT_COUNT,SHARED_FLAG,ATTACHMENT_FLAG,ORGANIZATION_ID,CREATED_DATE,CREATED_BY,MODIFIED_DATE,MODIFIED_BY,TYPE) values (1,'root1','111',0,2,3,'0','0','Org_498',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'11',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'1','1');
Insert into FOLDER_MAPPING (FOLDER_MAPPING_ID,FOLDER_NAME,FOLDER_FILENET_ID,PARENT_FOLDER_MAPPING_ID,FOLDER_COUNT,DOCUMENT_COUNT,SHARED_FLAG,ATTACHMENT_FLAG,ORGANIZATION_ID,CREATED_DATE,CREATED_BY,MODIFIED_DATE,MODIFIED_BY,TYPE) values (2,'root2','111',1,2,33,'0','0','Org_498',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'11',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'1','1');
Insert into FOLDER_MAPPING (FOLDER_MAPPING_ID,FOLDER_NAME,FOLDER_FILENET_ID,PARENT_FOLDER_MAPPING_ID,FOLDER_COUNT,DOCUMENT_COUNT,SHARED_FLAG,ATTACHMENT_FLAG,ORGANIZATION_ID,CREATED_DATE,CREATED_BY,MODIFIED_DATE,MODIFIED_BY,TYPE) values (3,'root3','111',1,2,1,'0','0','Org_498',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'11',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'1','1');
Insert into FOLDER_MAPPING (FOLDER_MAPPING_ID,FOLDER_NAME,FOLDER_FILENET_ID,PARENT_FOLDER_MAPPING_ID,FOLDER_COUNT,DOCUMENT_COUNT,SHARED_FLAG,ATTACHMENT_FLAG,ORGANIZATION_ID,CREATED_DATE,CREATED_BY,MODIFIED_DATE,MODIFIED_BY,TYPE) values (4,'root4','111',2,2,2,'0','0','Org_498',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'11',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'1','1');
Insert into FOLDER_MAPPING (FOLDER_MAPPING_ID,FOLDER_NAME,FOLDER_FILENET_ID,PARENT_FOLDER_MAPPING_ID,FOLDER_COUNT,DOCUMENT_COUNT,SHARED_FLAG,ATTACHMENT_FLAG,ORGANIZATION_ID,CREATED_DATE,CREATED_BY,MODIFIED_DATE,MODIFIED_BY,TYPE) values (5,'root5','111',3,2,1,'0','0','Org_498',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'11',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'1','1');
Insert into FOLDER_MAPPING (FOLDER_MAPPING_ID,FOLDER_NAME,FOLDER_FILENET_ID,PARENT_FOLDER_MAPPING_ID,FOLDER_COUNT,DOCUMENT_COUNT,SHARED_FLAG,ATTACHMENT_FLAG,ORGANIZATION_ID,CREATED_DATE,CREATED_BY,MODIFIED_DATE,MODIFIED_BY,TYPE) values (6,'root6','111',5,2,1,'0','0','Org_498',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'11',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'1','1');
Insert into FOLDER_MAPPING (FOLDER_MAPPING_ID,FOLDER_NAME,FOLDER_FILENET_ID,PARENT_FOLDER_MAPPING_ID,FOLDER_COUNT,DOCUMENT_COUNT,SHARED_FLAG,ATTACHMENT_FLAG,ORGANIZATION_ID,CREATED_DATE,CREATED_BY,MODIFIED_DATE,MODIFIED_BY,TYPE) values (7,'root7','111',6,2,1,'0','0','Org_498',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'11',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'1','1');
Insert into FOLDER_MAPPING (FOLDER_MAPPING_ID,FOLDER_NAME,FOLDER_FILENET_ID,PARENT_FOLDER_MAPPING_ID,FOLDER_COUNT,DOCUMENT_COUNT,SHARED_FLAG,ATTACHMENT_FLAG,ORGANIZATION_ID,CREATED_DATE,CREATED_BY,MODIFIED_DATE,MODIFIED_BY,TYPE) values (8,'root8','111',7,2,1,'1','0','Org_498',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'11',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'1','1');
Insert into FOLDER_MAPPING (FOLDER_MAPPING_ID,FOLDER_NAME,FOLDER_FILENET_ID,PARENT_FOLDER_MAPPING_ID,FOLDER_COUNT,DOCUMENT_COUNT,SHARED_FLAG,ATTACHMENT_FLAG,ORGANIZATION_ID,CREATED_DATE,CREATED_BY,MODIFIED_DATE,MODIFIED_BY,TYPE) values (9,'root9','111',8,2,1,'0','1','Org_498',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'11',to_timestamp('02-MAY-16 03.06.24.352000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'1','1');

A:
ORA-00913 too many values
Cause: The SQL statement requires two sets of values equal in number. This error occurs when the second set contains more items than the first set. For example, the subquery in a WHERE or HAVING clause may return too many columns, or a VALUES or SELECT clause may return more columns than are listed in the INSERT.
Action: Check the number of items in each set and change the SQL statement to make them equal.

In your case your subquery is returning two columns to the first query expecting one column.
You can change your query as follow.
SELECT  folder_name name,
  document_count,
  (SELECT SUM(e2.document_count)
    FROM       folder_mapping e2      START WITH e2.folder_mapping_id       = e1.folder_mapping_id CONNECT BY prior e2.folder_mapping_id = e2.parent_folder_mapping_id
  )
  sum_sal, (SELECT SUM(e2.document_count)
    FROM       folder_mapping e2      START WITH e2.folder_mapping_id       = e1.folder_mapping_id CONNECT BY prior e2.folder_mapping_id = e2.parent_folder_mapping_id
  ) folder_count_total
FROM
  folder_mapping e1

That was just the fix for your error. Actually you can use the following query to get the desired output which is better(In terms of cost) than the original query.
SQL> desc folder_mapping;
 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 FOLDER_MAPPING_ID                  NUMBER
 FOLDER_NAME                        VARCHAR2(20)
 FOLDER_FILENET_ID                  NUMBER
 PARENT_FOLDER_MAPPING_ID               NUMBER
 FOLDER_COUNT                       NUMBER
 DOCUMENT_COUNT                     NUMBER
 SHARED_FLAG                        NUMBER
 ATTACHMENT_FLAG                    NUMBER

SQL> select * from folder_mapping;

FOLDER_MAPPING_ID FOLDER_NAME          FOLDER_FILENET_ID
----------------- -------------------- -----------------
PARENT_FOLDER_MAPPING_ID FOLDER_COUNT DOCUMENT_COUNT SHARED_FLAG ATTACHMENT_FLAG
------------------------ ------------ -------------- ----------- ---------------
        4 root3                  111
               2        2          2           0           0

        1 root                    11
               0        2          3           0           0

        2 root1                  111
               1        2         33           0           0

SQL> SELECT folder_name, SUM(document_count) "Total_Doc_Count", SUM(folder_count) "Total_Folder_Count"  FROM(
   SELECT CONNECT_BY_ROOT folder_name as folder_name, document_count, folder_count
      FROM folder_mapping
      CONNECT BY PRIOR folder_mapping_id = parent_folder_mapping_id)
      GROUP BY folder_name;

FOLDER_NAME      Total_Doc_Count Total_Folder_Count
-------------------- --------------- ------------------
root1                 35              4
root                  38              6
root3                  2              2

SQL>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I detect that a user has gone through the 'Forgot Password' workflow in Wordpress? I'm currently using the action hook profile_update to execute some code whenever the user updates his/her profile, but this action is not called when the user goes through the 'forgot password' workflow (click forgot password -> send email -> click link in email -> change password) to change their password.
I've read through the list of available actions and nothing seems appropriate. Note, I need to execute code after they've changed their password.

A: change the link of the "forget password" to a PHP that you'll write and which will log all the details (user-id, time, etc), and then your PHP script can redirect the customer to the original URL using header() method.


text:
Q: XML generation in ASP.NET 2.0 web services? I'm building a web service (.asmx) with ASP 2.0, and a lot of my methods return custom objects.  It's always converted my objects into XML for me using the properties of the objects, but I've run into a situation where it doesn't.
I need to return a bunch of objects of different classes at once, and the classes are unfortunately not related through inheritance, so I'm returning an array of objects from my web method.  The output looks like this:
<ArrayOfAnyType>
<anyType xsi:type="Type1"/>
<anyType xsi:type="Type2"/>
</ArrayOfAnyType>

The Type1 and Type2 classes have properties defined, but they're not auto-implemented, and they're read only.  All properties I've seen auto-converted into XML so far have been fully auto-implemented.  Is this why it doesn't convert properly?  Am I going to have to redesign my classes to get this to work, or is there an attribute I can add somewhere, or an interface I can implement, or something like that?
My class declarations look like this:
Public Class Type1
    Dim _var1 As Decimal

    Public Sub New()
        Dim conn As New SqlConnection(ConfigurationManager.AppSettings("myString"))
        conn.Open()
        Dim command As New SqlCommand("SELECT * FROM table1", conn)
        Dim reader As SqlDataReader = command.ExecuteReader()
        reader.Read()
        _var1 = reader("Var1")
        reader.Close()
        conn.Close()
    End Sub

    Public ReadOnly Property Var1() As Decimal
        Get
            Return _var1
        End Get
    End Property
End Class

EDIT: clarifying my question: why is the XML serialization process ignoring my properties in this class?  Because they're not auto-implemented?  Or because they're read only?  Or something else?

A: XML Serialization only works with public, read/write properties. Sorry, but your read-only properties will never be serialized.

A: ASP.NET 2.0 web services run off the XML Serializer in System.Xml.Serialization (if memory serves) and the related attributes there such as XmlIgnore().
Unfortunately, getting that to work with a polymorphic collection can be a bit of a trick.  If it is a limited number of classes, the easiest way out would be to do something like:
public class Shelf
{
    public Bottle[] Bottles {get; set;}
    public Box[] Boxes {get; set;}
}

It might be worth looking at WCF here, it has much better options.


text:
Q: Cant resolve fbjs/lib/memoizeStringOnly Just did a refresh of my computer but now Im having trouble running my code....
When running "npm start" I get the following error:
> ERROR in ./~/react-dom/lib/CSSPropertyOperations.js Module not found:
> Error: Can't resolve 'fbjs/lib/memoi zeStringOnly' in
> 'C:\Code\Project.Web\node_modules\react-dom\lib'
> @ ./~/react-dom/lib/CSSPropertyOperations.js 20:24-61
> @ ./~/react-dom/lib/ReactDOMComponent.js  @
> ./~/react-dom/lib/ReactDefaultInjection.js  @
> ./~/react-dom/lib/ReactDOM.js  @ ./~/react-dom/index.js  @
> ./source/components/index.js  @ multi
> (webpack)-dev-server/client?http://0.0.0.0:30 00
> webpack/hot/dev-server ./index.js

I tried to update all packages but got same error...
Here is my package.json file:
{
  "name": "homecore.web",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dashboard -t 'HomeCore' -- webpack-dev-server --colors --no-info",
    "build": "rm -rf ./build && NODE_ENV=\"production\" webpack",
    "lint-break-on-errors": "eslint ./source/js ./webpack.config.js -f table --ext .js --ext .jsx",
    "lint": "eslint ./source/js ./webpack.config.js -f table --ext .js --ext .jsx || true",
    "preview": "NODE_ENV=\"production\" webpack-dashboard -t 'Preview Mode - React-Redux Boilerplate' -- webpack-dev-server",
    "hook-add": "prepush install",
    "hook-remove": "prepush remove"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "autoprefixer": "^6.7.7",
    "babel-core": "^6.24.1",
    "babel-eslint": "^7.2.3",
    "babel-loader": "^7.0.0",
    "babel-plugin-syntax-decorators": "^6.13.0",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-react-hmre": "^1.1.1",
    "babel-preset-stage-0": "^6.24.1",
    "babel-runtime": "^6.23.0",
    "css-loader": "0.28.1",
    "eslint": "^3.19.0",
    "eslint-config-airbnb": "^14.1.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^4.0.0",
    "eslint-plugin-react": "^6.10.3",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.11.1",
    "html-webpack-plugin": "^2.28.0",
    "less": "^2.7.2",
    "less-loader": "^4.0.3",
    "postcss-loader": "^1.3.3",
    "prepush": "^3.1.11",
    "style-loader": "^0.17.0",
    "url-loader": "^0.5.8",
    "webpack": "^2.4.1",
    "webpack-dashboard": "^0.4.0",
    "webpack-dev-server": "^2.4.5"
  },
  "dependencies": {
    "alt": "0.18.6",
    "alt-utils": "^1.0.0",
    "babel-polyfill": "^6.23.0",
    "es6-promise": "^4.1.0",
    "immutable": "^3.8.1",
    "isomorphic-fetch": "^2.2.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router": "^4.1.1",
    "react-router-dom": "^4.1.1",
    "semantic-ui-react": "^0.68.2",
    "whatwg-fetch": "^2.0.3"
  },
  "prepush": [
    "npm run lint-break-on-errors --silent"
  ]
}

A: Ok so after a lot of googleing, I found a work around. Im still not sure why i get this error.
But according to this post there is a way to add alias in webpack.
So i added this to my webpack.config.js
var alias = {};
alias['fbjs/lib/memoizeStringOnly'] = '../node_modules/fbjs/lib/memoizeStringOnly';
module.exports = {
  .
  .
  alias : alias,
  .
  .
}

and now it works!
But, and now Im guessing, some package must be broken trying to access this component from the wrong location

A: Within the last week or so, I've run into the same issue but with react-dom@15.4.2 instead of react-dom@15.5.4.  What I think I've found to be the issue is that Webpack isn't able to resolve the fbjs dependency within the react-dom/node_modules directory.
For me, I was able to solve the issue by including the fbjs package as an explicit dependency in the package.json.  Now instead of the project-level dependency linking to the peer of react-dom, the module in react-dom links to the project-level module.
Now, I don't think this is necessarily the right solution, especially if you allow minor version bumps with '~' and '^' in your package.json, but because we are only updating our dependencies when we need to by hand, our team is comfortable specifying the version of fbjs.
Snippet of our package.json:
"dependencies": {
    "assets-webpack-plugin": "3.5.1",
    "babel-core": "6.24.0",
    "babel-loader": "6.4.1",
    "babel-preset-es2015": "6.24.0",
    "babel-preset-react": "6.23.0",
    "css-loader": "0.26.4",
    "del": "2.2.2",
    "es6-promise": "4.1.0",
    "fbjs": "0.8.12",
    "file-loader": "0.10.1",
    "flux": "2.1.1",
    "highcharts": "5.0.10",
    "imports-loader": "0.7.1",
    "jquery": "2.1.3",
    "keymirror": "0.1.1",
    "lodash": "3.10.1",
    "lodash.clonedeep": "4.5.0",
    "material-design-icons": "2.2.3",
    "material-ui": "0.17.1",
    "moment": "2.18.1",
    "object-assign": "4.1.1",
    "postcss-loader": "1.3.3",
    "rc-progress": "2.1.0",
    "react": "15.4.2",
    "react-addons-perf": "15.4.2",
    "react-data-grid": "1.0.85",
    "react-dom": "15.4.2",
    "react-highcharts": "11.5.0",
    "react-router": "3.0.3",
    "react-tap-event-plugin": "2.0.1",
    "sass-loader": "6.0.3",
    "style-loader": "0.13.2",
    "superagent": "3.5.2",
    "underscore": "1.8.3",
    "url-loader": "0.5.8",
    "webpack": "2.4.1"
},

A: I ran into this error as well after uninstalling a package. It seems fbjs was somehow removed as well, even though other packages still depended on it.
I fixed it by manually installing fbjs with npm install fbjs --save


text:
Q: Vertical alignment of inline element in table-cell I have multiple divs with dynamic content and all of them have the same height. Beside the content a Submit Button is inside of each div, which is directly next to the content.
But i want to display the Button at the bottom of the div.
HTML Markup:

Title

Content Content Content Content Content Content Content Content Content Content Content Content Content Content

        <button class="btn btn-grey" type="submit" name="action">Ansehen</button>

Title 2

Content

        <button class="btn btn-grey" type="submit" name="action">Ansehen</button>

CSS Code:
div.product-teaser {
    border: 1px #c7d2d6 solid;
    padding: 0px 10px 10px 10px;
    width: 216px;
    height: 100%;
    display: table-cell;
}

div.product-teaser-row {
    display: table;
    border-collapse: separate;
    border-spacing: 10px;
}

I've already tried different things like vertical-align: bottom on the div and display: inline-block on the Button, but nothing worked for me.
Here is a JSFiddle Demo of my code.

A: You can try this
CSS
div.product-teaser {
    border: 1px #c7d2d6 solid;
    padding: 0px 10px 20px 10px; /*Increase the bottom padding so the button does not overlap the content*/
    width: 216px;
    height: 100%;
    display: table-cell;
  position: relative; /*Add this css*/
}

/*Set the button at the bottom using position: absolute;*/
    .btn-grey {
      bottom: 5px;
        left: 5px;
        position: absolute;
    }

A: To do that you just have to position absolute your button and define the bottom position and give a padding-bottom to your container to be sure that no content will override your button.
here for a jsfiddle exemple.

A: You could try adding a height property to the p element.
Example:
p{
  height: 95px;
}

JSFiddle Demo : http://jsfiddle.net/robcabrera/g3p2Y/1/

A: why don't you put button in separate
 tag like:

     <button class="btn btn-grey" type="submit" name="action">
           Ansehen
     </button>

set according margin-top to put the button at bottom like:
#my
{
   margin-top:100px;

}

FIDDLE here


text:
Q: Automapper won't install on my UWP project anymore I've been working on an UWP app for some time now, and a couple of weeks ago I installed Automapper and got it up and running. Worked perfectly, no issues, until today when I was going to continue working on my project. I went through a system restore before it stopped working, and I also updated to the latest version of Visual Studio 2017 Community Edition.
The problem: Visual Studio suddenly couldn't recognize the reference. Despite having already installed it, I tried to uninstall and then install it again, but without success. Now it complaints about compatibility. Example:

Checking compatibility for System.Globalization.Extensions 4.3.0 with UAP,Version=v10.0.16299 (win10-x86-aot).
  NU1202: Package System.Globalization.Extensions 4.3.0 is not compatible with uap10.0.16299 (UAP,Version=v10.0.16299) / win10-x86-aot. Package System.Globalization.Extensions 4.3.0 supports:
    - monoandroid10 (MonoAndroid,Version=v1.0)
    - monotouch10 (MonoTouch,Version=v1.0)
    - xamarinios10 (Xamarin.iOS,Version=v1.0)
    - xamarinmac20 (Xamarin.Mac,Version=v2.0)
    - xamarintvos10 (Xamarin.TVOS,Version=v1.0)
    - xamarinwatchos10 (Xamarin.WatchOS,Version=v1.0)

Why? It worked without problems just a few days ago? Now it won't even install.

A: I found out that it's most likely not related to automapper, but NuGet was messed up for some reason. I simply cleared the nuget cache, and now it works as intended.


text:
Q: Exensible application shell for Windows Forms We're about to start development of an in-house WinForms app (no WPF here), and I'm looking for a kind of an extensible "shell" application, which would take care of all the low-level stuff like menu & toolbar management, dialogs, etc. Pretty much like Visual Studio Shell:

What it should do is to allow us to write some kind of "add-ins" which would use services provided by this "shell" and do all the business stuff.

A: How about Composite Application Block?. Check the examples on the Internet, and see if that is what you want. It is not really a app. shell but more of a architecture to build complex app around; but the notion of application shell and loosely coupled parts are main theme in CAB (check Event Dispatcher among other things)


text:
Q: How to copy and paste rows before deleting them in excel VBA I am looking to filter out a set of data with the criteria being if column A has over 5 characters in the string delete it.
However, before I delete it, I want to copy these entries to a sheet named "fixed"
The code I have at the moment works for the first entry, but doesn't loop through and I am unsure how to fix that...
Code:
Dim LR As Long, i As Long

LR = Worksheets("Output Sheet").Range("A" & Rows.Count).End(xlUp).Row
                For i = LR To 1 Step -1

                    If Len(Range("A" & i).Value) >= 5 Then
                    Rows(i).EntireRow.Cut Worksheets("Fixed").Range("A:D")
                    Rows(i).Delete

                      End If
                   Next i

The data it is copying has 4 columns if that's of any help? I just can't seem to figure out why it doens't look but I am nearly positive it's a simple fix so any pointers would be appreciated.
Dim  f As Long

Set Rng = Worksheets("Black List").Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)
Application.ScreenUpdating = False
With Worksheets("Output Sheet")

    Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
    For f = Lastrow To 1 Step -1
             If Not IsError(Application.Match(.Range("A" & f).Value, Rng, 0)) Then
            .Rows(f).Delete
        End If
    Next f
End With
Application.ScreenUpdating = True

A: Backup Data

*

*This will add a formula (=LEN(A1)) to an inserted column range (E), to calculate the length of the values of the criteria column (A), and filter this range.

*The filtered data (sdvrg) will be copied (appended) to another worksheet (Fixed) and the filtered data's entire rows will be deleted.

*Finally, the inserted column (E) will be deleted.

Option Explicit

Sub BackupData()

    Const sName As String = "Output Sheet"
    Const sCols As String = "A:D"
    Const scCol As Long = 1 ' Criteria Column
    Const shRow As Long = 1 ' Header Row
    Const sLenCriteria As String = ">5"

    Const dName As String = "Fixed"
    Const dCol As String = "A"

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
    If sws.AutoFilterMode Then sws.AutoFilterMode = False
    Dim slRow As Long
    With sws.Columns(sCols).Columns(scCol)
        slRow = .Cells(.Cells.Count).End(xlUp).Row
    End With
    If slRow <= shRow Then Exit Sub ' no data or just headers

    Dim srCount As Long: srCount = slRow - shRow + 1
    ' Source Table Range ('strg') (headers)
    Dim strg As Range: Set strg = sws.Rows(shRow).Columns(sCols).Resize(srCount)
    ' Source Data Range ('sdrg') (no headers)
    Dim sdrg As Range: Set sdrg = strg.Resize(srCount - 1).Offset(1)
    Dim scCount As Long: scCount = strg.Columns.Count

    Application.ScreenUpdating = False

    ' Source Inserted Column Range ('sicrg') (headers)
    Dim sicrg As Range: Set sicrg = strg.Columns(1).Offset(, scCount)
    sicrg.Insert Shift:=xlShiftToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Set sicrg = sicrg.Offset(, -1) ' account for 'Insert'
    ' The formula is also written to the header row which is irrelevant
    ' to the upcoming 'AutoFilter'.
    sicrg.Formula = "=LEN(" & strg.Cells(1, scCol).Address(0, 0) & ")"
    sicrg.AutoFilter 1, sLenCriteria

    ' Source Data Visible Range ('sdvrg') (no headers)
    Dim sdvrg As Range
    On Error Resume Next ' prevent 'No cells found' error.
        Set sdvrg = sdrg.SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    sws.AutoFilterMode = False

    Dim WasBackedUp As Boolean

    If Not sdvrg Is Nothing Then

        Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
        If dws.AutoFilterMode Then dws.AutoFilterMode = False
        Dim dfCell As Range
        Set dfCell = dws.Cells(dws.Rows.Count, dCol).End(xlUp).Offset(1)

        sdvrg.Copy dfCell
        sdvrg.EntireRow.Delete Shift:=xlShiftUp ' resizes 'sicrg' appropriately

        WasBackedUp = True

    End If

    sicrg.Delete Shift:=xlShiftToLeft

    Application.ScreenUpdating = True

    If WasBackedUp Then
        MsgBox "Data backed up.", vbInformation
    Else
        MsgBox "No action taken.", vbExclamation
    End If

End Sub


text:
Q: Block transition between minimum value and maximum value in NumberPicker I am working on an Android application. Somewhere inside, I am displaying the NumberPicker widget.
How can I disable the transition between the minimum value and the maximum value?
What I mean, I am using a number picker, with a minimum value of 0 and a maximum value of 9999. It looks like this,

In this way, the user can quickly fling the widget to jump from 0 to 9999.
I do not want this behavior. The number picker widget as it is now looks like a closed circle, and I am trying to see how I can break the circle exactly between the minimum and maximum value, so that it looks like this from the minimum value and maximum value:

How can I achieve this?
What I have tried :

*

*I searched everywhere in the NumberPicker API, it doesn't seem like this is something that one can simply set using a method.

*I think that I can use the method setDisplayedValues(String[] displayedValues) method to add empty strings before the minimum value and after the maximum value, so that no value is displayed before the minimum value or after the maximum value, BUT the user will still be able to fling past them or WORSE: select the empty value.

Any ideas? Will I have to get my hands dirty and dig in the widget implementation? Inside the touch listener maybe?

A: Isn't this setWrapSelectorWheel(false) (from the API)?

A: As pointed out, setWrapSelectorWheel(false) does the trick, so one of the offered answers should be accepted.
In general, this order of calls work:
picker.setMinValue(0);
picker.setMaxValue(stringValuesArray.length - 1);
picker.setDisplayedValues(stringValuesArray);
picker.setValue(defaultValue);
picker.setWrapSelectorWheel(false);

A: You have to call setWrapSelectorWheel(false) on the number picker. Be careful though that you do setMinimumValue(...) and setMaximumValue(...) before the call to setWrapSelectorWheel(false). It simply won't work if you do otherwise.
Like me, you may be looking for a way to do this via xml, but there is no way at the time.


text:
Q: Tkinter Dynamically Create and Delete Buttons I'm trying to dynamically delete the last button and create a new button on the next row via the command function shared by all the "+" button. However, with my current code, I've got nothing but one button staying at the very first row, and it never disappear as I wish and no new buttons appear below it either.
import tkinter as tk
root = tk.Tk()
root.title('test1')
root.geometry('300x300')

def num_add():

    prev_row = int(btn_list[-1].grid_info()['row'])
    add_btn = tk.Button(root,text='+',command=num_add)
    btn_list.append(add_btn)
    r1 = prev_row +1
    btn_list[-1].grid(row=r1,column=0)

    btn_list[-2].grid_forget()

btn_list = []
add_btn = tk.Button(root,text='+',command=num_add)
add_btn.grid(row=0,column=0)
btn_list.append(add_btn)

root.mainloop()

A: Your code is actually working as expected. If you look at the .grid_info() for the button after you click it, you will see that it says the button is on row 1, column 0. The reason it doesn't look as you'd expect is, that there is nothing in row 0 anymore so the row effectively has a height of 0.

A: It this what you need?: i used place(x,y)
import tkinter as tk
root = tk.Tk()
root.title('test1')
root.geometry('300x300')
global i
def num_add():
    global i
    add_btn.place_forget()
    i=i+1
    add_btn.place(x=2, y=i*30+20)

i=0
add_btn = tk.Button(root,text='+',command=num_add)
add_btn.place(x=2, y=i*30+10)

root.mainloop()


text:
Q: When using rxjs why doesn't switchMap trigger a complete event? Recently, in my Angular app, I've started to use the rxjs switchMap operator in a couple of different scenarios. I soon realised that when using switchMap, when you subscribe to this stream, the completion block does not fire (I don't think error block does either). All the examples I've seen online don't seem to handle a completion block either, and I'm baffled as to what the reason is for this?
I'm obviously missing something in regard to switchMap or how it is used, but I don't know what.
I'd ideally like to call a function with triggers a Http request, and then deal with the error in the error block and then handle post-request stuff in the completion block.
Here's my example of what I'm doing:
export class ResultsComponent {

  ngAfterViewInit() {

    Observable.combineLatest(...filters)
        .debounceTime(500)
        .distinctUntilChanged()
        .switchMap((activeFilters: Array<ActiveFilter>) => {
            const filters = this.mapFilters(activeFilters);
            return this.doSearch(this.term$.getValue(), filters);
        })
        .subscribe((res) => {
           this.onSearchSuccess(res);
        },
        (err) => {
            // THIS NEVER FIRES
            console.error(err);
            this.loading$.next(false);
        ,() => {
            // THIS NEVER FIRES
            this.loading$.next(false);
        });
  }

  private doSearch(input: string, filters: object): Observable<object> {
    return this.searchService.search(input, filters);
  }
}

service
export class SearchService {

  private baseUrl: string = 'http://mydomainhere.com/api';

  constructor(private http: Http) {}

  public search(input: string, filters: object): Observable<object> {
    const params = {
      "keyword": input,
      "filters": filters
    };
    const url = `${this.baseUrl}/search`;
    return this.http.post(url, params)
       .map(res => res.json())
       .catch(this.handleError);
  }
}

A: For switchMap the completion of the inner observable does not trigger the completion of the stream unless the outer observable has already completed. Here is an example illustrating this:

const first = Rx.Observable.interval(2000).take(2)
 .do(console.log.bind(null, 'first next'),
      console.log.bind(null, 'first error'),
      console.log.bind(null, 'first complete'));
const second = Rx.Observable.interval(200).take(2)
 .do(console.log.bind(null, 'second next'),
      console.log.bind(null, 'second error'),
      console.log.bind(null, 'second complete'));

first.switchMap(() => second)
 .subscribe(console.log.bind(null, 'stream next'),
      console.log.bind(null, 'stream error'),
      console.log.bind(null, 'stream complete'));

An error thrown in the inner observable will call the error block on the outer observable. Here is an example illustrating this:

const source = Rx.Observable.interval(2000).take(4)
 .do(console.log.bind(null, 'source next'),
      console.log.bind(null, 'source error'),
      console.log.bind(null, 'source complete'));
const error = Rx.Observable.create((o) => {
  o.error();
}).do(console.log.bind(null, 'error next'),
      console.log.bind(null, 'error error'),
      console.log.bind(null, 'error complete'));

source.switchMap(() => error)
 .subscribe(console.log.bind(null, 'stream next'),
      console.log.bind(null, 'stream error'),
      console.log.bind(null, 'stream complete'));

So you can put a catch on the outer observable and get the error if you like.
If you want to observe the completion of the inner observable then you will have to observe it inside of the switchMap.
As far as why you don't see much about using the completion block online, I can't speak for everyone but personally I don't find myself needing it much in my application. I just care about the data that comes out of next.

A: Completing the Outer Observable with the Inner
There are a number of ways to cause the outer observable to complete with the inner. (The next section explains why you might not want to do this, followed by an example of detecting inner observable completion when the outer observable doesn't complete.)
If you know your inner observable will only emit one value before completing, like with an API call, you can just pipe first onto your outer observable.

const { of , pipe } = rxjs;
const { switchMap, first } = rxjs.operators;

const stream = of(1, 2, 3).pipe(
    switchMap(() => of(4)),
    first()
  )
  .subscribe({
    next: (x) => console.log(x),
    complete: () => console.log('outer complete')
  });

But if the inner observable emits multiple values a simple change would be to use endWith and takeWhile to tell the outer observable when to complete. This assumes we know the inner observable will never emit null.

const { of , pipe } = rxjs;
const { switchMap, endWith, takeWhile } = rxjs.operators;

const stream = of(1, 2, 3).pipe(
    switchMap(() => of(4, 5, 6).pipe(
      endWith(null)
    )),
    takeWhile((x) => x != null)
  )
  .subscribe({
    next: (x) => console.log(x),
    complete: () => console.log('outer complete')
  });

A general solution is to have a Subject emit when the inner observable completes, and have the outer observable complete when the Subject emits, watching for it with takeUntil.

const { of , pipe, Subject } = rxjs;
const { switchMap, tap, takeUntil } = rxjs.operators;

const innerComplete = new Subject();

const stream = of(1, 2, 3).pipe(
    switchMap(() => of(4, 5, 6).pipe(
      tap({
        complete: () => innerComplete.next()
      })
    )),
    takeUntil(innerComplete)
  )
  .subscribe({
    next: (x) => console.log(x),
    complete: () => console.log('outer complete')
  });

Why Doesn't It Complete?
When I first started working with RxJS I was mainly converting existing API calls to be handled with observables. In practice this meant that an outer observable would complete when the inner observable completed. But it is important to note the outer observable was not caused to complete because the inner observable did. It completed because it would only emit one value. If it was an observable that could emit multiple values, like from mouse click events, it would not complete with the inner observable.
This is a good thing. It allows you to have an outer observable that maps its emissions through an inner observable, without it completing the first time the inner observable does. For example, lets say you wanted to trigger an animation on each mouse click and the animation is controlled by a timer. The mouse clicks would be emitted by the outer observable. And the inner observable would run a timer for a few seconds to control the animation. After the animation completes, you'd still like mouse click events to be captured so the animation can start up again.
The following snippet will log a series of numbers to the console  (our makeshift animation) on each click. And since we're using switchMap the previous "animation" will stop if you click in the middle of it (The concatMap piece just adds a delay between each emission). You can see this visually in the marble diagram for switchMap at https://rxmarbles.com/#switchMap

const { of , pipe, fromEvent, Subject } = rxjs;
const { switchMap, concatMap, delay } = rxjs.operators;

const innerComplete = new Subject();

const stream = fromEvent(document, 'click').pipe(
    switchMap(() => of(1, 2, 3).pipe(
      concatMap(x => of(x).pipe(delay(500)))
    ))
  )
  .subscribe({
    next: (x) => console.log(x),
    complete: () => console.log('outer complete')
  });

Click here and watch the console.

Acting on Inner Observable Completion
Given that it makes sense that the outer observable doesn't need to complete when the inner observable does you may want a way to do something when the inner observable completes without having to complete the outer observable. tap will let you do that when you pass an Observer as an argument.

const { of , pipe } = rxjs;
const { switchMap, tap } = rxjs.operators;

const stream = of (1, 2, 3).pipe(
    switchMap(() => of (4, 5, 6).pipe(tap({
      complete: () => console.log("Inner observable completed")
    }))))
    .subscribe({
      next: (x) => console.log(x),
      complete: () => console.log('Outer observable completed')
    });


text:
Q: Latex L3 Programming Layer Interface using \_ and \__ I have been looking at style files using the L3 Programming Layer Interface for Latex in which people use \_ and \__.  What is their purpose, are they standard indicators for specific things or simply an individual style?
I have also seen things like galex/theorem.  When are things with / used?

A: Private functions (macros) are explicitly marked in expl3 code: they start \__.... In the same way, private variables should be called \l__../\g__.. with two underscores, not one. This is a simple way to ensure that it is clear which parts of a module can be used by others: only the public interfaces.


text:
Q: How to read all the lines from an input file if there are multiple gaps between lines? I have created a hashmap> called myMap and i want to store all unique words in the keys of Hashmap and names of the files in values corresponding to key words.
taking input from multiple files and storing their names in values corresponding to key words.
Sample input from 1 file
AS YOU LIKE IT

by William Shakespeare

DRAMATIS PERSONAE.

DUKE, living in exile
FREDERICK, his brother, and usurper of his dominions
AMIENS, lord attending on the banished Duke
JAQUES,   "      "       "  "     "      "
LE BEAU, a courtier attending upon Frederick
CHARLES, wrestler to Frederick
  OLIVER, son of Sir Rowland de Boys
JAQUES,   "   "  "    "     "  "

Code
String name = f.getName();

    BufferedReader in = new BufferedReader(new FileReader(f));
    String words = in.readLine().trim().toLowerCase();

    for(String word: words.split("\\s+")) {
        if (myMap.get(word) == null) {
            myMap.put(word, new ArrayList<String>());
        }
            myMap.get(word).add(name);
        }

i am able to read only first line from all the files..

A: This is a different approach for reading all lines:
https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines(java.nio.file.Path,%20java.nio.charset.Charset)

A: This is nothing to do with the blank lines.
You call in.readLine().trim().toLowerCase(); once. It reads one line.
You will need to call it again to get the second line, and again to get the third line, and so on.
I'm sure you already know what a loop is -- use one.

A: I see that you're trying to solve some kind of homework.
There are already some relevant and good answers given to you, but there is another approach, that might be relevant as well -- specially in case you're taking some programming class.
It is called the "googling approach"
Depending on your previous search queries, you may get better or worse results. However on the google.com site you can really fast find relevant results for some common programming problems.
For example I search for "reading all lines from file in java" and first result I get is: How to read a large text file line by line using Java?
Similar question to yours but with already 19 answers and best one with over 700 up votes.
To narrow down your search results,  for example to only show results from stackoverflow, you may search so: "reading all lines from file texts in java site:stackoverflow.com"


text:
Q: IF and conditional SUM in Google Doc Spreadsheet I am trying to run an IF statement in Google Spreadsheet that will, if "Yes" SUM a series of values.
=IF(G3="Yes",=SUM(C3*D3)+(E3*D3))
This works (if I ignore the IF) and just do =SUM(C3*D3)+(E3*D3), so I know my math is correct.
I have read a few different posts that are asking similar questions, but many have "guesses" and are offering different structured formulas, so I'm not really even sure what the proper structure is any more.
Basically, for the nerdy portion of you, the spreadsheet does the following:
If the "killed" column is Yes, I need to calculate the XP of the monsters killed.
Base XP (C3) times Qty (D3), plus Bonus XP (E3) times Qty (D3) and them SUM the value.

A: The equal sign (=) in front of SUM should not be there. If your formula works I guess Google Docs just ignores it. Also, the function SUM() is useful to add the values from a range of cells from the same row or column when you don't know in advance how many cells you will add (or there are more than 2 cells and you use SUM() because it's less to write).
If I understood your request, the formula you need is:
    =IF(G3="Yes",C3*D3+E3*D3)

A: Right now the SUM function is only wrapping C3*D3 then you are adding (E3*D3). This is the same as (C3*D3)+(E3*D3) not using the SUM function. Order of operations tells us there is no need for the parentheses so you could write C3*D3+E3*D3.
The IF function has the following parameters:
IF(EVALUATION,IF TRUE,IF FALSE)

So your final equation would be:
=IF(G3="YES",C3*D3+E3*D3,"")

I always add the FALSE return to be blank so that if I need to change it later I can do so.


text:
Q: pretty formatted code doesn't break into new lines I am trying to embed a pretty formatted code in a div but it fails to break the code into new line and possibly into tabs, has copied.
I am using this code from here to test both php and html pretty formatted code in the div (Submitting form, mysql and php)
I am using the example from highlightjs but it seems not to work for me.
(How to format code in html / css / js/ php) Here are my html output formats:
ResultView and HTMLCSSView
I also added this script above the body closing tag html document

<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/highlight.min.js"></script>
<script>
hljs.initHighlightingOnLoad();
</script>

With the css link in the head tag

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/styles/default.min.css">

How Can I make this work perfectly?

A: You're missing the http: or https: part of the URL - currently, your file links look like this:
//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/highlight.min.js

//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/styles/default.min.css">

Change your links to look like this:

<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/styles/default.min.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/highlight.min.js"></script>

And your code will work.


text:
Q: How to add a key value pair to an array? ReactJs i get data from database like this:
[{
  id: 1,
  url: "1.jpg",
  message_id: 1,
},
{
  id: 2,
  url: "2.jpg",
  message_id: 2,
}]

But I need an array like this, using only one field from the previous array
images = [
            { url: "1.jpg" },
            { url: "2.jpg" }
          ];

How can i get it?

A: just use the map

const list = [{
  id: 1,
  url: "1.jpg",
  message_id: 1,
},
{
  id: 2,
  url: "2.jpg",
  message_id: 2,
}]

const res = list.map(i => ({url: i.url}))

console.log(res)


text:
Q: Graph clustering algorithms which consider negative weights I have a graph instance with weighted directed edges which values can be in range [-1,1]. I need to do clustering on this graph, in order to find out groups in which vertices are more correlated.
I searched for several clustering or community detection graph based algorithms, but most of them don't work because the negative weights. Up to now I have applied spinglass (it is so called in igraph library, it is an algorithm based on Potts model) algorithm which seems to work with both positive and negative weights.
Are there any other algorithms for doing clustering or community detection on graphs which have negative and positive edge weights?
Update: the edge weights represent correlations, 1 means that two vertices are strongly correlated, -1 that are inversely correlated and 0 means that are indipendent.

A: Have you tried mapping the values to [0;2]?
Then many algorithms may work.
Consider e.g. Dijkstra: it requires non-negative edge weights, but if you know the minimum a of the edges, you can run it on x-a and get the shortest cycle-free path.
Update: for correlation values, you may either be interested in the absolute values abs(x) (which is the strength of the correlation!) or you may want to break the graph into two temporarily: first cluster on the positive correlations only, then on the negative correlations only if the sign is that important for clustering & the previous approaches don't work.

A: Yes, there is an algorithm called 'Affinity Propagation' that works with negative weights; I believe this is implemented in sklearn (see the documentation here).  A reference for what is going on behind the scenes can be found here.
Hope that's what you're looking for!

A: It seems to me the problem you describe is known as the Correlation Clustering Problem. This information should help you find some implementations, such as:

*

*This Matlab code by Shai Bagon

*This Python code by GitHub user filkry
Note some community detection algorithms have also been modified in order to process signed networks, e.g. Amelio'13, Sharma'12, Anchuri'12, etc. However, I couldn't find any publicly available implementation.

A: Take a look at this code, it is quite scalable, works with positive and negative edges, and solves Correlation Clustering (CC) as a special case (r = 0). However, for the case of CC (maximizing positive links and minimizing negative links inside clusters), I would suggest other methods that are specialized in solving this objective.
To illustrate, Correlation Clustering (unlike what Community Detection literature pursues) does not take the positive density of clusters into account, so when a network has no or few negative ties (most real-world cases), all the network is put into one big cluster.

A: We sometimes call these graphs 'signed graphs' or 'signed networks' as links can be positive and negative (or even weighted, as in your case), where a negative link means the nodes are anti-correlated and thus should be repulsed iso attracted. In a social network setting for example a negative link could model a situation of two users that are enemies.
Take a look at Traag's Leidenalg, who integrated repulsion between negative ties in various graph clustering (community detection) algorithms, all code available through the python leidenalg module, easy to use.
https://leidenalg.readthedocs.io/en/stable/multiplex.html#negative-links
https://www.nature.com/articles/s41598-019-41695-z
some other useful refs (using the algorithm)

*

*https://journals.aps.org/pre/abstract/10.1103/PhysRevE.80.036115

*https://journals.sagepub.com/doi/full/10.1177/0003122412463574

*https://www.sciencedirect.com/science/article/pii/S0378873316300405


text:
Q: Expectation value of $p^2$ coming out complex I've got the wave function
$$\Psi(x,t) = \frac{e^{-x^2/4(a^2+i\hbar t/2m)}}{\sqrt[4]{2\pi}\sqrt{a+i\hbar t/2ma}}$$
and am trying to find the expectation value of $p^2$.  So I simplify things a bit by setting
$$\Psi(x,t) = \frac{e^{-x^2/4(a^2+i\hbar t/2m)}}{\sqrt[4]{2\pi}\sqrt{a+i\hbar t/2ma}} = \frac{e^{-x^2/A}}{B},$$
and then evaluating the integral $\int_{-\infty}^{\infty} dx\ \Psi^*(-\hbar^2\frac{\partial^2}{\partial x^2})\Psi$, and simplifying I'm getting
$$\frac{2\hbar^2}{|A|^2|B|^2}\frac{\sqrt{\pi}|A|\operatorname{Im}(A)\color{red}{iA^*}}{[\operatorname{Re}(A)]^{3/2}}$$
Before even plugging in my expressions for $A$ and $B$ I see something wrong: this is the expectation value of an observable and thus should be real.  But all of the numbers in this last expression are real except the part in red which will be complex.  Thus I've made some mistake.
I can't see a mistake in my calculations.  Can anyone see where I am going wrong here?

Edit:  Here is what I did to get that answer:
$$\begin{gather}\frac{\partial}{\partial x}\frac{e^{-x^2/A}}{B} = \frac{-2x}{A}\frac{e^{-x^2/A}}{B} \\ \implies \frac{\partial^2}{\partial x^2}\frac{e^{-x^2/A}}{B} = \left[\frac{-2}{A}+\frac{4x^2}{A^2}\right]\frac{e^{-x^2/A}}{B} = \frac{-2}{A}\left[1-\frac{2x^2}{A}\right]\frac{e^{-x^2/A}}{B} \\ \implies \hat p\frac{e^{-x^2/A}}{B} = \frac{2\hbar^2}{A}\left[1-\frac{2x^2}{A}\right]\frac{e^{-x^2/A}}{B} \\ \implies \frac{e^{-x^2/A^*}}{B^*}\hat p\frac{e^{-x^2/A}}{B} = \frac{e^{-x^2/A^*}}{B^*}\frac{2\hbar^2}{A}\left[1-\frac{2x^2}{A}\right]\frac{e^{-x^2/A}}{B} = \frac{2\hbar^2}{A|B|^2}\left[1-\frac{2x^2}{A}\right]e^{-x^2(\frac 1A+\frac 1{A^*})}\end{gather}$$
Then I use Mathematica to compute $$\int_{-\infty}^{\infty}dx\ \left[1-\frac{2x^2}{A}\right]e^{-x^2\operatorname{Re}(A)/|A|^2} = \frac{\sqrt{\pi}|A|(A-\operatorname{Re}(A))}{\operatorname{Re}(A)^{3/2}}$$
From there I multiply the "constant" back in and rearrange:
$$\frac{2\hbar^2}{A|B|^2}\frac{\sqrt{\pi}|A|(A-\operatorname{Re}(A))}{\operatorname{Re}(A)^{3/2}} = \frac{2\hbar^2}{A|B|^2}\frac{\sqrt{\pi}|A|(i\operatorname{Im}(A))}{\operatorname{Re}(A)^{3/2}}\frac{A^*}{A^*} = \frac{2\hbar^2}{|A|^2|B|^2}\frac{\sqrt{\pi}|A|\operatorname{Im}(A)iA^*}{\operatorname{Re}(A)^{3/2}}$$

A: $$z=\operatorname{Re}(z)+i\operatorname{Im}(z),\quad z^\ast=\operatorname{Re}(z)-i\operatorname{Im}(z)$$
therefore
$$z+z^\ast=2\operatorname{Re}(z)$$
You lost factor of $2$ in
$$\frac{1}{A}+\frac{1}{A^\ast}=2\frac{\operatorname{Re}(A)}{|A|^2}$$


text:
Q: Execute docker command with deis I have deis(1.5.2) with 3 host and I want "app" with database. I want to use postgres, so I found this docker image https://registry.hub.docker.com/_/postgres/ . I did deploy without problems, but I don't know how can I connect into this app/container (create some db, users) and link with other app/container. They write commands for it but it's for docker. So how can I run these commands from deis:
docker run --name some-app --link some-postgres:postgres -d application-that-uses-postgres

docker run -it --link some-postgres:postgres --rm postgres sh -c 'exec psql -h "$POSTGRES_PORT_5432_TCP_ADDR" -p "$POSTGRES_PORT_5432_TCP_PORT" -U postgres'

or do you have some other solution for using DB with deis?


text:
Q: High CPU usage when rendering DVD movie in Pinnacle I'm running Windows 7 Quad Core 4100. When rendering a DVD movie in Pinnacle 16 I get a pop up message of High CPU usage.  According to Task Manager it's running in the high 90 percent and has stopped working at times.
How can I slow the CPU usage down?

A: This behaviour is expected and perfectly good for video rendering. If you have a multi core machine (and if Pinnacle is multi core aware), you can go to task manager, right click the process and set the affinity to only a few cores.
However, I would leave it at 100% if I was you - would you rather run the CPU at 50% and it take twice as long?
Personally, I would also check for antivirus and see if you can exclude Pinnacle's temporary folder and whatever folder it is saving the file to as that may make a big difference (and if it doesn't lower CPU, it could increase speed heavily).

A: Check for other running programs and kill them. Make sure your computer has plenty of airflow, laptop assuming, and that the temperatures of your CPU cores aren't terribly high. CoreTemp is a good means of doing that.

A: I did your suggestion - cleaned the CPU. The CPU was factory installed on the mother board but when I took it apart it was obvious to me that the Heat Paste was not adaquat or aplied very well.
  It now still runs in the mid to high 90% range and hits 100 quite a lot now that it didn't do before but it hasn't crashed my program since.
  I suspect that if that paste was not adaquat the CPU could have developed enough temp to shut down; just guessing.  Thank you.  Jay


text:
Q: How do I Return an Invoice in Dyamics GP through eConnect or Web Services? We have invoice documents in GP 10.0.  Recently, the accounting department has decided that when the incorrect client has been billed, we will return the invoice and create a new one.  (Previously, we would issue a credit memo to the wrong client and a debit memo to the new client).
I have been pointed at taSopHdrIvcInsert, but I'm not sure what to do with it or how to save it back.  Because I'm never 100% sure what fields GP really needs, I was hoping I could use eConnect or web services to get the document by number, change the SOPTYPE to 4-Return and save it back since it appears everything else should be the same.
I can then invoice the new client and save that into GP using existing processes.
Thanks.

A: I got an answer over on the Dynamics GP Forums.  The Web Service did have a method for me to use that was called CreateSalesReturn.  I used the Web Service to pull back the invoice, and then I populated a SalesReturn object from the invoice's data and used CreateSalesReturn to get it into GP.


text:
Q: Why does Spark Streaming stop working when I send two input streams? I am develping a Spark Streaming application in which I need to use the input streams from two servers in Python, each sending a JSON message per second to the Spark Context.
My problem is, if I  perform operations on just one stream, everything works well. But if I have two streams from different servers, then Spark freezes just before it can print anything, and only starts working again when both servers have sent all the JSON messages they had to send (when it detects that  'socketTextStream is not receiving data.
Here is my code:
    JavaReceiverInputDStream<String> streamData1 = ssc.socketTextStream("localhost",996,
            StorageLevels.MEMORY_AND_DISK_SER);

    JavaReceiverInputDStream<String> streamData2 = ssc.socketTextStream("localhost", 9995,StorageLevels.MEMORY_AND_DISK_SER);

    JavaPairDStream<Integer, String> dataStream1= streamData1.mapToPair(new PairFunction<String, Integer, String>() {
        public Tuple2<Integer, String> call(String stream) throws Exception {

            Tuple2<Integer,String> streamPair= new Tuple2<Integer, String>(1, stream);

            return streamPair;
        }
    });

    JavaPairDStream<Integer, String> dataStream2= streamData2.mapToPair(new PairFunction<String, Integer, String>() {
        public Tuple2<Integer, String> call(String stream) throws Exception {

            Tuple2<Integer,String> streamPair= new Tuple2<Integer, String>(2, stream);

            return streamPair;
        }
    });

dataStream2.print(); //for example

Notice that there are no ERROR messages, Spark simple freezes after starting the context, and while I  get JSON messages from the ports it doesn't show anything.
Thank you very much.

A: Take a look at these caveats from the Spark Streaming documentation and see if they apply:

Points to remember

*

*When running a Spark Streaming program locally, do not use "local" or "local1" as the master URL. Either of these means that only one thread will be used for running tasks locally. If you are using a input DStream based on a receiver (e.g. sockets, Kafka, Flume, etc.), then the single thread will be used to run the receiver, leaving no thread for processing the received data. Hence, when running locally, always use "local[n]" as the master URL, where n > number of receivers to run (see Spark Properties for information on how to set the master).

*Extending the logic to running on a cluster, the number of cores    allocated to the Spark Streaming application must be more than the number of receivers. Otherwise the system will receive data, but not be able to process it.


text:
Q: Symfony 3 foreign key I have a problem displaying my table, when the foreign key is null the row does not want to be displayed, I do not know how I could solve this problem since the foreign key can be null or not null.
If anyone can show me how to do it, whenever foreign key null or not the should display.
Edit
I'm using left join query to join my table to display data,
here my entity
class Offers
{
    /**
     * @var string
     *
     * @ORM\Column(name="Nom", type="string", length=45, nullable=true)
     */
    private $nom;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;
}

class Product
{
    /**
     * @var string
     *
     * @ORM\Column(name="Product", type="string", length=45, nullable=true)
     */
    private $product;

    /**
     * @var integer
     *
     * @ORM\Column(name="cost", type="integer", nullable=true)
     */
    private $cost;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var \AppBundle\Entity\Offers
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Offers")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_offers", referencedColumnName="id_offers", nullable=false)
     * })
     */
    private $idoffers;
}

So I need, when insert for example in my entity Product, if idOffers is null it should give default value.


text:
Q: Database Query executes even though row hasn't been created yet I can't understand why mysqli_query returns true on an operation where one of the fields doesn't exist. I am trying to UPDATE a field when the field run_id matches the variable $id. However, when $id isn't set, the echo inside the if statement executes. Would really appreciate your thoughts on this phenomenon.
function sumMiles($id,$runnerRow,$weekArray,$cnn){
    //Calculate cumulative miles per week for every runner
    $weekMiles=0; //total miles per week
    foreach($weekArray as $weekday)
        {
            $weekMiles+=$runnerRow[$weekday];
        }
        $addMiles = "UPDATE run SET weekly_total = {$weekMiles} WHERE run_id=$id";//add weekly total into the database's run table
        if (mysqli_query($cnn,$addMiles)){
            echo "Your weekly total has been updated";
            return $weekMiles;
        }
        else {echo "Your weekly total could not be updated";}
    }

I am calling this function like so:
$weekMiles = sumMiles($id,$dailyMileage,$weekArray,$cnn);

A: The fact that the line doens't exist will not generate any exception at the database.
Verify the existence of the line first before run your update
  select count(1) from  run WHERE run_id=$id

EDIT
You need to check if the Count(1) is bigger than 0
$query = "SELECT count(1) from run WHERE run_id=$id";
if (mysqli_query($cnn,$query)>0){
 $addMiles = "UPDATE run SET weekly_total = {$weekMiles} WHERE run_id=$id";
 echo "updated";
}


text:
Q: Multiple content areas per page I'm having a complex content issue. Each page can have multiple sections (unknown number), each section can have multiple containers, each container can have multiple content blocks (either 1, 2 or 3).
I've currently got a theoretical solution with shortcodes, but I would like to solve this with the UI if possible by providing wysiwyg editors for each content block.
Sections: There can be any number of sections (a realistic/acceptable maximum would be 10).
Containers: A section can contain any number of rows (a realistic/acceptable maximum would be 5).
Containers: A row must know how many columns it needs to contain.
Content blocks: A row can contain 1, 2 or 3 columns.
The shortcode solution looks something like this:
[section id="summary"] //id is required but can be anything (no spaces)
   [container blocks="1"] //row can have 1, 2 or 3 columns
      [block]
      .content-block
      [/block]
   [/container]
[/section]
[section id="find us"] //id is required but can be anything (no spaces)
   [container blocks="3"] //row can have 1, 2 or 3 columns
      [block]
      .content-block
      [/block]
      [block]
      .content-block
      [/block]
      [block]
      .content-block
      [/block]
   [/container]
[/section]
[section id="team"] //id is required but can be anything (no spaces)
   [container blocks="2"] //row can have 1, 2 or 3 columns
      [block]
      .content-block
      [/block]
      [block]
      .content-block
      [/block]
   [/container]
[/section]

Does anyone have any suggestions on how I can go about this?
Thanks,
Josh

A: This sounds to me like a perfect use of Advanced Custom Fields "flexible content" feature to me. Flexible content fields allow you to define multiple layouts, and then add them to a page or post one by one, in any order or combination you need. Each layout can be a combination of text fields, images, wysiwyg editors, and other field types.
It's a brilliant UI on the client side, and easy to build a custom front-end in your template once you get the hang of it.
It's a premium plugin, but I've been building these kinds of interfaces for many years and it works really well. I haven't found anything else quite like it.

A: It's easier to code the Visual Editor so your content editors can highlight parts of the post content, rather than trying to add a large number of extra content blocks to the edit screen.
Here's what I use, the basics of which I think I got from the Codex originally, a long time ago.
// Callback function to insert 'styleselect' into the $buttons array
function wpse241267_mce_buttons_2( $buttons ) {
    array_unshift( $buttons, 'styleselect' );
    return $buttons;
}

add_filter('mce_buttons_2', 'wpse241267_mce_buttons_2');

This just enables the Style dropdown menu at the left hand end of the second row of Visual Editor buttons.
Now for the meat:
function wpse241267_mce_insert_formats( $init_array ) {

    $style_formats = array(
        // Each array child is a format with its own settings

        array(
            'title' => 'Find Us Block',
            'block' => 'div',
            'classes' => 'find-us',
            'wrapper' => true,
            'exact' => true,

        ),
    );

    // Insert the array, JSON ENCODED, into 'style_formats'

    $init_array['style_formats'] = json_encode( $style_formats );

    return $init_array;

}

add_filter( 'tiny_mce_before_init', 'wpse241267_mce_insert_formats' );

You can use IDs instead of classes if you want, but I don't think there's anything to prevent a user adding more than one into a page.
Then in the Visual Editor you can highlight some content, apply this style from the dropdown and the highlighted content will be surrounded by a div with the class find-us.
The exact argument prevents the editor merging multiple adjacent blocks.  Depending on your case you may wish to remove this.


text:
Q: Practical use of Python as Chrome Native Client There is a Python interpreter in naclports (to run as Google Chrome Native Client App).
Are there any examples for bundling the interpreter with a custom Python application and how to integrate this application with a HTML page?

A: The interpreter is currently the only python example in naclports.   However, it should be possible to link libpython into any nacl binary, and use it just as you would embed python in any other C/C++ application.   A couple of caveats: you must initialize nacl_io before making any python calls, and as you should not make python calls on the main (PPAPI) thread.
In terms of interacting with the HTML page, as with all NaCl applications this must be done by sending messages back and forth between native and javascript code using PostMessage().  There is no way to directly access the HTML or JavaScript from native code.


text:
Q: Check Modify Age of 100k files --> PathTooLongException currently I am working on a script that should give me the number of files that have been modified in the last 30 days or between 30 and 180 days or that have not been modified for 180 days. So three queries in total, everything gets its own variable in which the count is stored.
The whole thing should be executed on several remote servers.
However, the folder structure on these servers is very deep and PowerShell regularly hits the 260 character limit (PathTooLongException).
The following is the script:
$servers = "server1", "server2"

$folder = "\Path\to\folder\"

foreach ($server in $servers) {

  $session = New-PSSession -ComputerName $server

  $folder_30 = Invoke-Command -Session $session -ScriptBlock {
    (Get-ChildItem -LiteralPath $using:folder -Recurse -File | where{$_.LastWriteTime -ge (Get-Date).AddDays(-30)}).count
  }

  $folder_30_180 = Invoke-Command -Session $session -ScriptBlock {
    (Get-Childitem -LiteralPath $using:folder -Recurse -File | where{$_.LastWriteTime -ge (Get-Date).AddDays(-180) -AND $_.LastWriteTime -lt (Get-Date).AddDays(-30)}).count
  }

  $folder_180 = Invoke-Command -Session $session -ScriptBlock {
    (Get-Childitem -LiteralPath $using:folder -Recurse -File | where{$_.LastWriteTime -lt (Get-Date).AddDays(-180)}).count
  }

Remove-PSSession $session
}

Is there a way to change the script so that the "PathTooLongException" error no longer occurs? Would it be an option to change the script so that it first jumps to the lower levels and only then executes the "Get-ChildItem" and count cmdlt and how would I do that? Or is there a more elegant solution?
Thanks in advance :)
Edit: the remote servers are running win server 2012
Edit 2: I found a solution which is not perfect and takes like twice as long, but I can avoid the PathTooLongException;
You can use the following code snippet:
Get-Childitem -LiteralPath \\?\UNC\SERVERNAME\folder\
This didn't work with the Invoke-Command on the remote servers because they are running an old PowerShell version, but I was able to use this command and remotely connect from a Win 2016. Not perfect, but it works ¯_(ツ)_/¯
This link helped me: https://c-nergy.be/blog/?p=15339

A: You could probably do faster using Robocopy.
Suppose the local path on each server is 'C:\Somewhere\folder', then for each server you need to use the UNC path \\servername\C$\Somewhere\folder.
The easiest way of doing that is to create a template folder path where only the servername needs to be inserted:
$servers = "server1", "server2"
$folder  = '\\{0}\C$\Somewhere\folder'   # template UNC path whwere te servername or IP is inserted

foreach ($server in $servers) {
    $path = $folder -f $server
    $allFiles = @((robocopy $path NULL /L /E /NP /XJ /NC /NS /NDL /NJH /NJS /TS /R:0 /W:0) -replace '^\s+' -ne ''  |
                  Select-Object @{Name = 'LastWriteTime'; Expression = {([datetime]($_ -split "`t")[0]).ToLocalTime()}},
                                @{Name = 'FullName'; Expression = {($_ -split "`t")[1]}})

    # get the number of files newer than 30 days ago
    $date = (Get-Date).AddDays(-30).Date
    $folder_30 = ($allFiles | Where-Object { $_.LastWriteTime -ge $date }).Count

    # get the number of files older than 180 days ago
    $date = (Get-Date).AddDays(-180).Date
    $folder_180 = ($allFiles | Where-Object { $_.LastWriteTime -lt $date }).Count

    # output an object with the properties needed
    [PsCustomObject]@{
        ComputerName        = $env:COMPUTERNAME
        Path                = $path
        AllFiles            = $allFiles.Count
        NewerThan30Days     = $folder_30
        OlderThan180Days    = $folder_180
        Between30And180Days = $allFiles.Count - $folder_30 - $folder_180
    }
}


text:
Q: Is it possible to move JMenuBar without adding it in a JPanel I am facing a problem with my JMenuBar location in my Java application.
I am actually using ComponentResizer.java code from the article.
and everything with the resizing works fine except from the north area of my application
(undecorated JFrame) and its corners (of North Area) because the JMenuBar is preventing me from resizing from that area.
Is there a solution or maybe a hack to move the JMenuBar down a little or enable the Resizing
in the north area?
I also use setJMenuBar() method to add the JMenuBar to the north area of my application.
Code:
  public class MyApp extends JFrame {

private MyApp frame;
private JMenuBar menuBar;

public static void main(String[] args) {
    frame = new MyApp();
    frame.setUndecorated(true);
    frame.setVisible(true);
}
public MyApp(){
    initComponents();
}
private void initComponents(){
    setTitle("MediaForm");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 673, 482);
    menuBar = new JMenuBar();
    setJMenuBar(menuBar);
}
}

A: I've not tested this, but JRootPane is a JComponet, it may be possible to add a EmptyBorder to it, allowing the JMenuBar to be offset.
Failing that, you'll probably need to implement your own JRootPane to manage the layout of the JMenuBar & content pane
UPDATE with Testing
public class TestMenuFrame extends JFrame {

    public TestMenuFrame() throws HeadlessException {

        setTitle("Test");

        getRootPane().setBorder(new EmptyBorder(10, 10, 10, 10));

        JMenuBar mb = new JMenuBar();
        mb.add(new JMenu("Test"));

        setJMenuBar(mb);

        setSize(100, 100);

        getContentPane().setBackground(Color.RED);

        setLocationRelativeTo(null);

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        new TestMenuFrame().setVisible(true);

    }
}

A: JMenuBar extends JComponent, therefore you can put it anywhere you would put an ordinary component. Note that it could be confusing to the users if you put it to unexpected locations.
Also see this: add JMenuBar to a JPanel?


text:
Q: how to make ui-view to load a page on startup angularjs When I run my application it directs to localhost:8080/#/ and the header and footer which I setup in the app.html is called:

          //content here

  //content here

I have created two HTML pages and I want one of the html page to be shown when the app first loads.
Code in A.html:
<input type="text" class="form-control" data-ng-model="searchAll">
X

Code in B.html:
<input type="text" class="form-control" data-ng-model="search">

I have the following code in my router.js:
export default ['$stateProvider', '$urlRouterProvider', ($stateProvider, $urlRouterProvider) => {
  $stateProvider

    .state('app', {
      url: '/',
      template: require('./app.html'),
      controller: 'AppCtrl',
      controllerAs: 'app'
    })

    .state('app.A', {
      url: 'A',
      template: require('./A/index.html'),
      controller: 'ACtrl',
      controllerAs: 'a'
    })

    .state('app.B', {
      url: B
      template: require('./B/index.html'),
      controller: 'B',
      controllerAs: 'B'
    });

  $urlRouterProvider.otherwise('/');
}];

The header and footer should be in all the pages and the page A.html should be loaded when the app starts. Could anyone let me know how I could achieve this.

A: I think that you should set your 'app' state as abstracted.
using :
//...
abstract:true
//...

and removing the url property.
This way, the next app child state with root url "/" will be the first displayed on the screen :
.state('app.a', {
      url: '/',
      template: require('./A/index.html'),
      controller: 'ACtrl',
      controllerAs: 'a'
    })

A: I think better you call A.html URL in otherwise and keep the header and footer in the index.html instead of creating a separate state for this.

export default ['$stateProvider', '$urlRouterProvider', ($stateProvider, $urlRouterProvider) => {
  $stateProvider

    .state('app.A', {
      url: '/A',
      template: require('./A/index.html'),
      controller: 'ACtrl',
      controllerAs: 'a'
    })

    .state('app.B', {
      url: '/B',
      template: require('./B/index.html'),
      controller: 'B',
      controllerAs: 'B'
    });

  $urlRouterProvider.otherwise('/A');
}];


text:
Q: Passing a deserialized json string between methods I have a class that is performing a callout and getting a response that has multiple entities to work with. At the moment when I get the response I'm converting the response into a Json string and then passing that string to a number of different methods to process the detail. The first thing each method needs to do is to deserialize the jsonString into a Typed classes that i have created:
JobResponse jresp =  (JobResponse)JSON.deserialize(jsonString, JobResponse.class);

What i am wondering is can I deserialize this once and then pass my jresp between the methods that need to process the response?
    public class example{
    public class JobResponse{
        public string example{get; set;}
    }
    @future(callout=true)
    public static void callout(){
            //make a callout and get a response

            JobResponse jresp =  (JobResponse)JSON.deserialize(jsonString, JobResponse.class);
    }

    public static ProcessMethod(???){
        //process jresp
    }

}

If this is possible, what constructor would i use in the ProcessMethod to pass in the Job Response?

A: Yes you can easily do this. Also it would be better because it will save your CPU processing time. In your method you need to pass the class instance  and then your method you can easily use that.
public static ProcessMethod(JobResponse jresp){
        //process jresp
}


text:
Q: Dependency is not satisfiable: libfontconfig1 (>= 2.9.0) I am getting the following error code while trying to install the Chrome browser on a Linux/Gateway machine running Ubuntu 12.04:
Dependency is not satisfiable: libfontconfig1 (>= 2.9.0)

I'm presuming I should update something in my Library files, but the related online answers provide no clear direction into how to best locate those files and identify the errors, and what steps to take when those errors are found.
I tried:
sudo apt-get dist-upgrade
sudo apt-get install --reinstall --purge fontconfig-config

Nothing changed in the error message.

A: I installed 12.04.5 into a VM. It came installed with libfontconfig1 v.2.8.0-3ubuntu9.1.
I tried to used synaptic to search font libfontconfig1, rt-mouse click and Mark for upgrade for it. It said that fontconfig-config also needs to be upgraded. The list also shows fontconfig itself to be upgradable. It however offered to upgrade them to only 2.8.0-3ubuntu9.2.
I tried downloading the current google-chrome-stable_current_amd64.deb. dpkg -i for it reported:
dpkg: dependency problems prevent configuration of google-chrome-stable:
 google-chrome-stable depends on libfontconfig1 (>= 2.9.0); however:
  Version of libfontconfig1 on system is 2.8.0-3ubuntu9.1.
 google-chrome-stable depends on libstdc++6 (>= 4.8.0); however:
  Version of libstdc++6 on system is 4.6.3-1ubuntu5.
 google-chrome-stable depends on lsb-base (>= 4.1); however:
  Version of lsb-base on system is 4.0-0ubuntu20.3.

trusty has 2.11.0-0ubuntu4.2:
http://packages.ubuntu.com/trusty/libfontconfig1
It has multiple dependencies however:
libc6 (>= 2.14) [amd64]
libc6 (>= 2.7) [armhf, i386, powerpc]
libexpat1 (>= 2.0.1)
libfreetype6 (>= 2.2.1)

If chromium is enough, 12.04.5 supports 37.0.2062.120-0ubuntu0.12.04.4
It also supports firefox 31.0+build1-0ubuntu0.12.04.1
If those are not ok, I would suggest upgrading to trusty.


text:
Q: Line plots from two different data frames and Error- Discrete value supplied to continuous scale I am trying to create a line plot taking y values from two different data frames. However, I keep on encountering the error: Discrete value supplied to continuous scale. I have tried using as.numeric and have tried to scale the axis but it still does not work for me.
Example of the two dataframes:
structure(list(Years = 1961:1980, GDP.growth = c(13.2341274874115,
6.56992026378001, 11.6494473111434, 7.70627301508087, 3.2139048259846,
1.42190836629628, 6.46229426379345, 5.3432872663989, 0.068147071333243,
-5.54665996976902, 10.3970656983541, 4.29783746387267, -2.63683712200368,
3.84659112655312, -1.79430023712248, 10.9319135379163, 13.5245271383117,
5.17203033856374, -0.0649726864368176, 2.38241807770588)), row.names = c(NA,
20L), class = "data.frame")

structure(list(GCF.at.Mp = c(8.8, 8.8, 8, 6.7, 8.3, 9.2, 10,
9.5, 8.1, 7.4, 7.6, 8.9, 8.4, 8.5, 8.4, 8.8, 9.3, 9.9, 10.1,
10.3), Years = c("1950", "1951", "1952", "1953", "1954", "1955",
"1956", "1957", "1958", "1959", "1960", "1961", "1962", "1963",
"1964", "1965", "1966", "1967", "1968", "1969")), row.names = c(NA,
20L), class = "data.frame")

The base code that I have tried to use:
ggplot() +
  geom_line(data=WBDATA, aes(x=Years), y=GDP.growth), color='darkblue') +
  geom_line(data=ES.DATA, aes(x=Years, y=GCF.at.Mp), color='darkred', linetype= "twodash")

A: Convert Years of your second dataframe to numeric, which can be done within ggplot:
ggplot() +
  geom_line(data=WBDATA, aes(x=Years, y=GDP.growth), color='darkblue') +
  geom_line(data=ES.DATA, aes(x=as.numeric(Years), y=GCF.at.Mp), color='darkred', linetype= "twodash")

A: A different solution would be first convert your years from your WBDATA as character. Next set in the aes of both lines group = 1. To add a second scale (not necessary) use scale_y_continuous with sec.axis. And finally if you want, you can rotate the years on x-axis in the theme. You can use the following code:
WBDATA$Years <- as.character(WBDATA$Years)

library(tidyverse)
ggplot() +
  geom_line(data=WBDATA, aes(x=Years, y=GDP.growth, group = 1), color='darkblue') +
  geom_line(data=ES.DATA, aes(x=Years, y=GCF.at.Mp, group = 1), color='darkred', linetype= "twodash") +
  scale_y_continuous(
    "GCF",
    sec.axis = sec_axis(~ ., name = "GDP")
  ) + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

Output:

A: df2$Years is of class character (discrete scale) and not double (continuous scale). You can convert everything to character before joining them together. Then you can convert the types back. Its easier if you have one merged data frame for plotting, because they both share the same x axis:
library(tidyverse)

df1 <- structure(list(Years = 1961:1980, GDP.growth = c(
  13.2341274874115,
  6.56992026378001, 11.6494473111434, 7.70627301508087, 3.2139048259846,
  1.42190836629628, 6.46229426379345, 5.3432872663989, 0.068147071333243,
  -5.54665996976902, 10.3970656983541, 4.29783746387267, -2.63683712200368,
  3.84659112655312, -1.79430023712248, 10.9319135379163, 13.5245271383117,
  5.17203033856374, -0.0649726864368176, 2.38241807770588
)), row.names = c(
  NA,
  20L
), class = "data.frame")

df2 <- structure(list(GCF.at.Mp = c(
  8.8, 8.8, 8, 6.7, 8.3, 9.2, 10,
  9.5, 8.1, 7.4, 7.6, 8.9, 8.4, 8.5, 8.4, 8.8, 9.3, 9.9, 10.1,
  10.3
), Years = c(
  "1950", "1951", "1952", "1953", "1954", "1955",
  "1956", "1957", "1958", "1959", "1960", "1961", "1962", "1963",
  "1964", "1965", "1966", "1967", "1968", "1969"
)), row.names = c(
  NA,
  20L
), class = "data.frame")

df <-
  list(df1, df2) %>%
  # unify column classes
  map(~ .x %>% mutate(across(everything(), as.character))) %>%
  reduce(full_join) %>%
  as_tibble() %>%
  type_convert()
#> Joining, by = "Years"
#> ── Column specification
#> ──────────────────────────────────────────────────────── cols( Years =
#> col_double(), GDP.growth = col_double(), GCF.at.Mp = col_double() )

df %>%
  ggplot(aes(Years)) +
  geom_line(aes(y = GDP.growth), color = "darkblue") +
  geom_line(aes(y = GCF.at.Mp), color = "darkred")
#> Warning: Removed 11 row(s) containing missing values (geom_path).
#> Removed 11 row(s) containing missing values (geom_path).

Created on 2022-04-04 by the reprex package (v2.0.0)


text:
Q: Umbraco CMS - Update content on several environments I have problem in finding the best solution for synchronizing content between several Umbraco (Verison: 4.7.2) instances.
So the situation is: I have three environments (dev, pre-production, production) with their own separate databases and Umbraco installed on them. Currently if I updating content on my dev instance I need to repeat this procedure on other two.  Content can be updated on all of these environments. So I need to have some tool which will synchronize content on all others environments, immediately after it was updated.
I found couple of out-of-box solutions such as Umbraco Courier and uSync.
I have problems with both of them.
The first one is commercial; the second is working only with Umbraco version 4.10.x. I can't pay for this, and at the same time it's rather hard for me to upgrade Umbraco on all of these environments. Currently I need to upgrade only content.
I'm kind of wary of developing something which will work directly with databases, but that's the only solution I can see now.
So can you please advise me something on this?

A: uSync is open source, so it's possible that you could fork it and make a version that would work with older versions of Umbraco? There is a forum post here that implies that it can be done reasonably easily.


text:
Q: Virtual Domains extention not generating correct URLs on Joomla 3.7.1 I have been upgrading my Joomla 3.6.5 to 3.7.1 on my test site. I noticed that the extension 'Virtual domains' started to generate inaccessible URLs for articles that are shared between different sites.
While the URL-formation on the secondary domain is still correct, the default domain generates weird URL since the upgrade.
It now forms the URL as follows:
[domain]/component/content/[ID-childcategory]/[ID-Article Alias]?Itemid=501
This results in a 404.
Without SEF-URL enabled, the URL forms as follows:
[domain]/index.php?option=com_content&view=article&id=[Article ID]:[Article Alias]&catid=[Category ID]&Itemid=501
With this URL, the Article is displayed correctly but not the modules assigned to the menu item. The breadcrumb is shown, but contains only the main page.
I don't have other SEF extentions in use apart from the default Joomla one.
What has changed in Joomla 3.7.1 that causes this behaviour and how can it be reversed?

A: Joomla 3.7 was planned to introduce the new Router, which allows to remove the Id from the generated URLs; this required a massive effort, but it was removed from 3.7 and pushed to 3.8 at the last minute, you can read more about it here
As a consequence, the router should behave the same; but several changes impact how urls are built even with 3.7, so any component that alter the router needs to re-test for compatibility.
I'm afraid reversing it is not advisable. There are quite a few core files changed, and if you start core-hacking into Joomla, you'll spend endless hours at every new release.
You should stay with 3.6.5 on your production site and work with the extension developer to fix the issue.
--update--
I wrote to Michael from janguo.de but all the releases on the site are old, last release 4-5 years ago, all the forum links are dead, and it may be quite some work to figure out what's needed and update the extension.
It may take week(s) until a proper solution is found. Even if Michael himself were to work on this project, you should expect at least 2-3 weeks before you have a tested version that is safe to install.  With a third party developer, even longer.
In the meanwhile, you might handle the emergency with
.htaccess redirects
to block patterns or remove parts of the url (i.e. if the new urls contain an extra param or adds a new level of navigation, you can fix it there). This will be very rigid and hard to maintain, but it will remap all duplicate urls to their "official" one,
canonical
add the tag in your markup to let search engines know it's just a copy (this is fairly effective, if you can calculate the urls correctly from within the template / component). The tag looks like:
<link rel="canonical" href="https://yoursite/yourpage" />

sitemap
This is used as an alternative to determine canonical urls by search engines, make sure you have one and that it's advertised in the robots.txt (and name it /sitemap.xml this will make it faster to read by search engines).
Best of luck!

A: Update to version 1.4.1 which supports PHP 7.1 from below.  It is working well for me so far and I think we can get an effort going to move it forward as well.
https://github.com/smehrbrodt/virtualdomains


text:
Q: How to use independent, persistent disk à la VMWare in VirtualBox? VMware has the concept of "dependent disk" (snapshots are made and used along with the virtual machine), "independent persistent disk" (disk has his own state, no snapshot), "independent non persistent" (changes done since vm was powered on are reverted when vm is powered off again).
Can VirtualBox do that ?
Surprisingly, Googling those keywords with VirtualBox gave me nothing relevant.

A: Yes VirtualBox can
VirtualBox can do this and more, but the naming is different.
VirtualBox terminology
Names are defined in Chapter 5. Virtual storage:

*

*normal images (VMware's "dependent disk")

*write-through hard disks (VMware's "independent persistent disk")

*shareable hard disks (warning, expert feature, multiple VMs access same disk without safeguard, will eat your data if not mastered)

*immutable images (VMware's "independent non-persistent disk")

*multiattach mode (seen like "normal" while allowing multiple VMs, actually implemented similar to "immutable")

*read-only image (well, simply like the name says)

VirtualBox howto
GUI style

*

*Power down the virtual machine

*Go to configuration, storage, add a hard drive, set its size.

*In main window menu, Go to File -> media manager

*Select your new disk and click on modify.

*There you can choose your disk type.

Command line style
vboxmanage can do all these steps, but they are not specific to this question. The part specific to this question looks like this example:
vboxmanage modifyhd /some/path/to/myimage.vdi  --type=writethrough


text:
Q: exception in tests after upgrading from django 1.5 to 1.7 this is the test that broke:
def test_registering_user_twice_cause_error_msg(self):

    user=User(name='pyRock',email='python@rocks.com')
    user.save()

    #create the request used to test the view
    self.request.session = {}
    self.request.method = 'POST'
    self.request.POST = {
        'email':'python@rocks.com',
        'name':'pyRock',
        'stripe_token':'...',
        'last_4_digits':'4242',
        'password':'bad_password',
        'ver_password':'bad_password'
    }

    expected_form=UserForm(self.request.POST)
    expected_form.is_valid()
    expected_form.addError('python@rocks.com is already a member')

    #create the expected html
    html = render_to_response(
        'register.html',
        {
            'form': expected_form,
            'months': range(1, 12),
            'publishable': settings.STRIPE_PUBLISHABLE,
            'soon': soon(),
            'user': None,
            'years': list(range(2011, 2036)),
        }
    )

    #mock out stripe so we don't hit their server
    with mock.patch('stripe.Customer') as stripe_mock:

        config = {'create.return_value': mock.Mock()}
        stripe_mock.configure_mock(**config)

        #run the test
        resp = register(self.request)

        #verify that we did things correctly

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(self.request.session, {})
        self.assertEqual(resp.content, html.content)

        #assert there is no records in the database.
        users = User.objects.filter(email="python@rocks.com")
        self.assertEqual(len(users), 1)

So when running the test it throws the following:
ERROR: test_registering_user_twice_cause_error_msg (payments.tests.RegisterPageTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/1111/_realpython/d3/django_ecommerce/payments/tests.py", line 278, in test_registering_user_twice_cause_error_msg
    self.assertEqual(len(users), 1)
  File "/Users/1111/.virtualenvs/d317/lib/python2.7/site-packages/django/db/models/query.py", line 122, in __len__
    self._fetch_all()
  File "/Users/1111/.virtualenvs/d317/lib/python2.7/site-packages/django/db/models/query.py", line 966, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/Users/1111/.virtualenvs/d317/lib/python2.7/site-packages/django/db/models/query.py", line 265, in iterator
    for row in compiler.results_iter():
  File "/Users/1111/.virtualenvs/d317/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 700, in results_iter
    for rows in self.execute_sql(MULTI):
  File "/Users/1111/.virtualenvs/d317/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql
    cursor.execute(sql, params)
  File "/Users/1111/.virtualenvs/d317/lib/python2.7/site-packages/django/db/backends/utils.py", line 59, in execute
    self.db.validate_no_broken_transaction()
  File "/Users/1111/.virtualenvs/d317/lib/python2.7/site-packages/django/db/backends/__init__.py", line 386, in validate_no_broken_transaction
    "An error occurred in the current transaction. You can't "
TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.

I read a couple answers about Django wrapping up each test in a transaction, but I can't make anything out of it as I am a Django noob, and the code above is the tutorial.
It's even more interesting that the exception happens in the assertion. If I remove it the test passes, even with the query users = User.objects.filter(email="python@rocks.com") present. However, if I reference users in some way, say just print users the test breaks again.
So what's going on?
Thanks!

A:
So what's going on?

As stated, this is a duplicate.
But I'll separately address the reason it breaks if you access users. The reason this happens is that Django database calls are lazy and delays execution until you finally use query.
So if you never use or iterate through users it will save you a database call. This is why it looked like it was working, was because if you remove len(users) it never needs the result of users,so won't query for it.


text:
Q: Changing foreground color of  element while selected? I'm currently working with a <select> element with an indeterminate number of <option> children.
I have written some simple jQuery that adds or removes the .tagged class to the currently selected element.  This css class only changes the foreground color of the element.
The trouble I'm having is that the change in color is only visible once the user selects a different <option> within the list.  So long as the current <option> remains selected, it has white foreground and blue background.
Is anyone able to point me in the correct direction for altering this?  I'm assuming it's some css trick I don't know just yet.
Edit (to include code):
Here's the select element:<select size="4" name="ctl00$Searcher$lbResults" id="ctl00_Searcher_lbResults" class="search-results">
The option elements are nothing special, just an attribute for their value.
This is the css class for the tagged selector: option.tagged {
    color: #FF0000;
}

A: Looks to work for me:  (tested in chrome)
http://jsfiddle.net/y9Rz8/
$('#ctl00_Searcher_lbResults').on('change', function () {
    $(this).find('option:selected').addClass('tagged').siblings().removeClass('tagged');
    this.selectedIndex = -1
});


text:
Q: Linux driver : Pipelining with delay I want to create a driver with non-blocking read/write. Input of pipe0 is connected to output of pipe1. On write() the data is written into the pipe after a delay(using a kernel timer or workqueue). Write delay needs to be controllable(get and set) via ioctl(). Finally, I want to measure the throughput of the driver with read/write buffer size set to 1 B, 1 KB, I MB with delay set to 0,1 ms and 1 sec.
I have read some tutorials on how to make driver for linux.
But,I am facing following problems :

*

*How to first create a driver such that whenever any of the process generates output, my driver should read into the buffer.

*How to pass this buffer's data as input to another program which is running.

Essentially I need to create a "piping driver with delay".
Normal piping works with symbol '|'. How can I create my own symbol such as 'a|b' when I want to implement my driver('a' is size of buffer and 'b' is delay which is set)
Something like : ls myfile.txt 20|5 wc
In above example 20 is 20 KB buffer size and 5 is 5 ms delay

A: First of all, the system manages the FIFO size which typically defaults to 1MB.  You can check or change it with sysctl fs.pipe-max-size [newsize].  This does not require any new program.
You also do not need to reinvent the wheel, the kernel, or the shell to apply your intended program.  If you decide to go through with that idea, you just run command | yourbufferprogram | othercommand.
Writing that program would simply involve popen() system calls and memory controls to buffer the data and count the throughput.  Give it a try and if you get stuck, post a more specific question on StackOverflow.
Finally, note that such a buffer could quickly cause memory usage to balloon up if there's more input data than expected!


text:
Q: Is there any all_coeffs() for multivariable polynomials in sympy? I  want to extract all coefficients (INCLUDING ZEROS) of a multariable polynomial using sympy.
Sympy offers all_coeffs() but it only works for univariate. Otherwise I get this error PolynomialError: multivariate polynomials not supported
For example for a polynomial x^3+y^3+x*y+1 I woud like the output to be [3,3,0,0,0,0,1,0,0,1]

A: If you make the monomials of interest then you can see what their coefficients are in your expression. You have to watch out for requesting a monomial coefficient of x*y in an expression with terms like x*y*z, however. The following routine handles that by zeroing out any variables in the coefficient that is obtained. It also has a routine to create monomials of interest.
def all_coeffs(expr,*free):
    x = IndexedBase('x')
    expr = expr.expand()
    free = list(free) or list(expr.free_symbols)
    pows = [p.as_base_exp() for p in expr.atoms(Pow,Symbol)]
    P = {}
    for p,e in pows:
        if p not in free:
            continue
        elif p not in P:
            P[p]=e
        elif e>P[p]:
            P[p] = e
    reps = dict([(f, x[i]) for i,f in enumerate(free)])
    xzero = dict([(v,0) for k,v in reps.items()])
    e = expr.xreplace(reps); reps = {v:k for k,v in reps.items()}
    return dict([(m.xreplace(reps), e.coeff(m).xreplace(xzero) if m!=1 else e.xreplace(xzero)) for m in monoms(*[P[f] for f in free])])

def monoms(*o):
    x = IndexedBase('x')
    f = []
    for i,o in enumerate(o):
        f.append(Poly([1]*(o+1),x[i]).as_expr())
    return Mul(*f).expand().args

>>> eq = x**2 + x*y - 3
>>> all_coeffs(eq)
{1: -3, x**2: 1, x**2*y: 0, x*y: 1, y: 0, x: 0}
>>> all_coeffs(eq, x)
{1: -3, x**2: 1, x: y}