text:
Q: Getting Error: $injector:modulerr Module Error when adding angular-bootstrap-lightbox dependency I am trying to add a dependency for the project, is a simple gallery lightbox for angularjs.

https://github.com/compact/angular-bootstrap-lightbox

I followed the steps, tried using npm, I ended up copying the files into a folder in the root project.
I am using a index.html that loads some css and the scripts of the project, I am using that file to load the files for the lightbox.
index.html
<!DOCTYPE html>
<html ng-app="myApp">

<head>
<meta charset="utf-8">
<!-- styles -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<!-- favicon -->
<link rel="shortcut icon" href="/R/favicon/favicon.ico">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../scripts/jquery.cycle2.min.js"></script>

    <!-- lightbox CSS -->
    <link rel="stylesheet" href="plugins/angular-lightbox/angular-bootstrap-lightbox.css">

 </head>

<body>

<div ng-view></div>

  <!-- scripts -->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>

  <script src="plugins/angular-lightbox/angular-bootstrap-lightbox.js"></script>

 <script src="./controllersJS/main.js"></script>
 <script src="./controllersJS/controllerTaniguchi.js"></script>
 <script src="./controllersJS/services.js"></script>
 <script src="./controllersJS/articleServices.js"></script>
 <script src="./controllersJS/actionServices.js"></script>
 <script src="./controllersJS/smoothScrollService.js"></script>

</body>

</html>

so far without including the dependency in the module, the project loads good, no problems in console. But when adding the dependency it fails:
main.js
var myApp = angular.module('myApp', ['ngRoute','bootstrapLightbox']);

console error log
jquery.min.js:2 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.6/$injector/modulerr?p0=myApp&p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.6.6%2F%24injector%2Fmodulerr%3Fp0%3DbootstrapLightbox%26p1%3DError%253A%2520%255B%2524injector%253Amodulerr%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.6.6%252F%2524injector%252Fmodulerr%253Fp0%253Dui.bootstrap%2526p1%253DError%25253A%252520%25255B%252524injector%25253Anomod%25255D%252520http%25253A%25252F%25252Ferrors.angularjs.org%25252F1.6.6%25252F%252524injector%25252Fnomod%25253Fp0%25253Dui.bootstrap%25250A%252520%252520%252520%252520at%252520https%25253A%25252F%25252Fajax.googleapis.com%25252Fajax%25252Flibs%25252Fangularjs%25252F1.6.6%25252Fangular.min.js%25253A7%25253A76%25250A%252520%252520%252520%252520at%252520https%25253A%25252F%25252Fajax.googleapis.com%25252Fajax%25252Flibs%25252Fangularjs%25252F1.6.6%25252Fangular.min.js%25253A26%25253A408%25250A%252520%252520%252520%252520at%252520b%252520(https%25253A%25252F%25252Fajax.googleapis.com%25252Fajax%25252Flibs%25252Fangularjs%25252F1.6.6%25252Fangular.min.js%25253A25%25253A439)%25250A%252520%252520%252520%252520at%252520https%25253A%25252F%25252Fajax.googleapis.com%25252Fajax%25252Flibs%25252Fangularjs%25252F1.6.6%25252Fangular.min.js%25253A26%25253A182%25250A%252520%252520%252520%252520at%252520https%25253A%25252F%25252Fajax.googleapis.com%25252Fajax%25252Flibs%25252Fangularjs%25252F1.6.6%25252Fangular.min.js%25253A42%25253A290%25250A%252520%252520%252520%252520at%252520p%252520(https%25253A%25252F%25252Fajax.googleapis.com%25252Fajax%25252Flibs%25252Fangularjs%25252F1.6.6%25252Fangular.min.js%25253A8%25253A7)%25250A%252520%252520%252520%252520at%252520g%252520(https%25253A%25252F%25252Fajax.googleapis.com%25252Fajax%25252Flibs%25252Fangularjs%25252F1.6.6%25252Fangular.min.js%25253A42%25253A138)%25250A%252520%252520%252520%252520at%252520https%25253A%25252F%25252Fajax.googleapis.com%25252Fajax%25252Flibs%25252Fangularjs%25252F1.6.6%25252Fangular.min.js%25253A42%25253A322%25250A%252520%252520%252520%252520at%252520p%252520(https%25253A%25252F%25252Fajax.googleapis.com%25252Fajax%25252Flibs%25252Fangularjs%25252F1.6.6%25252Fangular.min.js%25253A8%25253A7)%25250A%252520%252520%252520%252520at%252520g%252520(https%25253A%25252F%25252Fajax.googleapis.com%25252Fajax%25252Flibs%25252Fangularjs%25252F1.6.6%25252Fangular.min.js%25253A42%25253A138)%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.6%252Fangular.min.js%253A7%253A76%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.6%252Fangular.min.js%253A43%253A70%250A%2520%2520%2520%2520at%2520p%2520(https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.6%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.6%252Fangular.min.js%253A42%253A138)%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.6%252Fangular.min.js%253A42%253A322%250A%2520%2520%2520%2520at%2520p%2520(https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.6%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.6%252Fangular.min.js%253A42%253A138)%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.6%252Fangular.min.js%253A42%253A322%250A%2520%2520%2520%2520at%2520p%2520(https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.6%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(https%253A%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fangularjs%252F1.6.6%252Fangular.min.js%253A42%253A138)%0A%20%20%20%20at%20https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.6%2Fangular.min.js%3A7%3A76%0A%20%20%20%20at%20https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.6%2Fangular.min.js%3A43%3A70%0A%20%20%20%20at%20p%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.6%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.6%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.6%2Fangular.min.js%3A42%3A322%0A%20%20%20%20at%20p%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.6%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.6%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20hb%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.6%2Fangular.min.js%3A46%3A250)%0A%20%20%20%20at%20c%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.6%2Fangular.min.js%3A22%3A19)%0A%20%20%20%20at%20Uc%20(https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.6%2Fangular.min.js%3A22%3A332)
    at angular.js:88
    at angular.js:4957
    at p (angular.js:410)
    at g (angular.js:4917)
    at hb (angular.js:4839)
    at c (angular.js:1949)
    at Uc (angular.js:1970)
    at we (angular.js:1855)
    at HTMLDocument.<anonymous> (angular.js:33884)
    at j (jquery.min.js:2)

link to angular error -->
angular error
I can't find why is not injecting the bootstraplightbox module. Does this has to be with a compatibility issue?

A: I do not see any fault with your DI and the code.
It could be due to the angular and bootstrap version mismatch, please update the following scripts,
<script data-require="angular.js@*" data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js"></script>
<script data-require="bootstrap@*" data-semver="3.3.2" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script data-require="ui-bootstrap@*" data-semver="0.13.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.0.min.js"></script>
<script src="angular-bootstrap-lightbox.js"></script>

DEMO


text:
Q: ExoPlayer getDuration I'm trying to play mp3 file from url with ExoPlayer.
Everything is fine but now I wonder when is the time it's safe to getDuration() of the audio track. I just need it once track is loaded. Didn't find it in google's example project.
When I try to get it immediately after exoPlayer.prepare() then I get UNKNOWN_TIME.

A: private int getVideoDurationSeconds(SimpleExoPlayer player)
    {
        int timeMs=(int) player.getDuration();
        int totalSeconds = timeMs / 1000;
        return totalSeconds;
    }

just call this method with exoplayer object and you will find total seconds
complete method
private String stringForTime(int timeMs) {
    StringBuilder mFormatBuilder = new StringBuilder();
    Formatter mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
    int totalSeconds = timeMs / 1000;
  //  videoDurationInSeconds = totalSeconds % 60;
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;

    mFormatBuilder.setLength(0);
    if (hours > 0) {
        return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
    } else {
        return mFormatter.format("%02d:%02d", minutes, seconds).toString();
    }
}

A: Ok, looks like this is the only solution here.
We add listener to our player, and get duration when state changes to STATE_READY. It will obviously called on every play/pause action so we need to wrap it with boolean durationSet flag if check to call it once on track start. Then durationSet = false somewhere near audioPlayer.prepare()
audioPlayer.addListener(new ExoPlayer.Listener() {
        @Override
        public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
            if (playbackState == ExoPlayer.STATE_READY && !durationSet) {
                long realDurationMillis = audioPlayer.getDuration();
                durationSet = true;
            }

        }

        @Override
        public void onPlayWhenReadyCommitted() {
            // No op.
        }

        @Override
        public void onPlayerError(ExoPlaybackException error) {
            // No op.
        }
    });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fit ImageViews into Android GridLayout I need to place 4 images into GridLayout. If I define their sizes hard-coded.
e.g.
android:layout_width="150dp"
android:layout_height="200dp"

It works fine.
But my question is, if is it possible to do it without defining sizes?
Meanwhile I've tried this:
<GridLayout
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_margin="16dp"
    android:columnCount="2"
    android:orientation="horizontal"
    android:useDefaultMargins="true"
    app:layout_constraintTop_toBottomOf="@+id/top_object"
    app:layout_constraintBottom_toTopOf="@+id/bottom_object"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/poster_21"
            android:scaleType="centerCrop"/>

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/poster_22"
            android:scaleType="centerCrop"/>

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/poster_23"
            android:scaleType="centerCrop"/>

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/poster_24"
            android:scaleType="centerCrop"/>

  </GridLayout>

But in this case I have left top image occupies the whole Grid Layout and 3 other images have the same size and are located outside the screen.

A: You can use 0dp width & height for each GridLayout element, i.e. ImageView
And control the width & height using the column & row weights
<?xml version="1.0" encoding="utf-8"?>
<GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:grid="http://schemas.android.com/apk/tools"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_margin="16dp"
    android:useDefaultMargins="true"
    android:layout_constraintTop_toBottomOf="@+id/top_object"
    android:layout_constraintBottom_toTopOf="@+id/bottom_object"
    android:layout_constraintLeft_toLeftOf="parent"
    android:layout_constraintRight_toRightOf="parent"
    android:columnCount="2">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="centerCrop"
        android:src="@drawable/poster_21"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        grid:layout_gravity="center" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="centerCrop"
        android:src="@drawable/poster_22"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        grid:layout_gravity="center" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="centerCrop"
        android:src="@drawable/poster_23"
        android:text="item 0x2"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        grid:layout_gravity="center" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="centerCrop"
        android:src="@drawable/poster_24"
        android:text="item 1x0"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        grid:layout_gravity="center" />

