text:
Q: Lottery Pick 1 out of 10 or 10 out of 100 which is better To win the lottery you must pick the one winning ticket.
Given the option of drawing 1 out of 10 tickets or 10 out of 100 tickets to win which is the better option?  Are they both 1 out of 10 or is it better to pick 1 out of 100 first, then 1 out of 99, then 1 out of 98 (assuming you don't pick the winner) up to your 10 picks.  Both should be 10% but I don't know why the 10 separate picks out of 100 doesn't add up to more than 10%. Can someone explain the probability equation for this?

A: Why do you think it's not the same?
It's easier to count the probability that you will NOT win.
In the first case it is $P_1=\frac9{10}$
In the second case it is:
$P_2=\frac{99}{100}\times\frac{98}{99}\times\frac{97}{98}\times\frac{96}{97}\times\frac{95}{96}\times\frac{94}{95}\times\frac{93}{94}\times\frac{92}{93}\times\frac{91}{92}\times\frac{90}{91}=\frac{90}{100}=P_1$

A: Statistically your odds of winning indeed are increased by picking 10 times out of 100 assuming the 10 picks are distinct and without replacement.
1 pick of 10 = 10% Chance of selecting the winning ticket
1 of 100= 1%
1 of  99= 1.01%
1 of 98 = 1.02%
1 of 97 = 1.03%
1 of 96 = 1.04%
1 of 95 = 1.05%
1 of 94 = 1.06%
1 of 93 = 1.07%
1 of 92 = 1.08%
1 of 91 = 1.10%
The odds of picking the winning ticket in this manner is 10.46%


text:
Q: Asp.net razor textbox array for list items I can't find or figure out how to take a list of items (cupcakes) and display them in razor with a quantity field.
What is happening is I am not able to get the values for each cupcake quantity in the list. Can you do textbox arrays in Razor?
VIEW

    Cupcakes
    @foreach (var cupcake in Model.CupcakeList)
    {
        @Html.TextBox("CupcakeQuantities", cupcake.Id)  @cupcake.Name

    }

MODEL
public List<Cupcake> CupcakeList { get; set; }
public List<int> CupcakeQuantities { get; set; }

CONTROLLER
public ActionResult Create()
{
    var model = new PartyBookingModel()
    {
        CupcakeList = db.Cupcakes.ToList(),
        CupcakeQuantities = new List<int>()
    };

    return View(model);
}

CUPCAKE (ENTITY)
public class Cupcake
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal PerDozen { get; set; }
}

A: You have to use an index, rather than foreach for it to work.
@for (int i = 0; i < Model.CupcakeList.Count; i++)
{
    @Html.TextBoxFor(x=>Model.CupcakeQuantities[i]) @Model.CupcakeList[i].Name

}

This will create sequentially named+number entries that will be recombined back into the model on post back.
I realise this may seem like "why doesn't foreach work?", but with foreach there is not enough reflected information available to TextBoxFor (as it is just a single object), whereas the array index is extracted by reflection from the Model.CupcakeQuantities[i] expression.
The receiving controller method should take the same as the model passed to the view:
e.g.
[HttpPost]
public ActionResult(PartyBookingModel model)

A: Try it this way:
view:
@for (int i = 0; i < Model.Count; i++)
{
    @Html.HiddenFor(x=>Model[i].Id) @Model[i].Name
    @Html.TextBoxFor(x => Model[i].Quantity)

}

model:
public class CupcakeViewModel
{
   public int Id {get;set;}
   public string Name {get;set;}
   public int Quantity {get;set;}
}

controller:
public ActionResult Create()
{
    var model = db.Cupcakes.Select(c => new CupcakeViewModel {
                                                Id = c.Id,
                                                Name = c.Name,
                                                Quantity = 0
                           })
                           .ToList();

    return View(model);
}

