text:
Q: An equality about Fourier transform I have read an equality about Fourier transforms which I can not proof. It is as following: Let $u\in C_0(\mathbb{R}^n)$ and
\begin{equation}
g(x_1,x_2,...,x_{n-1}):=u(x_1,x_2,...,x_{n-1},0).
\end{equation}
Then
\begin{equation}
\hat{g}(x_1,...,x_{n-1})=\frac{1}{2\pi}\int_{\mathbb{R}}\hat{u}(x_1,...,x_{n-1},x_n)dx_n.
\end{equation}
(Here the Fourier transform is defined by $\hat{u}(t)=\int_{\mathbb{R}^n} u(x)e^{-it\cdot x}dx$.)
How to prove this?

A: I'm going to assume $u$ is in the Schwarz space, so we don't have to worry about various technicalities. I'm going to take $n=2$ for convenience. And I'm going to assume the Littlewood convention $2\pi=1$, because everyone puts the $2\pi$'s in different places (feel free to edit this, inserting the $2\pi$'s as needed for your version of the Fourier transform).
Hmm. Using the same letter for the variable on both sides is bad; I'm going to write $\hat u(s,t)$, where $u=u(x,y)$.
Ok. Let $$\phi(s)=\int_\mathbb R\hat u(s,t)\,dt.$$ By the inversion theorem (for $n=1$) it's enough to show that $$\int_{\mathbb R}\phi(s)e^{ixs}\,ds=u(x,0).$$
But this is clear from the definitions and the inversion theorem (for $n=2$):
$$\int_{\mathbb R}\phi(s)e^{ixs}\,ds=\int_{{\mathbb R}^2}\hat u(s,t)e^{i(x,0)\cdot(s,t)}\,dsdt=u(x,0).$$


text:
Q: How to pass params to the parent and child state at the same time in $state.go function? I want to redirect a user to the particular state. I have 2 states.
First is app and the URL for it is /{lang}, so eg. mydomain.com/en.
The child state of app is app.login. The URL for this state is /login/{slug}. So full link, including app state, may be mydomain.com/en/login/settings.
Next state calls login, and the URL is /login/settings eg. mydomain.com/login/settings. When user enters this link, I want to redirect him to the app.login state and pass settings param for {slug}. But also I have to pass earlier {lang} param for the app state.
How can I pass two paramaters separetly for the app and app.login in order to redirect user.
It should looks like this: $state.go('app.login', { lang: 'en', redirect: 'settings'). The first parameter should be for the app state and the second one for the app.login state. But I can't find a proper way to do this.
.state('app', {
    abstract: true,
    url: '/{lang}', // Example url: /en
    params: {
            lang: null
    }
})
.state('app.login', {
    abstract: true,
    url: '/login/{slug}', // Example url: /en/login/settings
    params: {
            redirect: null
    }
})
.state('login', {

    // When user enters '/login/settings', should be redirected to the 'app.login' state
    url: '/login/settings',
    controller: ['$state', function($state) {
            // So, I have to pass two parameters - 'lang' and 'redirect'
            // But first parameter is for to the 'app' state and the second to the 'app.login' state.
            // How can I pass a parameter at the same time for a parent and a child in one '$state.go'?
            $state.go('app.login', { lang: 'en', redirect: 'settings' })

            // Full link should looks like `/en/login/settings`
            // === `/{lang}/login/{slug}`
    }
})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python - Basic validation of international names? Given a name string, I want to validate a few basic conditions:
-The characters belong to a recognized script/alphabet (Latin, Chinese, Arabic, etc) and aren't say, emojis.
-The string doesn't contain digits and is of length < 40
I know the latter can be accomplished via regex but is there a unicode way to accomplish the first? Are there any text processing libraries I can leverage?

A: You should be able to check this using the Unicode Character classes in regex.
[\p{P}\s\w]{40,}

The most important part here is the \w character class using Unicode mode:

\p{P} matches any kind of punctuation character
\s matches any kind of invisible character (equal to [\p{Z}\h\v])
\w match any word character in any script (equal to [\p{L}\p{N}_])

Live Demo
You may want to add more like \p{Sc} to match currency symbols, etc.
But to be able to take advantage of this, you need to use the regex module (an alternative to the standard re module) that supports Unicode codepoint properties with the \p{} syntax.
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import regex as re

regex = r"[\p{P}\s\w]{40,}"

test_str = ("Wow cool song!Wow cool song!Wow cool song!Wow cool song!  \nWow cool song! Wow cool song! Wow cool song! \n")
matches = re.finditer(regex, test_str, re.UNICODE | re.MULTILINE)

for matchNum, match in enumerate(matches):
    matchNum = matchNum + 1

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

PS: .NET Regex gives you some more options like \p{IsGreek}.


text:
Q: Mysql Different order by result between inner join query and exists query I have 2 tables in the database

*

*User table
has columns (name, name_ar, ...)

*User Profile table
has columns (user_id, office_id, address, mobile, ...)

the relationship between the two tables is one to one relation
Now, I'm trying to filter users by their office and order them by name_ar.
I tried two different queries to do this and I expect the same result from the two queries but the result is different in order.
SELECT
    `id`, `name_ar`
FROM
    `users`
WHERE EXISTS
    (
    SELECT
        *
    FROM
        `user_profiles`
    WHERE
        `users`.`id` = `user_profiles`.`user_id` AND `office_id` = 1
) AND(
    `group` = "doctor" AND `state` = "active"
) AND `users`.`deleted_at` IS NULL
ORDER BY
    `name_ar` IS NULL, `name_ar` ASC

SELECT
    `u`.`id`,
    `name_ar`
FROM
    `users` u
INNER JOIN `user_profiles` up ON
    `u`.`id` = `up`.`user_id`
WHERE
    `group` = "doctor" AND `state` = "active" AND `up`.`office_id` = 1
ORDER BY
    `name_ar` IS NULL, `name_ar` ASC

the two results do not have the same order from the beginning of appearing null value in name_ar column (from the fifth row exactly the order is different between the two results), Can any explain for me why is this happens? Is it because of null values or another reason?

A: The 1st condition of the ORDER BY clause:
`name_ar` IS NULL

sends all nulls to the end of the results.
The 2nd:
`name_ar` ASC

sorts the non null names alphabetically but when it comes to the null names at the end there is not any defined order for them.
What you can do is add another final condition, like:
`id` ASC

so you have all the nulls (and duplicate names if they exist) sorted by id:
ORDER BY `name_ar` IS NULL, `name_ar`, `id`


text:
Q: update key values of NSManagedObjects safely I'm trying to pass key value pairs and have the attributes updated through a loop.
func update(storableClass : NSManagedObject.Type, id: ID, fields: [String : Any]) throws {

    // retreive manaagedObject
    for (key, value) in fields {
        manaagedObject.setValue(value, forKey: key)
    }
}

Apparently the setValue(_:forKey:) will throw an exception if the key doesn't exist.
From what I've learned you're not to catch an Objective-C exception in Swift.
Is there any safe way to update core data properties through a dictionary?
I know I can have a function like below:
func update(storableClass : ManagedObject.Type, id: ID, closure: (ManagedObject) -> ()) throws {}

and then call it as such:
update(storableClass: UserEntity.self, id: "123123", closure: { userEntity in
    userEntity.name = "new name"
})

I like to have both options...and any other safe/swifty option...

A: I've had this exact problem. Here's what you do.
With Core Data, you can easily find out what property names are valid for the object. Get a reference to the managed object's entity, and then ask the entity for the properties. You'd use managedObject.entity.propertiesByName. The result is a dictionary where the keys are valid properties. The code would be something like
let properties = managedObject.entity.propertiesByName
for (key, value) in fields {
    if properties[key] != nil {
        managedObject.setValue(value, forKey: key)
    } else {
        print("Unknown key: \(key)")
    }
}

This is fine as long as value is the right type. If you start getting bogus data types in JSON, you have a more complex problem to solve.
For relationships, do the same thing with managedObject.entity.relationshpsByName.


text:
Q: Turning JSON into date object I have get request here
$http.get('php/getactivity.php')
    .then(
        function (response) {
            $scope.data.activities = response.data;
        },
        function (response) {
          // error handling
        }
    );

which gets data from database . in my php
<?php
include('dbconnect.php');

$result = $conn->query("SELECT * FROM Activities WHERE EventID =1;");

$outp = "";

while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    if ($outp != "") {
        $outp .= ",";
    }
    $outp .= '{"ActivityDate":"'  . $rs["ActivityDate"] . '",';
    $outp .= '"StartTime":"'  . $rs["StartTime"] . '",';
    $outp .= '"EndTime":"'  . $rs["EndTime"] . '"}';
}
$outp ='['.$outp.']';
$conn->close();

echo($outp);
?>

which gets the date string from the database. An example of the data is as such :
Thu Jan 01 1970 11:11:00 GMT+0800 (Malay Peninsula Standard Time)
Because I'm accessing the data using ng-repeat and {{ActivityDate||date:"dd/MM/yyyy"}} to make it show on the view, I cannot convert it do a date object manually using new Date().
I have tried adding new date to the json produced as such but it does not work:
$outp .= '"ActivityDate": new Date("'. $rs["ActivityDate"] . '"),';
What is the right way to do it?

A: It would probably be simplest to format the date server-side, the way you want it displayed on the client.
One option:
date('d/m/Y', strtotime($rs["ActivityDate"]));

Here's an example of that: https://3v4l.org/6Xv03
Side note: I'd recommend you change how you generate your JSON. Build a PHP array first, and then json_encode it. This will avoid potential JSON format issues.
Something like:
$output = [];
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    $output[] = [
        "ActivityDate" => date('d/m/Y', strtotime($rs["ActivityDate"])),
        "StartTime" => $rs["StartTime"],
        "EndTime" => $rs["EndTime"]
    ];
}

$conn->close();

echo(json_encode($output));

And then as one commenter mentioned, it helps to add a header to indicate your content type:
header("Content-Type: application/json");
echo(json_encode($output));


text:
Q: Validator of JSON against JSON schema online I would like to find an online validator of JSON against JSON schema – both provided by URL.
Good example is http://www.jsonschemavalidator.net/ but I need to copy&paste the content of JSON file and JSON scheme, not URL of my files.
Do you know any?

A: I know it's an old question, but https://json-schema-validator.herokuapp.com/ seems to do the trick.

A: To check whether json content is valid or not, try the following json validator -

*

*http://jsonlint.com/

*http://codebeautify.org/jsonvalidator


text:
Q: Use resolveActivity To Check if Intent Can Be Handled I am trying to disable the camera launch button in my app if the camera intent cannot be handled by the device. I am targeting Android R (11). The code that I have so far is this
  val packageManager: PackageManager = requireActivity().packageManager

  val captureImage = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
  if (captureImage.resolveActivity(packageManager) == null) {
    isEnabled = false
  }

The issue that I am having is that when I implement this code the camera launch button is always disabled even on devices that support it. I am not sure why it is doing this other than that maybe I need to add package-visibility into the manifest file but I am unsure how that all works as the documentation isn't the best when it comes to examples. Any help or guidance would be greatly appreciated.

A: You can add queries like this in your manifiest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="app.android">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <queries>
        <package android:name="com.whatsapp" />

        <intent>
            <action android:name="android.media.action.IMAGE_CAPTURE" />
        </intent>
        <intent>
            <action android:name="android.intent.action.DIAL" />
        </intent>
    </queries>

     <application
      ...
     </application>