</GridLayout>


text:
Q: How to reject student if they don't have a course prerequisite completed
I am working on the above university database and am wondering how to enforce the prerequisite table. I have it so that each crs_code has a prerequisite relating to crs_requires. However, I need to figure out a way so that when a student goes to enrol in a class it will check whether they have the required prerequisite in order to enrol. If the student does have the prerequisite it should just create the new row and let them enrol, if the student does not have the required prerequisite a table should show which course they are trying to get into and which course they need.
Here is an example of some of the data in the prerequisite table:
+----------+--------------+
| crs_code | crs_requires |
+----------+--------------+
| 10       | 1            |
| 11       | 10           |
| 14       | 11           |
| 15       | 11           |
| 20       | 11           |
| 16       | 13           |
| 17       | 13           |
| 18       | 13           |
| 21       | 13           |

EDIT: The student has all of their courses in the enrolment table (both previously taken and currently taken courses) They are assigned a credit of 1 if they passed the class and credit 0 if they are currently in the class or failed it. How can I check to see if they have the credit for the prerequisite course that is needed before they enrol in a course that requires a particular prerequisite?
Thanks for any help!

A: Try This
SELECT crs.crs_code, req.crs_requires
FROM COURSE crs
    LEFT JOIN PREREQUISITES req ON req.crs_code = crs.crs_code
WHERE crs.crs_code = @course AND (req.crs_code IS NULL OR
    req.crs_requires IN (SELECT crs2.crs_code FROM ENROLLMENT en2
                            JOIN SECTION se2 ON se2.sec_id = en2.sec_id
                            JOIN COURSE crs2 ON crs2.crs_code = se2.crs_code
                         WHERE en2.stu_id = @id))

I am assuming you will provide the Student Id and the course that the student wants to register to the query.
EDIT: The way I see it, a student logs in and selects a course to register, in which scenario we know both the course he wants to register to and his id. If he is eligible we let him register.
EDIT2: To check for credits in the prerequisite you could simply add AND en2.Credits = 1 to the WHERE clause in the sub query (which actually checks if the student has enrolled in the prerequisite).
It seems that in MySql an IF..ELSE can be used only in functions or Stored procs. If you decide to go that way you could do something like
IF(EXISTS (a Prequisite AND the student has a particular grade/credit))
    //This student has the prereqisite.
ELSE
    //This student does not have the required prerequisite
END

A:
yes that would be great if you could tell me what the issue is

You need to pay attention to your prerequisite and course tables.
The way you have it (because the FKs are not nullable as the ERD indicates). This implies that each time you create a course, you must create a prerequisite course which is practically not valid. You should be able to create a course without a prerequisite if the is the case.
The same issue appears with other tables as well. This could also affect the delete to act like delete cascade.


text:
Q: highlight cell if previous column meets specific condition R I have a dataframe
library(flextable)
df = structure(list(col1 = c(1, NA, 1, 1, 1), col2 = c(NA, 1, NA,
1, 1), col3 = c(1, 1, NA, 1, NA), col4 = c(1, 1, 1, 1, NA)), class = "data.frame", row.names = c(NA,
-5L))
df %>% flextable()

I want

to return the last 3 columns highlighted based on the following logic:

*

*red if it is blank

*green if and only if the preceeding column was blank.

Based on this, I am trying to create a color matrix to identify the green highlights, but have hit a brick wall.
To identify the red matrix, I used the following code ifelse(is.na(df),"red","").
what would be the best method to identify the green labels

A: Not the prettiest, but works
df=data.frame(col1 = c(1,NA,1,1,1,1),
              col2 = c(NA,1,NA,1,1,1),
              col3 = c(1,1,NA,1, NA,1),
              col4 = c(1,1,1,1,NA,1))
df %>% flextable()
red = ifelse(is.na(df),1,0)
green = data.frame()
for(n in 1:(ncol(red)-1)){
  print(n)
  r=ifelse(red[,n]==1 & red[,n+1] == 0,1,0)
  green = rbind(green, r)
}
green = t(green)
colnames(green) = paste0("col",2:4)
green
red[,2:4]
ft = df[,2:4] %>%
  flextable() %>%
  bg(i = ~ is.na(col2), j = 1,bg='red') %>%
  bg(i = ~ is.na(col3), j = 2,bg='red') %>%
  bg(i = ~ is.na(col4), j = 3,bg='red') %>%
  bg(i = ~ green[,1]==1,j = 1, bg='green') %>%
  bg(i = ~ green[,2]==1,j = 2, bg='green') %>%
  bg(i = ~ green[,3]==1,j = 3, bg='green')
ft


text:
Q: SQL Server - Update rows based on a list I'm working with Windows Forms - VB.NET.
Here's what I have:

*

*A ListView with checkboxes set to True

*A Button (triggers the update)

*A database table with similar fields as the ListView
What I want to happen:

*

*when the user clicks the Button, all items on the ListView with checkbox checked will be updated.

My progress:

*

*I've already collected the ID of the checked items and stored them in an array. I'll be using this to update the database table.

The problem:

*

*I don't know how to put them in the SqlCommand.Parameters

*Also, I don't know the update command for such scenario (where in/exist (@parameters))

Thanks in advance!

A: If you're using SQL Server 2008 or later, you can use table-valued parameters. These let you continue to deal with the separate IDs on separate rows, perform SQL joins, etc. There are plenty of examples on the page I've linked to, e.g.:
Using connection
  ' Create a DataTable with the modified rows.
  Dim addedCategories As DataTable = _
    CategoriesDataTable.GetChanges(DataRowState.Added)

  ' Define the INSERT-SELECT statement.
  Dim sqlInsert As String = _
  "INSERT INTO dbo.Categories (CategoryID, CategoryName)" _
  & " SELECT nc.CategoryID, nc.CategoryName" _
  & " FROM @tvpNewCategories AS nc;"

  ' Configure the command and parameter.
  Dim insertCommand As New SqlCommand(sqlInsert, connection)
  Dim tvpParam As SqlParameter = _
     insertCommand.Parameters.AddWithValue( _
    "@tvpNewCategories", addedCategories)
  tvpParam.SqlDbType = SqlDbType.Structured
  tvpParam.TypeName = "dbo.CategoryTableType"

  ' Execute the query
  insertCommand.ExecuteNonQuery()
End Using

You could easily replace that INSERT with an UPDATE, as shown earlier on the page:
UPDATE dbo.Categories
SET Categories.CategoryName = ec.CategoryName
FROM dbo.Categories INNER JOIN @tvpEditedCategories AS ec
ON dbo.Categories.CategoryID = ec.CategoryID;

And adjust parameter names accordingly.

A: It seems you want to use a single call to the database, for that you would need to build a string with the command, I don't think you can pass a list as parameter to a command / sp.
The update command:
UPDATE [table] SET [field1] = value1, [field2] = value2
WHERE [ID] IN (id1, id2, ..., idN)


text:
Q: How can I get the value of DocumentID in the Message field? How can I get the value (DocumentID) in the Message field
example:
ID                        Message
7898    <Portfolio><DocumentID>10545</DocumentID></Portfolio>

A: select  ID,
document_id = xmlextract("//Portfolio/DocumentID/text()", Message)
FROM TableA

A: If you are using an ASE version older than 12.5.1 you can accomplish this using character manipulation functions:
select
  id,
  substring(
    message,
    charindex('ID>', message)+3,
    charindex('</Doc', message) - charindex('ID>', message)-3
    ) as DocumentID
from your_table

If you're on a later version using xmlextract as suggested in the answer by RADAR seems much easier.


text:
Q: Haskell compiling DLL "undefined reference" I was following the guide for making DLL's to be called from other languages here:
http://www.haskell.org/ghc/docs/7.0.4/html/users_guide/win32-dlls.html
I first compile the Haskell module and the helper C file like so:

ghc -c SanitizeXSS.hs
ghc -c StartEnd.c

But when I try to link it all together like so:

ghc -shared -o SanitizeXSS.dll SanitizeXSS IdsSanitizeXSS_stub.o StartEnd.o

I get lots of error messages like this:

SanitizeXSS.o:fake<.data+0760>: undefined reference to 'textzm0zi11zi1zi5_DataziText_zdf0rdText_closure'

SanitizeXSS.o an object file that was auto-generated when I compiled the Haskell module.
I've tried the -no-hs-main trick mentioned in other threads.
Context: I'm trying to use the FFI to export a Haskell function that I will then hopefully call in a Managed Wrapper in C#.

A: Try passing --make to ghc, so that it will resolve references to missing Haskell libraries. Alternatively, list the Haskell packages you're linking against explicitly.


text:
Q: How to set up diferent password rules for regular users and for root on PAM Bear with me for a moment. I'm doing a college exercise setting up a VM and I'm having a very hard time understanding what PAM is and actually works. All the results that come on google are either too basic or too complex and I really don't know what to look up. My exercise requires me to set up a bunch of rules for both normal users and root:
To set up a strong password policy, you have to comply with the following requirements:

*

*Your password must be at least 10 characters long.

*It must contain an uppercase letter and a number.

*It must not contain more than 3 consecutive identical characters.

*The password must not include the name of the user.

*The following rule does not apply to the root password: The password must
have at least 7 characters that are not part of the former
password.

*Of course, your root password has to comply with this policy
I haven't been able to find any good sites that explain how PAM works in a good way however I found that for the normal user I need to edit /etc/pam.d/common-password with:
password        requisite          pam_pwquality.so retry=3 minlen=10 ucredit=-1 dcredit=-1 maxrepeat=3 reject_username difok=7 enforce_for_root

Although I don't understand how PAM works I do understand it's flags.
My question is how do I set up different rules for root?

A: Note that root is not asked for an old password so the checks that compare the old and new password are not performed.
So, basically, the phrase

The following rule does not apply to the root password

means you can't make difok=7 work for root and not that you must create a separate rule for root.


text:
Q: How to use a proc to format groupdate keys? I'm trying to understand how the format option works in the groupdate gem.
The readme explains that format takes a string that is passed to strftime or a proc (here).
I'm having trouble understanding the proc part of this.
A simple example, if User.group_by_month(:created_at).count.keys returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] (i.e., months of the year), how would I do a simple transformation of these keys, say key * 2?
Looking at the source, format appears to be expecting a method
if options[:format].respond_to?(:call)
  options[:format]