[HttpPost]
public ActionResult Create(CupcakeViewModel[] cakes)
{
     //Save choosen cakes
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Uncaught TypeError: Object(...) is not a function for Cordova plugin reference I created a cordova plugin using plugman and am trying to use it in my ionic app. But I am getting Uncaught TypeError: Object(...) is not a function... I am unable to figure out what this error is.
Did some research and found that upgrading ionic-native version might work but it did not in my case.
I am trying to create a wrapper service for the plugin like this:
    import { Injectable } from '@angular/core';
    import { Plugin, Cordova, IonicNativePlugin } from '@ionic-native/core';

    @Plugin({
      pluginName: 'mathcalculator',
      plugin: 'cordova.plugin.mathcalculator',
      pluginRef: 'MathCalculator',
      repo: 'https://github.com/dkandel/MathCalculator.git',
      platforms: ['Android']
    })

    @Injectable({
     providedIn: 'root'
    })
    export class MathService extends IonicNativePlugin {

      @Cordova()
      add(args: any): Promise<any> {
       return;
      }
    }

The service has been added to the providers in App module file.
I also have the plugin in my plugins folder. When i try to run the app I keep getting Object(...) is not a function and the error points to @Cordova() on my service file.
Can anyone help me out please?

A: I ran into this same issue today and I was making the same mistake as you.
The problem is that you're using the @Plugin and @Cordova decorators directly in an Angular service, which isn't where those decorators are intended to be used. Many of the tutorials I could find on the topic of writing an ionic-native cordova plugin wrapper didn't make this very clear.
The way I resolved the problem was by cloning the ionic-native repo and following these instructions to build the plugin.  Building it also creates an ngx directory with another version of the plugin that you should import instead if you want the plugin to operate with Observables instead of Promises.
Once it's built, copy it over to the node_modules/@ionic-native directory of your project.  Then you can add it to a module in your project and inject it into a service or component and use it as you use any built-in native plugin.

A: Not sure if you still need the solution but this worked for me.
import { Injectable } from '@angular/core';
import { cordova, IonicNativePlugin } from '@ionic-native/core';

@Injectable()
export class PluginService extends IonicNativePlugin {
  static pluginName = 'mathcalculator';
  static plugin = 'cordova-plugin-mathcalculator';
  static pluginRef = 'MathCalculator';
  static repo = 'https://github.com/GitUser/Cordova-Plugin-Example.git';
  static platforms = ['iOS']

  add(num1, num2): Promise<any> {
    const x = cordova(this, 'add', {}, [{ param1: num1, param2: num2 }])
    return x;
  }

  substract(num1, num2): Promise<any> {
    const x = cordova(this, 'substract', {}, [{ param1: num1, param2: num2 }])
    return x;
  }

}


text:
Q: Send Message to Nearby Mobile Phone I have been given the task of sending messages (SMS/Flash/ other formats) to any phone entering a restricted area... How do I detect the phone and send message to it without any prior knowledge of it's SIM Number?

A: If you rely on GSM technology then you need a server-based solution. You need a mechanism for registering devices on the server. The server queries the mobile networks location center for device positions and send a message if a position trigger fires. Position information may be less accurate for this solution.
If you have the means to do nearfield communication, e.g. WiFi or Bluetooth, you could build a solution on top of this. You would mark the restricted zone with NFC technology and have software running on the device looking for these markers. If the device detects such a marker this would trigger an appropriate action, maybe ask the mobile network for a message.

A: Standard GSM phones communicate their position unsolicited only when changing the location area. Usually a location area consist of a different number of single cells (in cities much more than in rural areas). So, basically you do not know where the phone is currently located within a location area except it is in use, it is logging in or after a specified time (depending on th eprovider). If called, all cells will query until the phone reveals its current position. So, you would have to force the phone to log in again (neither nice nor legal) or call it/send an SMS (but you don't know the number). Smart phones are easier in this context because the communicate a lot if you do not switch of some "features".
But, you would have to work somehow for mobile phone providers and have access to their servers. So, you would have access to SIM data anyway. So, the task you were given is quite unusual...

A: I know it's been a long time since the question was asked, but I think this link explains two ways this can be done:
Someone Sent a Mysterious Mass Text to Protesters in Kiev
It explains that you can use something called IMSI catcher, or stingray. But I don't think they are legal to use. I don't know if there's any better/easier solution.


text:
Q: Smith Normal form of a matrix Let $A$ be a matrix over $\mathbb{Z}$ of the following form.
$$A=
\begin{bmatrix}
1 & 0 & \cdots & 0\\
0 & a_{22} & \cdots & a_{2n}\\
\vdots & \cdots & \ddots & \vdots\\
0 & a_{m2} & \cdots & a_{mn}
\end{bmatrix}=\begin{bmatrix} 1 & \mathbf{0}\\\mathbf{0} & B\end{bmatrix}.$$
Claim 1. If Smith normal form of $B$ is has invariant factors $d_2,\cdots, d_k, 0 ,\cdots$, then for $A$, the invariant factors are $1,d_2,\cdots, d_k, 0 ,\cdots$.
Proof: This is simply because if $P$ and $Q$ are invertible matrices over $\mathbb{Z}$ such that $PBQ$ is in Smith normal form with invariant factors  $d_2,\cdots, d_k, 0 ,\cdots$ then, the product
$$
\begin{bmatrix}1 & \mathbf{0}\\\mathbf{0} & P\end{bmatrix} A
\begin{bmatrix}1 & \mathbf{0}\\\mathbf{0} & Q\end{bmatrix}
$$
will be almost diagonal with entries $1,d_2,\cdots, d_k, 0,\cdots, 0$ and these entries satisfy the codition of invariants in Smith normal form (i.e. $1|d_2$, $d_2|d_3$, $\cdots$) so by uniqueness of Smith normal form, we can conclde that above product gives Smith normal form of $A$ with invariant factors $1,d_2,\cdots, d_k,0,\cdots$.
Claim 2. GCD of $2\times 2$ minors of $A$ is equal to GCD of $1\times 1$ minors of $B$.
Proof: If previous claim is correct, then $d_2=1.d_2$ is GCD of $2\times 2$ minors of $A$.
Question 1. Are the above claims with proof are correct?
Question 2. What are some simple methods (tricks) to compute Smith normal form (other than finding GCD's of minors), which can be implemented nicely in computation, rather than going by first principle?


text:
Q: how to iterate in a bson document in java I am trying to iterate through a bson document in java but I get an error
new Document().append("test",1).forEach(record -> {
        System.out.println(record);           ^ error here
});

I get:

Error:(556, 49) java: incompatible types: incompatible parameter types
  in lambda expression, expected parameter 2 but found 1

when I try to add another parameter everything broke
new Document().append("test",1).forEach(record, param2 -> {

A: Due to the fact that Document implements the Map interface, that means it also inherits the default forEach method which takes a BiConsumer as a parameter. Thus your lambda should be like this:
.forEach((key, value) -> { ... }


text:
Q: Error resolving class with excel-report plugin I am trying to install excel-plugin but I got an error resolving class.
..\plugins\excel-export-0.2.1\src\groovy\pl\touk\excel\export\XlsxExporter.groovy: 3: unable to resolve class groovy.transform.TypeChecked
 @ line 3, column 1.
   import groovy.transform.TypeChecked
   ^

as installations say I have this in my BuildConfig file.
    inherits("global") {
    excludes 'xercesImpl'
    excludes 'xercesImpl', 'xml-apis'

   }

    plugins {
        runtime (":excel-export:0.2.1")
   }

Any ideas ? I dont know which library I need.
I am using Grails 2.1.5

A: I've run into the same problem.
If you just uncomment the annotation at the start of the AdditionalSheet.groovy and XlsxExporter.groovy (and the import), your project should compile.


text:
Q: Where to get vDateFeed view definition for SSAS Labs? I have download and installed the Adventure Works database to use with the SSAS labs and videos.
However they all seem to make use of a view called vDateFeed that is non existent in the datasource and setup files. So that basically puts an end to using the tutorials. There doesn't seem to be anywhere to download this view definition.
Does anyone have it and if so can you please post it here?

A: Please, install SQL Server 2008 R2 Update for Developers Training Kit (May 2011 Update), and try to execute Setup_AdventureWorksDW2008R2.sql from this kit. There are many instances of this script, one of them is in the following folder: {training kit installation folder}\Demos\SQL10R2BYFBI00-DEMO-01\Source\Setup\scripts\Tasks\sql. This script contains code to create vDateFeed.

A: I just went into the virtual lab.  If you want a shortcut, the view is defined as
CREATE VIEW [dbo].[vDateFeed]
AS
    SELECT
        [DateKey],
        [FullDateAlternateKey] AS [Date],
        CAST([CalendarYear] AS NCHAR(4)) + N' ' + LEFT([EnglishMonthName], 3) + N', ' + CASE WHEN [DayNumberOfMonth] < 10 THEN N'0' ELSE N'' END + CAST([DayNumberOfMonth] AS NVARCHAR(2)) AS [DateLabel],
        (([CalendarYear] * 100) + [MonthNumberOfYear]) AS [MonthKey],
        CAST([CalendarYear] AS NCHAR(4)) + N' ' + LEFT([EnglishMonthName], 3) AS [MonthLabel],
        [MonthNumberOfYear] AS [MonthOfYearKey],
        LEFT([EnglishMonthName], 3) AS [MonthOfYearLabel],
        (([CalendarYear] * 10) + [CalendarQuarter]) AS [CalendarQuarterKey],
        N'CY' + CAST([CalendarYear] AS NCHAR(4)) + N' Q' + CAST([CalendarQuarter] AS NCHAR(1)) AS [CalendarQuarterLabel],
        [CalendarQuarter] AS [CalendarQuarterOfYearKey],
        N'CY Q' + CAST([CalendarQuarter] AS NCHAR(1)) AS [CalendarQuarterOfYearLabel],
        [CalendarYear] AS [CalendarYearKey],
        N'CY' + CAST([CalendarYear] AS NCHAR(4)) AS [CalendarYearLabel]
    FROM
        [dbo].[DimDate];
GO


text:
Q: Spring mvc: bind hash map with same/different value depending on user input I have a requirement where I am asked to capture a fee applicable for a certain course. But the problem is for few courses the same fee is applicable to all type of users and for some courses profession-wise fee is applicable. eg if the user is a teacher then he has fewer fees than if he is an industry professional.
There are predefined professions in database.
Here is my current logic with code.
Depending on the radio button, I am toggling the proper div and particular logic at the back end.
<input type="radio"  name="professionWiseFees" value="true">
<input type="radio"  name="professionWiseFees" value="false">

   <input class="feeAmountOnly" name="feeAmount" type="text"  />

  <c:forEach items="${applicationScope.professionList}" var = "profession" >
     Course Fee For ${profession.profession}
     <input type="hidden" value="${profession.id}" name="profession" type="text"/>
     <input class="feeAmoun2t" name="profession" type="text" />
  </c:forEach>

Now I am checking which type of fees is applicable and filling the hashmap accordingly. if prefessionWiseFees is not applicable then adding the same fees to all the profession.
Boolean isProfessionWiseFeesApplicable = Boolean.parseBoolean(reqParams.get("professionWiseFees")[0]);
Map<Integer,Double> feeProfessionMap = new HashMap<>();

List<Profession> professions = (List<Profession>) servletContext.getAttribute("professionList");

if(isProfessionWiseFeesApplicable) {
    String[] propfessionWiseFees = reqParams.get("profession");
    // [1(profession_id),1000(fees),2,2000,3,7000], hence i+2 i=profession_id, i+1=fees
    for(int i=0; i < propfessionWiseFees.length-1 ;i=i+2){
        feeProfessionMap.put(Integer.valueOf(propfessionWiseFees[i]),Double.parseDouble(propfessionWiseFees[i+1]));
    }
}
else {
    double feeAmount = Double.parseDouble(reqParams.get("feeAmount")[0]);
    for(Profession profession: professions){
        feeProfessionMap.put(Integer.valueOf(profession.getId()),feeAmount);
    }
}

courseBean.setProfessionWiseFees(feeProfessionMap);
courseBean.setProfessionWiseFees(isProfessionWiseFeesApplicable);

Model class:
public class CourseBean {
    // few fields
    private Map<Integer, Double> professionWiseFees; // <profession_id ,fees>
    // all setters and getters
}

So How can I solve this problem elegantly? requestParam.get is making the code cluttery

A: If you think that

use of requestParam.get reducing readability and maintainability of code.

You may use Spring web binding.
First define a FeeForm bean:
public class FeeForm {
    boolean isProfessionWiseFees;
    ProfessionAmount[] professionAmounts;
    Double feeAmount;
}

Then define the ProfessionAmount bean:
public class ProfessionAmount {
    int profession;
    double amount;
}

Then change the controller method in this way:
    @RequestMapping(value = { "/test.html" }, method = RequestMethod.POST)
    public String testOverflow(Map<String, Object> model,
            FeeForm form)
    {
        Map<Integer,Double> feeProfessionMap = new HashMap<>();

        List<Profession> professions = (List<Profession>) servletContext.getAttribute("professionList");

        if(form.isProfessionWiseFees()) {
            for(ProfessionAmount f : form.getProfessionAmounts()){
                feeProfessionMap.put(f.getProfession(),f.getAmount());
            }
        }
        else {
            for(Profession profession: professions){
                feeProfessionMap.put(profession.getId(),form.getFeeAmount());
            }
        }

HTML:
   <input type="radio"  name="professionWiseFees" value="true"> true
    <input type="radio"  name="professionWiseFees" value="false">  false

       <input class="feeAmountOnly" name="feeAmount" type="text"  />

      <c:forEach items="${applicationScope.professionList}" var = "profession" varStatus="status" >
         Course Fee For ${profession.profession}
         <input type="hidden" value="${profession.id}" name="professionAmounts[${status.index}].profession" type="text"/>
         <input class="feeAmoun2t" value='0' name="professionAmounts[${status.index}].fee" type="text" />
      </c:forEach>

A: You should come to the jsp holding flag in the model bean which indicate if the fees is applicable or not based on it play on the design and disable the inapplicable options .
or
use AJAx. you can use radio button and use onchange of them to check by ajax. if it's inapplicable return validation error message.


text:
Q: Smoothen line on linerender I've created a square using linerenderer but my problem now is that the line is not smooth. see below picture. I've tried enabling anti-aliasing and setting lr.numCapVertices to no avail.

 private void DrawLine()
{
    GameObject myLine = new GameObject();
    myLine.transform.position = start;
    myLine.AddComponent<LineRenderer>();
    lr = myLine.GetComponent<LineRenderer>();
    lr.material = new Material(Shader.Find("Sprites/Default"));
    lr.positionCount = 4;
    lr.startWidth = .1f;
    lr.endWidth = .1f;

    lr.SetPosition(0, new Vector3(1, 0, 0));
    lr.SetPosition(1, new Vector3(2, 0, 0));
    lr.SetPosition(2, new Vector3(2, -1, 0));
    lr.SetPosition(3, new Vector3(1, -1, 0));
    lr.loop = true;

    Gradient gradient = new Gradient();
    gradient.SetKeys(
        new GradientColorKey[]
        {
            new GradientColorKey(Color.red, 0.25f),
            new GradientColorKey(Color.green, 0.50f),
            new GradientColorKey(Color.blue, 0.75f),
            new GradientColorKey(Color.yellow, 1f),
        },
            new GradientAlphaKey[] { new GradientAlphaKey(1f, 0.0f)

        }
        );
    lr.colorGradient = gradient;

}

A: Have a look at line renderer documentation. Specifically the following properties:

*

*Corner vertices

*End cap vertices

*Alignment

The corner and cap vertices will determine the 'roundness' of corners and line endings.
Different alignment settings may give you a more orthogonal view of the line which should prevent the illusion of varying thickness as can be seen at the green corner in your image.


text:
Q: Finding the minimum of two dates - PSQL PSQL Newbie.. I have a table that has a primary key and two time stamps
ID  Start_date  end_date
100 9/4/14 14:53    9/4/14 14:56
100 4/24/13 12:49   4/24/13 14:08
100 9/25/15 11:06   9/25/15 11:14
101 2/7/15 12:05    2/7/15 12:09
101 2/4/13 17:18    Null
102 12/6/12 13:22   NULL
102 12/6/12 13:28   NULL
102 12/6/12 13:36   12/12/12 8:38

I want the output to be the minimum of the dates for each ID
ID  Start_date  end_date
100 4/24/13 12:49   4/24/13 14:08
101 2/4/13 17:18    Null
102 12/6/12 13:22   NULL

I have the following query:
SELECT distinct ID,
       min(end_date) ,
       min(Start_date)
from x
group by ID.

That pulls wrong corresponding values. How do I go about it?

A: Use ROW_NUMBER:
SELECT
    ID,
    Start_date,
    end_date
FROM (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Start_date) AS rn FROM x
) AS t
WHERE rn = 1;


text:
Q: não consigo colocar imagem no background tentei colocar a imagem no background coloquei o background-image, também coloquei o caminho na URL porém n pega de jeito nenhum.
body{
    margin: 10px;
    padding: 10px;
    background-image:url( ooo/imagens/back.jpg);
}

A: background-image: url('../imagens/back.jpg');


text:
Q: Как вы реализуете валидацию форм? На самом деле в каждом новом проекте меня мучает неопределенность в выборе валидации форм. То в одном плагине нет проверки на email, то нет проверки на only numbers и таких примеров привести можно очень много. В ответах я не хочу получить ссылки на поисковики. Просто напишите как проверяете формы вы. Спасибо!
A: плагин jquery.validate
A: Один раз сделал так: регулярку вписал в атрибут поля.
И навешал обработчик на каждый импут с проверкой по этой регулярке.


text:
Q: Why atan2(y,x) is faster to compute than arcsin or arccos? I've read that when I know Y and X it's better to compute atan2(y,x) to get the angle instead of using a single value with asin and acos. I've tried to dig into math.h lib but I didn't found any formula.
Can someone explain why atan2 is better?

A: I guess you are comparing two pieces of code that look mostly like this:
angle = atan2(x, y);

and
angle = acos(x / sqrt(x * x + y * y));

(I assume C code)
The first part calculates what you need directly, while the second part does it in a roundabout way - it's natural to expect that the first one is faster (unless atan2 implementation contains some variant of the second code example).
In addition, atan is a pretty "primitive" function - it "feels" more general than "acos" or "asin". x87 has a command for it, so I expect old implementations of acos to use atan2 internally. Also, I don't know enough of SSE, but it would be reasonable to expect SSE to implement atan2, even just for compatibility with x87.

A: theta = atan2(y,x);

is more simple than:
float in = 1.0/sqrt(x*x+y*y);
theta = acos(x*in);
if(y<0)
    theta = -acos(x*in);
else
    theta = acos(y*in);

Don't you think? It's simpler, and maybe faster, depending on the implementation.
Now, if x and y are not arbitrary, but if you can assume for instance that x²+y²=1 and y>=0, then
theta = acos(x);

Is more simple, and maybe faster than atan2. But again, speed with vary with implementations. The atan2 might, or might not, be implemented with acos and asin, or using faster algorithms.


text:
Q: how to match other languages words with regex Replace words in a Greek given text, for example with English words.
Here an example:
 var str= "Ενώ Gallant δεν λειτουργεί στην προσπάθεια να χτίσει πια μηχανές αποκωδικοποίησης, οι άλλοι."

function findword(){
  word = new RegExp("\\b(προσπάθεια)\\b","gi")
  var sust = str.replace(word,'effort');
}

It should return:
"Ενώ Gallant δεν λειτουργεί στην effort να χτίσει πια μηχανές αποκωδικοποίησης, οι άλλοι.
Trying to do it in JavaScript I failed, but I have read that this is not possible since this language does not handle Unicode characters other than English. The only possibility I found is xregexp, but it seems that only would work to detect character classes and not individual words. ¿Is really impossible to make it work in JavaScript?
The Python 3 Documentation states that this language can handle unicode characters, but in this case it seems that it's necessary to write characters with the unicode code... With which languaje would it be possible to replace words in the simplest way as I wrote in the code? Python, Java, Perl ...?

A: This should do it:
'Ενώ Gallant δεν λειτουργεί στην προσπάθεια να χτίσει πια μηχανές αποκωδικοποίησης, οι άλλοι.'.replace( /(προσπάθεια)/g, 'effort' )
Edit
I think this does exactly what you want:
String.prototype.translate = function translate( greek, english ) {
  return this.replace( new RegExp( '(' + greek + ')' ), english );
}

var translatedString = 'Ενώ Gallant δεν λειτουργεί στην προσπάθεια να χτίσει πια μηχανές αποκωδικοποίησης, οι άλλοι.'.translate( 'προσπάθεια', 'effort' );
console.log( translatedString );

A: Perl has exceptional unicode handling. E.g. the following code:
use 5.016;
use warnings;
use utf8;
use open qw(:std :utf8);

my $str= "Ενώ Gallant δεν λειτουργεί στην προσπάθεια να χτίσει πια μηχανές αποκωδικοποίησης, οι άλλοι.";
$str =~ s/\bπροσπάθεια\b/effort/g;
say $str;

prints
Ενώ Gallant δεν λειτουργεί στην effort να χτίσει πια μηχανές αποκωδικοποίησης, οι άλλοι.


text:
Q: Problem compiling C-Function to Postgres; compiler didn't find postgres.h I was asked to create a C-Function to integrate with Postgres. The Postgres documentation to this kind of function is available here: Postgres documentation.
The function I am trying to compile is from the manual and it is called add_one, just for test. But I had a problem while compiling it. The command I followed of the documentation was:
cc -fPIC -c foo.c
cc -shared -o foo.so foo.o

And the problem it returned was:
[igoralberte@localhost inside-postgres]$ cc -fPIC -c serializacao.c
serializacao.c:1:10: fatal error: postgres.h: Arquivo ou diretório inexistente
 #include "postgres.h"
          ^~~~~~~~~~~~
compilation terminated.

In English, it means: Non-existent file or directory (postgres.h).
I have tried to copy some files I thought were important to /usr/lib directory. They were on /usr/include/pgsql or on /lib64. Those files were:

*

*libpq.so

*libpq.so.5

*libpq.so.5.13

*libpq (directory)

*postgres_ext.h

Some important informations about my system:

*

*I am using CentOS 8

*System architecture: x86-64

*GCC version: gcc (GCC) 8.4.1 20200928 (Red Hat 8.4.1-1)

*Postgres version: 13.3

Thanks in advance!

A: It is a bold step to write a postgres plugin before you have a solid grasp on linux/unix, shell programming and how to compile c programs.
Typically your c compiler has to be told where to find header files using the -I compiler switch. So if postgres.h is in /path/containing/headerfile, you must add -I/path/containing/headerfile to the compile command:
cc -I/path/containing/headerfile -fPIC -c foo.c

The postgres documentation you linked to tells you to use pg_config --includedir-server to find out where the the header files are stored.
I am not familiar with pg_config, but if it acts like similar tools and
gives the output -I/path/containing/headerfile when calling it with the paramater --includedir-server, then you don't have to hardcode the path in your compile command. But just write:
cc `pg_config --includedir-server` -fPIC -c foo.c

See "Command Substitution" in your favorite shell documentation.
I also recommend learning how to use a build-tool like make. Things are soon going to be tedious if you have to retype compilation and link commands all the time.
Oh, and by the way, you probably want to write #include <postgres.h> and not #include "postgres.h" (Unless you are a postgres contributor and postgres.h is part of your project files)


text:
Q: Concurrent writes to a shared network resource Here is the context for the problem I am trying to solve.
There are computers A and B, as well as a server S. Server S implements some backend which handles incoming requests in a RESTful manner.
The backend S has a shelf. The goal of users A and B is to make S create and place numbered boxes on that shelf. A unique constraint is that no two boxes can have the same number. Once a box is created, S should return that box (JSON, or xml...) back to A and B with its allocated number.
The problem boils down to concurrency, as A and B's POST ("create-numbered-box") transactions may arrive at the exact same time at the database - hence get cancelled (?). I remind, there is a unique constraint - no two boxes are allowed to have a same number.
What are possible ways to solve this problem? I wouldn't like to lock the database, so I am looking for alternatives of that. You are allowed to imagine that between the database and the backend layer calling the database we may have an extra layer of abstraction, e.g. a microservice, messaging queue... whatever or nothing at all - a direct backend - db exec. query call. If you think a postgres database is not a good choice to say a graph one, or document one, key-value one - feel free to substitute it.
The goal is in the end given concurrent writes users A and B to get responses to their create (POST) requests and each of them have a box on that shared shelf with a unique number, with no "Oops, something went wrong. Please retry" type of server response.
I described a simple world with users A and B but that can in theory go up to 10 000 users writing, not just 2.
As a secondary question, I'd like to ask, is there a way to test conflicting concurrent transactions in postgres?
I will go first.
My idea is, let A and B send requests and fail. Once they fail, have retries with random timeouts in some interval. Let's say up to 3 retries. This way for A and B I will try to separate the requested writes to the db and this would allow for some degree of successful resolution of the scenario. However, I don't think this is a clean solution and I am looking for alternatives you can think of. Just, please keep in mind the constraints and freedoms I mentioned above.

A: Databases such as Posgres include capabilities to have a unique number generated by the database (see PostgreSQL - SERIAL - Generate IDs (Identity, Auto-increment)). So the logic for your backend service S could be:

*

*lookup if user has a record in the database already

*return the id if it does

*otherwise, create a record and return the newly allocated id

To avoid creating multiple boxes for the same user you need to serialize the lookup/create logic based on user id. Approaches to that vary from merely handling one request at a time in your service S to, for example, having Kafka topics that partition requests to different instances of service S based on user ids -- all depends on the scale.


text:
Q: How to go from an explicit proof of size decrease to a halting reduction algorithm? Suppose I have:

*

*A Linear : Set type for linear λ-calculus terms.

*A reduce-once : Term → Term function that performs a global reduction of redexes.

*A size : Linear → Nat relation that counts the number of constructors.

*A proof reduce-once-halts : (t : Linear) → size (reduce-once t) < size t.
That is, I have a proof that applying reduce-once always decreases the size of a term. From that, one should logically be able to implement a terminating function, reduce : (t : Linear) → Sigma t IsNormalized, that reduces the term to normal form. Since I believe this is a common situation, my question is: how is that usually formalized in Agda? How can I convince it that a function that decreases the size of its argument can be applied recursively and will eventually halt?

A: You can use <-rec from the Data.Nat.Induction module to do well-founded induction over _<_. In this case, one solution is to do induction on the predicate "terms of size strictly less than n can be reduced":
open import Data.Nat
open import Data.Nat.Induction
open import Data.Nat.Properties
open import Relation.Binary.PropositionalEquality

postulate
  Term : Set
  reduce-once : Term → Term
  size : Term → ℕ
  reduce-once-halts : (t : Term) → size (reduce-once t) < size t

reduce-aux : (n : ℕ) (t : Term) → size t < n → Term
reduce-aux = <-rec
  (λ n → (t : Term) → size t < n → Term)
  λ n h t size-t<n → h (size t) size-t<n (reduce-once t) (reduce-once-halts t)

reduce : Term → Term
reduce t = reduce-aux (1 + size t) t ≤-refl


text:
Q: thread 1: "GDB:Program received signal: "SIGABRT"." with openears I was installed pocketsphinx on mac 10.6.8 using OpenEars with English dictionary and it working on iphone and simulator perfectly but I want to replace the dictionary from Arabic to English and when I replace the dictionary to Arabic then there is error when I run it

thread 1: "GDB:Program received signal: "SIGABRT"

how can I load solve it
NSScanner *scanner = [[NSScanner alloc] initWithString:[pronunciationDictionary substringWithRange:limitingRange]];

A: OpenEars developer here. Changing the dictionary used by the LanguageModelGenerator class isn't supported and it will lead to a crash. It isn't necessary to use LanguageModelGenerator in order to do speech recognition or text to speech; it's only used for in-app dynamic language model generation in English. You can still generate language models using the CMU language tool or manually.


text:
Q: Unable to add assembly to the GAC gacutil confirms that I've added my own assembly to the GAC. But when I go to look, it's not there. I know that for version 4 and above,  they are located in GAC_MSIL. But it's not there either despite the following message in the developer command prompt:

C:\Users\Matheus\source>gacutil /l CarLibrary Microsoft (R) .NET
  Global Assembly Cache Utility.  Version 4.0.30319.0 Copyright (c)
  Microsoft Corporation.  All rights reserved.
The Global Assembly Cache contains the following assemblies:
  CarLibrary, Version=1.0.6685.33745, Culture=neutral,
  PublicKeyToken=a9431d52640b43f3, processorArchitecture=MSIL
  CarLibrary, Version=1.0.6685.35757, Culture=neutral,
  PublicKeyToken=a27f772b6d6ad3a3, processorArchitecture=MSIL
Number of items = 2


text:
Q: Issue with android class library resources after updating xamarin After updating to the newest release from xamarin I am experiencing some issues regarding resources.
We have a android class library which contains our core android app features, e.g activities, android resources(default Icons and so forth).
This is referenced by multiple android projects each containing their own android resources for example Icons. This is caused by we are selling different instances of the same app, only resource graphic is different.
When build the android application uses the Resources from the android class library and not its own Resources.
Earlier the android app woud use it owns resources so I am not sure what is different now.
We are using the same setup for ios and this works as earlier

A: If you look at the top of the Xamarin Forums, specifically in the Android section, you will find a post mentioning a plethora of breaking changes and known issues. This is also described in the release notes.
The workaround right now is to avoid having the same resource names both in the library and the application. See Xamarin Bugzilla 29326.


text:
Q: mechanize print to pdf
Possible Duplicate:
How do I grab a thumbnail screenshot of many websites?

I wrote a script using perl mechanize to login and fetch a page. How can I "print" that page to "pdf" directly from my perl script? I'd like to save a snapshot of how it looks in the browser.
I can get the html using $mech->content();

A: Check out wkhtmltopdf - there are variants for PDF and images (PNG etc). It's basically a command-line tool wrapping the webkit html engine. Works quite nicely, and it's cross-platform too. Whether you can get it past your login form will depend on how the target site works.

A: There's a number of CPAN modules to convert HTML to PDF.  Feed any of them the content from Mechanize.

A: The $mech contain plain html so you can't just print it. Check this thread: How do I grab a thumbnail screenshot of many websites?


text:
Q: Cannot find database driver: org.postgresql.Driver for RDS postgres connection-Liquibase I am trying to connect to RDS Postgres from Liquibase.
Maven dependency is:
<dependency>
    <groupId>software.aws.rds</groupId>
    <artifactId>aws-postgresql-jdbc</artifactId>
    <version>0.1.0</version>
</dependency>

I am not using properties file as the credentials are confidential and I cannot put them in properties file.
hence calling using command line
-liquibase --url:jdbc:postgressql://xxxx.rds.amazonaws.com:5432/database_name --username = $username --password = $password --changeLogFile=changelog_aurora.xml update

Also tried:
-liquibase --url:jdbc:postgressql://xxxx.rds.amazonaws.com:5432/database_name --username = $username --password = $password --changeLogFile=changelog_aurora.xml --driver=org.postgressql.Driver update

I am getting below error:

Unexpected error running liquibase: java.lang.RuntimeException:Cannot
find database driver: org.postgres.Driver

Please help me here. Do I need to install Postgres dependency as well? If so what should be the version? should it match with AWS RDS Postgres?

A: I have following recommendations for you:

*

*You can download Postgre JDBC driver file from here if you haven't already or if you don't have JAVA installed and configured.

*Preferably keep your postgresql-<version>.jar file in the same folder where your changelog file is OR add path (ref) OR use --classpath=path:anotherPath with your commandline to indicate where should liquibase go and look for the Postgre JDBC driver file.

*Also if you are familiar with AWS SSM, you can keep all your secrets in SSM and read at runtime from within your property file (FYI)


text:
Q: Solve single variable equation using if, else and while statements in python I am tutoring a 7th grade student in basic programming and mathematics. One of the problems the students needs to complete for a class assignment is "create a program to solve a given single variable linear equation". The student is required to use python and only use if, else and while statements. The program can include user defined functions and lists but cannot import any libraries like regex, sympy, numpy, etc.
The program should be able to solve these example equations:

*

*2*x - 5 = 8

*4*x + 3 = 3*x - 10

*11*x = 2 - (1/5)*x

*4*(x + 2) = 5*(x + 9)

I tried: For each character in the string note the numerals, operators, equals to sign and variable. Copy the variable and its coefficient into a new string and the constants with their signs to another string. My hope was that I would eventually extract the integers from each string and solve the equation for x. But I wasn't correctly capturing numbers with multiple digits. And the equation with parentheses completely stumped me. Not being able to use regex or sympy is painful!
I am looking for a pythonic solution to this problem if it exists.
I feel this is a very difficult question for a 7th grader because my grad and undergrad friends haven't been able to come up with a solution. Any advice on how to proceed will help if a programmatic solution isn't available.
Thank you.

A: Although it is completely possible to build a finite automaton solve an expression, it is not an easy task.
I myself had lots of assignments related to build a semantic or syntax parser, but it is usually done in C: https://codereview.stackexchange.com/questions/112620/simple-expression-calculator-in-c.
Nonetheless, if you accept a clever/dangerous/bad-practice solution:
def solve_expression(expr, var="x"):
    expr = expr.replace(var, "1j")
    left, right = map(eval, expr.split("="))

    return (right.real-left.real)/(left.imag-right.imag)

print(solve_expression("2*x - 5 = 8"))
print(solve_expression("4*x + 3 = 3*x - 10"))
print(solve_expression("11*x = 2 - (1/5)*x"))
print(solve_expression("4*(x + 2) = 5*(x + 9)"))

The idea is to convert the free variable to the imaginary unit and let python interpreter do the rest.


text:
Q: No sale JFRAME ni nada en consola Hola como ejercicio estoy intentando programar un buscaminas. Creía que con lo que tenía hecho ya se debería ver al menos la ventana y todos los botones pero no es así y no entiendo que es lo que me falta. Cada vez que compilo no pasa absolutamente nada. (dejo el metodo cargarNumeros() x las dudas pero el error no debería estar ahí. aclaro xq es engorroso leerlo y no creo que sea necesario).  La idea es generar 100 botones de los cuales 20 van a ser bombas y al igual que en el buscaminas de windows, cada boton va a tener un número que indica cuantas bombas tiene alrededor (pudiendo ser 0 o más)
import javax.swing.*;

public class Recursividad extends JFrame implements ActionListener  {

    JButton contenedor [] [] = new JButton [10] [10];

Recursividad() {
    setLayout (null);
    for (int f = 0 ; f < 10 ; f++) {
 for(int c = 0; c< 10; c++) {
contenedor [f][c] = new JButton("0");
contenedor [f] [c].setBounds (20 + c * 41, 50 + f * 41, 41, 41);
contenedor [f] [c].setBackground (Color.lightGray);
contenedor [f] [c].setForeground (Color.lightGray);
contenedor [f] [c].addActionListener (this);
add (contenedor [f] [c]);
    }
}
cargarBombas();
cargarNumeros();
}

public void cargarBombas() {
        for (int x = 0; x < 20; x++) {
            int f = 0;
            int c = 0;
            do {
                f = (int) (Math.random() * 10);
                c = (int) (Math.random() * 10);
            } while (contenedor[f][c].getText() != "b");
    contenedor [f] [c].setText("b");
        }
}

public void cargarNumeros() {
    for(int f = 0; f < 10 ; f++ ) {
        for (int c = 0; c < 10 ; c++)  {
    int contador = 0;

    if (contenedor [f][c].getText() != "b")  {

            if (f -1 >= 0 && c-1 >= 0 && contenedor [f-1][c-1].getText() == "b" )
            contador++;
            if (c -1 >= 0 && contenedor [f-1][c].getText() == "b")
            contador++;
            if (f +1 <= 9 && c -1 >= 0 && contenedor [f-1][c].getText() == "b")
                contador++;
            if (f +1 <= 9 && contenedor [f-1][c].getText() == "b")
                contador++;
            if (f +1 <= 9 && c+1 <= 9 && contenedor [f+1][c+1].getText() == "b")
                contador++;
            if (c +1 <= 9 && contenedor [f][c+1].getText() == "b")
                contador++;
            if (f -1 >= 0 && c+1 <= 9 && contenedor [f-1][c+1].getText() == "b")
                contador++;
            if (f -1 >= 0 && contenedor [f-1][c].getText() == "b")
                contador++;

            contenedor [f][c].setText(String.valueOf(contador));
    }

        }
    }
}

public void actionPerformed(ActionEvent e) {
    for (int f = 0 ; f < 10 ; f++) {

        for (int c = 0 ; c < 10 ; c++) {
            if (e.getSource () == contenedor [f] [c])
              {
                  if (contenedor [f] [c].getText ().equals ("b") == true)
                  {
                      setTitle ("Boooooooooooooomm");
                     // desactivarJuego ();
                  }

        }

        }
    }
}

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Recursividad p = new Recursividad();
        p.setBounds (0, 0, 470, 600);
        p.setVisible(true);
        p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

A: He corregido tu código para que muestre el Jframe
-solución: dentro del constructor agregar los metodos setVisible() y setBounds(), agregar un layout BorderLayout para ubicarlo al centro y que ocupe toda la ventana.
JButton contenedor[][] = new JButton[10][10];

public a() {
    setBounds(0, 0, 470, 600);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());
    for (int f = 0; f < 10; f++) {
        for (int c = 0; c < 10; c++) {
            contenedor[f][c] = new JButton("0");
            contenedor[f][c].setBounds(20 + c * 41, 50 + f * 41, 41, 41);
            contenedor[f][c].setBackground(Color.lightGray);
            contenedor[f][c].setForeground(Color.lightGray);
            contenedor[f][c].addActionListener(this);
            add(contenedor[f][c], BorderLayout.CENTER);
        }
    }
    cargarBombas();
    cargarNumeros();
}

public void cargarBombas() {
    for (int x = 0; x < 20; x++) {
        int f = 0;
        int c = 0;
        do {
            f = (int) (Math.random() * 10);
            c = (int) (Math.random() * 10);
        } while (contenedor[f][c].getText() != "b");
        contenedor[f][c].setText("b");
    }
}

public void cargarNumeros() {
    for (int f = 0; f < 10; f++) {
        for (int c = 0; c < 10; c++) {
            int contador = 0;

            if (contenedor[f][c].getText() != "b") {

                if (f - 1 >= 0 && c - 1 >= 0 && contenedor[f - 1][c - 1].getText() == "b") {
                    contador++;
                }
                if (c - 1 >= 0 && contenedor[f - 1][c].getText() == "b") {
                    contador++;
                }
                if (f + 1 <= 9 && c - 1 >= 0 && contenedor[f - 1][c].getText() == "b") {
                    contador++;
                }
                if (f + 1 <= 9 && contenedor[f - 1][c].getText() == "b") {
                    contador++;
                }
                if (f + 1 <= 9 && c + 1 <= 9 && contenedor[f + 1][c + 1].getText() == "b") {
                    contador++;
                }
                if (c + 1 <= 9 && contenedor[f][c + 1].getText() == "b") {
                    contador++;
                }
                if (f - 1 >= 0 && c + 1 <= 9 && contenedor[f - 1][c + 1].getText() == "b") {
                    contador++;
                }
                if (f - 1 >= 0 && contenedor[f - 1][c].getText() == "b") {
                    contador++;
                }

                contenedor[f][c].setText(String.valueOf(contador));
            }

        }
    }
}

@Override
public void actionPerformed(ActionEvent e) {
    for (int f = 0; f < 10; f++) {

        for (int c = 0; c < 10; c++) {
            if (e.getSource() == contenedor[f][c]) {
                if (contenedor[f][c].getText().equals("b") == true) {
                    setTitle("Boooooooooooooomm");
                    // desactivarJuego ();
                }

            }

        }
    }
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    new a();

}

Resultado


text:
Q: "Invalid declaration of or reference to symbol ..." errors I want to compile a makefile containing the following command on ubuntu 32 bit machine.
g77 -Wall -c -x f77-cpp-input -Wall

But I have some problems I cannot resolve.
[gustep.f][1] : In subroutine `gustep':
gustep.f:21:
           INCLUDE 'gcblocks.inc'
           ^
Unable to open INCLUDE file `[gcblocks.inc][2]' at (^)
gustep.f:122:
           CUTNEU = 1.0e-8
           ^
Invalid declaration of or reference to symbol `cutneu' at (^) [initially seen at (^)]
gustep.f:123:
           IHADR = 5
           ^
Invalid declaration of or reference to symbol `ihadr' at (^) [initially seen at (^)]
gustep.f:125:
           IF(NGKINE.GT.0) CALL GSKING(0)
              ^
Invalid declaration of or reference to symbol `ngkine' at (^) [initially seen at (^)]
gustep.f:129:
                 IF(GKIN(5,I).EQ.13) THEN
                    ^
Invalid declaration of or reference to symbol `gkin' at (^) [initially seen at (^)]
gustep.f:140:
           IF(INWVOL.EQ.1) THEN
              ^
Invalid declaration of or reference to symbol `inwvol' at (^) [initially seen at (^)]
gustep.f:141:
               CALL GMEDIA(VECT,NUMED)
                           ^
Invalid declaration of or reference to symbol `vect' at (^) [initially seen at (^)]
gustep.f:141:
               CALL GMEDIA(VECT,NUMED)
                                ^
Invalid declaration of or reference to symbol `numed' at (^) [initially seen at (^)]
gustep.f:144:
           CALL UHTOC(NAMES(NLEVEL),4,NAME,4)
                      ^
Invalid declaration of or reference to symbol `names' at (^) [initially seen at (^)]
gustep.f:144:
           CALL UHTOC(NAMES(NLEVEL),4,NAME,4)
                            ^
Invalid declaration of or reference to symbol `nlevel' at (^) [initially seen at (^)]
gustep.f:152:
           IF(ITRA.EQ.TRAK_P) THEN
              ^
Invalid declaration of or reference to symbol `itra' at (^) [initially seen at (^)]
gustep.f:173:
                COPY_NO      = NUMBER(NLEVEL-2)
                               ^
Invalid declaration of or reference to symbol `number' at (^) [initially seen at (^)]
gustep.f:177:
                DE_P_DEL(M)  = DE_P_DEL(M)+DESTEP*1000.
                                           ^
Invalid declaration of or reference to symbol `destep' at (^) [initially seen at (^)]
In file included from gustep.f:0:

Why this declaration is invalid? And how to solve the problem? May
someone explain it?

A: It's just what the compiler tells you:
Unable to open INCLUDE file `[gcblocks.inc][2]'

It can't find the file gcblocks.inc. The other errors are about missing variable declarations. Probably, these are declared in the missing file. Is gcblocks.inc in the current directory? If not, you will need to specify its directory with -I/path/to/include/dir/.


text:
Q: Rebuilding array from http_build_query() I'll try to make this short and sweet. Pretty much I am passing some variables from one page to the next and I want to rebuild that array on the next page.
<?php
 /* $user is and array of data specific to the user */
 $user_id = $user["userId"]; // we'll pretend the value is 13
 $manager_ids = array(42,56,76);
 $url = './mod-super-admin/edit-relationship.php?edit=true&repId=' . $user_Id  . '&';
 $url .= http_build_query($manager_ids, 'manager_');
?>

I am using that $url and echoing inside an href so that user can be editing on the next page. When I click that anchor tag, it brings me to:
http://localhost:8888/applicationName/mod-super-admin/edit-relationship.php?edit=true&repId=13&manager_0=42&manager_1=56&manager_2=76
This is fine and dandy and is exactly what I want, BUT I am having trouble bringing back those value that were in the array back into an array. The catch here is I DO NOT want edit => true and repId => 13 in that array. I just want those managers to go back into an array.
Thanks for looking!

A: I would propose making a managers array in the URL:
$url .= http_build_query(array('managers' => $manager_ids));

Yields:
managers%5B0%5D=42&managers%5B1%5D=56&managers%5B2%5D=76

When received by PHP it will be interpreted as:
managers[0]=42&managers[1]=56&managers[2]=76

So $_GET['managers'] will yield:
Array
(
    [0] => 42
    [1] => 56
    [2] => 76
)


text:
Q: How to change svg viewport programmatically? It is necessary to implement moving of ALL images inside of svg object. I plan to handle mouse events (down, move, up) and change viewport of svg (using JavaScript + probably jQuery).
The problem for me is I don't see how to change svg viewport parameters.
Please advise.
P.S. If you know something similar implemented already, please share the link. Thanks a lot!

A: jQuery SVG lets you do this
svg.configure({viewBox: '0 0 100 100'}, true);
http://keith-wood.name/svgRef.html#configure


text:
Q: How to have a deadlock scenario with boost MPI (I use MPICH compiler)? I am trying to find out in what cases a potentially blocking boost mpi "send" will actually block and causes a deadlock.
#include <boost/mpi.hpp>
#include <iostream>

int main(int argc, char *argv[])
{
  boost::mpi::environment env{argc, argv};
  boost::mpi::communicator world;
  if (world.rank() == 0)
  {
    char buffer[14];
    const char *c = "Hello, world from 1!";
    world.send(1, 1, c, 13);
    std::cout << "1--11111\n";
    world.send(1, 1, c, 13);
    std::cout << "1--22222\n";
    world.recv(1, 1, buffer, 13);
    std::cout << "1--33333\n";
    world.recv(1, 1, buffer, 13);
    std::cout << "1--44444\n";
     buffer[13] = '\0';
    std::cout << buffer << "11 \n";
  }
  else
  {
    char buffer[14];
    const char *c = "Hello, world from 2!";
    world.send(0, 1, c, 13);
    std::cout << "2--11111\n";
    world.send(0, 1, c, 13);
    std::cout << "2--22222\n";
    world.recv(0, 1, buffer, 13);
    std::cout << "2--33333\n";
    world.recv(0, 1, buffer, 13);
    std::cout << "2--44444\n";
    buffer[13] = '\0';
    std::cout << buffer << "22 \n";
  }
}

but it runs just fine and the with this order:
2--11111
2--22222
1--11111
1--22222
1--33333
1--44444
Hello, world 11
2--33333
2--44444
Hello, world 22

I will be grateful if someone could give me a scenario in which I have actually deadlock.
How does the potentially blocking boost mpi works?
Thank you.

A: Implementations may or may not complete MPI_Send before the recieve is posted. Your code is not a correct MPI application. It may deadlock with a specific message size, on a specific network, during full moon while it's raining.
In practice it mostly depends on the message size as implementations commonly send small messages to preallocated buffers. There may be a tuning parameter depending on your implementation.
MPI describes several communication modes. The default is blocking1 or standard mode, as described above. A synchronous send (MPI_Ssend) must wait for the receive to be posted. This will guarantee a deadlock.
A buffered send (MPI_Bsend) must complete even if the recieve is not posted. In addition to the modes, there are nonblocking or immediate calls that will always complete locally, but may not copy the data yet. Both will guarantee no deadlock. However only the latter is supported by boost.MPI.
1: blocking in the terminology only means that the call blocks until the send buffer can be reused. Either because it was sent, or because it was buffered locally. Also take a look at the standard.

A: The generally easiest way to force blocking behavior is to use larger messages that cause a switch to a so-called 'rendezvous' protocol, where the sender will wait for the recipient to post the matching receive operation before starting data transfer.


text:
Q: How can I make the following 2 fractions integers? Let $m,n$ be integers. I want to find the possible values of $m,n$ such that $4(m+n)\over (2m+n)^2+3n^2$ and $4n\over (2m+n)^2+3n^2$ are both integers too. Would someone please help? Of course letting $(2m+n)^2+3n^2=4$ gives some good values, but is this all the $m,n$ I can get?
Added: I can see that the problem can be reduced to  asking for $4k\over (2m+n)^2+3n^2$ to be an integer for both $k=m,n$

A: We find all integer values of $m$ and $n$ such that $\frac{4n}{(2m+n)^2+3n^2}$ is an integer.  Once this is done, your problem that imposes additional conditions is easily solved.
If $3n^2 > 4n$, then the bottom has absolute value greater than the absolute value of the top.  Thus all but $n=0$, $n=\pm 1$ are immediately ruled out.
If $n=0$, we are looking at $\frac{0}{4m^2}$, which is an integer for all non-zero $m$.
If $n=1$, then we are looking at $\frac{4}{4m^2+4m+4}$, or equivalently at $\frac{1}{m^2+m+1}$.  This is an integer only in the cases $m^2+m+1=\pm 1$. The equation $m^2+m+1=1$ has the solutions $m=0$ and $m=-1$.  The equation $m^2+m+1=-1$ has no real solutions, let alone integer solutions.
By a similar argument, or by symmetry, the case $n=-1$ gives the solutions $m=0$ and $m=-1$.
So for integer values of $n$ and $n$, $\frac{4n}{(2m+n)^2+3n^2}$ is an integer precisely in the following cases:
(i) $n=0$, $m$ arbitrary non-zero; (ii) $n=1$, $m=0$ or $m=-1$; and (iii) $n=-1$, $m=0$ or $m=1$.

A: Since $(2m+n)^2 + 3n^2 = 4m^2 + 4mn + n^2 + 3n^2 = 4m^2 + 4mn + 4n^2$, then
$$\frac{4(m+n)}{(2m+n)^2+3n^2} = \frac{4(m+n)}{4m^2+4mn+4n^2} = \frac{m+n}{m^2+mn+n^2}.$$
Similarly,
$$\frac{4n}{(2m+n)^2+3n^2} = \frac{4n}{4m^2+4mn+4n^2} = \frac{n}{m^2+mn+n^2}.$$
For both to be integers, you need $m^2+mn+n^2$ to divide both $m+n$ and $n$; hence, it must divide both $m$ and $n$.
If $mn\gt 0$, then this is clearly impossible, since then $m^2+mn+n^2$ is strictly larger than each of $m$ and $n$ (as they are all integers). So $m$ and $n$ cannot both be positive or both be negative.
If $m=0$ or $n=0$, then you have that $m^2$ divides $m$, or $n^2$ divides $n$, hence you must have $(m,n) = (0,\pm 1)$ or $(\pm 1,0)$.
So we are now reduced to the case where one of $m,n$ is negative and one is positive. Let us say, without loss of generality that $m\lt 0\lt n$. If $|m|\lt n$, then $mn\lt n^2$, so $m^2+mn+n^2 \gt m^2 \geq |m|$; so $m^2+mn+n^2$ cannot divide $m$. If $|m|\gt |n|$, then $-m\gt n$, so $-m^2\lt mn$; hence $m^2+mn\gt 0$, so $m^2+mn+n^2\gt n^2\geq n$; hence $m^2+mn+n^2$ cannot divide $n$.
Finally, if $|m|=n$, then $mn=-n^2$, so $m^2+mn+n^2 = m^2 = n^2$; this divides $n$ if and only if $n=1$. So another solution is $(m,n) = (\pm 1,\mp 1)$, in which case your first fraction is $0$, and your second fraction is $1$.

A: We can't have $m=n=0$. Let's suppose for a moment that $n=0$ then (using Graphth's answer) $n/(m^2+mn+n^2)=0$ and $m/(m^2+mn+n^2)=1/m$ and $1/m$ is integer only if $m=-1$ or $m=1$. Since the problem is symmetric in $m$ and $n$ we found the solutions $(m,n)=(0,-1),(0,1),(1,0),(-1,0)$.
We know that if $a|b$ and $a,b\neq0$ then $|a|\le|b|$. Since $m^2+mn+n^2$ is always positive, we can say $m^2+mn+n^2\le |n|$ and since $|n|\le n^2$ for $n\in\mathbb{Z}$ we have $m^2+mn+n^2\le n^2$ then $m^2+mn\le 0$. Analogously $mn+n^2\le 0$. Summing up we get $m^2+2mn+n^2\le0$ or $(m+n)^2\le 0$. This inequality is only true if $(m+n)=0$. Now suppose $m=-n$.
We get that $m^2=m^2+mn+n^2|m$ then $m=1$ or $m=-1$. Using the symmetry we get two more solutions $(m,n)=(1,-1),(-1,1)$.

A: I wrote small Maple program that search for possible solutions :
for n from -1000 to 1000 do
for m from -1000 to 1000 do
if not(m = 0 and n = 0) then
a:=(4*(m+n))/((2*m+n)^2+3*n^2):
b:=(4*n )/((2*m+n)^2+3*n^2):
if type(a,integer) and type(b,integer) then
print(m,n);
end if;
end if;
end do;
end do;

It seems that there are only four pairs :
$(m,n)=(0,-1) , (m,n)=(-1,0) , (m,n)=(1,0) , (m,n)=(0,1)$
EDIT :
As Arturo rightly observed pairs :
$(m,n)=(-1,1) , (m,n)=(1,-1)~$ are also solutions .

A: Hint: put  $k = m^2+mn+n^2$. Reducing  fractions shows $k\ |\ m+n,n\ \Rightarrow \ k\ |\ (m+n,n) = (m,n)$.
But $\:(m,n)^2\:|\: k\ |\ (m,n)$ so $(m,n) = 1,\ k = \pm 1$.


text:
Q: RDP from 2008 R2 through a tunnel fails I'm trying to RDP from a Win7 to a 2008 R2 machine through a tunnel (think SSH, but not exactly).
It fails and the following is in the 2008 R2 (destination) event log:

System Event Log, LsaSrv source, Event ID 6037
"The program lsass.exe, with the
  assigned process ID 632, could not
  authenticate locally by using the
  target name TERMSRV/{WIN7_name}. The
  target name used is not valid. A
  target name should refer to one of the
  local computer names, for example, the
  DNS host name.
Try a different target name. "

The WIN7 side shows:

System Event Log, TermDD event source, Event ID 56
The Terminal Server security layer
  detected an error in the protocol
  stream and has disconnected the
  client. Client IP: {WIN7_name}.
(with an error code of C000018D = STATUS_TRUSTED_RELATIONSHIP_FAILURE)

So apparently the the RDP client is passing the local server name to the remote side (I did tell it to RDP to the Win7 machine, but to a tunneled port).
I haven't been able to find any way to tell the RDP client or server to ignore this problem.  It looks like it would be possible to use setspn.exe to set the {Win7_name} service principle name on the 2008 R2 box, but that seems messy, and in my case, my clients won't know how to do that.  Plus, you'd have to do it for all clients that might connect to that server.
Is anyone else able to RDP between 2008 R2 and Win 7 using tunneling?

A: It sounds like you've got the server computer setup to only allow RDP connections that pass "Network Level Authentication" (certificate-based authentication to prevent man-in-the-middle attacks). You can turn this off on the server side by going into "Remote Desktop Session Host Configuration", bringing up the properties for the "RDP-Tcp" connection in the "Connections" dialog, and unticking the "Allow connections only from comptuers running Remote Desktop with Network Level Authentication".
When you do this be warned that an attacker could setup a bogus RDP server that appears to be your server for the purpose of collecting passwords.
Edit:
Using rinetd to tunnel a local port on a Windows 7 Professional machine to the RDP port on a Windows Server 2008 R2 computer I am able to access the remote computer fine w/ the Microsoft RDP client.
It feels like your RDP client isn't falling back to NTLM after Kerberos fails. I'm not immediately seeing what configuration setting might casue that to happen, though. Do you have any policy settings on the server computer to disallow NTLM authentication?
I'd be curious to know if disabling CredSSP would help. Save the RDP connection properties to a file, edit the file with your favorite text editor, and add a line enablecredsspsupport:i:0 (or, if the line already exists, change '1' to '0' and the end of the line).


text:
Q: Retrofit - Pass URL values dynamically - GET method I have a URL for example :
https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/KMHDC8AEXAU084769?format=JSON
Here I want to change KMHDC8AEXAU084769?format=JSON this part dynamically
How to do it with Retrofit2.
I tried like:
@FormUrlEncoded
    @GET("{input}")
    Call<Result> getVin(@Path("input") String input, @Field("format") String format);

But @FormUrlEncoded is only supports for POST not for GET.
This is the way I am calling it:
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

        Call<Result> call = apiService.getVin(vin, "JSON");
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                Result result = response.body();

                Log.e("Result: ", "" + response.body());

                Gson gson = new Gson();
                String json = gson.toJson(result);

                responseTV.setText("" + json);
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                // Log error here since request failed
                Log.e("MainActivity", t.toString());
                Toast.makeText(MainActivity.this, "Try later", Toast.LENGTH_SHORT).show();
            }
        });

A: This is described in the documentation....

URL MANIPULATION
A request URL can be updated dynamically using replacement blocks and
  parameters on the method. A replacement block is an alphanumeric
  string surrounded by { and }. A corresponding parameter must be
  annotated with @Path using the same string.
Query parameters can also be added.
@GET("group/{id}/users") Call> groupList(@Path("id") int
  groupId, @Query("sort") String sort);
For complex query parameter
  combinations a Map can be used.
@GET("group/{id}/users") Call> groupList(@Path("id") int
  groupId, @QueryMap Map options);

For your desired url structure this should work with something like this:
@GET("{id}")
Call<List<User>> groupList(@Path("id") int id, @Query("format") String format);

http://square.github.io/retrofit/

A: Try this:
@GET("/api/vehicles/DecodeVinValues/{input}")
Call<Result> getVin(@Path("input") String input, @Query("format") String format);

@FormUrlEncoded and @Field annotations are for POST requests.
Current value of the parameter of @GET annotation may differ according to your baseUrl value you are using.


text:
Q: Starcraft II Practicing new units and game changes Since Legacy of the Void the challenge missions are banned to the terran campaign "Episode I Wings of Lilberty", followed by the Challenge Missions image.
These missions still use the game settings for WoL.
Are there similar Challenges available to practise your skills with the new LotV rules and units? Maybe somewhere in the Arcade section, something like Starcraft Masters?

A: I would highly recommend you to:
Watch Streams: Watch some of the best SC2 streamers. Of course, watch the players which play your race. You'll see how to use new tricky units and which build to learn in order to build them. Take a look at Twitch SC2 and Team Liquid Stream Wall;
Play custom games with friends or vs AI: You'll be able to test new units without failing or being stressed;
Play Micro Arena - Arcade: You'll be only focused on using a bunch of units to win. You will learn, also, how to use some of the new units or just combine them with the old ones;
Play Unit Tester - Arcade: You'll be able to create any army you want and test every unit and its ability;
Play Unranked and Ranked Games: When you'll be a bit more confident, try starting to climb the ladder;
Play off-race games: Try playing with all 3 different races to understand deeply how new units work.
I hope I've been Helpful.


text:
Q: Flutter - I can't change the state of a static method of onWillPop I have a bottomNavigatorBar in my app, and on some screens I don't make it visible, so create a static method to handle it from any class. it works, but when I use the instance of this static method in onWillPop I have the following problems...
E/flutter (10927): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: setState() called in constructor: _telaPrincipalState#cb9c4(lifecycle state: created, no widget, not mounted)
E/flutter (10927): This happens when you call setState() on a State object for a widget that hasn't been inserted into the widget tree yet. It is not necessary to call setState() in the constructor, since the state is already assumed to be dirty when it is initially created

I already used mounted, but it still didn't work
if(!this.mounted){
}
Here is the 3 page code where I use routes
class AtivarEmailPage extends StatefulWidget {
  static const String route = "/ativarEmail";

  @override
  _AtivarEmailPageState createState() => _AtivarEmailPageState();
}

class _AtivarEmailPageState extends State<AtivarEmailPage> {
@override
 Widget build(BuildContext context) {

    return WillPopScope(
      onWillPop: () {
        if (!mounted) {
          setState(() => telaPrincipal.show());
        }

        Navigator.of(context).pushNamedAndRemoveUntil(
            HomeView.route, (Route<dynamic> route) => false,
            arguments: null);
      },
      child: Scaffold(code...),);
  }
}

the problem happens when I call onWillpop to return to HomeView
class HomeView extends StatefulWidget {
  static const String route = "/";

  @override
  _HomeViewState createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> {

Widget home(BuildContext context) {
    return Scaffold(code..);
  }
}

the bottomNavigatorBar manipulated by the static method is in the code below. It is the screen that is under the whole stack, so the navigation bar is floating on top of the other pages
class telaPrincipal extends StatefulWidget {
  telaPrincipal({this.categoria, this.exercicio});
  static _telaPrincipalState tela = _telaPrincipalState();

  @override
  _telaPrincipalState createState() {
    return tela;
  }

  static indexBar(int index) {
    tela.onItemTapped(index);
  }

  static void hide() {
    tela.hideNavBar();
  }

  static void show() {
    print("show");
    tela.showNavBar();
  }
}

class _telaPrincipalState extends State<telaPrincipal> {
  void hideNavBar() {
    setState(() {
      _show = false;
      _bottomBarHeight = 0;
    });
  }

  void showNavBar() {
    setState(() {
      _show = true;
      _bottomBarHeight = 60;
    });
  }

  void onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  int _selectedIndex = 0;

  final navigatorKey = GlobalKey<NavigatorState>();

//bottomNavigatorBar routes
  final pagesRouteFactories = {
    HomeView.route: () => MaterialPageRoute(builder: (context) => HomeView()),
    programaTreino.route: () => MaterialPageRoute(
        builder: (context) => programaTreino(
              exercicioEscolhido: null,
              categoria: null,
            )),
    pesquisar_view.route: () =>
        MaterialPageRoute(builder: (context) => pesquisar_view()),
  };

  bool _show = true;
  double _bottomBarHeight = 60;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            backgroundColor: HexColor("#121212"),
            body: _buildBody(),
            bottomNavigationBar: Container(
              height: _bottomBarHeight,
              width: MediaQuery.of(context).size.width,
              child: _show
                  ? _buildBottomNavigationBar(context)
                  : Container(
                      color: Colors.white,
                      width: MediaQuery.of(context).size.width,
                    ),
            )),
      ),
      onWillPop: () async {
        navigatorKey.currentState.maybePop();
        return false;
      },
    );
  }

  Widget _buildBody() => MaterialApp(
      debugShowCheckedModeBanner: false,
      navigatorKey: navigatorKey,
      onGenerateRoute: (settings) {
        String routeName = settings.name;

        //Map<String, dynamic> args = route.arguments;  // Get any arguments passed to the route
        print("ongenate$routeName}");
        switch (routeName) {

          case AtivarEmailPage.route:
            return MaterialPageRoute(builder: (context) => AtivarEmailPage());
            break;
          default:
            return pagesRouteFactories[settings.name]();
            break;
        }
      });

  Widget _buildBottomNavigationBar(context) => BottomNavigationBar(
        currentIndex: _selectedIndex,
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home_filled),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.fitness_center),
            label: 'Treinos',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.search),
            label: 'Pesquisar',
          ),
        ],
        onTap: (routeName) {
          print(pagesRouteFactories.keys.toList()[routeName]);
          navigatorKey.currentState.pushNamed(
              pagesRouteFactories.keys.toList()[routeName],
              arguments: routeName == 0 ? null : [null, null]);
          onItemTapped(routeName);
        },
        backgroundColor: HexColor("#FFFFFF").withOpacity(0.08),
        selectedItemColor: HexColor("#FFCC80"),
        unselectedItemColor: HexColor("#FFFFFF").withOpacity(0.30),
      );
}

screens:
HomeView

AtivarEmail

I would like to go back with the bottomNavigatorBar visible to Homeview after pressing the android back button on the ActivateEmail screen

A: It looks like you are using mounted in reverse. mounted is true when the widget is part of the tree. See The API documentation
Try
    if (mounted) {
      setState(() => telaPrincipal.show());
    }

instead of if (!mounted)

A:
so create a static method to handle it from any class.

The short answer is: don't do that.
Read up on flutter state management. Pick the one you like best, but don't home-brew a solution.


text:
Q: mockBackend = getTestBed().get(MockBackend);? I am learning testing Angular 2 with Karma, and was wondering about some points in code I didn't understand. After the TestBed "mock module" is configured, the following code runs:
    mockBackend = getTestBed().get(MockBackend);

What does this do? I found the following explanation in another article: "gets a reference to the mock backend so we can respond with fake data when it is fetched with Http.get", but I don't see why I need to "get it", isn't it already there from import {MockBackend, MockConnection} from '@angular/http/testing';? Or does the module get the method somehow?
I use it later like so...and still don't understand why I had to attach it to the test bed:
    mockBackend.connections.subscribe(
        (connection: MockConnection) => {
            connection.mockRespond(new Response(
                new ResponseOptions({
                        body: "lol data"
                    }
                )));
        });

In short, the actual question is - what does the first line of code I posted do?
Complete code, just for context:
import { TestBed, getTestBed, async, inject } from '@angular/core/testing';
import { Headers, BaseRequestOptions, Response, HttpModule, Http, XHRBackend, RequestMethod} from '@angular/http';

import {ResponseOptions} from '@angular/http';
import {MockBackend, MockConnection} from '@angular/http/testing';
import {FooHttpService} from '../../services/foo-service.service.ts';

describe('My Service Making an Http Call', () => {

    let mockBackend: MockBackend;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            providers: [
                FooHttpService,
                MockBackend,
                BaseRequestOptions,
                {
                    provide: Http,
                    deps: [MockBackend, BaseRequestOptions],
                    useFactory:
                        (backend: XHRBackend, defaultOptions: BaseRequestOptions) => {
                            return new Http(backend, defaultOptions);
                        }
                }
            ],
            imports: [
                HttpModule
            ]
        });

        mockBackend = getTestBed().get(MockBackend);
        TestBed.compileComponents();
    }));

Code is taken from a tutorial here.

A:
isn't it already there from import {MockBackend, MockConnection} from '@angular/http'

This only give you access to the symbol/class. Just like if you want to use a service in your component, you need to import the service into the component file
import { SomeService } from './some.service'

class SomeComponent {
  constructor(service: SomeService) {}
}

If we didn't import SomeService, we would get an error "can't find symbol SomeService". But this is just a compile-time check. This is not enough to use an instance of the service as runtime. If this was all we had, at runtime, we would get the error "no provider for SomeService". We still need to add if to the providers so that Angular knows to create it, and pass the instance to the component at runtime
import { NgModule } from '@angular/core';
import { SomeService } from './some.service';
import { SomeComponent } from './some.component';

@NgModule({
  declarations: [ SomeComponent ],
  providers: [ SomeService ]
})
class SomeModule {}

Here is the same thing, we need to import the component symbol/class into the module file so that we can use the symbol/class in that file.
As far as the MockBackend, you add the class to the providers
providers: [ MockBackend ]

This tells Angular to create the instance, allowing it to be injectable. You then inject the instance created By Angular, into the factory method
useFactory: (backend: MockBackend, options: BaseRequestOptions) => {
  return new Http(backend, options);
}

Now Http will use that instance of the MockBackend when we make requests. But we need access to that same instance so that we can mock the response. In order to get it, we need to get it from Angular injector (which is the container for all the providers). To access the injector during the test, we can go through the TestBed, which acts like an injector for the test environment
mockBackend = TestBed.get(MockBackend);

Here we are asking Angular to look in its injector for a provider MockBackend. This will be the same instance that is injected into the useFactory function. So we insure that we mock the responses on the same MockBackend instance that the Http is using.


text:
Q: How to set YUV 255:255:255 and 0:0:0 using fade filter I want to fade in|out YUV 255:255:255 and 0:0:0 color, but check RGB color using datascope filter setting YUV 255:255:255 and 0:0:0, then sets color option at fade filter dose not display YUV 255:255:255 and 0:0:0.
Set YUV 255:255:255
ffmpeg -f lavfi -i color,format=yuvj444p,lutyuv=255:255:255 -vframes 1 255.png

Check RGB Hex using datascope filter
ffmpeg -i 255.png -vf datascope rgb.png

Set color option 0xff79ff
ffprobe -f lavfi -i "color,format=yuvj444p,fade=out:nb_frames=1:c=0xff79ff,signalstats,trim=start_frame=1:end_frame=2" -show_entries frame_tags=lavfi.signalstats.YAVG,lavfi.signalstats.UAVG,lavfi.signalstats.VAVG

output
TAG:lavfi.signalstats.YAVG=167
TAG:lavfi.signalstats.UAVG=167
TAG:lavfi.signalstats.VAVG=177

Same way YUV 0:0:0, but dose not fade to YUV 0:0:0.

A: The default pixel format for color is yuv420p, which is limited range. The LUT filter will clip any set values to (minval,maxval) which is (16,235) for limited/mpeg range. To force full range, convert to a full range YUV format. e.g.
ffmpeg -f lavfi -i color,format=yuvj444p,lutyuv=255:255:255 -vframes 1 255.png


text:
Q: Using {\AA} when \r is redefined I'd like to use {\AA} to input a capital A with a ring above. However, the document I am writing has to import some definitions which I have no control over.
One of the definitions changes \r:
\renewcommand{\r}[1]{\right#1}

Is there a way to import the above definition without changing it, and somehow still use {\AA}? I can put definitions before the file that changes \r is imported, if that helps.

A: whatever is defining \r is incorrect and breaking latex so you should report a bug even if you can not change it.
Use \let\temp\r before importing the bad definitions and put \let\r\temp after them to restore \r.
You could of course redefine \AA but \r is an encoding specific command so it is (re)defined if you switch encodings such as
\usepackage[T1]{fontenc}

it is used internally if you use Å directly using inputenc, so you would have to make multiple changes in many files to make latex not call \r anywhere.


text:
Q: Help calculating the following Integral? How can I calculate this? $\int_{0}^2 f(x)$  $\mathrm{dx}$ if $$f(x) =
\begin{cases}
x, & 0 \le x <1 \\
x-2 & 1 \le x \le 2
\end{cases}
$$

A: $$\displaystyle \int\limits_{0}^{2}f(x)\mathrm{d}x = \int\limits_{0}^{1}f(x)\mathrm{d}x + \int\limits_{1}^{2}f(x)\mathrm{d}x$$

A: Hint:
The integral you're working with is equivalent to $$\int_0^1 x\ dx +\int_1^2 (x-2)\ dx.$$
Can you take it from here?


text:
Q: How to zoom to layer using ArcGIS Javascript API I tried to get the function "Zoom to Layer" done using the following code snippet. But it does not change anything. The layer is a feature service layer, and I can see the full extent object of the layer which is not null. Any idea?
tree.on("dblClick", function (item, node, event) {
  var layerId=item.id[0];
  var layer = map.getLayer(layerId);

   if (!layer)
   {
    return;
   }
   else
   {
    var lyrExt=layer.fullExtent;
    var gsvc=  esriConfig.defaults.geometryService;
    var outSR = new esri.SpatialReference({ wkid: 102100 });
    gsvc.project([lyrExt], outSR, function(newExt) {
    map.setExtent(newExt[0],true);
   }
});

A: From @Alex's comment indicating he found the solution :
You "need to convert the projection of the layer to map's projection first."

A: If this is your full code, try adding

map.refresh();


text:
Q: Bib file with apostrophes gives error during compilation I have the following bib entry in my file:
@inproceedings {prekopa1980logarithmic,
title={Logarithmic concave measures and related topics},
  AUTHOR = {Pr\'{e}kopa, Andr\'{a}s},
  booktitle={Stochastic programming},
  year={1980},
  PUBLISHER = {Academic Press, London-New York}
}

and I get the undefined control sequence error
<argument> Pr\8
               0
l.383 \bibitem[Pr\80]{prekopa1980logarithmic}

The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

I have other escape characters in the bib file but for some reason this particular entry is problematic. The problems disappears if I remove the escape characters.
Any tips on how to fix this would be highly appreciated.
My bibliography settings are
\bibliographystyle{alpha}
\bibliography{references}

I don't use any bibliography package but I am using my university's dissertation template which comes with some proprietary package.

A: I can reproduce the error with
\begin{filecontents*}{\jobname.bib}
@inproceedings {prekopa1980logarithmic,
title={Logarithmic concave measures and related topics},
  AUTHOR = {Pr\'{e}kopa, Andr\'{a}s},
  booktitle={Stochastic programming},
  year={1980},
  PUBLISHER = {Academic Press, London-New York}
}
\end{filecontents*}

\documentclass{article}
\usepackage{hyperref}

\begin{document}

\cite{prekopa1980logarithmic}

\bibliographystyle{alpha}
\bibliography{\jobname}

\end{document}

After running pdflatex, bibtex and pdflatex again, this produces
! Undefined control sequence.
<argument> Pr\8
               0

The problem is in how the author name is input: there should be additional braces around the accented letters.
@inproceedings {prekopa1980logarithmic,
title={Logarithmic concave measures and related topics},
  AUTHOR = {Pr{\'{e}}kopa, Andr{\'{a}}s},
  booktitle={Stochastic programming},
  year={1980},
  PUBLISHER = {Academic Press, London-New York}
}


text:
Q: Find closest date to today from API results I've come across a problem which I cannot figure out. I'm trying to display single event on my home screen which is next upcoming by date. That event comes from list of events in the api.
Currently I am using listview.builder to display those events however when I set item count to 1 I cannot get the next event by date to be displayed. I was trying to display all events in listview.builder and then filter but I couldn't get it to work.
I need to display events in that order but they need to be shown 1 by 1 based on todays time. So when current time is the same as the events time next event will be shown:
firstImage
And this is what I'm getting when the itemCount is 1. This is the last event from the list
which I tried to reverse but no success. secondImage
This is code for the ListView.builder
ListView.builder(
        reverse: true,
        shrinkWrap: true,
        physics: ClampingScrollPhysics(),
        // itemCount: 1,
        itemCount: 1,
        itemBuilder: (context, index) {
          var x = eventController.event.value!.data![index];
          DateTime formattedStartDate = new DateFormat('yyyy-MM-dd hh:mm')
              .parse(eventController
                  .event.value!.data![index].eventStartDate
                  .toString());
          DateTime splitStartDate = new DateTime(
              formattedStartDate.year,
              formattedStartDate.month,
              formattedStartDate.day,
              formattedStartDate.hour,
              formattedStartDate.minute);

          DateTime today = DateTime.now();
          bool isAfter = splitStartDate.isAfter(today);

          return Column(
            children: [
              isAfter == true
                  ? GestureDetector(
                      onTap: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => EventDetails(
                                    event: eventController
                                        .event.value!.data![index])));
                      },
                      child: EventTileMain(
                          eventController.event.value!.data![index]))
                  : Container()
            ],
          );
        });

This is model calss of event:
    // To parse this JSON data, do
//
//     final event = eventFromJson(jsonString);

import 'dart:convert';

Event eventFromJson(String str) => Event.fromJson(json.decode(str));

String eventToJson(Event data) => json.encode(data.toJson());

class Event {
  Event({
    this.success,
    this.data,
    this.code,
    this.count,
  });

  bool? success;
  List<Datum>? data;
  int? code;
  int? count;

  factory Event.fromJson(Map<String, dynamic> json) => Event(
    success: json["success"],
    data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
    code: json["code"],
    count: json["count"],
  );

  Map<String, dynamic> toJson() => {
    "success": success,
    "data": List<dynamic>.from(data!.map((x) => x.toJson())),
    "code": code,
    "count": count,
  };
}

class Datum {
  Datum({
    this.id,
    this.postTitle,
    this.postContent,
    this.postName,
    this.postUrl,
    this.organizer,
    this.venue,
    this.category,
    this.speaker,
    this.eventStartDate,
    this.eventEndDate,
    this.eventDate,
    this.featuredImage,
  });

  String? id;
  String? postTitle;
  String? postContent;
  String? postName;
  String? postUrl;
  List<Category>? organizer;
  List<Category>? venue;
  List<Category>? category;
  dynamic speaker;
  String? eventStartDate;
  String? eventEndDate;
  DateTime? eventDate;
  String? featuredImage;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
    id: json["ID"],
    postTitle: json["post_title"],
    postContent: json["post_content"],
    postName: json["post_name"],
    postUrl: json["post_url"],
    organizer: List<Category>.from(json["organizer"].map((x) => Category.fromJson(x))),
    venue: List<Category>.from(json["venue"].map((x) => Category.fromJson(x))),
    category: List<Category>.from(json["category"].map((x) => Category.fromJson(x))),
    speaker: json["speaker"],
    eventStartDate: json["event_start_date"],
    eventEndDate: json["event_end_date"],
    eventDate: DateTime.parse(json["event_date"]),
    featuredImage: json["featured_image"],
  );

  Map<String, dynamic> toJson() => {
    "ID": id,
    "post_title": postTitle,
    "post_content": postContent,
    "post_name": postName,
    "post_url": postUrl,
    "organizer": List<dynamic>.from(organizer!.map((x) => x.toJson())),
    "venue": List<dynamic>.from(venue!.map((x) => x.toJson())),
    "category": List<dynamic>.from(category!.map((x) => x.toJson())),
    "speaker": speaker,
    "event_start_date": eventStartDate,
    "event_end_date": eventEndDate,
    "event_date": eventDate!.toIso8601String(),
    "featured_image": featuredImage,
  };
}

class Category {
  Category({
    this.id,
    this.name,
  });

  int? id;
  Name? name;

  factory Category.fromJson(Map<String, dynamic> json) => Category(
    id: json["id"],
    name: nameValues.map[json["name"]],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "name": nameValues.reverse![name],
  };
}

enum Name { AUDITORIUM, SEMINAR, XPOSURE, XPOSURE_INTERNATIONAL_PHOTOGRAPHY_FESTIVAL, TOR_SEIDEL, XPOSURE_AUDITORIUM }

final nameValues = EnumValues({
  "Auditorium": Name.AUDITORIUM,
  "Seminar": Name.SEMINAR,
  "Tor Seidel": Name.TOR_SEIDEL,
  "Xposure": Name.XPOSURE,
  "Xposure Auditorium": Name.XPOSURE_AUDITORIUM,
  "Xposure International Photography Festival": Name.XPOSURE_INTERNATIONAL_PHOTOGRAPHY_FESTIVAL
});

class EnumValues<T> {
  Map<String, T> map;
  Map<T, String>? reverseMap;

  EnumValues(this.map);

  Map<T, String>? get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap;
  }
}

API call
class EventApi {
  static var client = http.Client();
  static Future<Event?> fetchEvents() async {
    final response = await client.get(Uri.parse(
        'https://xposure.ae/api/v1/events/'));
        // 'https://xposure.ae/wp-json/wp/auditorium/v1/events'));
    if (response.statusCode == 200) {
      var jsonString = response.body;
      return eventFromJson(jsonString);
    } else {
      return null;
    }
  }
}

If you need more information please let me know.

A: you can try this:
ListView.builder(
        reverse: true,
        shrinkWrap: true,
        physics: ClampingScrollPhysics(),
        // itemCount: 1,
        itemCount: 1,
        itemBuilder: (context, index) {

          var now = DateTime.now();
          Datum? closestEvent;
          eventController.event.value!.data!.forEach((element) {
            var elementDate =
               DateFormat('yyyy-MM-dd hh:mm').parse(element.eventStartDate);
            if (closestEvent == null) {
              if (elementDate.isAfter(now)) {
                 closestEvent = element;
              }
            } else {
               var closestDate = DateFormat('yyyy-MM-dd hh:mm').parse(closestEvent!.eventStartDate);
               if (elementDate.isAfter(now) && elementDate.isBefore(closestDate)) {
                   closestEvent = element;
               }
             }
          });

          return Column(
            children: [
              isAfter == true
                  ? GestureDetector(
                      onTap: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => EventDetails(
                                    event: closestEvent)));
                      },
                      child: EventTileMain(
                          closestEvent))
                  : Container()
            ],
          );
        });

you can simply make a widget function and remove your listview, like this:
Widget buildEventWidget(BuildContext context){

   var now = DateTime.now();
          Datum? closestEvent;
          eventController.event.value!.data!.forEach((element) {
            var elementDate =
               DateFormat('yyyy-MM-dd hh:mm').parse(element.eventStartDate);
            if (closestEvent == null) {
              if (elementDate.isAfter(now)) {
                 closestEvent = element;
              }
            } else {
               var closestDate = DateFormat('yyyy-MM-dd hh:mm').parse(closestEvent!.eventStartDate);
               if (elementDate.isAfter(now) && elementDate.isBefore(closestDate)) {
                   closestEvent = element;
               }
             }
          });

    return Column(
            children: [
              isAfter == true
                  ? GestureDetector(
                      onTap: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => EventDetails(
                                    event: closestEvent)));
                      },
                      child: EventTileMain(
                          closestEvent))
                  : Container()
            ],
          );

}


text:
Q: LINQ to Entities - put all fields into final result Let's use this query as an example (this comes from the MSDN docs):
ObjectSet<SalesOrderHeader> orders = context.SalesOrderHeaders;
ObjectSet<SalesOrderDetail> details = context.SalesOrderDetails;

var query =
    from order in orders
    join detail in details
    on order.SalesOrderID equals detail.SalesOrderID
    where order.OnlineOrderFlag == true
    && order.OrderDate.Month == 8
    select new
    {
        SalesOrderID = order.SalesOrderID,
        SalesOrderDetailID = detail.SalesOrderDetailID,
        OrderDate = order.OrderDate,
        ProductID = detail.ProductID
    };

If I wanted to put all the fields present in "order" into the final object (i.e. the select new) in addition to the additional fields from detail, how would I do it?

A: var query =
    from order in orders
    join detail in details
    on order.SalesOrderID equals detail.SalesOrderID
    where order.OnlineOrderFlag == true
    && order.OrderDate.Month == 8
    select new
    {
        SalesOrderHeader = order;
        SalesOrderDetail = detail;
    };

A: You could either return the entire SalesOrderHeader object in your query, or use the Include method.
ObjectSet<SalesOrderHeader> orders = context.SalesOrderHeaders;
ObjectSet<SalesOrderDetail> details = context.SalesOrderDetails;

var query =
    from order in orders
    join detail in details
    on order.SalesOrderID equals detail.SalesOrderID
    where order.OnlineOrderFlag == true
    && order.OrderDate.Month == 8
    select new
    {
        SalesOrderID = order.SalesOrderID,
        SalesOrderDetailID = detail.SalesOrderDetailID,
        OrderDate = order.OrderDate,
        ProductID = detail.ProductID,
        Order = order
    };

Or using the Include method (Assuming your SalesOrderHeader class has a collection reference to the SalesOrderDetail class):
ObjectSet<SalesOrderHeader> orders = context.SalesOrderHeaders;
ObjectSet<SalesOrderDetail> details = context.SalesOrderDetails;

var query =
    (from order in orders
    where order.OnlineOrderFlag == true
    && order.OrderDate.Month == 8
    select order).Include(x => x.Details);

A: Do something like this?
            var query =
            from order in orders
            join detail in details
            on order.SalesOrderID equals detail.SalesOrderID
            where order.OnlineOrderFlag == true
            && order.OrderDate.Month == 8
            select new
            {
                SalesOrderID = order.SalesOrderID,
                SalesOrderDetailID = detail.SalesOrderDetailID,
                OrderDate = order.OrderDate,
                ProductID = detail.ProductID,
                Order = order
            };


text:
Q: Retrieve header(location) value of response using javascript I am trying to retrieve the value of "Location" from the response I get from an API call. The response does not have any body, but it contains a value(URL) in the Location section of the header.
Any way I can get the value of header using javascript. The response variable that i am using is of type XML. This is being implemented in IBM BPM 7.5

A: Typically, the Location header of a response comes in conjunction with a 3xx status code.  Unfortunately, with AJAX, redirects are followed, so you cannot inspect the header of a redirect response.
However, if your response is not a redirect, you can use the getAllResponseHeaders() function to inspect your headers.


text:
Q: Removing a revision from a question causes the tags and the title to be removed I edited How is it possible that a single user who is not a moderator can delete a comment? after an image was removed from the question, since the question without image was not that much clear.
When I tried to save it after editing it, I could not continue since:

*

*The tags were gone

*The title followed the tags
(Sorry, I didn't think to take a screenshot.)
As you can see from the revision page, it results that title and the tags were added in the second revision, when they were clearly present since the first revision, as it is not possible to post a question without title and tags.


text:
Q: What happens in the OS when multimedia keys are pressed? What commands are invoked when I press my media keys (play / pause, next, previous)?
I had a look at simulate media keys in the terminal, and my requirement is the same, except I cannot use the approach in the answer. The answers simulates the keys themselves using xdotools, which I cannot do because I have re-mapped what these keys do. What I want to know is the underlying mechanism in the OS which sends messages to apps which need to know multimedia keys are pressed. I suspect it may be related to dbus.
Background
I had to re-map my media keys (play / pause, next, previous) to other commands  this link contains some background.
I did this by removing the previous key-bindings for these media keys and  re-assigning them in settings > keyboard > shortcuts.
I want to know the original command so that I can invoke spotify-command ; original-command on the keypress instead of just invoking spotify-command.

A: when you press Multimedia Keys, they have keysymbols which can be known with the command xmodmap -pke | grep Audio
Example:
$ xmodmap -pke | grep Audio
keycode 121 = XF86AudioMute NoSymbol XF86AudioMute
keycode 122 = XF86AudioLowerVolume NoSymbol XF86AudioLowerVolume
keycode 123 = XF86AudioRaiseVolume NoSymbol XF86AudioRaiseVolume
keycode 171 = XF86AudioNext NoSymbol XF86AudioNext
keycode 172 = XF86AudioPlay XF86AudioPause XF86AudioPlay XF86AudioPause
keycode 173 = XF86AudioPrev NoSymbol XF86AudioPrev
keycode 174 = XF86AudioStop XF86Eject XF86AudioStop XF86Eject
keycode 175 = XF86AudioRecord NoSymbol XF86AudioRecord
keycode 176 = XF86AudioRewind NoSymbol XF86AudioRewind
keycode 198 = XF86AudioMicMute NoSymbol XF86AudioMicMute
keycode 208 = XF86AudioPlay NoSymbol XF86AudioPlay
keycode 209 = XF86AudioPause NoSymbol XF86AudioPause
keycode 215 = XF86AudioPlay NoSymbol XF86AudioPlay
keycode 216 = XF86AudioForward NoSymbol XF86AudioForward
keycode 234 = XF86AudioMedia NoSymbol XF86AudioMedia
$

from the link you provided, these commands should work for your Custom Keyboard Shortcuts

for Play/ Pause
dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.PlayPause

for Next
dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Next

for Previous
dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Previous

for Stop
dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Stop

for Play
dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Play


text:
Q: Did Debug=(os.getenv("DEBUG_VALUE")=='True') but still showing debug info on all devices I have hide my debug value and security key in env variable. but after accessing a unknown page on my website. it shows debug information. what am I doing wrong?
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv("SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!

DEBUG = (os.getenv("DEBUG_VALUE") == 'True')

DEBUG_VALUE = 'True' in env var.
and I have done heroku config:set Secret_Key="***" and Debug_value='True'

A: You've set the DEBUG to true. So the Django will show debug information. If you want to disable it, simply set DEBUG_VALUE='False', or any other value (based on your settings), in your Heroku config.


text:
Q: Rails 3 Model Name Convention Can anyone explain me about a model name convention in Rails 3?
For example:
I have a table named "materialtitles" in my database.
What name does a model file, a model class have to satisfy convention of names in Rails???
Thanks for help.

A: The filename would be materialtitle.rb and would reside in app/models.
The class name of your model would be would be Materialtitle.