</manifest>


text:
Q: Mostrar incompleto los datos de una consulta en html Resulta que al hacer una peticion a la base de datos e intentar mostrar los datos de un registro, este solo me muestra la primera palabra de cada registro, por ejemplo, los apellidos, solo me muestra el primero, y pasa lo mismo con el nombre y la direccion, me tocó usar un placerholder para que me mostrara los datos porque de otra forma, no se visualizan.
Este es el codigo html. En la terminal, el Json trae todos los datos, pero en la vista de html, no los muestra todos.Los datos estan completos en la db, al usar un label, me los muestra todos, pero si uso un form, no. Y necesito poder editar los valores si los quiero cambiar.

<form class="lista" action="" id="formregistro">

Tipo Documento
<input type="number" name="PerTipoDocumento" placeholder= <%= data.PerTipoDocumento %>>

Documento
<input type="number" name="PerDocumento_Persona" placeholder= <%= data.PerDocumento_Persona %>>

Nombre
<input type="text" readonly name="PerNombre"><%= data.PerNombre %>

Apellidos
<input type="text" readonly name="PerApellidos" placeholder= <%= data.PerApellidos %>>

Correo Electronico
<input type="email" readonly name="PerEmail" placeholder= <%= data.PerEmail %>>

Móvil
<input type="number" readonly name="PerMovil" placeholder= <%= data.PerMovil %>>

EPS
<input type="text" readonly name="PerEPS" placeholder= <%= data.PerEPS %>>

Telefono fijo
<input type="number" readonly name="PerTelefono" placeholder= <%= data.PerTelefono %>>

Fecha de Nacimiento
<input type="text" name="PerFecha_Nacimiento" placeholder= <%= data.PerFecha_Nacimiento %>>

Direccion de Residencia
<input type="text" readonly name="PerDireccion" placeholder= <%= data.PerDireccion %>>

Barrio
<input type="text" readonly name="PerBarrio" placeholder= <%= data.PerBarrio %>>

País Residencia
<input type="text"  readonly name="PerPais_Residencia" placeholder= <%= data.PerPais_Residencia %>>

Departamento o Estado
<input type="text" readonly name="PerDepartamento_Residencia" placeholder= <%= data.PerDepartamento_Residencia %>>

Municipio Residencia
<input type="text" readonly name="PerMunicipio_Residencia" placeholder= <%= data.PerMunicipio_Residencia %>>

Genero
<input type="genero" readonly name="PerSexo" placeholder= <%= data.PerSexo %>>

<input type="checkbox">
¿Acepta los términos y condiciones de la página?

<input type="checkbox">
¿Acepta el uso y tratamientos de  sus datos personales?

<input type="checkbox">
¿Desea ser notificado via correo electronico?


text:
Q: What is the difference between ix and element in the Lens library of Haskell In Haskell's lens library, ix and element both take an Int an can be used e.g. to read or write a list element at some index, like this
ghci> [1..10] ^? ix 4
Just 5
ghci> [1..10] & ix 4 .~ 1
[1,2,3,4,1,6,7,8,9,10]

and similarly:
ghci> [1..10] ^? element 4
Just 5
ghci> [1..10] & element 4 .~ 1
[1,2,3,4,1,6,7,8,9,10]

What is the difference between element and ix?

A: element is defined to work with types of the Traversable class, even class members which the lens library doesn't know about. As such it uses only Traversable functions to access the value, which have no concept of any index type specific to the type of value. As such, only Int indices are supported, giving elements in the usual traversal order.
element also gives an IndexedTraversal, giving some extra ways of handling indices.
ix is only defined for types the lens library knows about, but in return it can use different index types dependent on the type of the value.
For lists they give the same result.  But the difference can be seen e.g. for Data.Map:
Prelude Control.Lens Data.Map> singleton "a" 3 ^? element "a"

<interactive>:19:28:
    Couldn't match expected type 'Int' with actual type '[Char]'
    In the first argument of 'element', namely '"a"'
    In the second argument of '(^?)', namely 'element "a"'
    In the expression: singleton "a" 3 ^? element "a"

Prelude Control.Lens Data.Map> singleton "a" 3 ^? ix "a"
Just 3
Prelude Control.Lens Data.Map> singleton "a" 3 ^? element 0
Just 3
Prelude Control.Lens Data.Map> singleton "a" 3 ^? ix 0

<interactive>:22:23:
    Could not deduce (Num [Char]) arising from the literal '0'
    from the context (Num a)
      bound by the inferred type of it :: Num a => Maybe a
      at <interactive>:22:1-23
    In the first argument of 'ix', namely '0'
    In the second argument of '(^?)', namely 'ix 0'
    In the expression: singleton "a" 3 ^? ix 0

As you can see, with element the map is given Int indices, while with ix it is given the key type as index, and trying to switch that around gives a type error.

A: element works by walking an entire structure, counting the elements, and traversing the element with the target index. Therefore it always has time complexity O(n) in the size of the structure, and it only works  with Int indices.
In contrast, ix has its own class Ixed, and instances rely on the lookup/modify operations of the specific data structures. For example, ix for Data.Sequence is O(log n).
However, ix only works on specific data structures, while elementOf works with any Traversal, Lens or Iso, for example:
[0..10] ^? elementOf (reversed . each . filtered odd) 1
-- Just 7

A: With ix you can index not only by number, but by e.g. key in the Maps. The element index in Traverse order.
λ> let m = Map.fromList [("foo", 'f'), ("bar", 'b')]
λ> m ^? ix "foo"
Just 'f'

λ> m ^? element 0 -- Map is ordered container!
Just 'b'

The difference is even more obvious with e.g. IntMap
λ> let im = IntMap.fromList [(1, "one"), (2, "two")]
λ> im ^? ix 1
Just "one"
λ> im ^? element 1
Just "two"


text:
Q: .net mvc many to many What to POST I am trying to realize a many to many context. A Product can be made from different materials and has a different price for those materials:
Here is the product.cs:
namespace test.Models
{
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;
    using System;
    using System.Collections.Generic;
    public partial class Product
    {
        public Product()
        {
            this.ProductMaterials = new HashSet<ProductMaterial>();
        }
        public int Id { get; set; }
        [DisplayName("Product name"),
          Required(ErrorMessage = "Product Name is required"),
          StringLength(100)]
        public string Name { get; set; }
        [Required]
        public virtual ICollection<ProductMaterial> ProductMaterials { get; set; }
    }
}

Here is the ProductMaterials.cs:
namespace test.Models
{
    using System;
    using System.Collections.Generic;

    public partial class ProductMaterial
    {
        public int Id { get; set; }
        public int ProductId { get; set; }
        public int MaterialId { get; set; }
        public string PriceOffset { get; set; }

        public virtual Material Material { get; set; }
        public virtual Product Product { get; set; }
    }
}

And the Material.cs:
namespace test.Models
{
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;
    using System;
    using System.Collections.Generic;

    public partial class Material
    {
        public Material()
        {
            this.ProductMaterials = new HashSet<ProductMaterial>();
        }

        public int Id { get; set; }
        [Required,DisplayName("Material"),
          StringLength(100)]
        public string Mat { get; set; }
        [DefaultValue(0), Required]
        public decimal PriceOffset { get; set; }

        public virtual ICollection<ProductMaterial> ProductMaterials { get; set; }
    }
}

Now trying to add the right information in the context so an object can be created from a form, trying to make this as simple as possible to understand this in small steps.
the testContext.cs has the following:
using System.Data.Entity;
namespace test.Models
{
    public class testContext : DbContext
    {
System.Data.Entity.DropCreateDatabaseIfModelChanges<test.Models.testContext>());
        public testContext() : base("name=testContext")
        {
        }
        public DbSet<Product> Products { get; set; }
        public DbSet<Manufacturer> Manufacturers { get; set; }
        public DbSet<ProductMaterial> ProductMaterials { get; set; }
        public DbSet<Material> Materials { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
        modelBuilder.Entity<Product>()
            .HasMany(c => c.ProductMaterials);
        }
    }
}

This is the extra data I POST:
<input type="text" value="1" name="ProductId">
<input type="text" value="1" name="MaterialId">
<input type="text" value="0" name="PriceOffset">

When I set a breakpoint in the controller I see a Product object is created with 0 ProductMaterials objects.
Not sure if this is the right way to do it and I see in the example code I downloaded that updating will be far more complicated.

A: Giving up on how to create a new product with Materials added. Got it to work for edit product.
Added a route in global.asax.cs:
    routes.MapRoute(
        "Materials For Product", // Route name
        "Materials/{action}/{ProductId}/{MaterialId}", // URL with parameters
        new { controller = "ProductMaterial", action = "Index",
              ProductId = UrlParameter.Optional,
              MaterialId = UrlParameter.Optional
        } // Parameter defaults
    );

Changed the Index, create and delete in the ProductMaterialController.cs
public ViewResult Index(int ProductId)
{
    var productmaterialss = db.ProductMaterials.Include(p => p.Material).Include(p => p.Product).Where(
        p => p.ProductId == ProductId);
    Product pr = db.Products.Find(ProductId);
    ViewData["ProductId"] = ProductId;
    ViewData["ProductName"] = pr.Name;
    return View(productcolors.ToList());
}
public ActionResult Create(int ProductId)
{
    Product p = db.Products.Where(i => i.Id == ProductId).Single();
    ViewBag.MaterialId = new SelectList(db.Materials, "Id", "Mat");
    ViewData["ProductName"] = p.Name;
    ViewData["ProductId"] = p.Id;
    return View();
}
[HttpPost]
public ActionResult Create(ProductMaterial productmaterial)
{
    if (ModelState.IsValid)
    {
        db.ProductMaterials.Add(productmaterial);
        db.SaveChanges();
        return RedirectToAction("Index/"+productmaterial.ProductId);
    }
    Product p = db.Products.Where(i => i.Id == productmaterial.ProductId).Single();
    ViewBag.MaterialId = new SelectList(db.Materials, "Id", "Mat");
    ViewData["ProductName"] = p.Name;
    ViewData["ProductId"] = p.Id;
    return View();
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
    ProductMaterial productmaterial = db.ProductMaterials.Find(id);
    int ProductId = productcolor.ProductId;
    db.ProductMaterials.Remove(productmaterial);
    db.SaveChanges();
    return RedirectToAction("Index/"+ProductId);
}

Changed edit view of Product to open a model dialog with the ProductMaterial view and changed all the ProductMaterial views (only index and delete because the other are not used) to not include template and show product name.
Added script to Product to open the Modal and attached event listeners on all links and forms to ajax submit the needed info and reset the innerHTML of the modal dialog with the response.


text:
Q: Extract pixel values by points and convert to a table in Google Earth Engine I am undertaking a project that is relating field measurements of fire severity to band values and spectral indices derived from Landsat imagery before and after the fire. I am currently using Google Earth Engine to extract surface reflectance values from a collection of Landsat images. The approach I am using imports my field site locations (point data) as a feature collection and uses the getRegion function to extract band values from a Landsat image collection at each point. The code is provided below:
//IMPORT SAMPLE POINTS
var pts =     ee.FeatureCollection('ft:1N9Hb01uCSHqGpz262K_f9VzWedxvTiV0g6tJwfw4');

//IMPORT LANDSAT IMAGE
var L82014pre = ee.ImageCollection('LANDSAT/LC8_SR') //Landsat 8 Surface   reflectance
.filter(ee.Filter.eq('wrs_path', 94))
.filter(ee.Filter.eq('wrs_row', 86))
.filterDate(ee.Date.fromYMD(2013,12,13), ee.Date.fromYMD(2014,1,15))