end

So I would have expected to be able to do something like User.group_by_month(:created_at, format: 'Proc.new { |d| d * 2 }')....
But this returns only Proc.new { |d| d * 2} as a string.
What am I doing wrong?

A: Most *_by methods expect Procs (or lambdas or blocks) as arguments. It looks like you are accidentally wrapping your Proc literal in quotes, making it a string. Try removing the quotes to turn it back into a Proc, like so:
User.group_by_month(:created_at, format: Proc.new { |d| d * 2 })


text:
Q: Receiver for Wifi connection on Marshmallow and above I have an app that needs to know when the user connects to a specific wifi network. This wifi network may or may not provide the user with internet access.
When targeting Android v25 and below, we could just use a BroadcastReceiver that intent-filters for android.net.wifi.STATE_CHANGE in the manifest. As of v26, though, this is no longer the case, it appears. The documentation states:

Beginning with Android 8.0 (API level 26), the system imposes additional restrictions on manifest-declared receivers. If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for most implicit broadcasts (broadcasts that do not target your app specifically). You can still use a context-registered reciever [sic] when the user is actively using your app.

Moreover, Google is requiring app submissions to target the latest API level. So, looks like we have to register the broadcast receiver with a valid Context.
My question, then, is how do we run some code whenever the device connects to a specific wifi network which may not provide internet connectivity, and not just as long as our Context is valid? Is the only solution to register it with a valid Context, listen for when that context gets destroyed, set an alarm for a second later that creates a new Context and register the receiver again? Seems like the opposite of what they want us to do, but also the only way to accomplish this.

