text:
Q: Unable to inject @Stateless EJB into CDI bean (multi-module) Jakarta EE 8 Migrating a legacy project to Jakarta EE 8 (Maven EAR build on Wildly 26) I am struggling to get the dependancy injection working from my Entities module (EJB packaging) to WAR module, the maven project structure is:
-WebApp.ear
    -WebApp-entities.jar
    -WebApp-ejb.jar
    -WebApp-web.war
    -WebApp-mobile.war
    -WebApp-api.war

The structure was created based on the wildfly-jakartaee8-with-tools archetype
My DAO to be injected is a @Stateless bean that uses @LocalBean no-interface eg.
@Named
@LocalBean
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class UserDAO extends GenericDAOBean<User,Long> {

    @PersistenceContext(unitName="ReadOnlyDatabase")  private EntityManager readOnlyEntityManager;

    /**
     * Default constructor
     */
    public UserDAO() {
        //Super call to construct AbstractDAO
        super();
    }

    public User findNonDeletedByEmail(String email){
        String s = "from User where email = :email and disabled = false";
        Query query = this.getEntityManager().createQuery(s);
        query.setParameter("email", email);
        try{
            return (User)query.getSingleResult();
        }catch(NoResultException nre){
            return null;
        }catch(Exception e){
            return null;
        }
    }

}

My CDI bean is a standard @RequestScoped bean in the WAR module that is attempting to inject the DAO to perform login
@Named
@RequestScoped
public class LoginBean implements Serializable {

private static final long serialVersionUID = 1504441323094295359L;

@Inject private SecurityContext securityContext;
@Inject private UserDAO userDAO;
@Inject private FacesContext facesContext;
@Inject private ExternalContext externalContext;

private String username, password;

public void login() throws IOException {

    Credential credential = new UsernamePasswordCredential(username, new Password(password));

    User user = userDAO.findByEmailForUserLogin(username);
   AuthenticationStatus status = securityContext.authenticate(
           getRequest(facesContext),
           getResponse(facesContext),
           AuthenticationParameters.withParams()
                   .credential(credential));

   switch (status) {
       case SEND_CONTINUE:
           facesContext.responseComplete();
           break;
       case SEND_FAILURE:
           facesContext.addMessage(null,
                   new FacesMessage(FacesMessage.SEVERITY_ERROR, "Login failed", null));
           break;
       case SUCCESS:
           facesContext.addMessage(null,
                   new FacesMessage(FacesMessage.SEVERITY_INFO, "Login succeed", null));
           externalContext.redirect(externalContext.getRequestContextPath() + "/user/home.xhtml");
           break;
       case NOT_DONE:
   }

}

private static HttpServletResponse getResponse(FacesContext context) {
   return (HttpServletResponse) context
       .getExternalContext()
       .getResponse();
}

private static HttpServletRequest getRequest(FacesContext context) {
   return (HttpServletRequest) context
       .getExternalContext()
       .getRequest();
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

}
When I call the login() method from JSF page I get the following error:
Target Unreachable, identifier 'loginBean' resolved to null: javax.el.PropertyNotFoundException

If I comment out the userDAO injection the method calls ok so I know its the UserDAO causing the problem, there are no other errors
In the server startup logs I can see that UserDAO is registered ok eg:
    java:global/WebApp/Web-entities/UserDAO!com.webapp.dao.beans.UserDAO
java:app/Web-entities/UserDAO!com.webapp.dao.beans.UserDAO
java:module/UserDAO!com.webapp.dao.beans.UserDAO
java:global/WebApp/Web-entities/UserDAO
java:app/Web-entities/UserDAO
java:module/UserDAO

I have beans.xml defined in /web-inf/beans.xml (war) and /meta-inf/beans.xml (jar) both with bean-discovery-mode="annotated"
My EJB module is included as a maven dependancy in the WAR .pom with <scope>provided</scope>
I have also tried injecting using @EJB have the same error
UPDATE:
I found that by setting <ear-subdeployments-isolated>false</ear-subdeployments-isolated> in boss-deployment-structure.xml allows injection to work however this then creates issues with dependancies being duplicated across modules and class-path errors so I don't think its the right solution (our legacy EE 6 project had EAR deployments isolated and the DI worked ok)

A: Eventually got this working by adding module dependancies to the EJB and Entity modules in jboss-deployment-structure.xml as below...
<sub-deployment name="WebApp-web.war">
    <dependencies>
        <module name="deployment.WebApp.ear.WebApp-entities.jar" />
        <module name="deployment.WebApp.ear.WebApp-ejb.jar" />
    </dependencies>
  </sub-deployment>

Injection into the WAR now works ok, this was not required in the legacy EE 6 / JBoss 7 app so the class loading behaviour must have changed


text:
Q: LSI MegaRaid 9260-8i low performance in comparison I was given the task (aka dumped into my lap) to examine low Read/Write performance on a system running Server 2012 R2 /w HyperV role.
The system in question:
Lenovo RD340
LSI MegaRaid 9260-8i (no BBU)
    -Drive Group 0 consisting of 2 SAS Drives, each 279.397 GB, RAID1
    -Drive Group 1 consisting of 3 SAS drives, each 558.912 GB, RAID5
Virtual machines are stored on drive group 1.
VMs: Two domain controllers, a terminal server & an application server
It seems that read/write performance for drive group 1 is quite low. For example, when I try to export one of the VMs via HyperV Export onto the same drive (BYA: necessary for scripted exports), the max throughput is around 25~30 Megabytes/s. Seems low, especially in comparison to another system (Lenovo TD340 with LSI 9260-8i (with BBU)) where such an export nets around at least 150 MB/s and more.
Any idea what I should look out for to maximize performance?
Further settings for drive group 1:

*

*Strip size 64 KB

*Read Policy: No Read Ahead

*IO Policy: Direct IO

*Current write Policy: Write Through

*Default Write Policy: Writhe Through

*Current Access Policy: Read Write

*Default Access Policy: Read Write

The "control group" drive group on the RAID controller in the TD340:

*

*strip size 256 KB

*Read Policy: Always Read Ahead

*IO Policy: Direct IO

*Current Write Policy: Write Back

*Default Write Policy: Write Back with BBU

*Current Access Policy: Read Write

*Default Access Policy: Read Write

Thanks a lot!

A: From my measurements done a while ago on 9240 and 9260 LSI Megaraid cards in UCS servers the I/O perfomance using RAID 5 and 6 was significantly lower than in RAID 0 or 10, everything else being the same.
My suggestions would be (depending on the tolerance to failures in your context) either:

*

*switching to RAID 0 (best I/O performance)

*adding a 4th drive and switching to RAID 10

Using WriteBack instead of WriteThrough will boost write (and, depending on usage, even read) performance, regardless of the RAID type. It needs to be specifically enabled if you don't have a BBU or if it goes bad. A BBU is highly recommended :)
Finally I second @SteffenNielsen's comment about the write cache, also regardless of the RAID type.

redpajama_set_name: RedPajamaStackExchange


text:
Q: using if statements with command line parameters in c I am having trouble with getting my if statements to work with parameters from the command line. I get an error saying, 'comparison between pointer and integer ('char *' and 'int')' every time. Any help will be greatly appreciated. Here is the description for what I have to do:
This program will read a parameter from the command line and translate it to the name of the corresponding month.  I.e. if you run the program with the following parameter:
It will print the following message:
The month is 'April'.
#include <stdio.h>

int main(int argc, char *argv[]) {
    if(argv[1] == 1){
        printf("You entered the number 1.");
    } else {
        printf("You entered a different number.");
    }

    return 0;
}

A: The parameters passed on the command line are strings, so you need to use strcmp to compare them.
int main(int argc, char *argv[]) {
    if(argc > 1 && (strcmp(argv[1],"1") == 0)){
        printf("You entered the number 1.");
    } else {
        printf("You entered a different number.");
    }

    return 0;
}

A: Compiler is right - you are comparing char * and int.
You have to either convert argv[1] to int (e.g. with strol()) or convert 1 to char * (by adding quotes - "1") and then compare with strcmp() instead of ==.
And checking number of arguments in argc is also something you should do, when working with arguments. (thanks @Ingo Leonhardt)

A: Argv returns pointer to array of chars, so your programm must looks like:
 #include <stdio.h>

    int main(int argc, char *argv[]) {
        if(argv[1][0] == '1'){
            printf("You entered the number 1.");
        } else {
            printf("You entered a different number.");
        }

        return 0;
    }

Or you can use atoi (man 2 atoi) function to convert ascii array to int like this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
    if(atoi(argv[1]) == 1){
        printf("You entered the number 1.");
    } else {
        printf("You entered a different number.");
    }

    return 0;
}

A: If you want to use your command line parameter like a integer, you must modify the type with atoi
#include <stdio.h>

int main(int argc, char *argv[]) {
    if(atoi(argv[1]) == 1){
        printf("You entered the number 1.");
    } else {
        printf("You entered a different number.");
    }

    return 0;
}


text:
Q: javascript indexOf always returning -1 making (lame) game, and i want to check if selected square contains a monster, however my indexOf keeps returning -1. relevant code below.
intialization:
var monsters = [];

var monsterPositions = [2,8,13,15,22];

var player = { "currentPosition": 0 };

for ( var i in monsterPositions ) {
    monsters[i] = new createMonster("monster",monsterPositions[i],1); }

function createMonster(name,startingPoint,level) {
    this.currentPosition = startingPoint; }

function triggered with <td> onclick:
function processClick(trigger){
    console.log( trigger.id + " " + monsterPositions );
    if ( monsterPositions.indexOf(trigger.id) >= 0 ){
        if ( !fight( findMonster( parseInt( trigger.id ) ) ) ){
            return;
        }
    }
    if ( gameOn ) move( parseInt( trigger.id ) );
}

the page always goes straight to move(), even when  it is a monster spot, here is console.log() results:
1 2,8,13,15,22 adventure.js (line 79)
2 2,8,13,15,22 adventure.js (line 79)
7 2,8,13,15,22 adventure.js (line 79)
8 2,8,13,15,22 adventure.js (line 79)
13 2,8,13,15,22 adventure.js (line 79)
18 2,8,13,15,22 adventure.js (line 79)
23 2,8,13,15,22 adventure.js (line 79)
22 2,8,13,15,22 adventure.js (line 79)
21 2,8,13,15,22 adventure.js (line 79)
20 2,8,13,15,22 adventure.js (line 79)
15 2,8,13,15,22 adventure.js (line 79)

(link here if above code isnt enough), and im stumped help please.(of course why else would i be here)

A: trigger.id is probably returning a string where your array is full of numbers.
This jsfiddle shows that in action as well as it working with a Number and how to convert your string IDs to numbers using parseInt().

A: try this
 if ( monsterPositions.indexOf(Number(trigger.id)) >== 0 )


text:
Q: Swift Triggering Segue upon special if else conditions I've followed documentation briefly and this is what I have so far:
ViewController.swift
 let x = "Registered!";
 let y =  jsonData.value(forKey: "results") as! String?;
 let isEqual = (x == y)
 print(isEqual) // Gives me true or false works as expected
 if(isEqual==true){
  self.performSegue(withIdentifier:"Test", sender: self);

}

I'm trying to see if a condition is true; then execute the Segue.
I've created Segue in my storyboard like this.
I have two View Controller.
First View and Second View.
I then pressed cntrl and dragged the button from first view to second view creating a Segue.
I then gave my Segue a unique identifier "Test"
However; I want to only execute the new view only if the statement is true or else void it and throw an error message; however my segue seems to be working; it redirects to my second page weather the condition is true or not.
I also made sure; that my second view has a class and it's been set-up properly. No idea; why it keeps redirecting user to another view regardless of the statement. What could I have possibly done wrong?

A: The thing is that your segue is from Button to ViewController. You should drag and drop the segue with same identifier from ViewController to ViewController. Not from Button to ViewController