//EXTRACT BY SAMPLE POINTS
var sample = L82014pre.getRegion(pts, 30);

My question is how can I convert the resulting 'sample' variable (a list of lists) to a table that can be exported to google drive? Or is there a better approach to extract image data by points in Google Earth Engine?
I am new to Google Earth Engine and the Java programming language, so I apologise if the answer to this question is obvious. I have spent a lot of time trying to find a solution to this problem and I feel like I am getting nowhere.
Thank you,
Luke

A: I can't get access to your fusion table, so I made up some random points for the example.
I'm pretty sure there is other ways to do it. GEE has many functions and some times they are a bit tricky to use. This would be my way:
// As I can't access your FusionTable,
// I make random points and create a FeatureCollection
var p1 = ee.Geometry.Point([142.36083984375, -37.466138602344046])
var p2 = ee.Geometry.Point([143.23974609375, -37.04640889969956])
var pts = ee.FeatureCollection(ee.List([ee.Feature(p1),ee.Feature(p2)]))

//IMPORT LANDSAT IMAGE
var L82014pre = ee.ImageCollection('LANDSAT/LC8_SR') //Landsat 8 Surface   reflectance
.filter(ee.Filter.eq('wrs_path', 94))
.filter(ee.Filter.eq('wrs_row', 86))
.filterDate(ee.Date.fromYMD(2013,12,13), ee.Date.fromYMD(2014,1,15))

// Empty Collection to fill
var ft = ee.FeatureCollection(ee.List([]))

var fill = function(img, ini) {
  // type cast
  var inift = ee.FeatureCollection(ini)

  // gets the values for the points in the current img
  var ft2 = img.reduceRegions(pts, ee.Reducer.first(),30)

  // gets the date of the img
  var date = img.date().format()

  // writes the date in each feature
  var ft3 = ft2.map(function(f){return f.set("date", date)})

  // merges the FeatureCollections
  return inift.merge(ft3)
}

// Iterates over the ImageCollection
var newft = ee.FeatureCollection(L82014pre.iterate(fill, ft))

// Export
Export.table.toDrive(newft,
"anyDescription",
"anyFolder",
"anyNameYouWant")

A: @Rodrigo, thank you for your prompt reply. The point extraction code worked perfectly for that example. I tried the point extraction for another set of images for which a cloud mask had been applied, and discovered that if the first point of the first image in the collection fell outside the mask (i.e. on a pixel assigned a 'null' value), the exported table would not contain band data for any of the point. To get around this I added a filter to remove points containing 'null' values before they are merged with the feature collection.
Below is the code containing an example with both the failed extraction that does not remove 'null' values and the successful extraction removing 'null' values.
//cloud mask ------------------------------------------------------
var maskCloudShadow = function(image){
var cfmask = image.select('cfmask');
return image.updateMask(cfmask.lt(1));   // keep clear (0) pixels
};

//select images from image collection -----------------------------
//extract filtered collection of Landsat 5 Surface Reflection
var L5fs1998post = ee.ImageCollection('LANDSAT/LT5_SR') //Landsat 5 Surface reflectance
.filterDate('1998-1-9', '1998-2-27') //filter to date bounds
.filter(ee.Filter.eq('wrs_path', 91))//filter to path and row
.filter(ee.Filter.eq('wrs_row', 86))
.map(maskCloudShadow); //apply cloud and cloud shadow mask function
print(L5fs1998post);

//Create sample points --------------------------------------------
//var pts =
ee.FeatureCollection('ft:1lfLgiQQSIIOpgjuZV5MZJno9_kLyQC49w6u3Hf9W');
var p1 = ee.Geometry.Point([146.84341192245483, -37.47371711676642]);
var p2 = ee.Geometry.Point([146.84167385101318, -37.4]);
var pts = ee.FeatureCollection(ee.List([ee.Feature(p1),ee.Feature(p2)]));

// Empty Collection to fill
var ft = ee.FeatureCollection(ee.List([]));

//Without removal of null values ----------------------------------
//Function to extract values from image collection based on point file and export as a table
var fill = function(img, ini) {
// type cast
var inift = ee.FeatureCollection(ini);

// gets the values for the points in the current img
var ft2 = img.reduceRegions(pts, ee.Reducer.first(),30);

// gets the date of the img
var date = img.date().format();

// writes the date in each feature
var ft3 = ft2.map(function(f){return f.set("date", date)});

// merges the FeatureCollections
return inift.merge(ft3);
};

// Iterates over the ImageCollection
var newft = ee.FeatureCollection(L5fs1998post.iterate(fill, ft));
print(newft);

// Export
Export.table.toDrive(newft,
"anyDescription",
"EarthEngine",
"sample_include_null");

//With removal of null values ------------------------------------------
//Function to extract values from image collection based on point file and export as a table
var fill = function(img, ini) {
// type cast
var inift = ee.FeatureCollection(ini);

// gets the values for the points in the current img
var ft2 = img.reduceRegions(pts, ee.Reducer.first(),30);

// gets the date of the img
var date = img.date().format();

// writes the date in each feature
var ft3 = ft2.map(function(f){return f.set("date", date)});

// merges the FeatureCollections

var ft3a = ft3.filter(ee.Filter.neq('B1', null));//filter first to remove null values
return inift.merge(ft3a);
};

// Iterates over the ImageCollection
var newft_remove_null = ee.FeatureCollection(L5fs1998post.iterate(fill, ft));
print(newft_remove_null);

// Export
Export.table.toDrive(newft_remove_null,
"anyDescription",
"EarthEngine",
"sample_remove_null");

//plot cloudy scene and sample points ------------------------------------
var scene = ee.Image('LANDSAT/LT5_SR/LT50910861998042');
Map.setCenter(147, -37.5, 9);
Map.addLayer(scene, {bands: ['B3', 'B2', 'B1'], min: 0, max: 2000}, 'false-color composite');
Map.addLayer(pts);


text:
Q: Kicad: Drag with left button mouse click by default when working with Eeschema I want to change default behavior of left mouse click when working with Eeschema. Is it possible to change it from Move (M key) -> Drag (G key) when I select one/many elements?
I'm using KiCAD 5.0 on Mac.I have found below information:

*

*https://en.wikibooks.org/wiki/Kicad/eeschema/General_Commands
BUT Ctrl + left mouse button [Drag selection] does not work

A: No you are unable to change the mouse behaviour.
I can attest that CTRL + left mouse button does certainly work. Hold control, drag a box around the symbol to be moved then release and you will be dragging the symbol.
Now with MAC I believe it would be command instead of control.


text:
Q: How to trace these following codes? using recursion? Value of a is 6. Answer is 12. How is it done?
    if (a==0)
        return 1;

    return (a*a)/addxy(a-1)

And this, value of a is 20. How come 11 is produced? It must be a negative answer since it becomes like 20-19-18-17-...and so on
    if (a==0)
        return 1;

    return a-addxy(a-1);

I dont understand how it is done.
PS: Ive been reading recursions in java like a thousand times. Still didnt get it. Someone kind, please help.

A: Assuming this is your addxy method
int addxy(a){
  if (a==0)
        return 1;

    return (a*a)/addxy(a-1)
}

You are recursing and it turns out that this is what the calculation turns out to be.
(6*6)/((5*5)/((4*4)/((3*3)/((2*2)/((1*1)/(1))))))
Ok, now to show you why that is.  This is the stack that gets created when you call it:
a=6: (6*6)/(a=5)
a=5: (5*5)/(a=4)
a=4: (4*4)/(a=3)
a=3: (3*3)/(a=2)
a=2: (2*2)/(a=1)
a=1: (1*1)/(a=0)
a=0: 1

So thats what the stack looks like when it hits the base case, now pop off the stack until you're done.
a=6: (6*6)/(a=5)
a=5: (5*5)/(a=4)
a=4: (4*4)/(a=3)
a=3: (3*3)/(a=2)
a=2: (2*2)/(a=1)
a=1: (1*1)/1

a=6: (6*6)/(a=5)
a=5: (5*5)/(a=4)
a=4: (4*4)/(a=3)
a=3: (3*3)/(a=2)
a=2: (2*2)/1

a=6: (6*6)/(a=5)
a=5: (5*5)/(a=4)
a=4: (4*4)/(a=3)
a=3: (3*3)/4 // This is (9)/4, so integer division will happen

a=6: (6*6)/(a=5)
a=5: (5*5)/(a=4)
a=4: (4*4)/2 // Note the integer division that happened to get 2

a=6: (6*6)/(a=5)
a=5: (5*5)/8

a=6: (6*6)/3

a=6: 12

A: So this is your addxy method
int addxy(a){
  if (a==0)
        return 1;

    return (a*a)/addxy(a-1)
}

For Input : addxy(3);
Output
addxy(3) : will return (3*3)/addxy(2);
addxy(2) : will return (2*2)/addxy(1);
addxy(1) : will return (1*1)/addxy(0);
addxy(0) : will return (1);

Now backtrace :
(1*1)/1=1 <-------Since  addxy(0) is 1
(2*2)/1=4 <------- Since return (1*1)/addxy(0); is 1
(3*3)/4=2 <--------- Since Integer Division so no decimal .

Final Result : 2


text:
Q: Automatically resize font in a text box I'm using dynamic text for owner names in my layout.  Problem is some are two words and some are a lot more.
When using a text box if the font is to big it just drops the extra.
Is there an easy way to simply have the font automatically resize to fit in the text box?  Something like the legend being able to resize/shrink to fit?

A: The best thing I can think of is using the Adding text that flows within a graphic.
This allows you to:

You can add text that flows within a graphic to your map annotation or graphic text by using the Polygon Text, Rectangle Text, and Circle Text tools on the Draw toolbar.
Choose either Polygon Text Polygon Text , Rectangle Text Rectangle Text , or Circle Text Circle Text .

You can create your custom text box

Your text will conform to that text box shape

So, depending on the shape you would choose that option from the Draw Toolbar.

A: I'm not aware of a way to dynamically resize the font. Perhaps a workaround would be to calculate a new field which will contain suitable abbreviations of the owner names (depending on the data you could possibly take just the last word, or first and last, whatever is going to suit your purpose), and use that in your dynamic text.


text:
Q: 60 degrees angled text in HTML / HTML5 ( in scriptable format ) One of the outputs from my software is written in to html5 format. It involves color-coding a particular column of text (depending on position chosen by user) and I have implemented this using monospace font so as to keep text alignment which is of primary requirement. Such highlighted column should be labelled so as to easily track them.
Currently I am doing this by displaying label text (shown in red color) vertically but as you could see it is not easily readable (especially true when labels are right next to each other). It will be 1000x better if I could show the label in an angled manner -preferably at 60 degrees. It cannot be hard-coded as the solution needs to scripting compatible. Is there a way to do it in a way that can be scripted? Thanks in advance!!
Expected Output:

Screenshot of current output:

Current HTML code:
<!doctype html>

    <META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=utf-8">

                                <vert>2