A: You can use JobScheduler to achieve this. Schedule a Job as follows:
  JobScheduler js =
      (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
  JobInfo job = new JobInfo.Builder(
    MY_BACKGROUND_JOB,
    new ComponentName(context, MyJobService.class))
      .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
      .build();
  js.schedule(job);

And perform operation in your JobService when OS triggers it. Step by step tutorial to achieve is available here


text:
Q: Output from one stage is not available for a subsequent one I have these two stages
stages:
- stage: PrepareBuildTools
  jobs:
  - job:
    steps:
    - task: NuGetToolInstaller@1
    - task: NuGetCommand@2
      inputs:
       restoreSolution: '$(solution)'
 - stage: Build
   jobs:
   - job:
     steps:
     - task: DotNetCoreCLI@2
       displayName: 'Initialize EntityFrameworkCore'
       inputs:
       command: custom
       custom: tool
       arguments: 'install --global dotnet-ef'
     - task: DotNetCoreCLI@2
       displayName: 'Create migration'
       inputs:
         command: custom
         custom: ef
         arguments: 'migrations script -i -o $(System.DefaultWorkingDirectory)\migration.sql --project $(dbProject) -s $(startUpProject)'
     - task: VSBuild@1
       displayName: Build solution
       inputs:
         solution: '$(solution)'
         msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:DesktopBuildPackageLocation="$(build.artifactStagingDirectory)\WebApp.zip" /p:DeployIisAppPath="Default Web Site"'
         platform: '$(buildPlatform)'
         configuration: '$(buildConfiguration)'
     - task: FileTransform@1
       displayName: Transform appSettings.json
       inputs:
        folderPath: '$(build.artifactStagingDirectory)\WebApp.zip'
        fileType: 'json'
        targetFiles: '**/appsettings.json'

As you can see, the Build solution task builds the solution and produces WebApp.zip in D:\a\1\a\
The problem in that in a subsequent stage, the ZIP file is non existant, which leads me to believe the stages are all running in their own environment (different virtual machines?).
Is there any way to make sure every stage runs in the same environment ? I don't really need them to run in different ones, I mostly want to use stages so I can put an approval before an eventual "deploy" stage.
I tried defining a pool at the root of my YAML definition file as such:
pool:
 vmImage: 'windows-latest'

Then assumed all stages would run on that one, but no.

A: I had to add a couple more tasks to make that work
- task: CopyFiles@2
  displayName: Copy build output
  inputs:
    contents: '$(build.artifactStagingDirectory)\WebApp.zip'
    targetFolder: '$(Build.StagingDirectory)'
- task: CopyFiles@2
  displayName: Copy migration file
  inputs:
   contents: '$(System.DefaultWorkingDirectory)\migration.sql'
   targetFolder: '$(Build.StagingDirectory)'
- task: PublishBuildArtifacts@1
  inputs:
   PathtoPublish: '$(Build.StagingDirectory)'
   ArtifactName: 'buildoutput'
   publishLocation: 'Container'

And in the stage where I need the files above, simply download the artifact
- task: DownloadBuildArtifacts@0
  inputs:
   artifactName: 'buildoutput'
   buildType: 'current'
   downloadType: 'single'
   downloadPath: '$(System.ArtifactsDirectory)'

I can then use them as such: $(System.ArtifactsDirectory)\buildoutput\WebApp.zip


text:
Q: Laravel Composer Error: Installation failed, reverting ./composer.json to its original content I'm actually new to Laravel and I'm working with Laravel 5.8 to develop my project.
Basically I wanted to check the file ExampleComponent.vue at resources/js/components directory but it wasn't there so as this link says, I have to run composer require laravel/ui command and after that, php artisan ui vue command, then npm install && npm run dev.
But I typed the first command which is composer require laravel/ui and it suddenly said:
Your requirements could not be resolved to an installable set of packages.
Problem 1
    - Conclusion: remove laravel/framework v5.8.38
    - Conclusion: don't install laravel/framework v5.8.38
    - laravel/ui 2.x-dev requires illuminate/support ^7.0|^8.0 -> satisfiable by illuminate/support[7.x-dev, 8.x-dev, v7.0.0, v7.0.1, v7.0.2, v7.0.3, v7.0.4, v7.0.5, v7.0.6, v7.0.7, v7.0.8, v7.1.0, v7.1.1, v7.1.2, v7.1.3, v7.10.0, v7.10.1, v7.10.2, v7.10.3, v7.11.0, v7.12.0, v7.13.0, v7.14.0, v7.14.1, v7.15.0, v7.16.0, v7.16.1, v7.17.0, v7.17.1, v7.17.2, v7.18.0, v7.19.0, v7.19.1, v7.2.0, v7.2.1, v7.2.2, v7.20.0, v7.21.0, v7.22.0, v7.22.1, v7.22.2, v7.22.3, v7.22.4, v7.23.0, v7.23.1, v7.23.2, v7.24.0, v7.25.0, v7.26.0, v7.26.1, v7.27.0, v7.3.0, v7.4.0, v7.5.0, v7.5.1, v7.5.2, v7.6.0, v7.6.1, v7.6.2, v7.7.0, v7.7.1, v7.8.0, v7.8.1, v7.9.0, v7.9.1, v7.9.2].
    - laravel/ui v2.2.0 requires illuminate/support ^7.0|^8.0 -> satisfiable by illuminate/support[7.x-dev, 8.x-dev, v7.0.0, v7.0.1, v7.0.2, v7.0.3, v7.0.4, v7.0.5, v7.0.6, v7.0.7, v7.0.8, v7.1.0, v7.1.1, v7.1.2, v7.1.3, v7.10.0, v7.10.1, v7.10.2, v7.10.3, v7.11.0, v7.12.0, v7.13.0, v7.14.0, v7.14.1, v7.15.0, v7.16.0, v7.16.1, v7.17.0, v7.17.1, v7.17.2, v7.18.0, v7.19.0, v7.19.1, v7.2.0, v7.2.1, v7.2.2, v7.20.0, v7.21.0, v7.22.0, v7.22.1, v7.22.2, v7.22.3, v7.22.4, v7.23.0, v7.23.1, v7.23.2, v7.24.0, v7.25.0, v7.26.0, v7.26.1, v7.27.0, v7.3.0, v7.4.0, v7.5.0, v7.5.1, v7.5.2, v7.6.0, v7.6.1, v7.6.2, v7.7.0, v7.7.1, v7.8.0, v7.8.1, v7.9.0, v7.9.1, v7.9.2].
    - don't install illuminate/support 7.x-dev|don't install laravel/framework v5.8.38
    - don't install illuminate/support 8.x-dev|don't install laravel/framework v5.8.38
    - don't install illuminate/support 8.x-dev|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.0.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.0.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.0.2|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.0.3|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.0.4|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.0.5|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.0.6|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.0.7|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.0.8|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.1.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.1.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.1.2|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.1.3|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.10.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.10.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.10.2|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.10.3|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.11.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.12.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.13.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.14.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.14.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.15.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.16.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.16.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.17.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.17.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.17.2|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.18.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.19.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.19.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.2.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.2.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.2.2|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.20.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.21.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.22.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.22.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.22.2|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.22.3|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.22.4|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.23.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.23.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.23.2|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.24.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.25.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.26.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.26.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.27.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.3.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.4.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.5.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.5.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.5.2|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.6.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.6.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.6.2|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.7.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.7.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.8.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.8.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.9.0|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.9.1|don't install laravel/framework v5.8.38
    - don't install illuminate/support v7.9.2|don't install laravel/framework v5.8.38
    - Installation request for laravel/framework (locked at v5.8.38, required as 5.8.*) -> satisfiable by laravel/framework[v5.8.38].
    - Installation request for laravel/ui ^2.2 -> satisfiable by laravel/ui[2.x-dev, v2.2.0].

Installation failed, reverting ./composer.json to its original content.

So I don't know what to do now, would you please help me out with this?
I would really appreciate any idea or suggestion...
Thanks in advance.

A: Your problem is with your laravel version, which is old for latest laravel/ui Project.
Try with a fresh project:
composer create-project --prefer-dist laravel/laravel blog For new project, replace your project name with blog, then try composer require laravel/ui to add vue/react/angular scaffolds.
Also I'm suggesting to do a new project since you said you're new to laravel and you should keep your project and libraries up to date.
Full Laravel Installation Documents Here
Edit:
If you don't want to create a new project you can simply, edit your composer.json in project and change these lines to the latest versions or just replace parts with below:
"require": {
    "php": "^7.2.5",
    "fideloper/proxy": "^4.2",
    "laravel/framework": "^7.24",
    "laravel/tinker": "^2.0",
 }

Then simply run Composer update, ofc there are some big changes to take care since you're using 5.* but this is where you should start to just simply include new ui library to project.
Good Luck

A: Your problem is explained by the following two lines:
- laravel/ui 2.x-dev requires illuminate/support ^7.0|^8.0 -> satisfiable by illuminate/support[7.x-dev, 8.x-dev, v7.0.0, v7.0.1, v7.0.2, v7.0.3, v7.0.4, v7.0.5, v7.0.6, v7.0.7, v7.0.8, v7.1.0, v7.1.1, v7.1.2, v7.1.3, v7.10.0, v7.10.1, v7.10.2, v7.10.3, v7.11.0, v7.12.0, v7.13.0, v7.14.0, v7.14.1, v7.15.0, v7.16.0, v7.16.1, v7.17.0, v7.17.1, v7.17.2, v7.18.0, v7.19.0, v7.19.1, v7.2.0, v7.2.1, v7.2.2, v7.20.0, v7.21.0, v7.22.0, v7.22.1, v7.22.2, v7.22.3, v7.22.4, v7.23.0, v7.23.1, v7.23.2, v7.24.0, v7.25.0, v7.26.0, v7.26.1, v7.27.0, v7.3.0, v7.4.0, v7.5.0, v7.5.1, v7.5.2, v7.6.0, v7.6.1, v7.6.2, v7.7.0, v7.7.1, v7.8.0, v7.8.1, v7.9.0, v7.9.1, v7.9.2].
- laravel/ui v2.2.0 requires illuminate/support ^7.0|^8.0 -> satisfiable by illuminate/support[7.x-dev, 8.x-dev, v7.0.0, v7.0.1, v7.0.2, v7.0.3, v7.0.4, v7.0.5, v7.0.6, v7.0.7, v7.0.8, v7.1.0, v7.1.1, v7.1.2, v7.1.3, v7.10.0, v7.10.1, v7.10.2, v7.10.3, v7.11.0, v7.12.0, v7.13.0, v7.14.0, v7.14.1, v7.15.0, v7.16.0, v7.16.1, v7.17.0, v7.17.1, v7.17.2, v7.18.0, v7.19.0, v7.19.1, v7.2.0, v7.2.1, v7.2.2, v7.20.0, v7.21.0, v7.22.0, v7.22.1, v7.22.2, v7.22.3, v7.22.4, v7.23.0, v7.23.1, v7.23.2, v7.24.0, v7.25.0, v7.26.0, v7.26.1, v7.27.0, v7.3.0, v7.4.0, v7.5.0, v7.5.1, v7.5.2, v7.6.0, v7.6.1, v7.6.2, v7.7.0, v7.7.1, v7.8.0, v7.8.1, v7.9.0, v7.9.1, v7.9.2].

To install laravel/ui 2.x, you need to have illuminate/support 7.x or 8.x, which corresponds to laravel/framework 7.x or 8.x.
To make it work with your version of laravel (5.8), you need to find a version of that library that does work with that version of laravel. If you go to packagist, you can browse all versions of laravel/ui, and it turns out that 1.2.0 does support laravel 5.8. You can thus solve your problem by installing an earlier version composer require laravel/ui:1.2.0. Note that this version might or might not contain the functionality you seek though. If you have the option of upgrading laravel instead, that is probably the better option.

A: You installed laravel/ui version 3.0 which corresponds laravel 8.x.
you should install ui 2.x version with this command:
composer require laravel/ui:2.x

A: If you are using Laravel 6 run the commands:
composer require laravel/ui "2.x"

php artisan ui vue --auth

npm install && npm run dev


text:
Q: Strangeness with a decorator I want to make a decorator which will catch exceptions and adequately logged their.
def logger(foo):
    try:
        print foo()
    except Exception as e:
        print e

@logger
def d():
    return 2/2

if __name__ == '__main__':
    d()

Thats right i think, but then I run it and I have an exception like this:
1

Traceback (most recent call last):

  File "log.py", line 14, in <module>

    d()

TypeError: 'NoneType' object is not callable

Why interpreter tells me that the function has None type, but call it and print answer?

A: Your decorator needs to return a function, but it's not returning anything, hence the 'TypeError: 'NoneType' object is not callable'. You can implement it this way:
def logger(foo):
    def fn():
        try:
            print foo()
        except Exception as e:
            print e
    return fn

Check out This question for a good example of how to write/use a decorator.

A: logger as you have defined, does not return a value. All such functions can be thought of as returning None. You have not defined your decorator correctly. It should look more like this:
def logger(foo):
    def _logger(foo):
        try:
            print foo()
         except Exception as e:
            print e
    return _logger

...but keep in mind that this loses a great deal of information, catches and swallows a great deal of exceptions, and also swallows any return values from the foo function so decorated. While you probably do something different in your production code than what you have shown here, the important thing is that the decorator function must itself return a function that can be called (_logger in my example).


text:
Q: Is it possible to create a Debug-only method in .NET? Is it possible to create a method which performs debugging assistance like the System.Diagnostics.Debug class?
I'm looking for a way to construct a method which when called by an assembly compiled with the DEBUG conditional compilation symbol defined, results in an operation, and which is a no-op when called by an assembly without the symbol defined.
If possible, I'd like it to be possible for the calls to the debugging methods to add minimal overhead or increase in size to the release version of the assembly.
To clarify, the debugging methods should be in an assembly compiled in Release mode. Calls to the methods should only generate operations when called from an assembly with the DEBUG symbol defined in the scope of the method call.

A: ConditionalAttribute
BTW the code for the method being called remains in the assembly -- it's the calls to it that are removed at compilation time
Bonus topical blog post: http://blogs.msdn.com/ericlippert/archive/2009/09/10/what-s-the-difference-between-conditional-compilation-and-the-conditional-attribute.aspx

A: Add the Conditional attribute to the method, like this:
[Conditional("DEBUG")]
public void Whatever() {
    //...
}

Note that the method must return void, and cannot have any out parameters; otherwise, it would be impossible to remove a call to it.
The method will be compiled into the assembly, but CLS-compliant compilers will only emit calls to the method if the assemblies that they are compiling has DEBUG defined.  Note that the C++ compiler is not CLS-compliant and will always emit the call.

A: If you disassemble System.Diagnostics.Debug class using Reflector you can see that this is done using the [Conditional("DEBUG")] attribute:
public sealed class Debug
{
    private Debug();
    [Conditional("DEBUG")]
    public static void Assert(bool condition);
    // etc...
}

A: If you need another signature than void func(..) without out parameters,
what would be wrong with
MyDebugObject Foo(out int justForGrins)
{
    justForGrins = <safe value for release builds>;
    MyDebugObject result = <safe value for release builds>;
    #if DEBUG
     .. run code you need for your debugging...
    #endif
     return result;
}

It is more verbose and less elegant than the ConditionalAttribute, but it would allow you a more flexible signature.

A: Why not try something like this ?
#if DEBUG
        private void DebugLog(string message)
        {
            // do whatever u want.
        }
#endif


text:
Q: How to find the critical gain K from the root locus I am going through Ogata's Discrete-Time Control Systems and working out the following problem found on Page 262.
The problem states:

Draw root locus diagrams in the \$z\$ plane for the system shown in Figure 4-45 for the
  following three sampling periods: \$T = 2\$ sec

I first obtain the Z-transform of G(s):

and I worked all the way till the very end and calculated break-away and break-in points to arrive at:

and root locus:

However I am unable to calculate the critical value \$K\$ for stability (Answer is 1.4557).
I know I need to use the magnitude condition but I am not sure which value of \$z\$ I should substitute in the formula to obtain the critical value of \$K\$.
Any suggestions would be appreciated.

A:
Any suggestions would be appreciated.

You get the poles, for the closed-loop system \$ L(z) = \frac{G(z)}{1+G(z)}\$, moving on those root locus trajectories by changing the gain \$K\$. And you want to find the critical gain \$K\$ such that the poles are on the unit circle. Summing up the mathematics:

*

*\$ G(z) = \frac{1.1353K(z+0.5232)}{(z-1)(z-0.1353)} \$,

*\$ L(z) = \frac{\frac{1.1353K(z+0.5232)}{(z-1)(z-0.1353)}}{1+\frac{1.1353K(z+0.5232)}{(z-1)(z-0.1353)}} = \frac{1.1353K(z+0.5232)}{(z-1)(z-0.1353)+1.1353K(z+0.5232)}\$,

*\$|z_0| = 1\$.

Now, to solve this, expand the denominator of \$L(z)\$ (since its roots are the poles of the transfer function), then find the roots of the denominator, which is a second-degree polynomial, you will get some
$$z_0 = \frac{-b ~\pm ~\sqrt{b^2-4ac}}{2a},$$
Now, from the breakpoints and a sketch of the root locus you know that \$ z_0 \$ has a real part and an imaginary one, \$b\$ is the real part and the square root will be the imaginary one. You also know that \$|z_0| = 1\$, so combine that to have
$$ |z_0|^2 = 1 = \left(\frac{b}{2a}  \right)^2 + \left(\frac{\sqrt{4ac-b^2}}{2a} \right)^2,$$
Which will only have \$ K\$ as an unknown.
obs: really long maths, if anyone ever do the numeric calculation feel free to update this.

A: The root locus, and the locus of \$\small \mid z\mid=1\$ are both unit circles. The centre of the \$\small \mid z\mid=1\$ circle is at the origin, and the centre of the root locus circle is at \$\small x=-0.5232\$. We need to find either one of the two complex conjugate points where these circles intersect, and we can then determine the value of \$\small K_{cr}\$.
Thus we have the two loci:
\$\small x^2 +y^2=1\$
\$\small (x+a)^2+y^2=1\$
Solving these simultaneously gives:
\$x=-\frac{a}{2}\$
Hence, the circles intersect at:
\$x=\frac{-0.5232}{2}=\small-0.2616\$
and the corresponding \$y\$ values are \$y=\small \pm 0.9652\$
Expressing this in complex form:
\$z=\small-0.2616\pm j0.9652 \$
Now substitute one of these values in the characteristic equation, and \$\small K_{cr}\$ is determined.


text:
Q: strange "template-like" syntax (generics?) In the following line
Graph<Number,Number> ig = Graphs.<Number,Number>synchronizedDirectedGraph(
                              new DirectedSparseMultigraph<Number,Number>());

could you please explain what Graphs.<Number,Number>synchronizedDirectedGraph means ? It looks like a call to a method Graphs.synchronizedDirectedGraph, but the template-like thingie after the dot puzzles me (at least due to my C++ background).

A: It is specifying the types for the static method.  See Generic Types, Part 2 (particularly the "Generic mehods" section) for more information.

A: The problem is that Java is not very intelligent in the places it supports type inference.
For a method:
class A{}
class B extends A{}
class Y{
  static <T> List<T> x(T t)
}

It infers the type List<B> from the parameter type B
List<B> bs = Y.x(new B());

But if you need List<A> you have to cast B or add the compiler hint:
List<A> as1 = Y.<A> x(new B());
List<A> as2 = Y.x((A) new B());

Part of the problem is that java generics are invariant so List<B> is not a subtype of List<A>.


text:
Q: Is it possible to install Debian within a Windows filesystem in the same manner as Ubuntu can be installed with Wubi? I have a Windows 7 laptop whose hard drive has four primary partitions out of the box.
The first partition is labeled "SYSTEM" (209 MB NTFS) and seems to contain the Windows boot loader.
The second partition is labeled "NTFS" (237 GB NTFS) which is obviously the main Windows partition.
The third partition is labeled "RECOVERY" (13 GB NTFS) which I can only assume contains the factory recovery tools and data.
The forth partition is labeled "HP_TOOLS" (108 MB FAT), probably has something to do with the diagnostic tools that can be set to run after POST.
I would like to be able to dual-boot Windows 7 and Debian on this laptop. Normally I would resize the main Windows partition to make space for Debian but because a hard drive has a limit of four primary partitions, I can't add a fifth partition for the Debian installation.
I could delete either the RECOVERY or HP_TOOLS partition and resize and move the remaining three partitions to allow space for an extended partition into which I could create logical partitions for a Debian installation but I really don't want to that.
I already have Ubuntu installed on this laptop using Wubi to create the Ubuntu partitions as files within the Windows 7 partition, which works very well.
Is there a tool available like Wubi that will allow me to do the same with Debian?


text:
Q: Selecting an inner Element of the same outer Element type Works:
doc.select("table#mainTable table#newTable table")

Doesn't work:
doc.select("table#mainTable table#newTable").select("table")

Given an Element, such as doc.select("table#mainTable table#newTable"), how can I iterate on all of the nested
's?  I'm just getting the table#newTable returned back to me.

A: The problem with the selector that doesn't give you what you expect doc.select("table#mainTable table#newTable").select("table") is that it includes the parent table too.
Example html

    First table

          Second table

                Third table

The selector will return two elements
First element is the parent (that contains the table that you want)

      Second table

              Third table

And the second element is the one you need

   Third table

Don't be alarmed by the tags that are missing from the example but are present in the result (tbody). They are added by jsoup's normalizer in order to give you a valid html in regards to the specification. So to conclude the answer, this query doc.select("table#mainTable table#newTable table") is fine. It will return Elements that will contain all the table elements that are children (bare in mind, not necessary immediate children) of a table with id newTable which in will be a child (again not necessary immediate) of a table with id mainTable.
Example html

    First table

          Second table

                Third table

                Third table

Code
Document doc = Jsoup.parse(htmlStr);
Elements tables = doc.select("table#mainTable table#newTable table");

int i = 0;
for(Element l : tables) {
    System.out.println(i++ + " - " + l.attr("id"));
}

Result
0 - lastone_1
1 - lastone_2

Update
Document doc = Jsoup.parse(htmlStr);
Elements newTables = doc.select("table#mainTable table#newTable");

for(Element newTable : newTables) {
    Elements leafTables = newTable.children().select("table");
    for(Element leaf : leafTables) {
        System.out.println(leaf.attr("id"));
    }
}


text:
Q: set_error_handler vs set_exception_handler
Possible Duplicate:
In PHP5, should I use Exceptions or trigger_error/set_error_handler?

In PHP 5+, what is better to use?

*

*set_error_handler, because it can also trap errors which are not exceptions;

*set_exception_handler, because it's a new feature and it maybe came to replace set_error_handler; or

*both, because one does not supersedes the other, and both are useful?


text:
Q: Excel VBA: Initialise public module-level variables when file is opened? I have a whole bunch of dates in three columns which are used by several macros. Currently each macro that uses these dates has to:

*

*Declare the range

*Have a for-loop through the range to get the date-cell and

*Read the value of the cell into a variable of type date

This also includes checking the cell isn't empty, checking the date is valid.
Instead of this, I would like to have a macro that reads these dates into (VBA) arrays, which persist as long as the file is opened. I would also like to have this macro run when the file is opened, so that the dates are guaranteed to be initialised when any macro that uses them is run.
Any way to do these things?

A: Put your code in the Workbook_Open() event.

*

*Alt-F11 to bring up the VBA Editor

*Double-click the "ThisWorkbook" in the Project Explorer.

You'll see two drop-downs at the top of the code window. Pick "Workbook" from the first one and "Open" from the second to have a stub for your code created.


text:
Q: Error when rendering a 3d cube with matplotlib I want to render a 3D cube using matplotlib.
The cube is rendered but there are glitches when looking from certain directions:
The magenta side is bleeding in when looking from the front.
How can i fix this?
This is my code:
import numpy as np
import math
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection

a=0.5
cube = np.array([
[-a,-a,-a], \
[+a,-a,-a], \
[+a,+a,-a], \
[-a,+a,-a], \
            \
[-a,-a,+a], \
[+a,-a,+a], \
[+a,+a,+a], \
[-a,+a,+a]  \
])

bottom = [0,1,2,3]
top    = [4,5,6,7]
front  = [0,1,5,4]
right  = [1,2,6,5]
back   = [2,3,7,6]
left   = [0,3,7,4]

def rotation(theta = np.random.random_sample(3) * math.pi * 2, R = np.zeros((3,3))):
    cx,cy,cz = np.cos(theta)
    sx,sy,sz = np.sin(theta)
    R.flat = (cx*cz - sx*cy*sz, cx*sz + sx*cy*cz, sx*sy,
        -sx*cz - cx*cy*sz, -sx*sz + cx*cy*cz,
        cx*sy, sy*sz, -sy*cz, cy)
    return R

def render_rotation(rot):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=0, azim=0)
    ax.grid(False)
    plt.axis('off')
    ax.set_proj_type('persp')
    # rotate cube
    rotated=np.linalg.linalg.dot(rotation(rot), cube.transpose()).transpose()
    def render_side(idx, clr):
        ax.add_collection3d(Poly3DCollection([
            [rotated[idx[0]]+a, rotated[idx[1]]+a, rotated[idx[2]]+a, rotated[idx[3]]+a]
        ], facecolors=clr, linewidths=0))
    render_side(top   , 'red')
    render_side(front , 'green')
    render_side(right , 'blue')
    render_side(bottom, 'cyan')
    render_side(back  , 'magenta')
    render_side(left  , 'yellow')
    plt.show()
    plt.close()