text:
Q: How to do a delay on a for loop that makes dynamic number of div's on JavaScript? I'm trying to do a delay on each iteration on a Script that makes dynamic div's based on elements of an array that has some links to images on it, to achieve some kind of effect like the one in GameCube console intro where a div appears one by one and not all at the same time.
i've tried with setTimeout() and Async functions but they just dont work

var arraydas  = ["aviso1.jpg","aviso2.jpg","a","s","s",2,3,4];

var array = ["sYDqBU1.jpg","t1LuvGZ.jpg","l660ATK.jpg","iNWWr7b.jpg"]

var htmlElements = "";
for (var i = 0; i < array.length; i++) {
   htmlElements += '

';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
html,body {
    width: 100%;
    height: 100%;
}

#container {
    height: 100%;
    background-color: black;
}

.box {
    width: 25%;
    height: 25%;
    background-color: red;
    float:left;
}

A: The solution is to use a timer and not a loop. Because the timer will run over and over, it creates the effect of a loop, but with the added benefit of doing it on your time scale.

var array = ["sYDqBU1.jpg","t1LuvGZ.jpg","l660ATK.jpg","iNWWr7b.jpg"]

// This will keep track of the currently displayed array index
let counter = 0;

let container = document.getElementById("container");

function makeDiv(){
  // If we've reached the end of the array, stop the timer
  if(counter >= array.length-1) { clearInterval(timer); }

  // Don't build HTML strings, create DOM elements
  let div = document.createElement("div");

  // Configure their properties
  div.classList.add("box");

  let img = document.createElement("img");
  img.src = "https://i.imgur.com/" + array[counter];

  // And append them to the DOM
  div.appendChild(img);
  container.appendChild(div);

  // Increase the counter
  counter++;
}

// Start the timer
let timer = setInterval(makeDiv, 1000);
html,body {
    width: 100%;
    height: 100%;
}

#container {
    height: 100%;
    background-color: black;
}

.box {
    width: 25%;
    height: 25%;
    background-color: red;
    float:left;
}

div > img { width:100%;  }

  Hola kaskdkasdkasdk

A: I would continue to use setTimeout to control the delay you want to apply. The function should determine if we need to keep processing more array items:
Snippet

var array = ["sYDqBU1.jpg", "t1LuvGZ.jpg", "l660ATK.jpg", "iNWWr7b.jpg"]

var container = document.getElementById("container");

var current = 0;

function getEm() {
  const div = document.createElement('div');
  setTimeout(() => {
    div.innerHTML = `<div class="box"><img src="https://i.imgur.com/${array[current]}" width="100%" height="100%"></div>`
    container.appendChild(div);

    current++
    if (current < array.length) {
      getEm();
    }
  }, 500);
}

getEm();
html,
body {
  width: 100%;
  height: 100%;
}

#container {
  height: 100%;
  background-color: black;
}

.box {
  width: 25%;
  height: 25%;
  background-color: red;
  float: left;
}


text:
Q: How to get mobile page address from web page address in crawling? I have made 'crawling tool by python' for personal project and I want to get mobile page address from each web page address.
like transform 'www.youtube.com' to 'm.youtube.com'
I want to know only mobile page address.
Is it possible to get mobile page address without using 'selenium'?

A: There is two way to serve a mobile page.
You can first just check URL. As the example you gave in comments m.youtube.com explicit the fact you are browsing in mobile mode.
But you can check the HTTP header User-Agent too. This header show what browser was used to send query.
The server can extract this info and according to given value can determine if browser is mobile or desktop one.
This will be your main issue here, all web servers does not use the same method to handle mobile templates. Lot of websites use both methods I explained and it will be hard to create a generic scraper that find alone how to access to mobile template.
Si what you can do:
Use a mobile browser with selenium: https://github.com/SeleniumHQ/selenium/wiki/WebDriver-For-Mobile-Browsers
Or
If you want to dynamically switch from desktop to mobile, play with user-agent: Change user agent for selenium driver


text:
Q: RequireNativeComponent: "ToolbarAndroid" was not found in the UIManager I followed the steps of the installation tutorial toolbarAndoid and the implementation tutorial expo, but when running on the android application the following stack appears:
InvariantViolation: requireNativeComponent: "ToolbarAndroid" was not found in the UIManager.

This error is located at:
   in ToolbarAndroid (at ToobarAndroid.android.js:228)
   in ToolbarAndroid (at ToobarAndroid.android.js:242)
   in FowardRef (at Main.js:9)
   in Main (created by SceneView)
   in SceneView (created by Drawer)
   in RCTView (created by ResourceSavingScene)
   ...

I'm using:

*

*Expo 37.0.3 (SDK37)

*React Native: 0.61.4

*React Navigation: 4.3.9

*App Expo Client version: 2.15.4


text:
Q: How to Optimize A query with Join I have a query which applies inner join on 540 million records table. This query took time more than 9 hrs.
I want to optimize the query, how can I handle that.
Query is-
Delete top(1000)
FROM table1 fact
INNER JOIN
table2 uu
ON uu.User1 = fact.User1
Where uu.Is_Archived$ = 'true'
and fact.Snapshot_Date$Snapshot_Date$ > uu.User_End_Date$

Columns used in join are integers and both columns have same data type. and there has many invalid number of records.
Any help would be great. Thanks!!!

A: Assuming that your delete is really:
Delete top(1000) from fact
    FROM table1 fact INNER JOIN
         table2 uu
         ON uu.User1 = fact.User1
     Where uu.Is_Archived$ = 'true' and
           fact.Snapshot_Date$Snapshot_Date$ > uu.User_End_Date$;

Then indexes should help the query.  One possibility is:  table1(Snapshot_Date$Snapshot_Date$, User1) and table2(User1, IsArchived$).  Another is table2(IsArchived$, User1) and table1(User1, Snapshot_Date$Snapshot_Date$).


text:
Q: Input type text with array Here is what i'm doing so far. I'm printing with AJAX some checkboxes and some text inputs.
1 checkbox and 1 input text for each plauer (from a DB).
Problem is when i submit the data to another php file i only see both for certain cases.
Below is the code i'll explain more.
PHP called by AJAX
if($_GET['function']=="chkplayers")
{
     $sql=mysql_query("SELECT * FROM tbl_Player ORDER BY team_name")
     or die(mysql_error());
     $i = 1;
        echo'Players : ';
        echo '
';
     while ($row = mysql_fetch_array($sql)) {
        echo '<input type="checkbox" name="chk_player[]" value="'.$row['player_id'].'" /> '.$row['player_name'].' in team '.$row['team_name'];
        echo '<input type="text" name="chk_target[]" placeholder="Target Name"/>
';
    $i++;
  }

}

PHP called on submit
if (isset($_POST['chk_player']) && isset($_POST['chk_player'])) {
    $optionArray = $_POST['chk_player'];
    $optionArrayTarget = $_POST['chk_target'];
    for ($i=0; $i<count($optionArray); $i++) {
        echo "i :";
        echo $i;
        echo "Player : ";
        echo $optionArray[$i];
        echo "Target : ";
        echo $optionArrayTarget[$i];
        echo '
';

    }
}

If i check every box in a row (not leave empty checkboxes in between) it shows up fine.
Example:
i :0Player : 15Target : A1
i :1Player : 18Target : A2
i :2Player : 14Target : A3

If i leave a box unchecked and then check some more i get this
i :0Player : 15Target : A2
i :1Player : 16Target :

Anyway way i can fix this?
If i look for $optionArrayTarget i get
i :0Player : 15Target : A1
i :1Player : 14Target :
i :2Player : 12Target : A2
i :3Player : 13Target :
i :4Player : Target : A3
i :5Player : Target : A4
i :6Player : Target :
i :7Player : Target :

A: Instead of looping till $optionArray loop till optionArrayTarget
if (isset($_POST['chk_player']) && isset($_POST['chk_target'])) {
   $optionArray = $_POST['chk_player'];
   $optionArrayTarget = $_POST['chk_target'];
   for ($i=0; $i<count($optionArrayTarget); $i++) {
     if (isset($optionArrayTarget[$i]) || trim($optionArrayTarget[$i])!=''){
         echo "i :";
         echo $i;
         echo "Player : ";
         echo $optionArray[$i];
         echo "Target : ";
         echo $optionArrayTarget[$i];
         echo '
';
    }
  }
}

so that based on that checked values you can print player and targets, else for every Player present at index 'X' there may be or may not be a Target.
EDITED: One more thing i observed, if (isset($_POST['chk_player']) && isset($_POST['chk_player'])) { the second condition should have been  chk_target instead of chk_player
Happy Coding :)

A: I managed to figure it out. Basically im using array_filter first to remove the empty values then array_values to reorder them and vuala. Thank you for your ime –
if (isset($_POST['chk_player']) && isset($_POST['chk_target'])) {
 $optionArray = $_POST['chk_player'];
 $optionArrayTargetsB4 = array_filter($_POST['chk_target']);
 $optionArrayTargets = array_values($optionArrayTargetsB4);
 for ($i=0; $i<count($optionArray); $i++) {
   .....
  }
}

A: i used array_filter first to remove the empty values then array_values to reorder them and vuala.


text:
Q: passing session value in Wordpress post url I have a post in wordpress.
[insert_php]

$_SESSION[ref_no] =1001;

global $wpdb;
$query = $wpdb->get_var("SELECT name FROM table_reg WHERE ref_no = $_SESSION[ref_no]");
echo $query;

[/insert_php]

This post have an URL:http://localhost/wp/?p=123
What i want is, when an user data is stored in a database table from a form, a message need to generate as an email using wp_mail() with the above url to the user, from which user can download the above "post" data as pdf using the session variable as ref_no .
I was lacking in generating pdf file from the url.
I have tried to write the code below for that.But failed.
[insert_php]
$_SESSION[ref_no] =1001;
$dateTime=date('Y-m-d H:i:s');
$multiple_to_recipients = array(user@eg.com);
$subject = 'You Have registered for DATA on '. $dateTime ;

$message = "Download your registration details by clicking this link: http://localhost/wp/?p=123\n";
$message .= "Email Us:admin@eg.com \n";

$headers = array(
'From: admin@eg.com'

);

wp_mail( $multiple_to_recipients, $subject, $message, $headers );
[/insert_php]

Please help me.


text:
Q: discontinuous predictions time series model I am trying to predict patient census by hour for a hospital and the historical data provided to me is in hourly format.  The issue however is that the there is a discontinuous region between the end of the historical data and the beginning of the first time value in the prediction period.  For example, I am given historical data from [1/1/2020,10/15/2021], and from this data my first predicted point forecast is 12/1/2021 at 12AM.  ARIMA models require the first predicted point period t+1 to be the end of the training period at time t, however clearly with this gap region I cannot use ARIMA.  ARIMA also has issues with long-term forecasting at short intervals asymptotic convergence.
In my research in time series modelling I have not encountered this gap issue before, most models will train and then predict the first prediction point as the next point following the end of the training interval.


text:
Q: What am I missing on this spyder Loan Calculator? I´m learning Python at one of my college classes and I was asked to create a "Loan Calculator".... I might have an idea but I´m not sure how to fix an error that I´m getting  TypeError: 'float' object is not subscriptable
This is the announcement
The user has to enter the cost of the loan, interest rate and the number of years of the loan.
Calculate the monthly payments with the following formula:
M = L[i(1+i)^n]/[(1+i)^(n)-1]
Data:
M = monthly payment
L = loan amount
i = interest rate (remember that 5%, i = 0.05)
n = number of payments

And this is my code:
# Loan Calculator
# Equation: M = L[i(1+i)^n]/[(1+i)(n)-1]

print("Loan Calculator")
L = float(input("Loan amount: "))
i = float(input("Interest rate: "))
# Remember: 5% ---> i=0.05
n = float(input("Number of payments: "))
M = (L[i*(1+i)**n]/[(1+i)**(n)-1])
# M = Monthly payment

print("Monthly payment: " + M)

PS: I first thought I was missing convert "M" into a string, but after I changed to
print("Monthly payment: " + str(M))

I'm still getting the same error... Please help!