1
</vert>        <vert>3
0
</vert> <vert>3
2
</vert>           <vert>4
4
</vert>           <vert>5
6
</vert>
Line1       MSLLNVPAGKDLPEDIYVVIEIPANADPIKYEIDKESGALFVDRFMSTAMFYPCNYGYIN   60
Line2       MNIKEIPIGNNPPEDVNVIIEVPVDSQPVKYEMDKKSGSLFVDRFISTSMVYPGNYGFIP   60
Line3       -MFIDKIKAKANNDEINVIIEIPMNIGPIKYEFDKESGAVFVDRFMQTTMSYPCNYGFIP   59
Line4       -MFIDKIKAKANNDEINVIIEIPMNSGPIKYEFDKESGAVFVDRFMQTTMSYPCNYGFIP   59

Edit 1: Updated with expected output picture. And code updated per @FelipeAls suggestion on removing font and styling with css instead.

A: You can angle the labels with css
vert {
  transform: rotate(45deg);
  transform-origin: bottom left;
}

Though a screenshot would be preferred to be able to match correctly.
Update:
if you take the  out from in between each digit then you can use rotate(-45deg) that will get what you want for angling the text.

A:
You can have completely scripted control using html5 canvas:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
  var BB=canvas.getBoundingClientRect();
  offsetX=BB.left;
  offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }

var PI=Math.PI;
var leftMargin=25;
var topMargin=75;
var lineWidth=25;
var highlightMargin=topMargin-25;

var lines=[];
lines.push('we had everything before us');
lines.push('we had nothing before us');
lines.push('we were all going direct to Heaven');
lines.push('we were all going direct the other way');

var font='18px courier';
ctx.font=font;

var charWidth=ctx.measureText('w').width;

drawText();

highlight(13);
highlight(21);
highlight(22);

function highlight(column){

  var x=leftMargin+(column-1)*charWidth;

  // draw the highlight bar at the current mouseX
  ctx.globalAlpha=.25;
  ctx.fillStyle='gold';
  ctx.fillRect(x,highlightMargin,charWidth,topMargin+lines.length*lineWidth);
  ctx.globalAlpha=1.00;

  // display the tilted character position
  ctx.font='9px arial';
  ctx.fillStyle='red';
  ctx.textAlign='center';
  ctx.translate(x+charWidth/2,highlightMargin);
  ctx.rotate(-PI/4);
  ctx.fillText(column,0,0);
  ctx.setTransform(1,0,0,1,0,0);

}

function drawText(){
  // draw the lines[] of text
  ctx.textAlign='left';
  ctx.font=font;
  ctx.clearRect(0,0,cw,ch);
  ctx.fillStyle='black';
  for(var i=0;i<lines.length;i++){
    ctx.fillText(lines[i],leftMargin,topMargin+i*lineWidth);
  }
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=450 height=300></canvas>


text:
Q: Python: Pass execution statement as function parameter retVal = None
retries = 5
success = False
while retries > 0 and success == False:
    try:
        retVal = graph.put_event(**args)
        success = True
    except:
        retries = retries-1
        logging.info('Facebook put_event timed out.  Retrying.')
return success, retVal

In the code above, how can I wrap this whole thing up as a function and make it so that any command (in this example, 'graph.put_event(**args)') can be passed in as a parameter to be executed within the function?

A: To directly answer your question:
def foo(func, *args, **kwargs):
    retVal = None
    retries = 5
    success = False
    while retries > 0 and success == False:
        try:
            retVal = func(*args, **kwargs)
            success = True
        except:
            retries = retries-1
            logging.info('Facebook put_event timed out.  Retrying.')
    return success, retVal

This can then be called as such:
s, r = foo(graph.put_event, arg1, arg2, kwarg1="hello", kwarg2="world")

As an aside, given the above task, I would write it along the lines of:
class CustomException(Exception): pass

# Note: untested code...
def foo(func, *args, **kwargs):
    retries = 5
    while retries > 0:
        try:
            return func(*args, **kwargs)
        except:
            retries -= 1
            # maybe sleep a short while
    raise CustomException

# to be used as such
try:
    rv = foo(graph.put_event, arg1, arg2, kwarg1="hello", kwarg2="world")
except CustomException:
    # handle failure

A: def do_event(evt, *args, **kwargs):
   ...
      retVal = evt(*args, **kwargs)
   ...


text:
Q: contentResolver not returning distinct data from MediaProvider I have this function, which is supposed to give the list of albums or buck_display_name(s) but it is returning repeated value. I have searched a lot but could not find any help:
String[] projection = {"Distinct "+MediaStore.Images.Media.BUCKET_ID,
            MediaStore.Images.Media._ID,
            MediaStore.Images.Media.DATA,
            MediaStore.Images.Media.BUCKET_DISPLAY_NAME
    };
    cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,projection,null,null,"bucket_display_name ASC");
    Log.i("ResultCount",String.valueOf(cursor.getCount()));

    int i=0;
    _ALBUM_IDs = new ArrayList<>();
    URIs = new ArrayList<>();
    _IDs = new ArrayList<>();
    _ALBUM_NAMES = new ArrayList<>();
    while (cursor.moveToNext()){
        Log.i("Row",String.valueOf(i));
        for (int j=0;j<cursor.getColumnCount();j++){
            Log.i("Column "+j,cursor.getColumnNames()[j]+", value: "+cursor.getString(j));
        }
        _ALBUM_IDs.add(cursor.getString(0));
        _IDs.add(cursor.getString(1));
        URIs.add(cursor.getString(2));
        _ALBUM_NAMES.add(cursor.getString(3));
        i++;
    }

The output from the nested loop:
I/ResultCount: 6
I/Row: 0
I/Column 0: bucket_id, value: -2075821635
I/Column 1: _id, value: 43
I/Column 2: _data, value: /storage/emulated/0/DCIM/DSC_0339.jpg
I/Column 3: bucket_display_name, value: DCIM
I/Row: 1
I/Column 0: bucket_id, value: -2075821635
I/Column 1: _id, value: 44
I/Column 2: _data, value: /storage/emulated/0/DCIM/DSC_0934.jpg
I/Column 3: bucket_display_name, value: DCIM
I/Row: 2
I/Column 0: bucket_id, value: -2075821635
I/Column 1: _id, value: 45
I/Column 2: _data, value: /storage/emulated/0/DCIM/DSC_2057m.jpg
I/Column 3: bucket_display_name, value: DCIM
I/Row: 3
I/Column 0: bucket_id, value: -2075821635
I/Column 1: _id, value: 46
I/Column 2: _data, value: /storage/emulated/0/DCIM/DSC_2132.jpg
I/Column 3: bucket_display_name, value: DCIM
I/Row: 4
I/Column 0: bucket_id, value: -2075821635
I/Column 1: _id, value: 47
I/Column 2: _data, value: /storage/emulated/0/DCIM/DSC_4258.jpg
I/Column 3: bucket_display_name, value: DCIM
I/Row: 5
I/Column 0: bucket_id, value: 902704159
I/Column 1: _id, value: 63
I/Column 2: _data, value: /storage/emulated/0/DataSync/DSC_0249.jpg
I/Column 3: bucket_display_name, value: DataSync

You can see there are repeated values of bucket_id , bucket_display_name. Why is this? Thank you.

A: The _id values are distinct, so the function works correctly.
The ContentResolver.query() method does not really allow you to filter for distinct values in a specific column (this would require GROUP BY, which is not possible either), unless the content provider actually gives you a data source for that.
You have to filter the results manually.


text:
Q: Apache Commons lang: What's difference between SerializationUtils.clone() and BeanUtils.cloneBean(), when to use which While writing tests I came across a requirement to clone an object. found 2 Utill classes by apache-commons then I tried to find which one should I use,
I've tried to find the diff by reading out both API doc but didn't find which should I use when
BeanUtils cloneBean() API doc
As per doc:
Clone a bean based on the available property getters and setters, even if the bean class itself does not implement Cloneable.
Doubt: should i use this on DTO cloning ?
SerializationUtils clone()  API doc
As per doc:
Deep clone an Object using serialization.
This is many times slower than writing clone methods by hand on all objects in your object graph. However, for complex object graphs, or for those that don't support deep cloning this can be a simple alternative implementation. Of course, all the objects must be Serializable.
Doubt: should I use it for both DTO and Entity Object ? or only for Entity

A: The SerializationUtils will always produce a deep-copy. It will create a string of each field (it is called serialization) and parses the string back into a new object (deserialization).
This is quite slow, but you have the guarantee, that your copy is a deep copy.
A deep-copy means: All fields are new objects (and not a reference to a old object).
BeanUtils.cloneBean() on the other hand, will create a shallow copy of your object. Here is some code to explain what is the difference:
@Data // lombok annotation, will create getters, setters, equals and hashcode
public class ObjectA implements Serializeable {
    private List<String> values = new ArrayList<>();
}

public static main() {

    ObjectA objectA = new ObjectA();
    objectA().getValues().add("A");

    ObjectA beanClone = (ObjectA) BeanUtils.cloneBean(objectA);
    ObjectA serialClone = SerializationUtils.clone(objectA);

    log.info("Reference-Check: Bean is same: {}", objectA == beanClone); // <- false
    log.info("Reference-Check: Bean-Value is same: {}", objectA.getValues() == beanClone.getValues()); // <- true

    log.info("Reference-Check: Serial is same: {}", objectA == serialClone); // <- false
    log.info("Reference-Check: Serial-Value is same: {}", objectA.getValues() == serialClone.getValues()); // <- false

    serialClone.getValues().add("B");
    printValues(serialClone.getValues()); // <- prints "['A', 'B']"
    printValues(objectA.getValues()); // <- prints "['A']";

    beanClone.getValues().add("B");
    printValues(beanClone.getValues()); // <- prints "['A', 'B']"
    printValues(objectA.getValues()); // <- prints "['A', 'B']"

}

So to your questions: A deep-copy is "safer", you can't modify fields of the original object. This side-effect on shallow copies is often unwanted. Almost always, you need a deep copy.
Serialization is quite slow, so the best way is a copy-method or a copy-constructor.