render_rotation(np.array([0,0,0]))

Edit:
The comment of ImportanceOfBeingErnest was the solution.
I just had to change my render function slightly:
clrs=[]
verts=[]
def render_side(idx, clr):
    clrs.append(clr)
    verts.append([
        rotated[idx[0]]+a,
        rotated[idx[1]]+a,
        rotated[idx[2]]+a,
        rotated[idx[3]]+a])
render_side(top   , 'red')
render_side(front , 'green')
render_side(right , 'blue')
render_side(bottom, 'cyan')
render_side(back  , 'magenta')
render_side(left  , 'yellow')
ax.add_collection3d(Poly3DCollection(verts, facecolors=clrs, linewidths=0))

A: The comment of ImportanceOfBeingErnest was the solution.
The fix for render_rotation is using only one Poly3DCollection:
def render_rotation(rot):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.view_init(elev=0, azim=0)
    ax.grid(False)
    plt.axis('off')
    ax.set_proj_type('persp')
    # rotate cube
    clrs=[]
    verts=[]
    def render_side(idx, clr):
        clrs.append(clr)
        verts.append([
            rotated[idx[0]]+a,
            rotated[idx[1]]+a,
            rotated[idx[2]]+a,
            rotated[idx[3]]+a])
    render_side(top   , 'red')
    render_side(front , 'green')
    render_side(right , 'blue')
    render_side(bottom, 'cyan')
    render_side(back  , 'magenta')
    render_side(left  , 'yellow')
    ax.add_collection3d(Poly3DCollection(verts, facecolors=clrs, linewidths=0))
    plt.show()
    plt.close()


text:
Q: Read Windows Registry value into array I have to read Windows Registry value into array in VBA. Value has type REG_MULTI_SZ.
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
             strComputer & "\root\default:StdRegProv")
strKeyPath = "SYSTEM\CurrentControlSet\Control\Lsa\Authentication Packages"
strValueName = "Sources"
Return = objReg.GetMultiStringValue(HKEY_LOCAL_MACHINE, strKeyPath, _
         strValueName, arrValues)
If (Return = 0) And (Err.Number = 0) Then
    'Treat the multistring value as a collection of strings
    'separated by spaces and output
    For Each strValue In arrValues
        WScript.Echo  strValue
    Next
Else
    WScript.Echo "GetMultiStringValue failed. Error = " & Err.Number
End If

It gives an error with number 0 and no description. Any clue?

A: According to your screenshot your key is "Authentication Packages", not "Sources".
Change this:
strKeyPath = "SYSTEM\CurrentControlSet\Control\Lsa\Authentication Packages"
strValueName = "Sources"

into this:
strKeyPath = "SYSTEM\CurrentControlSet\Control\Lsa"
strValueName = "Authentication Packages"

A: It was a simple error. The working code is here.
const HKEY_LOCAL_MACHINE = &H80000002

strComputer = "."

Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\"& strComputer & "\root\default:StdRegProv")
strKeyPath = "SYSTEM\CurrentControlSet\Control\Lsa"
strValueName = "Authentication Packages"

Return = objReg.GetMultiStringValue(HKEY_LOCAL_MACHINE,strKeyPath, strValueName,arrValues)
 WScript.Echo  "GetMultiStringValue. Return = " & Return

    If (Return = 0) And (Err.Number = 0) Then
' Treat the multistring value as a collection of strings
'    separated by spaces and output
    For Each strValue In arrValues
    WScript.Echo  strValue
Next
Else
    Wscript.Echo "GetMultiStringValue failed. Error = " & Err.Number
End If