A: Needed a few changes:
# Loan Calculator
# Equation: M = L[i(1+i)^n]/[(1+i)(n)-1]

print("Loan Calculator")
L = float(input("Loan amount: "))
i = float(input("Interest rate: "))
# Remember: 5% ---> i=0.05
n = float(input("Number of payments: "))
M = L*(i*(1+i)**n)/((1+i)**(n)-1)
# M = Monthly payment

print("Monthly payment: " , M)

Using some arbitrary values:
Loan Calculator
Loan amount: 1000
Interest rate: 9
Number of payments: 100
('Monthly payment: ', 9000.0)


text:
Q: c++ library refrencing compiler error this is a easy question but i cant seem to find the issue
    #include <iostream>
namespace utils {
    class IntList {
      public:
        IntList();                         // constructor; initialize the list to be empty
        void AddToEnd(int k);              // add k to the end of the list
        void Print(ostream &output); // print the list to output

      private:
        static const int SIZE = 10;      // initial size of the array
        int *Items;                      // Items will point to the dynamically allocated array
        int numItems;                    // number of items currently in the list
        int arraySize;                   // the current size of the array
    };
}

here i have defined a class in my header file
but it throws a compiler error saying that it cannot find a reference to ostream

A: The class from the stl are in the namespace std.
So, unless you are doing using namespace std, you have to prefix them with std::. In your case you should be writing std::ostream.

A: You are missing the std:: in front of ostream.
You can either :

*

*use the whole namespace before your class definition : using namespace std; ;

*mark that you'll be using std::ostream : using namespace std::ostream; ;

*or write std::ostream everywhere you need to use it.

A: you can also add using namespace std before calling ostream


text:
Q: Joomla 3 Component - Upload Image and Convert with Imagick I am currently creating a component, where a user creates a new image and there's an upload button and a name input, all the basic gallery fields for an Image..
But I have come across two issues, the one is how would i write the following code so that it exports one image b/w and the other color scaled to amax width of 160, Here's the code I have:
function save(){
    if(!defined('DS')) define('DS', DIRECTORY_SEPARATOR);
    $input=JFactory::getApplication()->input;
    $input->get('jform', NULL, NULL);

    $file = JRequest::getVar('jform', null, 'files', 'array');
    $data = JRequest::getVar( 'jform', null, 'post', 'array' );
    $path = JPATH_ROOT;

    //
    //

    // Make the file name safe.
    jimport('joomla.filesystem.file');
    $file['name']['logo'] = JFile::makeSafe($file['name']['logo']);

    // Move the uploaded file into a permanent location.
    if (isset($file['name']['logo'])) {
        // Make sure that the full file path is safe.
        $filepath = JPath::clean($path. DS ."images". DS ."associations". DS . strtolower($file['name']['logo']));
        // Move the uploaded file.
        JFile::upload( $file['tmp_name']['logo'], $filepath );
        $data['logo'] = strtolower( $file['name']['logo'] );
        //convert image
        $image = $filepath;

        $im = new Imagick();
        $im->pingImage($image);
        $im->readImage( $image );

        $im->setImageResolution(72,72);
        $im->resampleImage(72,72,imagick::FILTER_UNDEFINED,1);
        $im->scaleImage(160,0);

        $im->setImageFormat('jpeg');
        $im->setImageCompression(imagick::COMPRESSION_JPEG);
        $im->setImageCompressionQuality(60);

        $im->modulateImage(100, 0, 100);
        $im->writeImage($image);
        $im->destroy();
    }

    $input->post->set('jform',$data);

    return parent::save();
}

And Finally, How Would I manage this? it saves the image name in the database but once i return to this item it just has an upload field, where it would be rather useful to have the image name or the actual image with a delete function showing and a reupload...
Am I going the right way about this?... Any Help Greatly Appreciated... Thank you :)

A: How to produce 2 images
You have to create 2 resources out from the uploaded original, transform each and save in the separate file. For example I'be using the JImage package (note there's no limitcolors filter available)
$image_one = new JImage($filepath);
$image_one
    ->filter('grayscale')
    ->toFile($path_one, IMAGETYPE_JPEG, array('quality' => 60));

$image_two = new JImage($filePath);
$image_two
    ->filter('limitcolors', array('limit' => 160))
    ->toFile($path_two, IMAGETYPE_GIF);

Managing images
Depends on the reason, why there"s functionality being implemented and so relation of the uploaded image to other objects/ events.
If the uploaded images are used for user profiles, you should store a user id in the database along with image location. Next time check if current users has any images related to his/ her account and display.


text:
Q: How do I call a classes method from another class without initialising the first class? I have something like the following:
class Class1(object):
    def __init__(self):
        print('I've init-ed')
    def print_me(self, string):
        print(string)

class Class2(object):
    def __init__(self):
        print('Class 2 init')
    def print_me_from_other_class(self, string):
        Class1().print_me(string)

And then if I call something like:
test = Class2()
test.print_me_from_other_class('TEST')

then I get:
Class 2 init
I've init-ed
TEST

What I want to do is call the method from Class1 from the method in Class2 but without calling the init from class 1. So I'd end up with:
Class 2 init
TEST

I've tried removing the brackets after Class1 in the print_me_from_another_class(self, string) function so it says:
print_me_from_another_class(self, string):
    Class1.print_me(string)

But that throws the error:
TypeError: print_me() missing 1 required positional argument: 'string'

Any ideas? Or is this a bad way to go about things? Seems like it will save rewriting code so should be a good thing.
EDIT:
I've worked out I need to pass the instance of Class2 to the function so that the function in Class2 becomes:
def print_me_from_other_class(self, string):
    Class1.print_me(self, string)

And it works! But I still want to know if this is a good way of doing things?

A: Note the "self" argument in print_me - this means that the function must be called on a specific instance of Class1.  What you want is a static function.  The code below demonstrates this.
class Class1(object):
    def __init__(self):
        print("I've init-ed")
    @staticmethod
    def print_me(string):
        print(string)

class Class2(object):
    def __init__(self):
        print('Class 2 init')
    def print_me_from_other_class(self, string):
        Class1.print_me(string)

test = Class2()
test.print_me_from_other_class('TEST')

Output:
Class 2 init
TEST

A: The problem with your code block is Class1.print_me(string) creates new object, thats why init method is get called to avoid this. The simple solution is to use the inheritance.
class Class1(object):
    def __init__(self):
        print('Ive init-ed')
    def print_me(self, string):
        print(string)

class Class2(Class1):
    def __init__(self):
        print('Class 2 init')
    def print_me_from_other_class(self, string):
        self.print_me(string)
obj=Class2()
obj2.print_me_from_other_class("hi")

you can directly call the base  class function as well
    obj2.print_me("hello")

A: has you tried with @staticmethod ? something like:
class C1:
 def __init__(self):
  print "C1 INIT"
 def f(self):
  C2.c()

class C2:
 def __init__(self):
  print "C2 INIT"
 @staticmethod
 def c():
  print "method c from C2"

The @staticmethod decorator is for make static methods, in general this kind of methods are usefull when you want to call a method wothout initialize the class. Is a good approach for organize the functions.

A: SOLUTION
Thanks all for your help, I have a better understanding of it now. What I did in the end as suggested in comments was to remove these particular methods from the classes and make them global functions. I actually went through and removed all methods that weren't specifically referencing self (or made sense to leave them as class methods) and made them global. Looking at it now I think this is a better way to structure the code.
Thanks all.


text:
Q: Почему вызов boost::interprocess::scoped_lock lock{ мьютекс }, не даёт выполняться следующим за ним строкам кода? Пишу на C++ в Visual Studio 2019 Community приложение межпроцессного взаимодействия с использованием boost::interprocess::managed_shared_memory. Процесс-сервер представляет собой консольное приложение C++, а процесс-клиент - оконное приложение Win32 API. Проекты обоих приложений находятся в одном решении и оба являются запускаемыми проектами. Порядок сборки - сначала сервер, а потом - клиент и запускаются они в том же порядке. Код взаимодействия процессов выполняется в соответствующей задаче PPL, как на клиенте, так и на сервере. для синхронизации работы клиента и сервера использую boost::interprocess::interprocess_mutex. У меня следующий вопрос: почему, когда я, в пошаговой отладке, дохожу до строки кода
scoped_lock<interprocess_mutex> lock{ *mtx };

(где mtx это указатель на interprocess_mutex) на процессе-сервере либо на процессе-клиенте и в очередной раз нажимаю F10 для выполнения очередного шага, то переход к следующей строке отлаживаемого кода не выполняется, хотя окно приложения, при этом, не зависает. (В окне приложения Win32, являющегося клиентом доступны кнопки.) Но, если я в приложении-клиенте Win32,например, попытаюсь выполнить отмену задачи взаимодействия с сервером, то приложение зависает на строке
operatingSupportTask.wait();

Ниже приводится снипет кода, реализующего отмену задачи взаимодействия с сервером:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
   case WM_COMMAND:
   {
       int wmId = LOWORD(wParam);
       switch (wmId)
       {
          . . . . . . . . . . . . . . .
          case BTN_CANCEL_SEND_FILE:
          {
             // Отменить передачу файла на сервер.
             cancelTokenSource.cancel();
             // Ожидать завершения задачи оперативной поддержки работы клиента
             // после отмены задачи отправки файла на сервер.
             operatingSupportTask.wait(); // !!! ЗДЕСЬ ЗАВИСАЕТ !!!
             . . . . . . . . . . . . . . . .
          }
          break;
          . . . . . . . . . . . . . . .
       }
   }
   . . . . . . . . . . . . . . . . . . . . .
}

где: cancelTokenSource это источник токенов для отмены задачи взаимодействия с сервером, а operatingSupportTask это задача, внутри которой из источника токенов создаётся токен отмены и запускается сама задача взаимодействия с сервером, которой передаётся токен отмены. См. снипет кода взаимодействия клиента с сервером ниже.
Процесс-Клиент; снипет кода для взаимодействия клиента с сервером:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
   case WM_COMMAND:
   {
       int wmId = LOWORD(wParam);
       switch (wmId)
       {
          . . . . . . . . . . . . . . .
          case BTN_SEND_FILE:
          {
                . . . . . . . . . . . . . . . .
                // Отправка файла на сервер.
                operatingSupportTask = create_task([]() {
                // Создать токен отмены для задачи отправки файла на сервер.
                cancelTokenSource = cancellation_token_source();
                cancellation_token token = cancelTokenSource.get_token();
                // Создать и запустить задачу отправки файла на сервер.
                fileSendingTask = create_task([&token]()
                    {
                        // Проверить, была ли отмена задачи.
                        if (token.is_canceled())
                        {
                            cancel_current_task();
                        }
                        else
                        {
                            try
                            {
                                . . . . . . . . . . . . . . . . . . . .
                                // Получить доступ к области общей памяти (shared memory).
                                managed_shared_memory managed_shm{ open_only, "MySharedMemory" };
                                // Получить мьютекс
                                pair<interprocess_mutex*, size_t> mutexPare = managed_shm.find<interprocess_mutex>("mtx");
                                // Получить условие запуска сервера для обработки данных клиента.
                                pair<interprocess_condition*, size_t> condExecPare = managed_shm.find< interprocess_condition>("cond_exec");
                                // Получить условие, извещения клиента о том, что полученные от него данные обработаны и ответ для него готов.
                                pair<interprocess_condition*, size_t> condDonePare = managed_shm.find< interprocess_condition>("cond_done");
                                pair<bool*, size_t> fileTransFlagPair = managed_shm.find<bool>("fileTransferInProgress");

                                // Захватить область общей памяти для выполнения передачи файла в неё.
                                scoped_lock<interprocess_mutex> lock{ *mutexPare.first }; // !!!!
                                // Показать, что выполняется передача файла.
                                *fileTransFlagPair.first = true;
                                // Здесь - непосредственно передача файла в общую память (пока не реализовано).
                                do
                                {
                                    if (token.is_canceled())
                                    {
                                        cancel_current_task();
                                    }
                                } while (true);
                                // По окончанию передачи, уведомить сервер о том, что выполнена передача файла в общую память.
                                condExecPare.first->notify_one();
                                // Ожидать от сервера подтверждения того, что передача файла выполнилась.
                                condDonePare.first->wait(lock);
                                // Показать, что передача завершена.
                                *fileTransFlagPair.first = false;
                            }
                            catch (interprocess_exception& ex)
                            {
                                . . . . . . . . . . . . . .
                            }
                        }
                    }, token);
                // Ожидать окончания задачи передачи файлов.
                fileSendingTask.wait();
                });
             . . . . . . . . . . . . . . . .
          }
          break;
          . . . . . . . . . . . . . . .
       }
   }
   . . . . . . . . . . . . . . . . . . . . .
}