text:
Q: ASP.NET Web Forms - Security of Web Forms simple but hard to solve question on Web Forms.
I enforced a role-based access on my web form application, but I would like to tailor the access based on WebForm or URL, something like
/Administration/* --> only admins
/Users/* --> admins and users
/* --> anonymous also
Any hint on how to do it on web.config?
Thank you and best regards

A: <location path="Admin">
                <authorization>
                                <allow roles="Admin" />
                                <deny users="*" />
                <deny roles="*" />
                </authorization>
</location>

or take a look here: http://support.microsoft.com/kb/316871 or http://weblogs.asp.net/gurusarkar/archive/2008/09/29/setting-authorization-rules-for-a-particular-page-or-folder-in-web-config.aspx

A: An easiest way would be to create local web.config files in each of your subfolders. Such local web.config would only contain the authorization information so that the built-in UriAuthorizationModule could do the rest for you.
For example, inside the /Admin folder create a web.config with
<configuration>
 <system.web>
 <authorization>
   <allow roles="Admin" />
   <deny users="*" />
 </authorization>
 </system.web>
</configuration>

thus giving the access to only users who are administrators. Apply the same to other subfolders and you are done - under a condition that a role manager exists and provides the information about users' roles.
Creating local web.configs containing only the authorization data in each subfolder gives you fine-grained control over your authorization. The alternative would be to provide this information in the main web.config but it would soon become overloaded with many authorization nodes referring to different locations.


text:
Q: What's wrong with my TikZ? I've just installed MacTeX-2019 on my MacBook.
So I'm using TeXShop 4.27 which comes along.
I'm trying to execute the most basic GNUPLOT example:
http://www.texample.net/tikz/examples/gnuplot-basics/
Here is the output I get:

What could possibly go wrong?
I've tried other examples that work well.
But it looks like there is a specific problem with
\draw plot function
Thanks for your help,
Julien

A: Juste making @Seamus comment an answer.

*

*Gnuplot does not come with MacTeX-2019: so you need to install it.

*Then you have to enable shell-escape as explained here: https://stackoverflow.com/a/28586661/2886628


text:
Q: Legend placement, ggplot, relative to plotting region Problem here is a bit obvious I think. I'd like the legend placed (locked) in the top left hand corner of the 'plotting region'. Using c(0.1,0.13) etc is not an option for a number of reasons.
Is there a way to change the reference point for the co-ordinates so they are relative to the plotting region?
mtcars$cyl <- factor(mtcars$cyl, labels=c("four","six","eight"))
ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) +
opts(legend.position = c(0, 1), title="Legend placement makes me sad")

Cheers

A: Update: opts has been deprecated. Please use theme instead, as described in this answer.
Just to expand on kohske's answer, so it's bit more comprehensive for the next person to stumble upon it.
mtcars$cyl <- factor(mtcars$cyl, labels=c("four","six","eight"))
library(gridExtra)

a <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) +
opts(legend.justification = c(0, 1), legend.position = c(0, 1), title="Legend is top left")
b <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) +
opts(legend.justification = c(1, 0), legend.position = c(1, 0), title="Legend is bottom right")
c <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) +
opts(legend.justification = c(0, 0), legend.position = c(0, 0), title="Legend is bottom left")
d <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) +
opts(legend.justification = c(1, 1), legend.position = c(1, 1), title="Legend is top right")

grid.arrange(a,b,c,d)

A: I have been looking for similar answer. But found that opts function is no longer part of ggplot2 package. After searching for some more time, I found that one can use theme to do similar thing as opts. Therefore editing this thread, so as to minimize others time.
Below is the similar code as written by nzcoops.
mtcars$cyl <- factor(mtcars$cyl, labels=c("four","six","eight"))
library(gridExtra)

a <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + labs(title = "Legend is top left") +
theme(legend.justification = c(0, 1), legend.position = c(0, 1))

b <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + labs(title = "Legend is bottom right") +
theme(legend.justification = c(1, 0), legend.position = c(1, 0))

c <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + labs(title = "Legend is bottom left") +
theme(legend.justification = c(0, 0), legend.position = c(0, 0))

d <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) + labs(title = "Legend is top right") +
theme(legend.justification = c(1, 1), legend.position = c(1, 1))

grid.arrange(a,b,c,d)

This code will give exactly similar plot.

A: Update: opts has been deprecated. Please use theme instead, as described in this answer.
The placement of the guide is based on the plot region (i.e., the area filled by grey) by default, but justification is centered.
So you need to set left-top justification:
ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) +
  opts(legend.position = c(0, 1),
       legend.justification = c(0, 1),
       legend.background = theme_rect(colour = NA, fill = "white"),
       title="Legend placement makes me happy")

If you want to place the guide against the whole device region, you can tweak the gtable output:
p <- ggplot(mtcars, aes(x=wt, y=mpg, colour=cyl)) + geom_point(aes(colour=cyl)) +
  opts(legend.position = c(0, 1),
       legend.justification = c(0, 1),
       legend.background = theme_rect(colour = "black"),
       title="Legend placement makes me happy")

gt <- ggplot_gtable(ggplot_build(p))
nr <- max(gt$layout$b)
nc <- max(gt$layout$r)
gb <- which(gt$layout$name == "guide-box")
gt$layout[gb, 1:4] <- c(1, 1, nr, nc)
grid.newpage()
grid.draw(gt)

A: To expand on the excellend answers above, if you want to add padding between the legend and the outside of the box, use legend.box.margin:
# Positions legend at the bottom right, with 50 padding
# between the legend and the outside of the graph.
theme(legend.justification = c(1, 0),
    legend.position = c(1, 0),
    legend.box.margin=margin(c(50,50,50,50)))

This works on the latest version of ggplot2 which is v2.2.1 at the time of writing.


text:
Q: Umbraco 8 - How to get invariant properties values in case of publishing only the secondary culture node? I have an application which has two variant languages (English - Arabic) . When I publish node in Arabic only without English. All invariant properties are null and not even exists external index.
To create the The issue :

*

*In back-office, create a node which have title (text box vary by culture) , date(datepicker do not vary by culture) ,& Image (ImageCropper do not vary by culture).

*Save and publish in Arabic culture only.

*Try to look at externl index for the created node,  text has value while image  and date do not.

*view ContentModel object is also has empty properties

Is there a way to get these(date, image) values without publishing these properties in English Node ?

A: I found this github issue#5532 states the issue , it is closed with no solution. It is out of their scope.  Here is the contributor ronaldbarend commented on Oct 6, 2020

*"This can't be fixed without completely rewriting the way element types are stored, as currently all data is stored as JSON in a single property. There's a RFC to change this, but the feature to keep variants in sync is explicitly stated as being out of scope: umbraco/rfcs#24."

https://github.com/umbraco/Umbraco-CMS/issues/5532


text:
Q: Argument passing by auto in range based for vector<MyClass> objects;
for (auto obj : objects)
{}

Will obj be a copy of each object or a reference?

A: Yes, you will get a copy for each element, you won't with auto& or auto&&. This is better understood with an example
struct MyClass {
    MyClass() {}
    MyClass(const MyClass&) {
        cout << "copy ctor invoked" << endl;
    }
};

int main(){
    vector<MyClass> objects;
    MyClass obj1;
    objects.push_back(obj1); // Vector filling
    cout << "------" << endl;
    for (auto obj : objects) // Auto loop
    {}
    cout << "------" << endl;
    for (auto& obj : objects)
    {}
}

Output:
copy ctor invoked // Vector filling
------
copy ctor invoked // Auto loop
------

A: The way written you will get a copy for every element. To not get a copy, use
for (auto&& obj: object) {
}

You can also use one of the other obvious variations:

*

*Still with the type deduced but be explicit about using a reference: auto&.

*Be explicit but use a const reference: auto const&.

*You can actually also use the type: MyClass& or MyClass const&.

A: The simple answer is: your intuition is correct and you get a copy.
The reason behind that lies with the type deduced by auto. Scott Mayers gave a talk recently at CppCon 2014 on this topic: https://www.youtube.com/watch?v=wQxj20X-tIU


text:
Q: search and replace a character I have a string like this
x<-c("This is a test (120)")

I need to replace the empty space between test and ( so that text will be like this
x<-c("This is a test(120)")

I tried this
s<-gsub("\t\v\(", "", x)

not working, any input would be appreciated.

A: Using a lookahead:
gsub("\\s+(?=\\()", "", x, perl=TRUE)
[1] "This is a test(120)"

Answer depends on more specifications you require though. Do you want to remove all spaces in front of opening brackets? Or just one? Or only in front of brackets containing numbers?

A: One simple approach is to used fixed = TRUE as in:
gsub(" (", "(", x, fixed = TRUE)

or:
gsub(" \\(", "\\(", x)

A: You have to "double escape" things in R.  One for R and one for the regex:
s <- gsub('\\s\\(', '(', x)

That said, depending on your specific use case, you might want this to be more robust:
s <- gsub('(.+) \\((.+)\\)', '\\1(\\2)', x)


text:
Q: How can I say to JS to increase a value everytime multiple conditions are met..without hardcoding it I  am trying to figure out this problem, basically my problem is:  if  the length (in seconds) is < 180 return 500(pences) . For every extra 60 seconds add 70 pences.  So if for example I have 240seconds I should return 570pences  if I have 300seconds  i should return 640pences and so on. How can I achieve this result with JavaScript?
this is my code so far:
    function calculateTaxiFare(seconds) {
        if (seconds < 180) {
   return 500
      // I need something like this without hardcoding
}else if (seconds > 180 && seconds < 240) {
          return 575
}else if ( seconds > 240 && seconds < 300 ) {
          return 640
}
    }

console.log(calculateTaxiFare(245));

Thank you for your support.

A: You need to integer divide the (length of time - 180 seconds) by 60 and round upwards to the nearest integer (you can use Math.ceil for that operation) and then multiply that by 70 to get the additional fare, which is then added to the base fare (500):

function calculateTaxiFare(seconds) {
  return 500 + Math.ceil((seconds - 180) / 60) * 70
}

console.log(calculateTaxiFare(245));


text:
Q: Модальное окно FancyBox Доброе утро, почему не открывается по клику на вторую кнопку модалка?

$("#btnModal").fancybox();
$(".btn-modal").on("click", function () {
    $("#form-modal").fadeOut("fast", function () {
        $(this).before("
Вы получили выгоду!
");
        setTimeout("$.fancybox.close()", 1000);
    });
});
#feedback {
    display: none;
}

.fancybox-content {
    max-width: 430px;
    padding: 65px 65px 32px 65px;

    form {
        text-align: center;

        h1 {
            font-size: 24px;
            line-height: 48px;
            font-weight: 500;
            margin-bottom: 20px;
        }
    }
}

<link href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" rel="stylesheet"/>

<button href="#feedback" id="btnModal">Получить выгоду 1</button>
<button href="#feedback" id="btnModal">Получить выгоду 2</button>

    <form id="form-modal">

Получите все выгоды!

    </form>

A:

$(".btnModal").fancybox();
$(".btn-modal").on("click", function () {
    $("#form-modal").fadeOut("fast", function () {
        $(this).before("
Вы получили выгоду!
");
        setTimeout("$.fancybox.close()", 1000);
    });
});

<link href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" rel="stylesheet"/>

<button href="#feedback" class="btnModal">Получить выгоду 1</button>
<button href="#feedback" class="btnModal">Получить выгоду 2</button>

    <form id="form-modal">

Получите все выгоды!

    </form>


text:
Q: Dynamic queries in Spring Data JPA. Refactoring Working with Spring data jpa and specifications, I have a requirement to implement a filter/search feature in spring mvc.  The backend receives an object (ReportTemplateBean) which is basically a bean with some fields that represents the filters in the front end.
public class ReportTemplateBean implements Serializable {

private static final long serialVersionUID = -3915391620260021813L;

private Long id;

private String property;

private String city;

private String state;

private String zipCode;

private String propertyStatus;

private String realEstateRep;
//more code

We have the Controller
@RequestMapping(value = "/search", method = RequestMethod.GET)
@ResponseBody
public ReportBean search(@AuthenticationPrincipal ActiveUser activeUser,
    @ModelAttribute("templateForm") ReportTemplateBean template,
    Pageable pageable) throws GenericException {
LOGGER.info("Pulling report requested");

ReportBean report = reportService.searchProperties(template,
    pageable.getPageNumber(), pageable.getPageSize());

return report;
}

The service
@Override
@Transactional(readOnly = true, timeout = 20)
public ReportBean searchProperties(ReportTemplateBean template,
    Integer pageNumber, Integer pageSize) throws GenericException,
    TransactionTimedOutException {
LOGGER.info("searchProperties({})", template);

try {
    // pageNumber = (pageNumber == null ? 0 : pageNumber);
    // pageSize = (pageSize == null ? 10 : pageSize);
    ReportTemplate t = reportTemplateMapper.beanToEntity(template);
    List<PropertyBean> beans = new ArrayList<PropertyBean>();
    PropertySpecification spec = new PropertySpecification(t);
    Page<Property> properties = propertyRepository.findAll(spec,
        new PageRequest(pageNumber, pageSize, Sort.Direction.ASC,
            "name"));

And then it builds the query dynamically, but using a long IF chain that I don't like it.  This is the Specification.
@SuppressWarnings("unchecked")
@Override
public Predicate toPredicate(Root<Property> root, CriteriaQuery<?> query,
    CriteriaBuilder cb) {
Path<String> propertyName = root.get(Property_.name);
Path<String> city = root.get(Property_.city);
Path<String> state = root.get(Property_.state);
Path<String> zipCode = root.get(Property_.zipCode);
final List<Predicate> orPredicates = new ArrayList<Predicate>();
final List<Predicate> andPredicates = new ArrayList<Predicate>();
if (template.getProperty() != null
    && template.getProperty().length() > 0) {
    andPredicates.add(cb.equal(propertyName, template.getProperty()));
}
if (template.getCity() != null && template.getCity().length() > 0) {
    andPredicates.add(cb.equal(city, template.getCity()));
}
if (template.getState() != null && template.getState().length() > 0) {
    andPredicates.add(cb.equal(state, template.getState()));
}
if (template.getZipCode() != null && template.getZipCode().length() > 0) {
    andPredicates.add(cb.equal(zipCode, template.getZipCode()));
}
if (template.getRealEstateRep() != null) {
    Join<Property, User> pu = null;
    if (query.getResultType().getName().equals("java.lang.Long")) {
    pu = (Join<Property, User>) root.fetch(Property_.createdBy);
    } else {
    pu = root.join(Property_.createdBy);
    }
    Path<Long> userId = pu.get(User_.id);
    andPredicates.add(cb.equal(userId, template.getRealEstateRep()));
}
if (template.getProjectType() != null
    && template.getProjectType().length() > 0) {
    Join<Property, Project> pp = null;
    if (query.getResultType().getName().equals("java.lang.Long")) {
    pp = root.join(Property_.projects);
    } else {
    pp = (Join<Property, Project>) root.fetch(Property_.projects);
    }
    Path<String> projectType = pp.get(Project_.projectName);
    andPredicates.add(cb.equal(projectType, template.getProjectType()));
}
//more IF's
return query.getRestriction();
}

As you can notice the Specification seems ugly and besides that SONAR complains about The Cyclomatic Complexity of this method  (which is good).
So question is, How can I refactor the Specification (IF's) to be more OO code?.
Thanks in advance.
UPDATE- I would like to use/implement something like the new feature in Spring Data JPA (Query by Example)  It seems that if you pass a bean the ExampleMatcher class will ignore the null value in the bean fields which is almost what I am looking for.  Ignore null and empty values.

A: I write my solution to give you another option, but as i say in the comment i do not used Specification, and i am curious to see if anyone knows another way to do dynamic queries in spring jpa.
You could write your own query with the @Query annotation inside a @Repository interface.
In your case (assuming ReportTemplateBean is your Entity and its primary key is of Long type) it would be like:
@Repository
public interface ReportTemplateRepo extends JpaRepository<ReportTemplateBean, Long>{

    @Query("SELECT rb FROM ReportBeanTemplate rb JOIN ExampleTable et WHERE et.idTemplate = rb.id AND (:id is null OR :id = rb.id) AND (:city is null OR :city = rb.city) AND (:state is null OR :state = rb.state)")
    public List<ReportTemplateBean> findTemplates(@Param("id") Long id, @Param("city") String city, @Param("state") String state);
}

You can add all the parameters you want, pass it as null when you call the method.
Example of method invocation(in you service class):
@Autowire
ReportTemplateRepo templateRepo;

public void invocation(ReportTemplateBean template){
    List<ReportTemplateBean> templateRepo.findTemplates(
        template.getId(), template.getCity(), template.getState());
    }

This is the only way i found to do this kind of query.


text:
Q: scanf a string and printf it in C What I can do to do this?
#include <stdio.h>
#include <string.h>

void lee(char s[]);
void escribe(char s[]);

int main()
{
    char str[20];
    char ch;

    printf("1 escribe\n2 lee\n");
    ch=getchar();
    switch(ch) {
        case '1':
            printf("you are in escribe (write)\n");
            lee(str);
            break;
        case '2':
            printf("you are in lee (read)\n");
            escribe(str);
            break;
        default: puts("Error");
    }

    return 0;
}

void lee(char s[]){
    printf("write your sentense\n");
    scanf("%[^\n]", s);
}

void escribe(char s[]){
    printf("Entered string is %s \n", s);
}

A: I am not saying this is good code, but I "think" this is kind of what you are trying to do.
Maybe it will give you an idea so you can fix your code the way you want it.
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>

    void lee(char s[]);
    void escribe(char s[]);

    int main()
    {
        char str[20] = {0};
        char ch = '\0';

        while(1)
        {
            printf("\n1 escribe:\n2 lee:\n");
            ch = getchar();
            fseek(stdin, 0, 0);

            switch(ch) {
                case '1' :
                    printf("\nYou are in escribe (write)\n\n");
                    lee(str);
                    break;

                case '2' :
                    printf("\nYou are in lee (read)\n\n");
                    escribe(str);
                    break;

                default: puts("Error");
                    exit(1);
            }
        }
    return 0;
    }

void lee(char s[]){
    printf("Write your sentence: \n");
    scanf("%19[^\n]", s);
    fseek(stdin, 0,0);
    printf("\n");
}

void escribe(char s[]){
    printf("The entered string is: %s ", s);
    printf("\n");
}


text:
Q: Primitive function in R Can someone give me explanation for the below sentence highlighted in Bold.
"Primitive functions are only found in the base package, and since they operate at a low level, they can be more efficient (primitive replacement functions don't have to make copies), and can have different rules for argument matching (e.g., switch and call). This, however, comes at a cost of behaving differently from all other functions in R. Hence the R core team generally avoids creating them unless there is no other option.
Source Link:http://adv-r.had.co.nz/Functions.html#lexical-scoping


text:
Q: Converter acentos, &ordm e espaços em hífens Tenho um sistema de upload do qual ao subir um arquivo com esse tipo de nomenclatura:

Lei 4.472 - 2015 - Altera a Lei nº 4.000 de 10 de julho de 2013 -
  Arquivo Particular.pdf

Estou retirando os espaços e acentos da seguinte forma:
$arquivo = $_FILES["Arquivo"]['name'];
$extensao = pathinfo($arquivo);
$extensao = $extensao['extension'];
list($nomeArquivo,$extensaoArquivo) = explode(".".$extensao,$arquivo);
$novoNome = strtolower( preg_replace("[^a-zA-Z0-9-.]", "-", strtr(utf8_decode(trim($nomeArquivo)), utf8_decode("áàãâéêíóôõúüñçÁÀÃÂÉÊÍÓÔÕÚÜÑÇ."), "aaaaeeiooouuncAAAAEEIOOOUUNC-")) );
$arquivo $novoNome.".".$extensao;

Porém quando o arquivo tem º, aparece o sinal de ?. Como posso corrigir isso fazendo com que esse sinal também seja modificado para hífen?

A: Fiz dessa forma e parece que funcionou, mas se estiver errado, podem me corrigir:
$novoNome = strtolower( preg_replace("[^a-zA-Z0-9-|\.]", "-", strtr(utf8_decode(trim($nomeArquivo)), utf8_decode("áàãâéêíóôõúüñçÁÀÃÂÉÊÍÓÔÕÚÜÑǺ."), "aaaaeeiooouuncAAAAEEIOOOUUNC-")) );


text:
Q: Second monitor is not working on boot I have Ubuntu 20.04 installed with ubuntu-mate-desktop.
I work with a second monitor, connected via hdmi.
When I turned-off and then reboot my system, this monitor is black (and cursor does not pass into it), also it is in ON mode:

I need to turn it off, apply, then turn it on again.
It is annoying and does not have any sense.
How can I fix it?


text:
Q: Windows 8 CredentialPicker - Advice for a Win8 beginner I've been doing .NET console, .NET Webforms, and light WPF work before, but this is my first foray into Windows 8 Metro development.
I'm developing an app that's dependent on a web service that requires an authentication token. The app is kind of useless without this token; they only need to provide this token and not a username or password. The token can be revoked by the service provider in the event the app needs to be de-authorized.
Since the token is basically required for any app functionality; it needs to be global, it needs to persist for the lifetime of the app; it would be great if the app remembered the credential in a secure way after the app terminates to be loaded on the next run. I tried sticking a CredentialPicker in the App.xaml.cs file, however I guess the credentialpicker needs to be on an actual page? What's the best way to make this global, and spawn the credentialpicker whenever the model class detects there's no credentials for whatever reason?
My logic I thought would be:
Boot App
Load App Start Page
Check Disk for Credential Hash
If Hash Not Exist, Launch CredentialPicker
    Validate Credential/Key
    If Credential/Key not valid,
        Relaunch CredentialPicker
    Else
        Store Credentials To Disk
Else
    Use Existing Credentials; Proceed

Store Credentials In PasswordVault for use during this app lifecycle

Apologize for the verbosity; I just want to know best practices using an application-wide set of credentials in Win8

A: If you're authenticating with a web service, you want to use the Web Authentication Broker instead (Windows.Security.Authentication.Web.WebAuthenticationBroker, also see the sample on http://code.msdn.microsoft.com/windowsapps/Web-Authentication-d0485122). The collection of credentials stays in the broker, and you get the server response back that typically contains the key you need for subsequent calls.
Using the credential picker for this purpose isn't really what you want, as that UI is primarily intended for enterprise scenarios, and still requires that you manage the credentials directly in the app. The Web Auth Broker was designed so the credentials always exists on the service and all you get back is the key. There is also a topic in the docs Web authentication broker for online providers on creating a login page that will work great inside the broker.
Note that you can use the password vault for the key--just give it some dummy username in the credential object.


text:
Q: Storing @include() in a variable? Is it possible to store the output of @include('view.name') into a variable?
Something like this:
$var = @include('view.name')
{{$var}}

The reason I want to do that I want to pass @include('view.name') into Blade::directive()
For example:
@blocksection([
        'Title',
        '
Descrption
,
         @include('view.name'),
])
// HTML
@endblocksection

A: I don't know if this is possible, but I'd rather do it in the following way (a cleaner approach I think):

*

*In the corresponding controller, render the view manually and store it in some variable
$var = view('view.name')->render()

*Pass the variable to the target template
return view('your template', ['var' => $var])

*Just use it now :D


text:
Q: Capturing a picture in c++ using v4l2, explaining the process I have been struggling with making a c++ code for capturing a picture from web-camera. I successfully did it, but I would like some clarification about the process i took.
So my code can be described in 6 steps, i will write them here along with my questions:
I. step:    Initialize the device and set image format.
    const char* dev_name = "/dev/video0";
    int width=320;
    int height=240;
    int fd = v4l2_open(dev_name, O_RDWR | O_NONBLOCK, 0);
    struct v4l2_format format = {0};
    format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    format.fmt.pix.width = width;
    format.fmt.pix.height = height;
    format.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;//V4L2_PIX_FMT_YUYV //V4L2_PIX_FMT_RGB24
    format.fmt.pix.field = V4L2_FIELD_NONE; //V4L2_FIELD_NONE
    xioctl(fd, VIDIOC_S_FMT, &format);

II. step:   Request for a buffer.
    struct v4l2_requestbuffers req = {0};
    req.count = 2;
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    req.memory = V4L2_MEMORY_MMAP;
    xioctl(fd, VIDIOC_REQBUFS, &req);

*

*question: What exactly does this "request a buffer" do?

*question: Is this buffer physically located inside the camera or on my pc?

III. step:  Query the buffer and mapping.
    struct v4l2_buffer buf;
    buffer* buffers;
    unsigned int i;
    buffers = (buffer*) calloc(req.count, sizeof(*buffers));
    for (i = 0; i < req.count; i++) {
    clear_memmory(&(buf));

    (buf).type        = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    (buf).memory      = V4L2_MEMORY_MMAP;
    (buf).index       = i;

    xioctl(fd, VIDIOC_QUERYBUF, &buf);

    buffers[i].length = (buf).length;
    printf("A buff has a len of: %i\n",buffers[i].length);
    buffers[i].start = v4l2_mmap(NULL, (buf).length, PROT_READ | PROT_WRITE, MAP_SHARED,fd, (buf).m.offset);

    if (MAP_FAILED == buffers[i].start) {
        perror("Can not map the buffers.");
        exit(EXIT_FAILURE);
        }
    }

*question: I understand that i do some mapping here, but can somebody explain why is this needed and what exactly is mapped where. To me it sounds like actual buffer is somewhere else and then i mapp it into my own buffer so i can read things from my buffer. Is this correct and where is the actual buffer?

*question: Could i also avoid the mapping?
IV. step:   Start streaming. Queue the buffer.
    for (i = 0; i < 1; i++) {
        clear_memmory(&(buf));
        (buf).type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        (buf).memory = V4L2_MEMORY_MMAP;
        (buf).index = i;
        xioctl(fd,VIDIOC_QBUF, &(buf));
        }
    enum v4l2_buf_type type;
    type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    xioctl(fd,VIDIOC_STREAMON, &type);

*question: What does the VIDIOC_QBUF do? Please be very precise here and using mostly child words in answer to this since this is very confusing.

*question: Should VIDIOC_QBUF happen after VIDIOC_STREAMON? Does it matter?

V. step:    DeQueue the buffer and save a frame.
    do {
        FD_ZERO(&fds);
        FD_SET(fd, &fds);

        // Timeout.
        tv.tv_sec = 2;
        tv.tv_usec = 0;

        r = select(fd + 1, &fds, NULL, NULL, &tv);
        } while ((r == -1 && (errno = EINTR)));
    if (r == -1) {
        perror("select");
        exit(EXIT_FAILURE);
        }

    clear_memmory(&(buf));
    (buf).type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    (buf).memory = V4L2_MEMORY_MMAP;
    xioctl(fd,VIDIOC_DQBUF, &(buf));

    printf("Buff index: %i\n",(buf).index);
    sprintf(out_name, "image%03d.ppm",pic_count);
    fout = fopen(out_name, "w");
    if (!fout) {
        perror("Cannot open image");
        exit(EXIT_FAILURE);
        }
    fwrite(buffers[(buf).index].start, (buf).bytesused, 1, fout);
    fclose(fout);
    pic_count++;

*question: Why is VIDIOC_DQBUF needed and what does it do?

*question: If i want to capture 3 frames and if i have only 1 buffer for 1 picture, do i need to queue, dequeue 3 times?

*question: If i want 1000000 pictures, can I make that buffer big enough to hold them all? What is limiting the size of that buffer? Is that buffer on the camera and that means all this pictures would be sitting in it?

*question: If i want 10 pictures taken at moments I chose, and if i go with making a buffer large enough for 10 pictures. What should i call at the moment i want to take a picture? only VIDIOC_QBUF? VIDIOC_QBUF and VIDIOC_DQBUF?, only VIDIOC_DQBUF?

Please don't point me to https://01.org/linuxgraphics/gfx-docs/drm/media/uapi/v4l/vidioc-qbuf.html or other sites, as I have read everything i was able to found and I am still left with above unclarity. I really want detailed explanations about these questions. I thank you in advance for all helpful answers.


text:
Q: output of negative integer to %u format specifier Consider the following code
char c=125;
c+=10;
printf("%d",c); //outputs  -121 which is understood.
printf("%u",c); // outputs 4294967175.
printf("%u",-121); // outputs 4294967175

%d accepts negative numbers therefore output is -121 in first case.
output in case 2 and case 3 is 4294967175. I don't understand why?

A: Do

232  -  121 = 4294967175

printf interprets data you provide thanks to the % values

*

*%d signed integer, value from -231 to 231-1

*%u unsigned integer, value from 0 to 232-1

In binary, both integer values (-121 and 4294967175) are (of course) identical:
`0xFFFFFF87`

See Two's complement

A: printf uses something called variadic arguments. If you make a brief research about them you'll find out that the function that uses them does not know the type of the input you're passing to it. Therefore there must be a way to tell the function how it must interpret the input, and you're doing it with the format specifiers.
In your particular case, c is a 8-bit signed integer. Therefore, if you set it to the literal -121 inside it, it will memorize: 10000111. Then, by the integer promotion mechanism you have it converted to an int: 11111111111111111111111110000111.
With "%d" you tell printf to interpret 11111111111111111111111110000111 as a signed integer, therefore you have -121 as output. However, with "%u" you're telling printf that 11111111111111111111111110000111 is an unsigned integer, therefore it will output 4294967175.
EDIT: As stated in the comments, actually the behaviour is undefined in C. That's because you have more than one way to encode negative numbers (sign and modulo, One's complement, ...) and sone other aspects (such as endianness, if I'm not wrong, influences this result). So the result is said to be implementation defined. Therefore you may get a different output rather than 4294967175. But the main concepts I explained for different interpretation of the same string of bits and the lossness of the type of data in variadic arguments still hold.
Try to convert the number into base 10, first as a pure binary number, then knowing that it's memorized in 32-bit Two's complement... you get two different results. But if I do not tell you which intepretation you need to use, that binary string can represent everything (a 4-char ASCII string, a number, a small 8-bit 2x2 image, your safe combination, ...).
EDIT: you can think of "%<format_string>" as a sort of "extension" for that string of bits. You know, when you create a file, you usually give it an extension, which is actually a part of the filename, to remember in which format/encoding that file has been stored. Let's suppose you have your favorite song saved as song.ogg file on your PC. If you rename the file in song.txt, song.odt, song.pdf, song, song.akwardextension, that does not change the content of the file. But if you try to open it with the program usually associated to .txt or .whatever, it reads the bytes in the file, but when it tries to interpret sequences of bytes it may fail (that's why if you open song.ogg with Emacs or VIm or whatever text editor you get sonething that looks like garbage information, if you open it with, for instance, GIMP, GIMP cannot read it, and if you open it with VLC you listen to your favorite song). The extension is just a reminder for you: it reminds you how to interpret that sequence of bits. As printf has no knowledge for that interpretation, you need to provide it one, and if you tell printf that a signed integer is acutally unsigned, well, it's like opening song.ogg with Emacs...

A: printf is a function with variadic arguments. In such case a "default argument promotions" are applied on arguments before the function is called. In your case, c is first converted from char to int and then sent to printf. The conversion does not depend on the corresponding '%' specifier of the format. The value of this int parameter can be interpreted as 4294967175 or -121 depending on signedness. The corresponding parts in the C standard are:

6.5.2.2 Function call
6 - ... If the expression that denotes the called function has a type that does not include a
  prototype, the integer promotions are performed on each argument, and arguments that
  have type float are promoted to double. These are called the default argument
  promotions.
7- If the expression that denotes the called function has a type that does include a prototype,
  the arguments are implicitly converted, as if by assignment, to the types of the
  corresponding parameters, taking the type of each parameter to be the unqualified version
  of its declared type. The ellipsis notation in a function prototype declarator causes
  argument type conversion to stop after the last declared parameter. The default argument
  promotions are performed on trailing arguments.

A: If char is signed in your compiler (which is the most likely case) and is 8 bits wide (extremely likely,) then c+=10 will overflow it. Overflow of a signed integer results in undefined behavior. This means you can't reason about the results you're getting.
If char is unsigned (not very likely on most PC platforms), then see the other answers.


text:
Q: Is it possible to create a deterministic secure random string based on some input from the client? Two scenarios:
Say my user provides me the following:
long firstId;
long secondId;

or
UUID firstId;
long secondId;

and I have a variable to define a secret string:
private String mySecret = "2m75eB4xmAtMrz5cYQdSCch9R5R3xU6G";

Can I use the user inputs to generate a secure random string on the fly without hardcoding a string in the code (which seems pretty insecure)? If my program restarts and I provide the same input, I should get the same secret generated.

A: When you talk about security you should give some info about the context and what are you tryng to do, for random string i suggest a digest:
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] encodedhash = digest.digest(
  originalString.getBytes(StandardCharsets.UTF_8));

private static String bytesToHex(byte[] hash) {
    StringBuffer hexString = new StringBuffer();
    for (int i = 0; i < hash.length; i++) {
    String hex = Integer.toHexString(0xff & hash[i]);
    if(hex.length() == 1) hexString.append('0');
        hexString.append(hex);
    }
    return hexString.toString();
}

You can use as input string something like:
String input = mySecret + (firstId + secondId);

Given the same input this digest will give you always the same result but you would be exposed to an attack that is called dictionary attack, in this way a cracker that know what algorithm you are using "sha-256" can retrieve the original secret from the digest.


text:
Q: filling a collection using an iterator Google Collections has an Iterables utility class for taking in a collection and iterable and putting all the elements from iterable into the collection, called addAll.   Is there something similar when all you have is an iterator?

A: Yes, and it's called Iterators.addAll(Collection, Iterator), unsurprisingly.


text:
Q: Excel: Inconsistent sorting criteria from 'Smallest to Largest' to 'A-Z' Situation:
I am pulling information from a database and exporting it into an Excel 2010 template. The data consists of unique IDs (numeric), dates, and text in their respective columns. When going to sort, Excel usually recognizes the unique IDs as text and gives me the option of 'A-Z' which yields the correct result.
Problem:
Occasionally when sorting the unique IDs, Excel will give me the option to sort from 'Smallest to Largest' and when this happens the report yields a wildly incorrect result.
Pattern:
The sorting criteria is the only common denominator when a report fails, which makes little sense as they are both ascending orders. This issue only occurs ~20% of the time. The other times it sorts correctly from 'A-Z' as it does in the other worksheets within the same template.
-I've tried changing Number Format within the drop down to 'Text' 'General' and 'Numbers'
-I've tried manually sorting the data through filters as opposed to sort hierarchies
-I've tried clearing the table, and re-copying/pasting the data into the template's worksheet. This seems to work, but as the end goal is automation, I'd like to find out what the root cause is.
Expected result: Numeric data copied and pasted into the field to be sorted from 'A-Z', resulting in a successful report.
Actual result: Numeric data copied and pasted into the field typically results in the sort option of "A-Z', but occasionally sorts from 'Smallest to Largest' resulting in a failed report.

A: Excel is designed for numbers - and is generally very helpful in coercing text to numbers where appropriate. However, once in Number format the reverse is not easy. As you have discovered, merely choosing Text as format is not enough.
A clue is whether or not (assuming activated) the cells show green triangles.
Other than starting afresh with data entry into a cell already formatted as Text, the conventional solution for conversion with code is to prepend a quote, though appending a space would also serve.
Other than that, the easiest mass conversion approach may be to copy into Word (Keep text only) and copy back to Excel with pasting as Text.
The better solution may be to store IDs as text and prepend 0s to a standard length.


text:
Q: Calculate average values over blocks of consecutive hourly records separated by gaps in time The data come to me in Excel. MS-Access is also available, of course. I also have SAS and Python.
I have data in two columns which I named DateTime and Observation. Observations are numeric and correspond to hourly readings. When sorted, there are runs of consecutive hourly observations over one or more days, separated logically (and irregularly) by gaps in time greater than one hour.
I need to automate the identification of the the time blocks (24,000 records) and calculate average, minimum, and maximum Observation for each discrete time block.

A: Here is a PivotTable example:-


text:
Q: Significantly higher outcomes in stock price predicting LSTM model than expected I have made my LSTM model to estimate next day's stock prices. I have used tensorflow and keras.
However, I do not understand why my model's predicted price is almost always 2 or 3 factors higher than the current stock price. Is there anybody who knows what I am doing wrong?
The code is shown below:
def StockPredictor(stock, startdate, enddate, pricetype):

    #Get the stock quote
    df = web.DataReader(stock, data_source = 'yahoo', start=startdate, end=enddate)
    #df = pd.read_csv('StockData/TATA.csv')

    #Create a new dataframe with only the price type chosen
    data = df.filter([pricetype])
    dataset = data.values  #convert dataset into a numpy array
    training_data_len = math.ceil(len(dataset) * 0.80) #ik wil 80% van de dataset gebruiken om het LSTM model te trainen (naar boven afronden met math.ceil)

    #Scale the data (normalizing imput data) (helps the model)
    scaler = MinMaxScaler(feature_range=(0,1))  #scaled_data allemaal waardes tussen 0 en 1
    scaled_data = scaler.fit_transform(dataset)  #computes min and max values for scaling and transforms data based on these values

    #Create the training data set
    #Create the scaled training data set
    train_data = scaled_data[0:training_data_len , :]
    #split data into x_train and y_train datasets
    x_train, y_train = [], []  #x_train independent training feature, y dependent
    for i in range(60, len(train_data)):
        x_train.append(train_data[i-60:i,0])  #bevat de waardes van 60 vorige periodes
        y_train.append(train_data[i, 0])    #bevat 61e waarde waarvan we willen dat model het voorspelt

    #Convert x_train and y_train to numpy arrays
    x_train, y_train = np.array(x_train), np.array(y_train)

    #reshape data (LSTM expects data to be 3D in form of no. of samples, no. of timestamps and no. of features) (x_train is now 2D)
    x_train = np.reshape(x_train, (x_train.shape[0],x_train.shape[1], 1)) #reshape tot 3D, x_train.shape[0] = no of rows in 2D x_train, [1] is no of colums van 2D x_train

    #Build the LSTM model
    model=Sequential()
    model.add(LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
    model.add(LSTM(50, return_sequences= False))
    model.add(Dense(25))
    model.add(Dense(1))
    model.compile(optimizer='adam', loss='mean_squared_error') #model has loss function and optimizer

    #training the model with the fit function
    model.fit(x_train, y_train, batch_size=1, epochs=1) #epoch is no of iterations of the dataset forth and backwarth in neural network

    #Create the testing data set
    #Create new array containing scale valuels from index
    test_data = scaled_data[training_data_len - 60: , :]
    #create datasets x_test and y_test
    x_test = []
    y_test = dataset[training_data_len:, :]
    for i in range(60, len(test_data)):
        x_test.append(test_data[i-60:i,0])

    #convert data into numpy array
    x_test = np.array(x_test)

    #Reshape data (zelfde uitleg als regel 65)
    x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))

    #Get models predicted price values
    #predictions afhankelijk van x_test moeten zelfde values krijgen als y_test
    predictions = model.predict(x_test) #want predictions to contain same values as y_test
    predictions = scaler.inverse_transform(predictions) #unscale the values

    #Get the RMSE (om het model te testen)
    rmse = np.sqrt(np.mean(predictions - y_test)**2)
    rmse

    #Plot the data
    train = data[:training_data_len]
    valid = data[training_data_len:]
    valid['Predictions'] = predictions

    print('The RMSE for the training model =', rmse)

    new_df = df.filter([pricetype])
    #get the last 60 days
    last_60_days = new_df[-60:].values
    last_60_days_scaled = scaler.transform(last_60_days)
    #create empty list
    X_test = []
    #append past 60 days to list
    X_test.append(last_60_days)
    #Convert X_test to numpy array
    X_test = np.array(X_test)
    #reshape to 3D
    X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1],1))
    #Get predicted scaled price
    pred_price = model.predict(X_test)
    #undo scaling
    pred_price = scaler.inverse_transform(pred_price)
    print('Predicted price for the next day is :',pred_price)

    return pred_price

allprices = []
for i in range(10):
    pred_price = StockPredictor()
    allprices.append(pred_price)

average_pred_price = sum(allprices) / len(allprices)

A: You are using a min max scaler between 0 and 1, where the defined highs are historical. Your LSTM model will predict a new high and when you inverse_transform the prediction, it will likely be higher than the min and max that has been fitted to the scaler.
Therefore the scaler is the likely culprit that is resulting in your predictions being a factor of 2x higher. Using a standard scaler might help, or without scaling at all.
Side Note
LSTMs to predict stock prices simply on price data will not work.
What is likely to happen is that your LSTM model will predict prices with a T+1 lag - predicting the price with a 1 day lag.
Price data inherently contains noise, brought about by retail traders and especially now with social sentiment trading. An LSTM is likely to overfit on historical noise and therefore is unrepresentative of future "noises"
For more information on the problem of noise, check out this link - https://www.investopedia.com/articles/trading/06/marketnoise.asp


text:
Q: CriteriaBuilder select ManyToMany I have such code
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
public Registration getRegistration() {
    return registration;
}

@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "COMPANY_USER", joinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "COMPANY_ID", referencedColumnName = "ID"))

public List<CompanyInfo> getCompanyInfoList() {
    return companyInfoList;
}

For exmaple in Registration (@OneToOne)  I search so
private Predicate[] buildPredicates(UserFilter example, CriteriaBuilder qb, Root root) {
    ArrayList<Predicate> predicates = new ArrayList<>();
    if (example != null) {
    predicates.add(qb.like(qb.upper(root.get(UserInfo_.registration).get(Registration_.messageCode)), "%TEST%"));
    }
    return predicates.toArray(new Predicate[predicates.size()]);
}

And how to correctly search in the List CompanyInfo (@ManyToMany)
predicates.add(qb.like(qb.upper(root.get(UserInfo_.companyInfoList).... ??

For example I want get such sql
SELECT u.id, u.login_name, c.name
  FROM user_info  u
       INNER JOIN company_user cu ON cu.user_id = u.id
       INNER JOIN company_info c ON cu.company_id = c.id
 WHERE UPPER (c.name) LIKE 'ОДО%'

company_user is Link table.
With CriteriaBuilder
    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaQuery<Long> query = qb.createQuery(Long.class);
    Root<UserInfo> root = query.from(UserInfo.class);
    query.select(qb.count(root.get(UserInfo_.id)));

    Subquery<String> subquery = query.subquery(String.class);
    Root<CompanyInfo> subRoot = subquery.from(CompanyInfo.class);
    subquery.select(subRoot.get(CompanyInfo_.id));

    List<Predicate> restrictions = buildPredicates(example, qb, root);
    List<Predicate> restrictionsSub = buildPredicatesSub(example, qb, subRoot);
    Predicate[] predicates = joinList(restrictions, restrictionsSub);
    query.where(predicates);

    return em.createQuery(query.distinct(true)).getSingleResult();

A: Try this, Entity_A and Entity_B are the manyToMany associated entities:
Join<Entity_A, Entity_B> join = root.join("associationList", JoinType.INNER);
predicates.add(cb.like(join.get("name").as(String.class), "%test%"));


text:
Q: multiple iterators for map() function in python? I know there's a way to have the python map function execute for multiple iterators in one command, but I keep getting syntax or valueErrors, or if it does compile it just overwrites previous iterations or gives the wrong answer. What am I doing wrong?
num = ["1","2","3"]
num2 =["4","5","6"]
num3 = ["7","8","9"]

j = list(map(lambda x, y, z: int(x) and int(y) and int(z), num, num2, num3))
print(j)   #[7, 8, 9]
print(reduce(lambda x, y: x+y, j))   #24

The goal is to have all numbers across multiple lists mapped from string to integer into one big list, then summed using reduce()
j should come out to [1,2,3,4,5,6,7,8,9] all ints
the reduce should sum it to 45
update: this way doesnt work either
num = ["1","2","3"]
num2 =["4","5","6"]
num3 = ["7","8","9"]

j = list(map(lambda x, y, z: int(x+y+z), num, num2, num3))
print(j)  #[147, 258, 369]
print(reduce(lambda x, y: x+y, j)) #774

A: Map with multiple iterators:
Given your desired intermediate output I'd say that map isn't the right tool to get a j containing the integers 1-9.
That's because map with multiple iterators goes through the iterators simultaneously:

It doesn't repeat, that's just because it's a gif file.
The problem(s) in your approaches:
In the first iteration it will return "1", "4", "7" (the first elements of each iterable) the next iteration will return "2", "5", "8" and the last iteration "3", "6", "9".
On each of these returns it will apply the function, in your first example in the first iteration that's
int("1") and int("4") and int("7")

which evaluates to 7 because that's the last truthy value of the chained ands:
>>> int("1") and int("4") and int("7")
7

That also explains why the result is 24 because the results of the other iterations are 8 and 9:
>>> int("2") and int("5") and int("8")
8
>>> int("3") and int("6") and int("9")
9

>>> 7 + 8 + 9
24

In your second example you added the strings (which concatenates the strings) and then converted it to an integer:
>>> "1" + "4" + "7"
"147"
>>> int("147")
147

The solution:
So, you need the addition from your second approach but apply the int to each variable like you did in the first example:
j = list(map(lambda x, y, z: int(x)+int(y)+int(z), num, num2, num3))

A better solution:
But for that problem I would probably use a different approach, especially if you want the "desired" j.
To get that you need to chain the iterables:
import itertools
chained = itertools.chain(num, num2, num3)

Then convert all of them to integers:
chained_integers = map(int, chained)

This chained_integers is the iterator-equivalent to the [1, 2, 3, 4, 5, 6, 7, 8, 9] list you wanted as j. You could also use chained_integers = list(map(int, chained)) and print the chained_integers before proceeding if you want to double-check that.
And finally to reduce it I would actually use the built-in sum function:
reduced = sum(chained_integers)  # or "reduce(lambda x, y: x+y, chained_integers)"

Or the one-line-version:
sum(map(int, itertools.chain(num, num2, num3)))

An alternative solution using a comprehension instead of map:
Even simpler would be a comprehension (in this case I used a generator expression) instead of the map:
reduced = sum(int(v) for v in itertools.chain(num, num2, num3))

An alternative solution using a generator function:
That's pretty short and easy to understand but I would like to present another example of how to do it using your own generator function:
def chain_as_ints(*iterables):
    for iterable in iterables:
        for item in iterable:
            yield int(item)

And you could use it like this:
sum(chain_as_ints(num, num2, num3))

In this case a generator function is not really necessary (and probably not advisable given the alternatives) I just wanted to mention it for completeness.

A: Since you want to iterate over the elements of each list as one long list, it is easiest to just concatenate them:
nums = map(int, num + num2 + num3)