text:
Q: How to achieve spring security ACL like functionality in node aws lambda serverless way So I have a generic question in javascript, cant seem to find the answer for a question i.e. Spring security ACL lets to authorize users at an instance level for example if you have a blog and users are commenting, in spring security ACL particular user (or a role) can be banned from commenting on that particular blog dynamically that means blog owner could make a call to backend via block button or something to block a user or roles. How can such a fine grained authorization be achieved using AWS serverless approach using JavaScript, Lambdas, dynamo db etc. i cant seem to find the design or better an open source example which I can learn from.
Javascript or Typescript example would be awesome to learn from as I only these.

A: I was expecting atleast one answer being new here but no worries for others who are searching for same solution please user ABAC (Attribute Based Access Control) Authorization. Following are the examples:
https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html
https://scalesec.com/blog/practical-attribute-based-access-control-with-aws/


text:
Q: Backbone nested views I'm working on a Backbone application and I'm not sure if the way what I'm trying to do is the correct way.
I have an application view and inside that application view I'm trying to append a collection view, and each view in that collection is a collection too.
Let me explain that graphically.
----------------------------------------------------------------------
|                                                                    |
|    Application view                                                |
|                                                                    |
|    -------------------------------------------------------------   |
|    |  Windows Collection view                                  |   |
|    |                                                           |   |
|    |  --------------------------   --------------------------  |   |
|    |  | Tabs collection view   |   | Tabs collection view   |  |   |
|    |  |                        |   |                        |  |   |
|    |  | ---------- ----------  |   | ---------- ----------  |  |   |
|    |  | |Tab view| |Tab view|  |   | |Tab view| |Tab view|  |  |   |
|    |  | ---------- ----------  |   | ---------- ----------  |  |   |
|    |  |                        |   |                        |  |   |
|    |  | ---------- ----------  |   | ---------- ----------  |  |   |
|    |  | |Tab view| |Tab view|  |   | |Tab view| |Tab view|  |  |   |
|    |  | ---------- ----------  |   | ---------- ----------  |  |   |
|    |  |------------------------|   |------------------------|  |   |
|    |                                                           |   |
|    |  --------------------------   --------------------------  |   |
|    |  | Tabs collection view   |   | Tabs collection view   |  |   |
|    |  |                        |   |                        |  |   |
|    |  | ---------- ----------  |   | ---------- ----------  |  |   |
|    |  | |Tab view| |Tab view|  |   | |Tab view| |Tab view|  |  |   |
|    |  | ---------- ----------  |   | ---------- ----------  |  |   |
|    |  |                        |   |                        |  |   |
|    |  | ---------- ----------  |   | ---------- ----------  |  |   |
|    |  | |Tab view| |Tab view|  |   | |Tab view| |Tab view|  |  |   |
|    |  | ---------- ----------  |   | ---------- ----------  |  |   |
|    |  |------------------------|   |------------------------|  |   |
|    |                                                           |   |
|    -------------------------------------------------------------   |
|                                                                    |
|                                                                    |
----------------------------------------------------------------------

Currently I'm loading the application view from the initialize method in my Backbone router. That view loads the Windows collection view.
The main problem is that I'm not sure if I'm on the right way.
The second problem is that I'm not really sure how to load each Tabs collection view from my Windows Collecion view.
PS: Just to make things even clearer, I'm trying to replicate Firefox's panorama view: http://i.i.com.com/cnwk.1d/i/tim//2010/08/24/firefox-panorama.jpg

A: I would highly recommend using Marionette.js to structure your application.
It already has collection views built in which makes rendering easy. Your application seems to be a perfect use case. You will get a lot of boilerplate code for free.

A: I'm just posting this here so others can see how I solved the problem
A working demo of the solution can be found here (original fiddle).
As you can see from the link, the work is done thanks to Marionette's CompositeView which lets recursively render collections.
var TreeView = Backbone.Marionette.CompositeView.extend({

    initialize: function(){
        if(this.model.tabs){
            this.template = "#window-template";
        }else{
            this.template = "#tab-template";
        }
        this.collection = this.model.tabs;
    },

    appendHtml: function(cv, iv){
        cv.$("#tabs").append(iv.el);
    },
    onRender: function() {
        if(_.isUndefined(this.collection)){
            this.$("#tabs").remove();
        }
    }
});

The small trick I'm using in the initialize (the if/else with the template asignation) works the following way:
I get the current model and check if it has a "tabs" key. If it does have it, it means that the current model is a Window Data Model, so I need to use the window-template, else use the tab-template
The rest is pretty much plain Backbone structure.


text:
Q: Spark Performance on "Small Data" I'm hoping that someone familiar with Spark can give me a "gut check" on whether I'm likely abusing the SparkML framework or if the performance I'm seeing is understandable given the context (#rows, #features).
Briefly, I have a small dataset (~150 rows) that is fairly wide (~180 features). I have coded up analogous Lasso training codes in Spark and Scikit-learn, which result in identical models (same model coefficients and LOOCVE). However, the Spark code takes roughly 100x longer (sklearn takes about 5 seconds, close to 600 secs.
I understand that Spark is optimized for large distributed datasets and that this difference can reasonably attributed to overhead latency that would be hidden by data parallelism, but this still feels extremely sluggish.
The spark code is essentially:
//... code to add a number of PipelineStages to a List<PipelineStage> (~90 UnaryTransformer stages), ending in a StandardScaler

// Add Lasso model
LinearRegression lasso = new LinearRegression()
                .setLabelCol(response)
                .setFeaturesCol("normed_features")
                .setMaxIter(100000)
                .setPredictionCol(response+"_prediction")
                .setElasticNetParam(1.0)
                .setFitIntercept(true)
                .setRegParam(0.2);

// stages is the List<PipelineStage> loaded with 90 or so UnaryTransformer steps
stages.add(lasso);

Pipeline pipeline = new Pipeline(stages);
DataFrame df = getTrainingData(trainingData, response);
RegressionEvaluator evaluator = new RegressionEvaluator()
                .setLabelCol(response)
                .setMetricName("mae")
                .setPredictionCol(response+"_prediction")
);

df.cache();

ParamMap[] paramGrid = new ParamGridBuilder().build();

CrossValidator cv = new CrossValidator()
            .setEstimator(pipeline)
            .setEvaluator(evaluator)
            .setEstimatorParamMaps(paramGrid)
            .setNumFolds(20);

double cve = cv.fit(df).avgMetrics()[0];

the Python code uses Lasso and GridSearchCV with the same #folds (20).
Unfortunately, I can't really provide a MWE as we use a custom Transformer that I'd have to paste in, but I'm wondering if anyone would be willing to weigh in on whether this runtime difference between sklearn and spark implies user error. The only good practice I am knowingly applying is caching the training DataFrame before fitting the CrossValidator.


text:
Q: Website Freezes on the first load when i first load my website it completely freeze for a few seconds. After first load is all ok. I looked in console and it says there is problem with document.write() and i don't know what it is. I am using JOOMLA! 2.5
http://www.job-point.cz/index.php/zajemci-o-praci


text:
Q: Better chat room post tools I think the tooltips for chat room posts can be improved

*

*The onhover gray square is kindof distracting as you move your mouse around

*The arrow is too tiny to click

*Once I manage to open the tooltip, the star and flag are too tiny to click

*If a new post appears while I have a tooltip open, my tooltip moves right before I want to click on something.

Can this be improved?

A: Edit: Now a feature request! See Chat user interface suggestion
Cross-posting my answer from Gravatar bugs and improvements in Chat

I'm not quite sure why, but I think the chat controls would feel more natural on the right, rather than the left.
My idea, as seen below, would be to move the arrow thing to the right side of each chat "bubble". The controls would appear on mouseover, like now, but we could star or flag right from there (the most common tools) without having to have a second window to do that in. The arrow would let you open the window to access other controls, permalink, etc.
On your own posts, which you can't flag or star, you could change the controls to edit/delete, as those are the most common things to do on your own posts.

If you don't do this, at least close the pop-up window when I click in the text entry field, rather than make me aim for the little gray close button.

A: One option is to make the entire post clickable, and under the post will appear a row of tools, perhaps similar to how google reader works?


text:
Q: Converting a TextView->Bitmap->ImageView, and nothing's showing up I started a test project just to get this down.  No changes to main.xml.  I want to create a widget-sized ImageView (80x100) that contains a Bitmap converted from a TextView.  Yes, that sounds very roundabout but this is just for testing; in the end I want the ImageView to have a background image and multiple TextViews.  I'm not sure exactly what I'm doing wrong, but nothing is being pushed to the screen.
Is it a problem with declaring the TextView/ImageView and passing it "this" in the constructor?  Is it a problem with my layoutParams?  Here is the code:
package com.doaf.testproject;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TestProject extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView tv = new TextView(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(80, 100);
        tv.setLayoutParams(layoutParams);
        tv.setText("testing 1 2 3");
        tv.setTextColor(0xFFFFFF);
        tv.setBackgroundColor(0x555555);

        Bitmap testB;
        testB = loadBitmapFromView(tv);

        ImageView iv = new ImageView(this);
        iv.setLayoutParams(layoutParams);
        iv.setBackgroundColor(0x555555);
        iv.setImageBitmap(testB);

        setContentView(iv);
    }

    public static Bitmap loadBitmapFromView(View v) {
        Bitmap b = Bitmap.createBitmap(80, 100, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.layout(0, 0, 80, 100);
        v.draw(c);
        return b;
    }
}

Thanks for any help you can provide.  I'm relatively new to Android, and pretty lost with this one.