Ниже приводится снипет кода для взаимодействия сервера с клиентом. Этот код находится внутри функции main() консольного приложения C++, которое является процессом-сервером.
Процесс-Сервер; снипет кода для взаимодействия с клиентом:
cancelTokenSource = cancellation_token_source();
cancellation_token token = cancelTokenSource.get_token();
serverTask = create_task([&token]()
    {
        // Проверить, была ли отмена задачи.
        if (token.is_canceled())
        {
            cancel_current_task();
        }
        else
        {
            try
            {
                // Длина создаваемой области общей памяти.
                const int shmLength = 262144;
                // Создать область общей памяти.
                managed_shared_memory managed_shm{ open_or_create, "MySharedMemory", shmLength };
                // Определить:
                // мьютекс для синхронизации,
                interprocess_mutex* mtx = managed_shm.find_or_construct<interprocess_mutex>("mtx")();
                // флаг, показывающий, что клиент выполняет передачу файла в общую память,
                bool* fileTransferInProgress = managed_shm.find_or_construct<bool>("fileTransferInProgress")(false);
                // условие уведомления сервера о том, что клиент завершил передачу файла в общую память,
                interprocess_condition* cond_exec = managed_shm.find_or_construct<interprocess_condition>("cond_exec")();
                // условие, уведомления клиента о том, что сервер подтвердил получение файла, переданного в общую память.
                interprocess_condition* cond_done = managed_shm.find_or_construct<interprocess_condition>("cond_done")();

                scoped_lock<interprocess_mutex> lock{ *mtx }; // !!!!
                while (1)
                {
                    // Проверить, была ли отмена задачи.
                    if (token.is_canceled())
                    {
                        cancel_current_task();
                    }
                    else
                    {
                        // Если выполняется передача файла (пока не реализовано)
                        if (fileTransferInProgress && *fileTransferInProgress)
                        {
                            // Ожидать от клиента уведомления о завершении передачи файла.
                            cond_exec->wait(lock);
                            // Здесь - чтение файла, переданного в общую память.
                            // . . . . . . . . . . . . . . . . .
                            // По окончанию чтения, известить процесс, отправивший файл, что файл был принят и прочитан.
                            cond_done->notify_one();
                        }
                    }
                }
            }
            catch (interprocess_exception& ex)
            {
                . . . . . . . . . . . . . . . .
            }
        }
    }, token);
serverTask.wait();

Почему строка кода
scoped_lock<interprocess_mutex> lock{ *mtx };

так себя ведёт? Почему, когда курсор пошаговой отладки стоит на ней и я нажимаю F10 для выполнения перехода к следующей строке отлаживаемого кода, то этот переход не выполняется? Что я делаю неправильно в своей программе? Пожалуйста, помогите. Буду очень благодарен. Заранее спасибо.

A: В одном процессе мьютекс блокируется и начинается бесконечный цикл, и в другом. Код после while в обоих случаях недостижим. В клиенте разблокировки мьютекса вообще не может случится. А вот ожидание condition variable сделано неверно - как раз там-то и надо крутится в цикле проверяя условие ожидания.


text:
Q: fourier analytic proofs While searching through Mathoverflow, I found out a fourier analytic proof of the Isoperimetric Inequality.Also, by google search I found a fourier analytic proof of Quadratic Reciprocity theorem.I know of the fourier analytic approach used by combinatorialists like Ben Green. But what are the other fourier analytic proofs of some of the well known classical theorems other than what I have mentioned above specially those which admit a starkly different proofs.

A: The sign of the quadratic Gauss sum $\tau$ can be obtained from
the spectrum of the discrete Fourier transform $\Phi$: the trace of $\Phi$
gives $\tau$, and $\det\Phi$ distinguishes $\tau$ from $-\tau$.
Recall that for an odd prime $p$ the quadratic Gauss sum
can be defined by
$$
\tau = \sum_{n=0}^{p-1} \zeta^{n^2}
$$
where $\zeta = e^{2\pi i / p}$.  It is elementary that $|\tau|^2 = p$
and that $\tau$ is real or pure imaginary according as $p \equiv 1 \bmod 4$
or $p \equiv -1 \bmod 4$.  In fact $\tau$ is always $+\sqrt p$
in the former case, and $+i\sqrt p$ in the latter, but this is
notoriously tricky to prove.
One trick is to recognize $\tau$
as the trace of the discrete Fourier transform on ${\bf C}^p$,
which has matrix
$$
\Phi = (\zeta^{mn})_{m,n=0}^{p-1}.
$$
Now $\Phi^2$ is the matrix whose $(m,n)$ entry is $p$ if $m+n \equiv 0 \bmod p$
and $0$ otherwise (this is tantamount to discrete Fourier inversion).
This matrix has eiganvalues $+1$ and $-1$ with multiplicity $(p+1)/2$
and $(p-1)/2$ respectively.  Hence $\Phi$ has eigenvalues $i^k \sqrt p$
($k=0,1,2,3$) with multiplicities $m_k$ satisfying
$m_0 + m_2 = (p+1)/2$ and $m_1 + m_3 = (p-1)/2$, and then
$\tau = \sum_{k=0}^3 m_k i^k \sqrt p$.
Since we already know $\tau$ up to sign there are only two possibilities:
if $p \equiv 1 \bmod 4$ then $m_0$ or $m_2$ is $(p+3)/4$
and the other three $m_k$ are $(p-1)/4$, while
if $p \equiv -1 \bmod 4$ then $m_1$ or $m_3$ is $(p-3)/4$
and the other three $m_k$ are $(p+1)/4$.
We are to show that the odd man out is always
$m_0$ in the former case and $m_3$ in the latter.
In each case we can decide the correct choice by computing the
sign (a.k.a. argument) of $\det \Phi = p^{p/2} \prod_{k=0}^3 i^{k m_k}$.
We can do this because $\Phi$ is a Vandermonde matrix, whence $\det\Phi$
has the product expansion $\prod_{0 \leq m < n < p} (\zeta^n - \zeta^m)$.
Each factor $\zeta^n - \zeta^m$ is a positive real multiple of
$\exp((m+n+\frac12)\pi i)$.  It soon follows that
$\det\Phi = i^{(1-p)/2} p^{p/2}$ (we already knew $\left|\det\Phi\right|$
because each eigenvalue has absolute value $\sqrt{p}$),
and conclude as desired that $\tau = \sqrt{p}$ when $p \equiv 1 \bmod 4$
while $\tau = i\sqrt{p}$ when $p \equiv -1 \bmod 4$.
[This looks like a known but not very well-known argument
that is easier to rediscover than to find in the literature.
What is the original source?]

A: There are two very extensive monographs on this subject, more precisely, its relationship to convex geometry: by Groemer (Geometric applications of Fourier series and spherical harmonics) and Koldobsky (Fourier analysis in convex geometry).

A: Let me speak about the "Triumph of Fourier" according to the words of Laurent Schwartz in his autobiography. The Fourier transformation is a handy tool to characterize regularity of functions.
Let $u$ be a distribution on some open subset $\Omega$ of $\mathbb R^n$. A consequence of the Paley-Wiener theorem is that a point $x_0$ in $\Omega$ is not in the singular support of $u$ whenever there exists a neighbordhood $U$ of $x_0$ such that
$$
\forall \chi\in C_c^\infty(U),
\forall N\in \mathbb N,\quad\vert\widehat{\chi u}(\xi)\vert\vert \xi\vert^N\in L^{\infty}(\mathbb R^n).
$$
That notion can be refined to define the ($C^\infty$) wave-front-set, as a subset of the cotangent bundle (minus the 0 section): a point $(x_0,\xi_0)\in \Omega \times\mathbb S^{n-1}$ does not belong to the wave-front-set of $u$
whenever there exists a neighbordhood $U$ of $x_0$, a neighborhood $V$ of $\xi_0$ on the sphere such that
$$
\forall \chi\in C_c^\infty(U),
\forall N\in \mathbb N,\quad\vert\widehat{\chi u}(t\xi)\vert t^N\in L^{\infty}((1,+\infty)_t\times V).
$$
The wave-front-set (WF) can be used to detect the various directions of singularities: for instance
$$
WF(\delta_{0})=\text{\{0\}}\times (\mathbb R^n\backslash\text{\{0\}})
$$
but with $H=\mathbf 1_{(0,+\infty)}$ the Heaviside function, $H(x_1)$ in $\mathbb R^n$ is also singular at 0 but the structure of the singularity is quite different and indeed with $\Sigma=${$x\in \mathbb R^n, x_1=0$}
$$
WF(H(x_1))=\Sigma\times\text{\{$0\not=\xi\in \mathbb R^n, \xi_2=\dots=\xi_n=0$\}}
$$
which is the conormal bundle to $\Sigma$. The first projection of the wave-front-set is the singular support.
That definition can be extended to Sobolev regularity (spaces based on $L^2$), analytic regularity (more generally Gevrey) and is the only way to express the propagation of singularities for linear waves.

A: Hermann Weyl's delightful proof that for irrational $\alpha$ the sequence of values $k\alpha$ mod $1$, $k \in {\bf N}$, is uniformly distributed in $[0,1]$ deserves a mention.  It's so simple I can summarize it here. First we check that for any nonzero $n \in {\bf Z}$ we have $$\frac{1 + e^{2\pi i n\alpha} + \cdots + e^{2\pi in(k-1)\alpha}}{k} \to 0$$ as $k \to \infty$. This is just a simple computation since the numerator is a geometric series. For $n = 0$ the displayed fraction reduces to $\frac{k}{k} = 1$. Since $\int_0^1 e^{2\pi i nx} dx = 1$ or $0$ depending on whether $n = 0$ or $n \neq 0$, it follows that $$\frac{1}{k}\sum_{j=0}^{k-1} e^{2\pi i nj\alpha} \to \int_0^1 e^{2\pi inx} dx$$ for all $n \in {\bf Z}$. Setting $x_j = j\alpha$ mod $1$ and taking linear combinations then yields $$\frac{1}{k}\sum_{j=0}^{k=1} f(x_j) \to \int_0^1 f(x) dx$$ for any trigonometric polynomial $f$, and by straightforward approximation arguments we get the same conclusion, first for any continuous function $f$ on $[0,1]$ and then for $f = \chi_{[a,b]}$. But with this $f$ the left side becomes the fraction of values $j\alpha$ mod $1$ for $0 \leq j \leq k-1$ which lie in $[a,b]$ and the right side becomes $b-a$, so this is just the statement of uniform distribution.


text:
Q: How can I recover a recently expired BigQuery table? A table I had been updating every day disappeared, and I found out it may have expired. I hadn't taken notice of it.
Is there a simple way to recover that table?

A: If it is within 7 days, you may be able to fetch the data using time-travel:
https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#for_system_time_as_of
And once you are able to read the data, you can save the result to a destination table as kind of a way to recover the table.


text:
Q: Is $f^{-1}(1)$ a submanifold of $\Bbb S^2\times \Bbb S^2$? We consider $f:\Bbb S^2\times\Bbb S^2\to\Bbb R$ as the standard dot product of two points in $\Bbb R^3$. We need to prove that $f^{-1}(1)$ is a regular submanifold of $\Bbb S^2\times\Bbb S^2$.
If $1$ were a regular value, then it would be direct, but it isn't (the jacobian of $f$ is zero in every two points $x$ and $y$ such that $x=y$, and $f(x,x)=1$). Also, the rank of $f$ is not constant (since it can vary from $1$ and $2$).
I don't understand well how to prove it by definition. Could anyone please help me out?