A: I believe its taking up the whole screen because you don't have a container such as a Linear Layout which then contains an ImageView with layout constraints, so the ImageView expands to fill the available screen. Try this:
@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView tv = new TextView(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(80, 100);
        tv.setLayoutParams(layoutParams);
        tv.setText("testing 1 2 3");
        tv.setTextColor(Color.BLACK);
        tv.setBackgroundColor(Color.TRANSPARENT);

        Bitmap testB;

        testB = Bitmap.createBitmap(80, 100, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(testB);
        tv.layout(0, 0, 80, 100);
        tv.draw(c);

        ImageView iv = (ImageView)findViewById(R.id.menuIcon);
        iv.setLayoutParams(layoutParams);
        iv.setBackgroundColor(Color.GRAY);
        iv.setImageBitmap(testB);
        iv.setMaxHeight(80);
        iv.setMaxWidth(80);
    }

And in your main.xml file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <ImageView android:id="@+id/menuIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

I'm not sure what you want to achieve, but I'm sure there are more efficient ways of approaching it.

A: Quick modification of the code, try this and see if it's what you want to archieve:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView tv = new TextView(this);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(80, 100);
    tv.setLayoutParams(layoutParams);
    tv.setText("testing 1 2 3");
    tv.setTextColor(Color.BLACK);
    tv.setBackgroundColor(Color.TRANSPARENT);

    Bitmap testB;

    testB = Bitmap.createBitmap(80, 100, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(testB);
    tv.layout(0, 0, 80, 100);
    tv.draw(c);

    ImageView iv = new ImageView(this);
    iv.setLayoutParams(layoutParams);
    iv.setBackgroundColor(Color.GRAY);
    iv.setImageBitmap(testB);

    setContentView(iv);
}

A: Your TextView needs to be measured (call measure()) and laid out (call layout()) before you can draw it. You are doing neither.


text:
Q: wxPython translation to Chinese only translates some words I am using the steps and the files in the zip file on this page here: https://docs.wxpython.org/internationalization.html. I've double checked and the strings that are not showing up as translated on our GUI are in translated and in the correct .po file with the correct line referenced to the right code file. I have used
_(u"String to be translated") within these files. The strange thing is boilerplate code with the same syntax shows up translated for some words and not for others. I've tried manually setting the encoding of the font to Big5 using
font = wx.Font(wx.FontInfo().Encoding(wx.FONTENCODING_CP950))

but this doesn't help the problem. Any tips on why this is the case is appreciated.


text:
Q: Vaadin 14.2: Intercept logout (invalidate session) with BeforeLeaveListener in my Vaadin 14.2.0 application there is a BeforeLeaveListener to show a confirmation dialog when the input is dirty (= there are unsaved changes in the input fields) to cancel (or intentionally proceed) the navigation:
BeforeLeaveListener listener = new BeforeLeaveListener() {
    @Override
    public void beforeLeave(BeforeLeaveEvent event) {
        if (dirtyFlag.isDirty()) {
            ContinueNavigationAction postponeAction = event.postpone();
            // show confirmation dialog and maybe execute a proceed
            [...] () -> postponeAction.proceed();
        }
    }
};
UI.getCurrent().addBeforeLeaveListener(listener);

This works fine for everything but for the logout.
This is how my logout button looked like in the start (what works as long as I do not want to postpone/cancel the logout):
Anchor link = new Anchor();
link.getElement().addEventListener("click", e -> {
    VaadinSession.getCurrent().getSession().invalidate();
    UI.getCurrent().navigate(LoginView.class);
});

Now I want to postpone the logout until the user confirms that the unsaved changes should get discarded. (Switching both lines in the EventListener seems to be a good idea, but did not work because of the following.)
Within the navigate-call the BeforeLeaveListener is called (good), but the logout is done nevertheless, because the code after the navigate()-call is executed (of course, because it is no blocking call), the session is invalidated and the user is logged out though the confirmation dialog just popped out (but the user had no chance to confirm/deny).
I tried to move the session invalidation into the LoginView (into a BeforeEnterObserver), but the result is that the login view is reloaded in an endless loop.
Question: is there something like "navigate to LoginView and if navigation is not postponed and not cancelled, then invalidate session"?
A workaround is to navigate to an intercepting LogoutView that just invalidates the session and redirects/forwards to the LoginView:
@Route(value = "logout")
public class LogoutView implements BeforeEnterObserver {
    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        VaadinSession.getCurrent().getSession().invalidate();
        event.forwardTo(LoginView.class);
    }
}

But this seems to me to be just a bad workaround with some overhead (creating a view just to forward to another view)...

A: I know, you didnt mention Spring. But that's actually what I believe Spring Security is doing under the hood.
My Logout Button (using Spring Security) is looking like this:
new Button("Logout", click -> {
    UI.getCurrent().getPage().executeJs("location.assign('logout')");
});

Once you click it, you are logged out and redirected to the login view (more details from Baeldung). I think it will be just fine if you do your LogoutView redirection detour.
The fact that you can even use the Navigator to go to your LogoutView is even better here, since this is caught by BeforeLeaveObserver (in contrast to completely new requests by assigning a new location or refreshing the page. See BeforeLeaveObserver vs. beforeunload for more details on that)

I would still like to propose another idea for your usecase. I think it will be much simpler, but requires that the logout link knows of the dirtyFlag:
Anchor link = new Anchor();
link.getElement().addEventListener("click", e -> {
    if(dirtyFlag.isDirty()){
        // show Dialog with
        // - a confirm btn that calls doLogout() on click
        // - a cancel btn that closes the Dialog
    } else {
       doLogout();
    }
});

...

private void doLogout(){
    VaadinSession.getCurrent().getSession().invalidate();
    UI.getCurrent().navigate(LoginView.class);
}


text:
Q: Help using variance in C# 4.0 Here's the problem. I would like to create a class which will contain configuration data. This data consists of key/value pairs. Some examples: "hostName"="localhost", "timeout"=1000, etc.. My initial idea was to store all these in a generic dictionary:
private Dictionary<string, ConfigurationItem<object>> Configuration =
    new Dictionary<string, ConfigurationItem<object>>();

And the ConfigurationItem class as:
public class ConfigurationItem<T>
{
    public string Name { get; set; }
    public T Value { get; set; }
}

My hopes are that I can query and set the configuration as follows:
int i = Configuration.Get<int>("Timeout");
Configuration.Set("Timeout", 1000);

Unfortunately, I can't insert items in the configuration dictionary using the following code:
public void SetValue<T>(string key, ConfigurationItem<T> value)
{
        if (Configuration.ContainsKey(key.ToUpper()))
            Configuration[key.ToUpper()] = **value**;
        else
            Configuration.Add(key.ToUpper(),  **value**);
}

The bold parts are showing errors:

Cannot convert type ConfigurationItem<T> to ConfigurationItem<Object>

I am using C# 4.0 since I hoped to fixed this problem using the new variance feature, but no luck so far. If more information is needed, just name it! Thanks for your help!

A: Covariance and contravariance in C# 4.0 only applies to interfaces and delegates.
You must prefix the type parameter with in or out, depending upon the location of usages of the type parameter in the interface member's definitions.
For example:
public interface IConfigurationItem<out T>
{
    public string Name { get; set; }
    public T Value { get; set; }
}

Because IDictionary<TKey,TValue> uses both its type parameters for inputs and outputs, dictionary are not covariant or contravariant.

A: From C# 4.0 draft specification variance limitations
23.3 Limitations
Co- and contravariant type parameters can only be declared on interfaces and delegate types. Co- and contravariance only applies when there is a reference (or identity) conversion between the type arguments. For instance, an IEnumerable<int> is not an IEnumerable<object> because the conversion from int to object is a boxing conversion, not a reference conversion.

A: You could just define your Dictionary as private Dictionary<string, object>, and cast the objects before you return them from your Get method.


text:
Q: iPhone App rejected. 9.4 : Video streaming over cellular network (etc) From Apple:

9.4
We found that your app does not use the HTTP Live Streaming protocol,
  with a baseline stream of 64 kbps, to broadcast streaming video, as
  required by the App Store Review Guidelines.

This is not the first time we had this error. The first time we had this they mentioned the url that was giving the error and pointed us towards their mediastreamvalidator tool.
We fixed our .m3u8's, added a low bitrate stream, have run through all our url's with that tool, and they have all passed.
Upon resubmitting they gave us the error above, with no details. We've replied in the resolution center with the validation output attached and are currently waiting for a reply. Does anyone have any ideas of things we've missed that would not be caught by their validation tool?
Thanks.

A: You must include 64kbps or lower bitrate stream (usually audio-only or audio with still images) in your streaming contents.
Check the guide: HTTP Live Streaming Overview

Requirements for Apps
Warning: iOS apps submitted for distribution in the App Store must
  conform to these requirements.
If your app delivers video over
  cellular networks, and the video exceeds either 10 minutes duration or
  5 MB of data in a five minute period, you are required to use HTTP
  Live Streaming. (Progressive download may be used for smaller clips.)
If your app uses HTTP Live Streaming over cellular networks, you are
  required to provide at least one stream at 64 Kbps or lower bandwidth
  (the low-bandwidth stream may be audio-only or audio with a still
  image).
These requirements apply to iOS apps submitted for distribution in the
  App Store for use on Apple products. Non-compliant apps may be
  rejected or removed, at the discretion of Apple.

A: Well, after finally getting through to someone at apple on the phone we got a case number and our app flagged for a fast tracked review. It was approved and is now available, despite there being no change whatsoever in the binary between the last rejection and this approval.


text:
Q: Adding dependencies to React hook leads to infinite loop I am trying to update a state using the props that I received from the parent component.
But react keeps putting up warning message to add the state that is being updated to add to the dependency list while I want effect to run once only when the component mounts.
Here is the code of the component that throws the warning message:
const [selectedDate, setSelectedDate] = useState(undefined);
  const [disableDate, setDisableDate] = useState([]);

  useEffect(() => {
    const key = Object.keys(slots);
    setDisableDate([
      ...disableDate,
      {
        before: new Date(key[0]),
        after: new Date(key[key.length - 1])
      }
    ]);

    if (!_.isEmpty(slots))
      Object.keys(slots).forEach(slot => {
        if (slots[slot].length === 0) {
          const date = moment(slot)
            .tz("Asia/Kolkata")
            .toISOString(true);
          setDisableDate([...disableDate, new Date(date)]);
        }
      });
  }, []);

When above code is run it works fine but it always gives the following warning.

React Hook useEffect has missing dependencies: 'disableDate' and
  'slots'. Either include them or remove the dependency array. You can
  also do a functional update 'setDisableDate(d => ...)' if you only
  need 'disableDate' in the 'setDisableDate' call
  react-hooks/exhaustive-deps

How do I resolve this issue?