A: The following result can be found in Lee's Introduction to Smooth Manifolds, Proposition 5.7.

Let $M, N$ be smooth manifold and let $g : M\to N$ be a smooth map. Then the graph of $g$
$$ \Gamma_g =\{ (x, g(x)) \in M \times N : x\in M\}$$
is an embedded submanifold of dimension $m = \dim (M)$.

Setting $M = N = \mathbb S^2$ and $g : \mathbb S^2 \to \mathbb S^2$, $g(x) = x$, then
$$D =  \{ (x, x) \in \mathbb S^2 \times \mathbb S^2 : x\in \mathbb S^2\}$$
is an embedded submanifold of $\mathbb S^2 \times \mathbb S^2$. Since $f^{-1}(1) = D$, $f^{-1}(1)$ is an embedded submanifold of $\mathbb S^2 \times \mathbb S^2$.


text:
Q: Society with standardized English language This is a question based on the thinnest of clues: In the future, an Earth man visits a society that has standardized its English so that there are no irregular forms. The characters say "bes" (or "bees"?) and "dos" instead of "is" and "does", "beed" and "doed" instead of "was" and "did". They scoff at the visitor, who speaks our irregular contemporary English. If I remember it right, there were other innovations, some of which made sense and others that were satirical. I don't remember whether this is a society on another planet or in Earth's own future, but I think it was set in the future in a culture that had branched off from Earth's many years ago.
I could have sworn that this was Stanton Coblentz' Next Door to the Sun (1960), but I recently found a copy of that novel and it's not. Although it does have a visitor from Earth encountering Mercurites whose language has evolved in amusing ways over the course of five hundred years of isolation, its language does not have the extreme regularity I remember.
I probably read this tale, which I am pretty sure was of novel length, in the 1960s or early 1970s. In English.

A: "Barrier" aka "The Barrier", a novella by Anthony Boucher, also the (unaccepted) answer to this question; first published in Astounding Science-Fiction, September 1942, available at the Internet Archive.
It's a time-travel story set on a dystopian future Earth.

The first difficulty was with language.

That is only to be expected when you jump five hundred years; but it is nonetheless perplexing to have your first casual query of: "What city is this?" answered by the sentence: "Stappers will get you. Or be you Slanduch?"

[. . . .]

No man alive in 2473 would have bestowed a second glance on the feloniously clad Brent, but in his speech, he realized at once, lay the danger. He pondered the alternatives presented by the stranger. The Stappers would get him, unless he was a Slanduch. Whatever the Stappers were, things that Get You sound menacing. "Slanduch," he replied.

The stranger nodded. "That bees O. K.," he said, and Brent wondered what he had committed himself to. "So what city is this?" he repeated.

"Bees," the stranger chided. "Stappers be more severe now since Edict of 2470. Before they doed pardon some irregularities, but now none even from Slanduch."

"I be sorry," said Brent humbly, making a mental note that irregular verbs were for some reason perilous.

Later the time traveler learns about the history of the dystopia:

In the middle of the twenty-fourth century, he learned, civilization had reached a high point of comfort, satisfaction, achievement — and stagnation. [. . .] Farthing had regularized the English language, an achievement paralleled by the work of Zinsmeister, Timofeov, and Tamayo y Sárate in their respective tongues.

[. . . .]

It was then that Dyce-Farnsworth proclaimed the Stasis of Cosmos. A member of the Anglo-
Physical Church, product of the long contemplation by English physicists of the metaphysical aspects of science, he came as the prophet needed to pander to the self-satisfaction of the age.

He was curiously aided by Farthing's laws of regularity. The article, direct or indirect, Farthing had proved to be completely unnecessary — had not languages as world-dominant as Latin in the first centuries and Russian in the twenty- first found no need for it? — and semantically misleading. "Article," he had said in his final and
comprehensive study This Bees Speech, "bees prime corruptor of human thinking."


text:
Q: Where do I find the source code for execve()? Could you give me the source code for execve() system call (exec family). I'm working with Linux.

A: execve() calls sys_execve() which calls do_execve(), which is where the action is: http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=blob;f=fs/exec.c#l1376

A: Youmight look at sys_execve at arch/x86/kernel/process.c which calls do_execve at fs/exec.c.

A: The execve() entry point is here, in the Linux Cross-Reference page. You can follow the function references (do_execve() is probably what you actually need) to see the source code.

A: You can get the linux source code at the kernel page
To browse inline, use the git browsing facility


text:
Q: Icecast with Liquidsoap not working All;
Ubuntu 18.04 - Icecast / LiquidSoap / opam /  (liquidsoap-daemon)
Installed: taglib mad lame Vorbis cry ssl samplerate magic opus
Plugins: liquidsoap-plugin-all
System Specs:
-System - VirtualBox
-CPU = Intel(R) Core(TM) i7-2720QM CPU @ 2.20GHz
-Memory = 1969MiB (2GB assigned to VM Client)

I have been messing with this for a while now and to no avail.
I have this thread that is now closed, that has near about everything that you would need to look at about my setup. icecast request parsing failed
The playlist I'm testing:
 #!/usr/bin/liquidsoap
 # Log dir
set("log.file.path","/var/log/liquidsoap/radioliq.log")

 # Music
myplaylist = playlist("/home/UserName/music-store/")
 # Some jingles
jingles = playlist("/home/UserName/music-store/jingles/jingles.m3u")
 # If something goes wrong, we'll play this
security = single("/home/UserName/music-store/Sec.mp3")

 # Start building the feed with music
radio = myplaylist
 # Now add some jingles
radio = random(weights = [1, 4],[jingles, radio])
 # And finally the security
 radio = fallback(track_sensitive = false, [radio, security])

  # Stream it out
output.icecast(%vorbis,
  radio, host = "192.168.2.20", port = 8000,
  password = "********", mount = "test.ogg")

When I run this
sudo /etc/init.d/liquidsoap restart

I get this
Stopping liquidsoap channels: no script found in /etc/liquidsoap
Starting liquidsoap channels: radio1.liq OK

It shows starting radio1.liq, however, it is STOPPING, because it cannot find anything in that directory, however. That is where it is picking up on the radio1.liq file.
When I run
sudo systemctl status liquidsoap

My output is this:
● liquidsoap.service - LSB: Starts the liquidsoap daemon
   Loaded: loaded (/etc/init.d/liquidsoap; generated)
   Active: active (exited) since Tue 2018-06-12 17:47:52 EDT; 3h 0min ago
     Docs: man:systemd-sysv-generator(8)
  Process: 1312 ExecStart=/etc/init.d/liquidsoap start (code=exited, status=0/SUCCESS)

Jun 12 17:47:47 liquid-ice systemd[1]: Starting LSB: Starts the liquidsoap daemon...
Jun 12 17:47:52 liquid-ice liquidsoap[1312]: Starting liquidsoap channels: radio1.liq OK
Jun 12 17:47:52 liquid-ice systemd[1]: Started LSB: Starts the liquidsoap daemon.

As you can tell, the Active is (exited) when other times, it is (running) like Icecast is. However, I usually have to do a reboot on the system, in order to get it to show (running)
I just did a reboot, and it is still showing (exited), this is the first time that it has not changed to (running). And usually it will give me an error that I have to fix something, but it is not doing it now.
● icecast2.service - LSB: Icecast2 streaming media server
   Loaded: loaded (/etc/init.d/icecast2; generated)
   Active: active (running) since Tue 2018-06-12 17:47:50 EDT; 3h 1min ago
     Docs: man:systemd-sysv-generator(8)
  Process: 1338 ExecStart=/etc/init.d/icecast2 start (code=exited, status=0/SUCCESS)
    Tasks: 4 (limit: 2289)
   CGroup: /system.slice/icecast2.service
           └─1403 /usr/bin/icecast2 -b -c /etc/icecast2/icecast.xml

Jun 12 17:47:48 liquid-ice systemd[1]: Starting LSB: Icecast2 streaming media server...
Jun 12 17:47:48 liquid-ice icecast2[1338]:  * Starting streaming media server icecast2
Jun 12 17:47:50 liquid-ice icecast2[1338]:    ...done.
Jun 12 17:47:50 liquid-ice systemd[1]: Started LSB: Icecast2 streaming media server.

when I open the web interface, I only get the following tabs (pages)
[Admin] | [Version]

All the other pages are all blank:
[Server Status] => Nothing, completely blank.
[Mountpoint List] => Active Mountpoints (This is all it shows on the page)

I also changed the username in the /etc/init.d/liquidsoap
user=username
group=username

Username Is what I am logged in as. And then gave permission to my user over the locations.
/etc/liquidsoap/radio1.liq
/run/liquidsoap/

using the following scripts:
sudo chmod o+w /run/liquidsoap/
sudo chmod o+w /etc/liquidsoap/radio1.liq

Here is the latest error log from the icecast error.log
[2018-08-08  02:22:18] INFO sighandler/_sig_die Caught signal 15, shutting down...
[2018-08-08  02:22:18] INFO main/main Shutting down
[2018-08-08  02:22:18] INFO fserve/fserve_shutdown file serving stopped
[2018-08-08  02:22:18] INFO slave/_slave_thread shutting down current relays
[2018-08-08  02:22:18] INFO slave/_slave_thread Slave thread shutdown complete
[2018-08-08  02:22:18] INFO auth/auth_shutdown Auth shutdown
[2018-08-08  02:22:18] INFO yp/yp_shutdown YP thread down
[2018-08-08  02:22:19] INFO stats/stats_shutdown stats thread finished
[2018-08-08  02:22:19] INFO main/main Icecast 2.4.3 server started
[2018-08-08  02:22:19] INFO connection/get_ssl_certificate No SSL capability
[2018-08-08  02:22:19] INFO stats/_stats_thread stats thread started
[2018-08-08  02:22:19] INFO yp/yp_update_thread YP update thread started