A: You can disable that warning message by adding the // eslint-disable-next-line react-hooks/exhaustive-deps line before the dependency array. In this way the useEffect callback will be still triggered only once but you won't see the warning message in the same time.
Just like the following:
useEffect(() => {
  // ... your code

// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

I hope this helps!

A: Try the functional update on both your setDisableDate calls, as suggested by the warning:
setDisableDate(prevDisableDate => [
   ...prevDisableDate,
   {
     before: new Date(key[0]),
     after: new Date(key[key.length - 1])
   }
]);

setDisableDate(prevDisableDate => [...prevDisableDate, new Date(date)]);

In that way, disableDate isn't used inside useEffect and there is no need to add it on the dependency array.


text:
Q: Strange recurring errors downloading python 3.10.9.tgz with wget I and several workmates have had a recurring problem building python in a docker container under WSL and VirtualBox. The download seems to succeed but then the unzipping reports 'trailing garbage ignored', and the build process exits with value 2. We typically hit this problem a few times, do a manual workaround and then don't see it for a while, so it feels intermittent.
If downloaded via a browser, or even directly from the command line (with wget) the process works, but if you get the file with by running a script that calls wget, it most often has this 'trailing garbage ignored' error, even though the downloaded file reports the same total number of bytes exactly.
I'm trying to eliminate this so our dev setup can be hassle free but I'm at a loss as to what is going wrong.
My most recent experience with this was this morning:
Running the wget command inside a bash script produced a file that unzipped with errors, pasting the same lines to a terminal downloaded the file and it unzipped perfectly.
> `# environment values
>
>   PYTHON_DOCKER_IMAGE="ken/python"
>   PYTHON_DOCKER_TAG="3.10.9"
>   UBI_DOCKER_IMAGE="redhat/ubi8"
>   UBI_DOCKER_TAG="8.7" `

# build_local.sh
#!/usr/bin/env bash
set -euo pipefail

function build_local() {
  mkdir -p output
  wget \
    -c \
    --no-cache \
    -O output/python.tar.gz \
    "https://www.python.org/ftp/python/${PYTHON_DOCKER_TAG}/Python-${PYTHON_DOCKER_TAG}.tgz"

  docker build \
    --file Dockerfile.python \
    --build-arg UBI_DOCKER_IMAGE="${UBI_DOCKER_IMAGE}" \
    --build-arg UBI_DOCKER_TAG="${UBI_DOCKER_TAG}" \
    --tag "${PYTHON_DOCKER_IMAGE}:${PYTHON_DOCKER_TAG}" \
    --tag "${PYTHON_DOCKER_IMAGE}:latest" \
    .

  docker compose -p "${PROJECT_NAME}" build
}

function main() {
  build_local "$@"
}

main "$@"`

This is the Dockerfile that builds Python. We don't use the pre-built images due to access issues on the work network.
`# Dockerfile.python

[snipped basic construction from redhat ubi]

COPY output/python.tar.gz /

RUN mkdir -p /usr/local/src/python && \
    tar -zxf python.tar.gz -C /usr/local/src/python --strip-components=1 && \
    cd /usr/local/src/python && \
    ./configure \
      --enable-loadable-sqlite-extensions \
      --enable-optimizations \
      --enable-option-checking=fatal \
      --with-system-expat \
      --with-ensurepip && \
    make && \
    make altinstall

[snipped a bunch of subsequent construction that runs if the previous lines run, and isn't reached if they fail.]


text:
Q: How to work with large projects I am working on a project and i want to slim it down a litle so please help me with the
following. I have a document structure like this:
/DocumentRoot
 |-main.tex
 |-title.tex
 |
 |-/chapter-1
 |  |-/images
 |  |-chapter-1.tex
 |
 |-/chapter-2
    |-/images
    |-chapter-2.tex

My document is like this:
\begin{document}
\include{./title}
\include{./chapter-1/chapter-1}
\include{./chapter-2/chapter-2}
\include{./chapter-3/chapter-3}
\end{document}

in my chapters i use both some images and some heavy tikz plots so i use externalize and
draft options for quicker compilation. But i want the images to be placed in the respective
chapter folders but for example in chapter 3 this works:
\includegraphics[width=\linewidth]{./chapter-3/images/img.jpg}

and this doesn't
\includegraphics[width=\linewidth]{./images/img.jpg}

for some reason xelatex has problems with the relative paths of included chapters. I also want to control the location output and the naming of the externalized tikz documents. Any help with that? I am working with miktex and texworks.

A: The idea is simple, just prepare directory paths (to import both chapter files and images files) whenever you include a new chapter.
Main.tex
\documentclass{book}
\usepackage{graphicx}

\def\Include#1{%
        \def\ChapterPath{#1/}%
        \def\GraphicsPath{\ChapterPath Images/}%
        \include{\ChapterPath#1}}

\newcommand\IncludeGraphics[2][width=\linewidth]{%
    \includegraphics[#1]{\GraphicsPath #2}}

\begin{document}
    \Include{Chapter-1}
\end{document}

Chapter-1.tex
\chapter{Chapter One}

\IncludeGraphics[width=0.5\linewidth]{Tulips}

Remarks:

*

*Folder Chapter-1 is in Docoment-Root folder.

*Chapter-1.tex is in folder Chapter-1.

*Tulips.jpg is in  folder Chapter-1/Images.
Tips

*

*If your TikZ code is not "linked" to the text with nodes, for example, then put such TikZ code into a separate, compilable input file. Use article document class plus preview to get a tight PDF output. You can also use standalone document class instead.

*If you table is not long enough to span across multiple pages, then put it into a separate, compilable input file to get a tight PDF output.

*It is better not to specify the image extension explicitly when invoking \includegraphics.

*Define macros for often-used materials and put them into a package such that you can change their definition later in one place and the changes effect the whole document.


text:
Q: combine jquery elements, hiding submit button until a field changes This is probably simple to solve, but today the brain isn't playing ball. I'm trying to hide a submit button until a form element changes. To make things a little more complicated, one of the form fields is a google places autocomplete field.
Thanks to SO I was able to find a solution for hiding the submit button, adapted it a little to produce the following:
var $inputs = $('#searchform :input');
  $('.submits').hide()
  $inputs.on('keyup change', function() {
    $('.submits').show();
    $('.submithide').hide();
});

However, this didn't show the submit button when the user clicked inside the google places autocomplete field and selected a new place (without pressing a key). So, a little more searching on SO and I found that I had to call an addListener event. I have the following jquery to handle this:
var $inputs = $('#searchform :input');
  $('.submits').hide()
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
     $('.submits').show();
     $('.submithide').hide();

});

I have tested both these jqueries by themselves and they work perfectly, but the question is, how do I combine both so that all changes (place_changed, change and keyup) are recognised? I have tried:
var $inputs = $('#searchform :input');
  $('.submits').hide()
  google.maps.event.addListener(autocomplete, 'place_changed', function());
  $inputs.on('keyup change place_changed', function() {
    $('.submits').show();
    $('.submithide').hide();
});

with zero luck. can someone point me in the correct direction? many thanks !

A: You can store a function inside a variable, then just pass the variable through as the callback function.
var toggleSubmits = function() {
    $('.submits').show();
    $('.submithide').hide();
}

google.maps.event.addListener(autocomplete, 'place_changed', toggleSubmits);
$inputs.on('keyup change', toggleSubmits);


text:
Q: How to disable submit form in Dropzone.js while files are auto uploading I am using dropzone.js working fine for me. It upload files automatically that's cool.....
Now I have a problem, I want to disable submit form button till it upload all the files to the server....
I have called Dropzone with basic code....
jQuery(function () {

                            Dropzone.autoDiscover = false;
                            var myDropzoneOptions = {
                                maxFilesize: 15,
                                addRemoveLinks: true,
                                acceptedFiles: 'image/*, .pdf, .doc, .docx,.xls,.xlsx,.csv,.txt',
        //                                acceptedFiles:'image/* , text/pdf ,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation',
                                clickable: true,
                                url: "<?php bloginfo('siteurl') ?>/?my_upload_of_task_files2=1",
                            };

                            var myDropzone = new Dropzone('div#myDropzoneElement2', myDropzoneOptions);

                            myDropzone.on("sending", function (file, xhr, formData) {
                                formData.append("author", "<?php echo $cid; ?>"); // Will send the filesize along with the file as POST data.
                                formData.append("ID", "<?php echo $pid; ?>"); // Will send the filesize along with the file as POST data.
                            });

`
etc that upload files to server....
and sample submit form in HTML
 <form action="..">
  <input type="submit" value="download" />
</form>

A: You can use the onsending and queuecomplete events to toggle the disabled attribute on the form submit button.
For example:
myDropzone.on("sending", function (file, xhr, formData) {
    // Disable the submit button
    $(":submit").prop("disabled", true);
    formData.append("author", "<?php echo $cid; ?>"); // Will send the filesize along with the file as POST data.
    formData.append("ID", "<?php echo $pid; ?>"); // Will send the filesize along with the file as POST data.
});

myDropzone.on("queuecomplete", function ( ) {
    // Re-enable the submit button
    $(":submit").prop("disabled", false);
});

A: combine https://www.dropzonejs.com/#dropzone-methods
and submit
$(form).submit(function () {
  if (youDropZone.getUploadingFiles().length != 0) {
    return false;
  }
  // if your file field is required additional check if .getAcceptedFiles() == 0
  // if (
  //   youDropZone.getUploadingFiles().length != 0
  //   || youDropZone.getAcceptedFiles() == 0
  // ) {
  //   return false;
  // }
})


text:
Q: Not able to update the version of tensorflow I am facing the below error while running the code for LinearClassifier in tensorflow.
AttributeError: module 'tensorflow.python.estimator.estimator_lib' has no attribute 'LinearRegressor'
My current version for tensorflow is 1.2.1. I tried to update the version of the package from ANACONDA environment, its not showing for an upgrade.
I tried to upgrade it from command prompt by using below command, it is successfully updating the package however it is not reflecting to the actual library when I am using it.
pip install --upgrade tensorflow==1.3.0
FYI, I am using Jupyter Notebook and have created a separate environment for tensorflow.
Please let me know if I have missed anything.

A: If your command pip install --upgrade tensorflowcompiles, then your version of tensorflow should be the newest. However you should restart your notebook. Also, as you said that you are using anaconda. You can also install and upgrade tensorflow as follows:
 conda install -c conda-forge tensorflow  # to install
 conda upgrade -c conda-forge tensorflow  # to upgrade

A: That should work. Check if you are using any environment but you are not updating the tensorflow version within the environment.
Also, please restart the notebook after saving it and run the cells and try. That should work.
Verify in the notebook : run - print(tf.__version__). Please mark the answer if it resolves.