Exerts from the radio.log file
2018/08/09 04:35:03 [dynamic.loader:3] Could not find dynamic module for fdkaac encoder.
2018/08/09 04:35:03 [dynamic.loader:3] Could not find dynamic module for aacplus encoder.
..........
2018/08/09 04:35:03 [frame:3] Using 44100Hz audio, 25Hz video, 44100Hz master.
2018/08/09 04:35:03 [frame:3] Frame size must be a multiple of 1764 ticks = 1764 audio samples = 1 video samples.
2018/08/09 04:35:03 [frame:3] Targetting 'frame.duration': 0.04s = 1764 audio samples = 1764 ticks.
2018/08/09 04:35:03 [frame:3] Frames last 0.04s = 1764 audio samples = 1 video samples = 1764 ticks.
2018/08/09 04:35:03 [decoder:3] Method "MAD" accepted "/home/darkice/music/Security/sec.mp3".
2018/08/09 04:35:03 [single:3] "~/music/Security/sec.mp3" is static, resolving once for all...
2018/08/09 04:35:03 [threads:3] Created thread "generic queue #1".
2018/08/09 04:35:03 [threads:3] Created thread "non-blocking queue #1".
2018/08/09 04:35:03 [Jingle(dot)mp3:3] Loading playlist...
2018/08/09 04:35:05 [Jingle(dot)mp3:3] No mime type specified, trying autodetection.
2018/08/09 04:35:05 [playlist.basic:3] Wrong mime type audio/mpeg for playlist!
2018/08/09 04:35:05 [playlist parser:3] No format found
2018/08/09 04:35:05 [Jingle(dot)mp3:3] Could not parse playlist: Not_found
2018/08/09 04:35:05 [Jingle(dot)mp3:3] Got an empty list: keeping the old one.
2018/08/09 04:35:05 [musicList:3] Loading playlist...
2018/08/09 04:35:05 [musicList:3] Playlist is a directory.
2018/08/09 04:35:05 [musicList:3] Successfully loaded a playlist of 1 tracks.
2018/08/09 04:35:05 [single_6363:3] Prepared "/home/darkice/music/Security/sec.mp3" (RID 0).
2018/08/09 04:35:05 [test(dot)ogg:3] Connecting mount test.ogg for source@192.168.2.4...
2018/08/09 04:35:05 [test(dot)ogg:2] Connection failed: 401, Authentication Required (HTTP/1.0)
2018/08/09 04:35:05 [test(dot)ogg:3] Will try again in 3.00 sec.
2018/08/09 04:35:05 [threads:3] Created thread "wallclock_main" (1 total).
2018/08/09 04:35:05 [clock.wallclock_main:3] Streaming loop starts, synchronized with wallclock.
2018/08/09 04:43:34 [decoder:3] Method "MAD" accepted "/home/darkice/music/List/01 Send Her To Me.mp3".
2018/08/09 04:43:34 [test(dot)ogg:2] Connection failed: 401, Authentication Required (HTTP/1.0)
2018/08/09 04:43:34 [test(dot)ogg:3] Will try again in 3.00 sec.
2018/08/09 04:43:34 [threads:3] Created thread "wallclock_main" (1 total).
2018/08/09 04:43:34 [clock.wallclock_main:3] Streaming loop starts, synchronized with wallclock.
2018/08/09 04:43:34 [fallback_6368:3] Switch to single_6363.
2018/08/09 04:43:34 [carrzkiss:3] Prepared "/home/darkice/music/List/01 Send Her To Me.mp3" (RID 3).
2018/08/09 04:43:34 [fallback_6368:3] Switch to random_6366 with transition.
2018/08/09 04:35:05 [random_6366:3] Switch to musicList.
2018/08/09 04:35:09 [test(dot)ogg:3] Connecting mount test.ogg for source@192.168.2.4...
2018/08/09 04:35:09 [test(dot)ogg:2] Connection failed: 401, Authentication Required (HTTP/1.0)
2018/08/09 04:35:09 [test(dot)ogg:3] Will try again in 3.00 sec.

I followed this page here, to get the logging to start.
Is there something I am missing here? is there something else that needs to be installed, in order to make liquidsoap function properly?
I followed this tutorial on the installation. Create an internet radio station with Icecast and liquidsoap
I really do not know what else to add to this. I have gone through everything and even did some extras while writing this up. Please let me know if there is anything else that you may need for me to check on. And please, have a look at my other thread, for more information on what I have set up here. icecast request parsing failed
running the following code.
curl -v 192.168.2.4:8000 >/dev/null

gives me this.
* Rebuilt URL to: 192.168.2.4:8000/
*   Trying 192.168.2.4...
* TCP_NODELAY set
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* Connected to 192.168.2.4 (192.168.2.4) port 8000 (#0)
> GET / HTTP/1.1
> Host: 192.168.2.4:8000
> User-Agent: curl/7.58.0
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Server: Icecast 2.4.3
< Date: Sun, 12 Aug 2018 18:28:52 GMT
< Content-Type: text/xml; charset=UTF-8
< Cache-Control: no-cache
< Expires: Mon, 26 Jul 1997 05:00:00 GMT
< Pragma: no-cache
< Access-Control-Allow-Origin: *
< Content-Length: 1144
<
{ [1144 bytes data]
100  1144  100  1144    0     0  95333      0 --:--:-- --:--:-- --:--:--  101k
* Closing connection 0

Thank You.
Wayne

A: OK, now that I think I have enough information/data, let's pick this apart:

2018/08/09 04:35:03 [single:3] "~/music/Security/sec.mp3" is static, resolving once for all...
2018/08/09 04:35:05 [single_6363:3] Prepared "/home/darkice/music/Security/sec.mp3" (RID 0).

Your liquidsoap internal 'fallback' configured by 'security' just became available.

2018/08/09 04:35:03 [Jingle(dot)mp3:3] Loading playlist...
2018/08/09 04:35:05 [Jingle(dot)mp3:3] No mime type specified, trying autodetection.
2018/08/09 04:35:05 [Jingle(dot)mp3:3] Could not parse playlist: Not_found
2018/08/09 04:35:05 [Jingle(dot)mp3:3] Got an empty list: keeping the old one.

There is no playlist for jingles. I'm guessing it will just ignore that.

2018/08/09 04:35:05 [musicList:3] Loading playlist...
2018/08/09 04:35:05 [musicList:3] Playlist is a directory.
2018/08/09 04:35:05 [musicList:3] Successfully loaded a playlist of 1 tracks.

"/home/darkice/music/List/01 Send Her To Me.mp3" is the only file in the specified directory.

2018/08/09 04:35:05 [test(dot)ogg:3] Connecting mount test.ogg for source@192.168.2.4...
2018/08/09 04:35:05 [test(dot)ogg:2] Connection failed: 401, Authentication Required (HTTP/1.0)

It's trying to connect to your Icecast server, but Icecast rejects the connection.
The most likely reason for this is that the password doesn't match the one configured as <source-password> in the Icecast config.
You will find details as to why the connection failed in the Icecast error.log at the timestamp 2018/08/09 04:35:05 - please note that there may be an offset if this is a different computer and the system time of either machine is not synchronized by e.g. NTP.

A: It has been a while since I messed with Icecast2 and Liquidsoap.
However, I did just that a few weeks ago.
After struggling for some time, I figured it out after getting help from another person and watching a video.
It was all a permissions issue.
Once you create your user, "Icedemo."
(logged in as root)
adduser Icedemo

Give user SUDO rights.
usermod -aG sudo Icedemo

Now give permissions to Icedemo to all the folders.
/opt/liquidsoap/Playlists/
/var/log/liquidsoap/
/etc/icecast2/web/
/etc/icecast2/admin/

Use the following script to give permissions.
cd /opt
sudo chown -Rv icedemo:icedemo liquidsoap/
cd /var/log/
sudo chown -Rv icedemo:icedemo liquidsoap/
cd /etc/icecast2/
sudo chown -Rv icedemo:icedemo web/
sudo chown -Rv icedemo:icedemo admin/

Leave permission the same for the icecast.xml file.
Log in as your user Icedemo
su Icedemo

Once you have done all the above and your script is properly formatted. Something like this.
# !/home/iceadmin/.opam/default/bin/liquidsoap
# log dir
set ("log.file.path","/var/log/liquidsoap/basic-radio.log")
set("scheduler.fast_queues",1)
 # Music
music = playlist("/opt/liquidsoap/playlists/RadioOne.m3u",mode="normal",reload_mode="watch")

# Start building the feed with music
radio = music

# Stream it out
output.icecast(%mp3(bitrate=256,samplerate=44100,internal_quality=0,id3v2=true,stereo=true,stereo_mode="stereo"),
name="Radio",
encoding="UTF-8",
host="192.168.2.203",
port=8000,
password="hackme",
icy_metadata="true",
description="Internet Radio Station",
mount="Radio",
mksafe(radio))

We will need to restart each service.
#Restart IceCast
sudo systemctl restart icecast2
#Check status of IceCast
sudo systemctl status icecast2
(Ctrl+Z to go to prompt)

Next, we will need to do the same to Liquidsoap.
#Restart Liquidsoap
sudo systemctl restart radio.liq-liquidsoap
#Check status of  Liquidsoap
sudo systemctl status radio.liq-liquidsoap
(After checking the status, you can use (Ctrl+Z to go to prompt))

Your output of the Liquidsoap status should look similar to mine.
Icedemo@linuxcore-03:~/liquidsoap-daemon$ sudo systemctl status radio.liq-liquidsoap
● radio.liq-liquidsoap.service - radio.liq Liquidsoap daemon
     Loaded: loaded (/etc/systemd/system/radio.liq-liquidsoap.service; disabled; vendor preset: enabled)
     Active: active (running) since Mon 2021-05-24 03:47:01 UTC; 4s ago
       Docs: http://liquidsoap.fm/
    Process: 54678 ExecStart=/home/Icedemo/.opam/default/bin/liquidsoap /home/Icedemo/liquidsoap-daemon/script/radio.liq-run.liq (code=exited, status=0/SUCCESS)
   Main PID: 54680 (liquidsoap)
      Tasks: 9 (limit: 2251)
     Memory: 17.3M
     CGroup: /system.slice/radio.liq-liquidsoap.service
             └─54680 /home/Icedemo/.opam/default/bin/liquidsoap /home/Icedemo/liquidsoap-daemon/script/radio.liq-run.liq
May 24 03:47:01 linuxcore-03 systemd[1]: Starting radio.liq Liquidsoap daemon...
May 24 03:47:01 linuxcore-03 systemd[1]: Started radio.liq Liquidsoap daemon.

If the above is showing:  Active: active (running)
Next, check your Icecast webpage, and you should see your mountpoints, and your radio should be working.
To access the radio station in our example script above would be.
(local) 192.168.2.203:8000/Radio

This will load the player in its own browser window, and your stream should start on its own. If not, click the PLAY button.
That's it; that is how you get your streaming radio to work.
I hope this helps others out.
Wayne


text:
Q: Is this the best way to add Font Awesome icons into header.links - Magento 2 Will this work?
<argument name="label" xsi:type="string">

</argument>

EDIT - I am trying to add font awesome icons into the header.panel and footer. Thanks to comments here, I added phtml templates into the blocks in the default.xml, referenced the correct containers and now the custom ul>li>a are rendering. However the font awesome i class and icons wont show. The cdn is loading (checked in chrome developer) and I set a width and height to the .fa class. still they aren't appearing.

A: No, this won't work. You cannot mix HTML code with XML code in a layout default.xml file.
In app/design/frontend/Magento/luma/Magento_Customer/layout/default.xml you can see for example how the header links are added:
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <referenceBlock name="header.links">
            <block class="Magento\Customer\Block\Account\Customer" name="customer" template="account/customer.phtml" before="-"/>
            <block class="Magento\Customer\Block\Account\AuthorizationLink" name="authorization-link-login" template="account/link/authorization.phtml"/>
        </referenceBlock>

</page>

The customer.phtml template file looks like this:
<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php if($block->customerLoggedIn()): ?>

            <button type="button"
                    class="action switch"
                    tabindex="-1"
                    data-action="customer-menu-toggle">
                <?php /* @escapeNotVerified */ echo __('Change')?>
            </button>

        <?php if($block->getChildHtml()):?>

            <?php echo $block->getChildHtml();?>

        <?php endif; ?>

<?php endif; ?>

As you can see, the CSS classes are added there.
How to add the fontawsome CSS classes
The easiest thing would be to override these files (for example account/customer.phtml and add the fontawesome css class tags in these templates. You have to copy the account/customer.phtml to your own theme and adjust the css classes there. Do not overwrite coure files :-)


text:
Q: How to fix 'argument is not numeric or logical: returning NA' Ive read in my excel data and found the max value for each column and calculated the mean from that.
library(readxl)
exp4 <- read_excel("exp4.xlsx")
View(exp4)

this gives you the highest value in the entire datase
maxpeak <- apply(exp4, MARGIN = 2, function(x) max(x, na.rm=TRUE))
maxpeak
#the mean of all the max peaks in this experiment
mean16052019exp4 <- mean(maxpeak)
mean16052019exp4

I've then taken the original max value and subtracted the baseline values using another excel spreadsheet read in BUT when i now want the mean of these new values:
realmaxpeak <- (maxpeak - exp4baseline)
realmaxpeak
#trying to calculate the mean of the baseline adjusted values
View(realmaxpeak)
mean(realmaxpeak)

I get: Warning message:

In mean.default(realmaxpeak[0.1]) :   argument is not numeric or
  logical: returning NA

Why can i not calculate the mean from the vector (realmaxpeak) i created?
TIA

A: Could you post the summary of the data in realmaxpeak? It could not be recognizing the field as a numeric field. If this is the case, you would utilize as.numeric()


text:
Q: Bash - Variables - bash -c command I'm pretty new to bash and I would need help with understanding these two lines of code. I already know how to assign a value to a variable and what command declare -p does. The main problem is with the bash -c command.
A=5; bash -c 'declare -p A'; declare -p A

A=7 bash -c 'declare -p A'; declare -p A


text:
Q: INNER JOIN with ON All columns except one Column I have 2 tables(Table1 and Table2). Both tables schema are exactly the same and both might have duplicated set of records except IDs since ID is auto generated.

I would like to get the common set of records but with ID to follow as Table1's ID. So, I query using Inner join. It works as I expected.
SELECT Table1.ID, Table1.Param1, Table1.Param2, Table1.Param3
INTO #Common
FROM Table1
INNER JOIN Table2 ON Table1.Param1 = Table2.Param1
  AND Table1.Param2 = Table2.Param2
  AND Table1.Param3 = Table2.Param3

However, in actual usage, the total number of parameters in both tables will be around 100. So, the total number of comparison inside ON clause will increase up to 100.
How can I do inner join by excluding one column instead of comparing all columns in ON clause?
By removing ID column from both tables and doing intersect also no possible since I still want to extract Table1 ID for other purpose.
I can achieve the common of 2 table by removing ID and compare those 2 table.
However, that still do not serve my requirement, since I need to get Table1 ID for those common data.
SELECT * INTO #TemporaryTable1 FROM Table1
ALTER TABLE #TemporaryTable1 DROP COLUMN ID

SELECT * INTO #TemporaryTable2 FROM Table2
ALTER TABLE #TemporaryTable2 DROP COLUMN ID

SELECT * INTO #Common FROM (SELECT * FROM #TemporaryTable1 INTERSECT SELECT * FROM #TemporaryTable2) data
SELECT * FROM #Common

A: If i understood your problem correctly i guess you could generate dynamically the query you want to use using the following code :
DECLARE @SQL nvarchar(max) = 'SELECT  ',
    @TBL1 nvarchar(50) = 'data',
    @TBL2 nvarchar(50) = 'data1',
    @EXCLUDEDCOLUMNS nvarchar(100)= 'ID,col1'

-- column selection
SELECT @sql += @tbl1 + '.' + COLUMN_NAME + ' ,
        '
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TBL1

-- from clause and remove last ,

set @SQL = LEFT(@sql,LEN(@sql) - 5)

SET @sql += '
FROM ' + @TBL1 + ' INNER JOIN
     ' + @TBL2 + '
  ON '

-- define the on clause
SELECt @SQL  += @tbl1 + '.' + COLUMN_NAME + ' = '+ @tbl2 + '.' + COLUMN_NAME +',
     '
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TBL1
  AND COLUMN_NAME not in (@EXCLUDEDCOLUMNS)

--remove last ,

set @SQL = LEFT(@sql,LEN(@sql) - 3)

--SELECt @SQL
EXEC SP_EXECUTESQL @sql

Before you execute make sure the @sql is properly generated. choose the columns you want to exclude from your on clause using the @EXCLUDEDCOLUMNS   parameter.


text:
Q: Can't USE any already installed npm packages: Not Recognized I'm clearly having a misunderstanding about what PATH does. I'm having trouble using any of my installed packages (globally as well as local). What I've tried to do so far:
npm install -g firebase-tools
npm install -g ionic cordova

The packages install just fine. I can see that when I run
npm list -g --depth=0

I get a list that shows the node, cordova, firebase, and ionic packages installed. But, if i want to access any of these packages by running a command, such as
firebase-init
  OR
ionic start myApp sidemenu

I get the same error message in my cmd
['firebase']/['ionic'] is not a recognized internal or external command, operable program or batch file.

Nodejs is installed in my Program Files(x86)/nodejs
Here is what i have my PATH variable set to:

C:\Program Files\nodejs;
C:\Program Files (x86)\nodejs\node_modules\npm;
C:\Users\...\myproject\node_modules

I added that last path after locally doing
npm install ionic

where I can clearly see the ionic package in the folder, but I still get the same error as above when I try to run an ionic command.
I'm really disheartened because I've not been able to figure out the issue for weeks now, and I can't get any progress on my project because of it. :(
Note: i'm working on WINDOWS 8

A: Solution 1: At the application directory, link the local project to the package
npm link firebase-tools
npm link ionic cordova

Solution 2: The problem may be caused by lacking of NODE_PATH definition

*

*Check if NODE_PATH variable is defined in the environment:

echo %NODE_PATH% (for Windows)
echo $NODE_PATH (for Linux)

*

*If not, define it:

setx NODE_PATH C:\Users\<Username>\AppData\Roaming\npm\node_modules (for Windows)
export NODE_PATH=/usr/lib/node_modules (for Linux)

A: Do you have git installed? Remove it and try out your commands. git causes trouble with paths in windows You can check this answer

A: @Alexsandra, i would recommmend to install the packages locally:
npm install --save firebase-tools
npm install --save ionic cordova
once installed,check in your project package.json to verify it has been added as one of your dependencies. then type firebase --help
hope that helps!


text:
Q: Add subview to lower left corner I'm trying to add a button as subview to the lower right corner. It will work with x, y coordinates but i think that's not a good way to do so.
I need to add the button to the left bottom of the view.

A: Just use cgrectmake so directly set the x and y
With:
CGRectMake(x,self.view.bounds.size.height-offsetfrombottom,....);
This would be it for the left button
The right button also should have self.view.bounds.size.width-rightSideOffset for x

A: This will work by playing with the autoresizingMask property of your button. Depending of what you want:
Bottom left corner:
yourButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin| UIViewAutoresizingFlexibleTopMargin;

Bottom right corner:
 yourButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin| UIViewAutoresizingFlexibleTopMargin;

if you rotate you device your button will then stay on its corner.
You still need to set-up once the coordinates(by either setting the frame or center property) of your button once for example when your view is loaded in your viewController.


text:
Q: Does hbase support double rows id filtering? Suppose I have designed hbase row id in following format (- is used as delimiters, _ instead of spaces):
timestamp-event_type-user_id

So now I want to select event sequences for user. For example, I need to select event typs than go in following sequence: 4,8,1,10.
It is obvious that I should create RowFilter combined with RegexStringComparator.
But in that case I select a group of rows, so it needs to extract them and order by timestamp to determine event sequence.
Is there a an approach in hbase to apply row filter twice? E.g. first to select row and second to perform selection in selected group?
Note
It may be seems not correct use of hbase, but the main idea is row key are stored in Hbase cache, so double filtering on row keys should be extremely fast. Does hbase provides something similar?

A: Have you looked at FilterList.
It could take multiple filters and join them by conditions. eg: MUST_PASS_ALL (AND) or MUST_PASS_ONE (OR).
Hope it helps.

A: You can use this code for reference:
FilterList filterList = new FilterList(FilterList.Operator.MUST_PASS_ALL);

filterList.addFilter(new RowFilter(...));

filterList.addFilter(new RowFilter(...));

Scan s = new Scan();
s.setFilter(filterList);

You can find more on http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/FilterList.html


text:
Q: ListPlot3D: color function with blend I have the following dataset:
test = {{0, 0, 0}, {0, 0.25, 0.020}, {0, 0.5, 0.0045}, {0, 0.75,
   0.0035}, {0, 1, 0.0025}, {0.25, 0, 0.10}, {0.25, 0.25,
   0.0018}, {0.25, 0.5, 0.0035}, {0.25, 0.75, -0.015}, {0.25,
   1, -0.02}, {0.5, 0, 0.15}, {0.5, 0.25, 0.015}, {0.5, 0.5,
   0.00025}, {0.5, 0.75, -0.025}, {0.5, 1, -0.04}, {0.75, 0,
   0.2}, {0.75, 0.25, 0.012}, {0.75, 0.5, 0.00015}, {0.75,
   0.75, -0.035}, {0.75, 1, -0.06}, {1, 0, 0.25}, {1, 0.25,
   0.007}, {1, 0.5, 0}, {1, 0.75, -0.045}, {1, 1, -0.09}}

The goal is to have a ListPlot3D of the {a,b,c} elements where:

*

*The maximum value of z is a pure red

*The minimum value of z is a pure green

*z=0 is depicted with a neutral color, like white or grey

I'm quite sure I need to use ColorFunction toghether with Blend, but I cannot make it work.
I can do it using discrete colors (red for positive and green for negative):
ListPlot3D[test, PlotRange -> All,
 ColorFunction -> Function[{x, y, z}, If[z >= 0, Red, Green]],
 ColorFunctionScaling -> False]

OR I can specify to use blend between red and green, without any control on the blending.
gradient[x_] := Blend[{Green, Red}, x]
ListPlot3D[test, PlotRange -> All, ColorFunction -> (gradient[#3] &)]

Clearly I can find the max and the minimum value of z
max = Max[test[[All, 3]]]
min = Min[test[[All, 3]]]

But I cannot create the graph I want. Thanks for helping!
EDIT
This seems to work
ListPlot3D[test, PlotRange -> All,
 ColorFunction ->
  Function[{x, y, z},
   If[z >= 0, Blend[{{0, Gray}, {max, Red}}, z],
    Blend[{{min, Green}, {0, Gray}}, z]]],
 ColorFunctionScaling -> False]


text:
Q: For what values of $\alpha >0$ and $\beta >0$ does the following series $\sum_{n=2}^\infty \frac{1}{n^{\alpha}(\log n)^{\beta}}$ converge? For what values of  $\alpha >0$ and $\beta >0$ does the following series $$\sum_{n=2}^\infty \frac{1}{n^{\alpha}(\log n)^{\beta}}$$ converge?
if $\alpha >1$ ,then limit comparison test  suggest that given series converge for any $\beta >0$
Also when $\alpha=1$ given series converge iff $\beta >1$ by integral test.
Is it correct ? Also what will happen when $0 <\alpha <1$
Any suggestions?Thanks

A: What you said until using integral test is correct.
If $0 \lt \alpha \lt 1$, then as
$(\log n)^\beta \lt n^{\frac{1-\alpha}{2}}$ for $n $ large enough, you get
$$\frac{1}{n^\alpha(\log n )^\beta} \ge \frac{1}{n^{\frac{1+\alpha}{2}}}.$$
Hence the series diverges as $\frac{1+\alpha}{2}\le 1$.


text:
Q: Can't generate a model with Z3 I have the following example code for the knapsack problem in a file called "knapsack.smt2", which I believe is in smt2 format and I have the latest version of Z3:
(declare-const s1 Int)
(declare-const o1 Int)
(declare-const b1 Bool)

(declare-const s2 Int)
(declare-const o2 Int)
(declare-const b2 Bool)

(declare-const s3 Int)
(declare-const o3 Int)
(declare-const b3 Bool)

(declare-const sack-size Int)
(declare-const filled Int)

(assert (< o1 sack-size))
(assert (< o2 sack-size))
(assert (< o3 sack-size))

(assert (>= o1 0))
(assert (>= o2 0))
(assert (>= o3 0))

(assert (=> (not b1)(= o1 o2)))
(assert (=> (not b2)(= o2 o3)))

(assert (=> b1 (= (+ o1 s1) o2)))
(assert (=> b2 (= (+ o2 s2) o3)))
(assert (=> b3 (= (+ o3 s3) filled)))

(assert (=> (not b3) (= o3 filled)))
(assert (<= filled sack-size))

(assert ( = o1 0))

(assert ( = s1 3))
(assert ( = s2 4))
(assert ( = s3 5))
(assert ( = sack-size 20))

(assert ( = filled 13))

(check-sat)
(get-model)

However, when I run "z3 -m knapsack.smt2" I get the following error message:
>> z3 -m knapsack.smt2
unsat
(error "line 46 column 10: model is not available")

where line 46 is the last line "(get-model)".
Can anyone tell me why this isn't working?
Thanks.

A: Z3 produces models for satisfiable instances.
Your formula is not satisfiable. Using the constraints
(assert ( = o1 0))
(assert ( = s1 3))
(assert ( = s2 4))
(assert ( = s3 5))
(assert ( = filled 13))

we have that o1 = 0 and s1 = 3, s2 = 3, s3 = 5, and filled = 13,
Using the constraints
(assert (=> (not b1)(= o1 o2)))
(assert (=> b1 (= (+ o1 s1) o2)))

We have that o2 = 0 or o2 = 3.
Using
(assert (=> (not b2)(= o2 o3)))
(assert (=> b2 (= (+ o2 s2) o3)))

We have that o3 = o2 or o3 = o2 + 3
Using
(assert (=> b3 (= (+ o3 s3) filled)))
(assert (=> (not b3) (= o3 filled)))

We have that o3 = 8 or o3 = 13
Now, we can see the conflict
o2 = 0 or o2 = 3
o3 = 8 or o3 = 13
o3 = o2 or o3 = o2 + 3

If we try o2 = 0 we get the unsatisfiable formulas
o3 = 8 or o3 = 13
o3 = 0 or o3 = 3

If we try o2 = 3 we get the unsatisfiable formulas
o3 = 8 or o3 = 13
o3 = 3 or o3 = 6


text:
Q: How to add PHP extension in Windows 10? I have downloaded PHP build from Chocolatey on my Windows 10 PC. I have attempted to install and activate the PHP Redis extension, so I downloaded the archive, copied the php_redis.dll extension file to the default ext folder and modified the php.ini file like so:
;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;

; If you wish to have an extension loaded automatically, use the following
; syntax:
;
;   extension=modulename
;
; For example:
;
;   extension=mysqli
;
; When the extension library to load is not located in the default extension
; directory, You may specify an absolute path to the library file:
;
;   extension=/path/to/extension/mysqli.so
;
; Note : The syntax used in previous PHP versions ('extension=<ext>.so' and
; 'extension='php_<ext>.dll') is supported for legacy reasons and may be
; deprecated in a future PHP major version. So, when it is possible, please
; move to the new ('extension=<ext>) syntax.
;
; Notes for Windows environments :
;
; - Many DLL files are located in the extensions/ (PHP 4) or ext/ (PHP 5+)
;   extension folders as well as the separate PECL DLL download (PHP 5+).
;   Be sure to appropriately set the extension_dir directive.
;
extension=bz2
extension=curl
extension=ffi
extension=ftp
extension=fileinfo
extension=gd2
extension=gettext
extension=gmp
extension=intl
extension=imap
extension=ldap
extension=mbstring
extension=exif      ; Must be after mbstring as it depends on it
extension=mysqli
;extension=oci8_12c  ; Use with Oracle Database 12c Instant Client
extension=odbc
extension=openssl
;extension=pdo_firebird
extension=pdo_mysql
;extension=pdo_oci
extension=pdo_odbc
extension=pdo_pgsql
extension=pdo_sqlite
extension=pgsql
extension=shmop

; The MIBS data available in the PHP distribution must be installed.
; See http://www.php.net/manual/en/snmp.installation.php
;extension=snmp

extension=soap
extension=sockets
extension=sodium
extension=sqlite3
extension=tidy
extension=xmlrpc
extension=xsl

; Added by Rumon:
extension=mongodb
extension=redis

Followed this same path to install mongodb extension as well (Downloaded from here).
Now, when I do anything related to those drivers, I get error that the system cannot find the extensions. For example:
$ php --ini
PHP Warning:  PHP Startup: Unable to load dynamic library 'mongodb' (tried: ext\mongodb (The specified module could not be found.), ext\php_mongodb.dll (The specified module could not be found.)) in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'redis' (tried: ext\redis (The specified module could not be found.), ext\php_redis.dll (The specified module could not be found.)) in Unknown on line 0
Configuration File (php.ini) Path:
Loaded Configuration File:         C:\tools\php74\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)

For everybody's convenience, I am providing a SS of the extensions directory, have a look.
Can anyone explain what's causing the issue? And how can I resolve this?

A: After researching for a while, I found that "Thread Safety" is a THING in PHP world! I wrongly installed the TS version, while I was needed the NTS version.

To everyone: When you try to install any PHP extension, check your system and make sure that you download the appropriate (TS/NTS) version.

Cheers!


text:
Q: Load satellite image in Matlab I've a problem about how can I load a Landsat image on Matlab. My image is in format .img and have the following information:
Columns and rows= 9487 x 8543
Number of bands= 6
Cellsize= 25 x 25
Source Type= continuous
Píxel type= unsigned integer
Pixel Depth= 16 bit
Scale factor= 0,9996

And this is my code:

IM= multibandread('2000.img',[9487, 8543,
  6],'int16',0,'ieee-le',{'Row','Range',[9487 8543]);

But there's the following error:
Error: Unbalanced or unexpected parenthesis or bracket.
I've tried to change but it doesn't work. What can I do?
Thanks in advance,
Emma

A: Dennis is right, you're missing a closing curly brace. It should be inserted between the bracket and the parenthesis at the end like this:

IM= multibandread('2000.img',[9487, 8543, 6],'int16',0,'ieee-le',{'Row','Range',[9487 8543]});

A: I think you may want to leave the subset argument out completely, this in addition to using unsigned uint16, try the following:
multibandread('2000.img',[9487, 8543, 6],'uint16',0,'ieee-le')

Note that with your current call it appears that you are trying to extract row 9487 to 8543.


text:
Q: Cast entities implicitly with EF Core Suppose I have following entities
public abstract class BaseEntity {
 public Guid Id { get;set; }
 public string Prop1 { get;set; }
 public long Prop2 { get;set; }
 public byte Type_Id { get;set; }
}

public class Type1 : BaseEntity { }

public class Type2 : BaseEntity { }

public class Type3 : BaseEntity {
  public long? Prop3 { get;set; }
}

And following context mapping:
builder.ToTable("Entities").HasDiscriminator(a => a.Type_Id)
                .HasValue<Type1>((byte)Types.Type1)
                .HasValue<Type2>((byte)Types.Type2)
                .HasValue<Type3>((byte)Types.Type3);
// in DbContext
public DbSet<BaseEntity> Entities { get; set; }

I want to create get IQueryable from DB (all records) Type1 and Type2 will have null in Prop3 ,
I do the following:
public DbSet<BaseEntity> DBSet { get;set; }
private static readonly MethodInfo FromSqlMethodInfo = typeof(RelationalQueryableExtensions).GetTypeInfo().GetDeclaredMethods("FromSql").Single(mi => mi.GetParameters().Length == 3);
public IQueryable<Type3> GetEntities(IEnumerable<Guid> ids) {
                RawSqlString sql = @"select [Id]
          ,[Prop1]
          ,[Prop2]
          ,[Prop3]
          ,[Type_Id]
            from [dbo].[Entities] where Id in (select item from @Ids)";
                var ids = new SqlParameter("@Ids", SqlDbType.Structured);
                ids.TypeName = typeof(Guid).Name.ToLowerInvariant() + "_item_list";
                ids.Direction = ParameterDirection.Input;
                ids.Value = CreateItemList(tpIds);
                var param = new object[] { ids };
                var conversion = from s in DBSet select (Type3)s;
                var result = conversion.Provider.CreateQuery<Type3>(Expression.Call(null, FromSqlMethodInfo.MakeGenericMethod(typeof(Type3)), conversion.Expression,
                   Expression.Constant(sql), Expression.Constant(param)));
                return result;
            }

var query = GetEntities(someIds);
var result = query.OrderBy(m => m.Type_Id).Skip(skip).Take(take).ToList();

And query executes successfully, but when ToLIst is called, Exception is thrown:
Unable to cast object of type 'Type1' to type 'Type3', which is quite expected, since we not telling how it should be converted...so the question is: can such trick be done with EF Core ?

A: Ok, so for now only possible solution is to create one more entity with all properties required,
public class NewEntity {
 public Guid Id { get;set; }
 public string Prop1 { get;set; }
 public long Prop2 { get;set; }
 public byte Type_Id { get;set; }
 public long? Prop3 { get;set; }
}

add new DbSet to context
public DbSet<NewEntity> NewEntities { get; set; }

Map it to old table and update context configuration properly,
to avoid redundant columns generation (in this scenario EF will probaly
try to add new columns with names NewEntity_Prop1 , NewEntity_Prop2 etc..
as well as Foreign keys and indexes
public override void Configure(EntityTypeBuilder<NewEntity> builder) {
    builder.ToTable("Entities");
    builder.Property(m => m.Prop1).HasColumnName("Prop1");
    builder.Property(m => m.Prop2).HasColumnName("Prop2");
    builder.Property(m => m.Type_Id).HasColumnName("Type_Id");
    builder.HasOne<BaseEntity>().WithOne().HasForeignKey<NewEntity>(e => e.Id);
}

Or create View
 public DbQuery<NewEntity> NewEntities { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder) {
 modelBuilder.Query<NewEntity>().ToView("NewEntities");
            base.OnModelCreating(modelBuilder);
}

A: You can use implicit Overload Cast Operators. Here is a link to help you.


text:
Q: Using Regex to find a reference with specific length I'm looking for help with using Regex to pull certain data from a string. I'm new to Regex and still relatively new to coding. I have looked for other questions but can't find any where the initial string might have more than one piece of data like mine.
In the below, I'm looking to extract the document number and assign to the "docNumber" string.
Case will always be 10 digits long.
Customer may be 4 or 5 digits long.
Document will always by 7 digits  long.
The issue is that my Regex expression is just capturing the first 7 digits of the Case number.
static void Main(string[] args)
    {

        String testText = "Case 1628855986 Customer 7739 Document 9153862";

        String docNumber = Regex.Match(testText, @"\d{7}").Value;

        Console.WriteLine("The reference you are looking for is: " + docNumber);

    }

Any help would be greatly appreciated!

A: If the document number is always preceded by Document , you can use a zero-width positive lookbehind assertion instead of relying on the length of the number:
string docNumber = Regex.Match(testText, @"(?<=Document )\d+").Value


text:
Q: Iterating of Dictionary Panda Excel File Reading
I am attempting to try and access an excel files rows and columns and do some basic distance calculations, but I keep getting the same values> i am attempting to find the distance from any two points of the map by iterating through the list of edges and their corresponding values in the dictionary I created. not sure what I am doing wrong here. Any guidance is appreciated.
import pandas as pd
import array
import numpy as np
import pyomo.environ as pyo
from math import sin, cos, sqrt, atan2, radians
import requests
import urllib.request
import time
from bs4 import BeautifulSoup

distance = pd.read_csv("Distance File.csv")
distance.head()

d_long = distance["Longitude"]
d_lat = distance["Latitude"]
print(d_long)
print(d_lat)

distance_dict = {}
location = list(range(0, 10))
print(location)
for i in d_long:
    for j in d_lat:
        for x in location:
            distance_dict[x] = i, j
            # distance_dict.update(d1)
print(distance_dict)

opt = pyo.SolverFactory("glpk")
V = list(distance_dict.keys())  # List of Customers
Customers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
distance_dict = distance_dict  # Dict of customers

E = []

for i in V:
    for j in V:
        if i != j:
            E.append((i, j))
print(E)
c = {}
for (i, j) in E:
    lat = radians(abs(distance_dict[i][1]))
    lon = radians(abs(distance_dict[i][0]))
    lat2 = radians(abs(distance_dict[j][1]))
    lon2 = radians(abs(distance_dict[j][0]))
    dlon = lon2 - lon
    dlat = lat2 - lat
    a = sin(dlat / 2) ** 2 + cos(lat) * cos(lat) * sin(dlon / 2) ** 2
    c[i, j] = 2 * atan2(sqrt(a), sqrt(1 - a))
    print(dlat)
print(c)

A: you're getting the same distance every time because of the way you're structuring your dictionary. specifically, this code right here:
for i in d_long:
    for j in d_lat:
        for x in location:
            distance_dict[x] = i, j

for all the keys in location, you set the value last values of whatever's in d_lat/long, overwriting what was put in there on any previous iteration.
to test, try printing your dictionary after the location for loop.