text:
Q: Why must you define the scanner inside the if statement? Why does the code below work:
import java.util.Scanner;

public class WholeNumber
{

    public static void main(String[] args)
    {
        System.out.println("Please enter a number:");
        Scanner scanner = new Scanner(System.in);
        if (scanner.hasNextInt())
        {
            float number = scanner.nextFloat(); //The if statement is testing THIS scanner value.
            System.out.println("The number you entered is an integer.");
        }
        else
        {
            System.out.println("The number you entered is not an integer.");
        }
    }
}

But this code doesn't:
import java.util.Scanner;

public class WholeNumber
{

    public static void main(String[] args)
    {
        System.out.println("Please enter a number:");
        Scanner scanner = new Scanner(System.in);
        float number = scanner.nextFloat(); //But when I put the scanner out here, it doesn't work??
        if (scanner.hasNextInt())
        {
            System.out.println("The number you entered is an integer.");
        }
        else
        {
            System.out.println("The number you entered is not an integer.");
        }
    }
}

It would seem like you would have to define the scanner first so the if statement could know what it was checking. Otherwise, how does it know what it is trying to check?
When I put the scanner.nextFloat line outside the if statement, though, it will compile but get stuck during run-time when the user is typing in input. And if I put the line outside and change the if statement to "number.hasNextInt," I get a compile-time error.

A: You are taking the value out of the Scanner before you are testing for the next int:
 float year = scanner.nextFloat();

The above line removes the int from the Scanner so hasNextInt() will return false.
Side note: Not sure why you are using hasNextInt() with nextFloat() you should be using Float or Int...

A: If the "has"-call is after the "next"-call, the scanner will wait for 2 values.
This is because next___() waits for a value, consumes it, AND then returns it, while has___() waits for a value, pushes it back, AND then returns the presence of it.


text:
Q: How to set "timeouts for RDS" via PowerShell I am trying to configure idle timeouts for RDS via PowerShell.  I have manually set them via gpedit, (Computer Configuration – Administrative Templates – Windows Components – Remote
Desktop Services – Remote Desktop Session Host – Session Time Limits), then went to the registry to find those values, they're not anywhere that I have searched.
I need to set:

*

*"Set Time Limit for disconnected sessions", "Enabled", "30 minutes"

*"Set Time limit for active but idle Remote Desktop Services Sessions", "Enabled", "1 Hour"

*"Set Time limit for active Remote Desktop Services Sessions", "Enabled", "8 hours"

*"Set End sessions when time limits are reached", "Enabled"

A: The policies you have set put their settings in this registry location:
SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services
A full reference of the keys can be found here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: write on an image in InteractiveViewer I am looking for the easy way to edit an image,
or write on an image so as not to have to manage the zooms and scrolls I use,
import 'package:flutter/material.dart';

void main() =>runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
       home: Center(child:MyInteractiveViewer("Assets/img/carte.png"),),
   );
  }
}

class MyInteractiveViewer extends InteractiveViewer {
  MyInteractiveViewer(String carte):super(
      constrained :false,
      child: Image.asset(carte),
      minScale:0.10,
      maxScale:100.0){
    init();}

  void init(){
    print ("test"+child.toString());
  }

}

and is it possible to retrieve an obj or there is a paint to do something like
void paint(Canvas canvas, Size size) {
    canvas.drawCircle(Offset(300, 240), 300.2,new Paint());
  }

thank you for any feedback

A: I answer my question
I did not find an answer but I propose a solution
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
import 'package:flutter/services.dart' show rootBundle;
import 'dart:async';
import 'dart:typed_data';

void main() =>runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String carte = "Assets/img/carte.png";
  ui.Image image;
  bool isImageloaded = false;
  TransformationController controller;
  void initState() {
    super.initState(); //init state
    init();// inii image load
  }

  Future <Null> init() async {
     Matrix4 matrix4 = Matrix4(
       1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1

    );
      controller = TransformationController(matrix4);

    final ByteData data = await rootBundle.load(carte);
    image = await loadImage(new Uint8List.view(data.buffer));
  }

  Future<ui.Image> loadImage(List<int> img) async {
    final Completer<ui.Image> completer = new Completer();
    ui.decodeImageFromList(img, (ui.Image img) {
      setState(() {
        isImageloaded = true;
      });
      return completer.complete(img);
    });
    return completer.future;
  }

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: InteractiveViewer(
            transformationController: controller,//pas très utile mais bon
            minScale:0.1,
            maxScale:5,
            constrained :false,
            child: CustomPaint(
                size: Size(image.width.toDouble(), image.height.toDouble()),
                foregroundPainter: TestPainter(image),
              ),
          ),
        ),
      ),
    );
  }
}

class TestPainter extends CustomPainter {

  final ui.Image image;
  TestPainter(this.image);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.blueGrey;
    canvas.drawImage(image, new Offset(0.0, 0.0), paint);
    canvas.drawCircle(Offset(400, 800), 50, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}


text:
Q: Select a range using MySQL ORDER BY So I have this game database, where I have several users with fields, id, name, points
I need a rank table for a specific user where its position can be seen in relation to the amount of points, there is room for 8 positions in the table, so I was looking for a way to do the following:
if I do SELECT * FROM users WHERE id = {user_id} ORDER By points Select the 4 results before and the 3 results after this id. is there a query to do this? the result should look like:
---------------------
|id   |name  |points|
---------------------
| 52  |name1 | 10   |
---------------------
| 23  |name1 | 09   |
---------------------
| 93  |name1 | 08   |
---------------------
| 12  |name1 | 07   |
---------------------
| 43  |queried_name1 | 06   |
---------------------
| 67  |name1 | 05   |
---------------------
| 32  |name1 | 04   |
---------------------
| 91  |name1 | 03   |
---------------------

I was trying to make this by software but it is pretty slow to iterate trough all the results. Thanks for your help!

A: Like that, I would say, for the above results:
SELECT * FROM users WHERE points > (SELECT points FROM users WHERE id = {user_id}) ORDER By points ASC LIMIT 3;

For the below results:
SELECT * FROM users WHERE points < (SELECT points FROM users WHERE id = {user_id}) ORDER By points DESC LIMIT 4;

So, with a big union, it would give:
SELECT * FROM (SELECT * FROM users WHERE points > (SELECT points FROM users WHERE id = {user_id}) ORDER By points ASC LIMIT 3 ) a
UNION
SELECT * FROM users WHERE id = {user_id}
UNION
SELECT * FROM (    SELECT * FROM users WHERE points < (SELECT points FROM users WHERE id = {user_id}) ORDER By points DESC LIMIT 4 ) b

A: You can use this query -
SELECT id, name, points FROM (
  SELECT u.*, @r:=@r+1 rank, @pos:=IF(@pos = 0 AND name = 'queried_name1', @r, @pos)
    FROM users u,
    (SELECT @r:=0, @pos:=0) t
  ORDER BY points DESC
  ) t
WHERE rank BETWEEN @pos - 4 AND @pos + 3

It ranks table by points, finds a record with name = 'queried_name1', and selects some rows before and after the found record.


text:
Q: OSMnx Difference between geometries_from_place tag highway and graph_from_place? I use OSMnx for my project and I need to retrieve information about roads.
I know I can use osmnx.graph_from_place(place, network_type="all") to get the graph of highways of a certain type from Open Street Map. However it does not provides lots of features, only 15.
I know I can use osmnx.geometries_from_place(place, tags={"highway"=True}) , it gives more features however it provides different result than the previous function (less rows).
Using 'Etterbeek, Brussels, Belgium' as place, with graph_from_place, I get 12636 rows in my dataframe but with geometries_from_place, I get 3636
So can anyone explain me what is the difference between the two functions and why they provide different results?
Code :
import osmnx as ox
place = 'Etterbeek, Brussels, Belgium'

etterbeek_all_highway_info = ox.geometries_from_place(place, tags={"highway":True})
len(etterbeek_all_highway_info) # 3636

street_graph = ox.graph_from_place(place, network_type='all', simplify=False)
nodes , streets = ox.graph_to_gdfs(street_graph)
len(streets["highway"]) #12636

Documentation :
https://osmnx.readthedocs.io/en/stable/osmnx.html#osmnx.graph.graph_from_place
https://osmnx.readthedocs.io/en/stable/osmnx.html#osmnx.geometries.geometries_from_place


text:
Q: What is Function Calling Sequence OF Virtual Function In C#? I have this code :
namespace ConsoleApplicationDemo
{
    class base
    {
        public virtual void   Sum()
        {
            Console.WriteLine("Sum in base ");
        }
    }
    class Program:base
    {

        public override void Sum()
        {

            Console.WriteLine("SUM  IN Program ");
        }

        static void Main(string[] args)
        {

            base A2 = new Program();
            A2.Sum();
            Program P2 = new Program();
            P2.Sum();
            Console.ReadLine();
        }
    }
}

getting OutPUT: SUM  IN Program SUM  IN Program

My question  is why base Class Sum FunCtion is not getting called by this code?
base A2 = new Program();
A2.Sum();

A: It is because you have overridden the base classes implementation. Virtual/Override says "Hey every time this method is called use the overridden method."
If you had marked the child class function with the new keyword, it would do what you describe. (Personally, I don't like using the new keyword, as most people don't understand the nuances of its implementation, but it performs the behavior you described.  There are better alternatives).
Article describing new keyword.

A: A method that is marked a override overwrites the complete implementation of its base-method. So if you create an instance of your derived class Program, this overriden method is called. However you may also call the base-implementation from within your derived method by using base.Sum()
public override void Sum()
{
    base.Sum();  // now you see why base is a really bad name for your class
    Console.WriteLine("SUM  IN Program ");
}

A: Polymorphism changes the implementation of your subclass. Even if you upcast a subclass reference to its base type, you won't be able to access base class virtual method implementation, but the deepest implementation of the object inheritance.
In the other hand, a derived class can effectively access base class implementation using the base keyword:
public override void Sum()
{
     // This calls base implementation.
     base.Sum();

     Console.WriteLine("SUM  IN Program ");
}

Anyway, base will call the immediate base class' implementation. You won't be able to call an implementation above one level in the inheritance tree.


text:
Q: ASP.NET returns HTTP 500 instead of 404 For some reason, my ASP.NET web application returns error 500 (apparently originating from handler "ExtensionlessUrlHandler-Integrated-4.0") when a non-existing route is accessed.
This issue has started to occur after I had changed path="*." to path="*" in the <add name="ExtensionlessUrlHandler-Integrated-4.0" ... line of my Web.config file in order to solve another problem (failure to process routes with a dot after the last slash).
I cannot change path back to "*.", even though exactly that is suggested as a solution in another question, because that will bring back the other problem - routes with a dot in the part after the last slash are not found anymore.
Like in that linked other question, I am using OData. However, I am not aware that it should play any role in route resolution in my case at all, because I think we treat it just as an ordinary library that is referenced in our C# projects and invoked by a few of our web API endpoints.
<modules runAllManagedModulesForAllRequests="true"/> is already set in my Web.config file.
What else can I do so 404 is returned for unknown routes and "extension-ful" routes (i.e. routes whose last part after the last slash contains a dot) are accepted?
EDIT: I have managed to increase my FREB log size and now see that the offending entry is number 1346, saying

ModuleName="ManagedPipelineHandler", Notification="EXECUTE_REQUEST_HANDLER", HttpStatus="500", HttpReason="Internal Server Error", HttpSubStatus="0", ErrorCode="Rekursion zu tief, Stapelüberlauf.
   (0x800703e9)", ConfigExceptionInfo=""

In English, the error message means: "Recursion too deep, stack overflow."
Therefore, it appears to be the same issue as in another question, however, the answers from there do not help in my case:

*

*Philip suggests to remove various handlers, which doesn't change anything for me.

*Joe Davis suggests the solution with the "*." path, which works, but causes the other problem, as described above.

Both answers refer to the <handlers> section in my Web.config file, which currently looks like this:
<handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
    <remove name="OPTIONSVerbHandler"/>
    <remove name="TRACEVerbHandler"/>
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
</handlers>

A: To make sure your web api works with '.' (dot) add a specific API handler BEFORE the global handler with path '*.'
See below example:
  <add name="ApiURIs-ISAPI-Integrated-4.0-ForApi" path="/api/*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />


text:
Q: How to connect to Oracle DB via "bequeath" OCI in Java? I tried the following url string variations:
String url = "jdbc:oracle:oci:"+msDbUser+"/"+msPassword+"/@";

String url = "jdbc:oracle:oci:@//<TNS entry>";

String url = "jdbc:oracle:oci:@//<hostname>:<port>:<SID>";

Then I connect using:
conn = DriverManager.getConnection(url);

But all of them result to a vague SQL Exception "java.sql.SQLException: ??" as shown below.  I tried googling this error but I cannot find any information on it.
java.sql.SQLException: ??
    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
    at oracle.jdbc.driver.T2CConnection.checkError(T2CConnection.java:650)
    at oracle.jdbc.driver.T2CConnection.logon(T2CConnection.java:338)
    at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:508)
    at oracle.jdbc.driver.T2CConnection.<init>(T2CConnection.java:133)
    at oracle.jdbc.driver.T2CDriverExtension.getConnection(T2CDriverExtension.java:53)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:510)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at com.pca.test.TestConn.main(TestConn.java:75)

Note that via regular THIN driver it's connecting fine, so I'm sure my DB is okay.  However, my requirement at work is to use a "bequeath" connection and OCI.
jdbc:oracle:thin:@<HOSTNAME>:<PORT>:<SID>

A: OCI connection is
jdbc:oracle:oci:@<host>:<port>/<SID>


text:
Q: css off-center border for an image I've got a fairly simple CSS where I want to display a border slightly off center to the right and bottom, I'm using the pseudo-selector :after to display it.
The problem i'm having is that the border it's displaying is running to the height of the outer div that's dictated by the amount of text displayed, rather than the img itself (which is what I want it to do).
If I put another div inside to wrap around the image it doesn't seem to make a difference, the same if I make the pseudo-selector after the image and convert the image to a block.
Js Fiddle to show all you lovely smart people that might be able to help me!

A:

.project {
  width: 60%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  margin: 0 auto;
  padding: 50px 0;
}

.projectimage {
  position: relative;
  display: inline-block;
}

.projectimage img {
  position: relative;
  z-index: 2;
}

.projectcontentleft {
  padding-right: 50px;
}

.projectimage img {
  width: 100%;
  height: auto;
}

.projectimage:after {
  content: " ";
  position: absolute;
  left: 30px;
  bottom: -30px;
  border: 10px solid rgba(214, 23, 71, 0.07);
  display: block;
  width: 100%;
  height: 100%;
  transition: all 300ms linear 0s;
  z-index: 1;
}

Header

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
        dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Appeals

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
        dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

A:
If I put another div inside to wrap around the image it doesn't seem to make a difference

That's because that div does not actually wrap around the image taking its dimensions – but is as high as your whole outer container, because that has display: grid
You'd need to wrap .projectimage into an additional div, so that that becomes the grid item that takes full height, and the .projectimage element can then gets is height from the image it contains.


text:
Q: How to encrypt a file in java using AES I need to know how to create an AES and using it to encrypt and decrypt a file in java.

A: Try using a CipherOutputStream and passing in a FileOutputStream. See http://www.java2s.com/Tutorial/Java/0490__Security/UsingCipherOutputStream.htm for a quick example, just use Cipher.getInstance("AES/CBC/PKCS5Padding") instead.


text:
Q: Modeling a restaurant menu with django I am creating a website with a collection of menus from restaurants in my town (since none of them seem to be on grubhub or the internet). I am having trouble creating a model for this. As you know every restaurant menu has sections(I.e Appetizers, Chicken, Steak) and entries under each section(I.e under Appetizers: Mozzarella Sticks, Nachos, etc.) I am trying to create a Menu model so that each section of the menu and all of its entries can automatically fill a template:

{{section}}

{{food}}

{{ food_details }}

With the above template, I can use a loop to loop through each section, then another inner loop to loop through each food and food_details belonging to that specific section, but I am not sure how to model this properly:
from django.db import models

class Restaurant(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=80)
    phoneNumber = models.CharField(max_length=10)

    def __str__(self):
        return "%s the place" % self.name

class Menu(models.Model):
    restaurant = models.OneToOneField(
        Restaurant,
        on_delete=models.CASCADE,
        primary_key=True,
    )
    # not sure how to build menu fields

    #if I do the following each menu will only have one of these fields, which will not work:
    section = models.CharField(max_length=50)
    food = models.CharField(max_length=50)
    food_details = models.CharField(max_length=200)

How can I create a model of a menu that has multiple section's and multiple food and food_details entries under each section? I hope this made sense, let me know if there is anything I can add and thanks in advance for any help.

A: You could try something like this:
# models.py
FOOD_TYPES = (
          ('appetizer', 'appetizer'),
          ('entree', 'entree'),
          ('dessert', 'dessert'),
)

class FoodItem(models.Model):
    name = models.CharField(max_length=30)
    description = models.CharField(max_length=100)
    type = models.CharField(max_length=100, choices=FOOD_TYPES)

class Menu(models.Model):
    restaurant = models.OneToOneField(
        Restaurant,
        on_delete=models.CASCADE,
        primary_key=True,
    )

    food_items = models.ManyToManyField(FoodItem)

In a view:
# views.py
class Restaurant(TemplateView):
    model = Restaurant
    template_name = 'name'

    ...

    def get_context_data
        context = super(Menu, self).get_context_data(**kwargs)
        restaurant = Restaurant.objects.get(name='McDonalds')
        context['restaurant'] = Restaurant.objects.get(name='McDonalds')
        context['menu'] = Menu.objects.get(restaurant=restaurant)
        return context

In the template:
# template.html

{{ restaurant.name }}

Menu

    {% for item in menu.food_items %}
     {% if item.type = 'appetizer' %}

       {{ item.name }}
       {{ item.description }}
       {{ item.type }}

     {% else %}

No appetizers

     {% endif %}

     {% if item.type = 'entree' %}

       {{ item.name }}
       {{ item.description }}
       {{ item.type }}

     {% else %}

No entrees

     {% endif %}

     {% if item.type = 'dessert' %}

       {{ item.name }}
       {{ item.description }}
       {{ item.type }}

     {% else %}

No dessert

     {% endif %}

   {% endfor %}


text:
Q: I want to redirect my all traffic to http://www.mywebsite.com I want to redirect my all traffic to http://www.mywebsite.com
When someone visit https://www.mywebsite.com it will go to http://www.mywebsite.com
When someone visit https://mywebsite.com it will go to http://www.mywebsite.com
When someone visit http://www.mywebsite.com it will go to http://www.mywebsite.com
When someone visit http://mywebsite.com it will go to http://www.mywebsite.com
What i mean is i want to redirect all traffic to http://www.mywebsite.com
Here is the code which i set in .htaccess but its not working on https
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

A: RewriteEngine On
RewriteCond %{HTTP_HOST} ^mywebsite.com [NC]
RewriteRule ^(.*)$ http://www.mywebsite.com/$1 [L,R=301]

when someone access  http://mywebsite.com the visitor will be redirected to  http://www.mywebsite.com.


text:
Q: Error: Value of type 'CGRect' has no member 'center' Trying to create layout for a circular collection view. Everything seems well apart from when I try to center the position.
override func prepare() {
        super.prepare()
        guard let collectionView = collectionView else { return }
        itemLayoutAttributes.removeAll()
        layoutCircleFrame = CGRect(origin: .zero, size: collectionViewContentSize)
            .inset(by: layoutInsets)
            .insetBy(dx: itemSize.width / 2.0, dy: itemSize.height / 2.0)
            .offsetBy(dx: collectionView.contentOffset.x, dy: collectionView.contentOffset.y)
            .insetBy(dx: -collectionView.contentOffset.x, dy: -collectionView.contentOffset.y)

        for section in 0..<collectionView.numberOfSections {
            switch section {
            case 0:
                let itemCount = collectionView.numberOfItems(inSection: section)
                itemLayoutAttributes = (0..<itemCount).map({ (index) -> UICollectionViewLayoutAttributes in
                    let angleStep: CGFloat = 2.0 * CGFloat.pi / CGFloat(itemCount)
                    var position = layoutCircleFrame.center
                    position.x += layoutCircleFrame.size.innerRadius * cos(angleStep * CGFloat(index))
                    position.y += layoutCircleFrame.size.innerRadius * sin(angleStep * CGFloat(index))
                    let indexPath = IndexPath(item: index, section: section)
                    let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
                    attributes.frame = CGRect(center: position, size: itemSize)
                    return attributes
                })
            default:
                fatalError("Unhandled section \(section).")
            }
        }

Expected to run but instead receive the error: Value of type 'CGRect' has no member 'center'. This error is on the line;
var position = layoutCircleFrame.center

A: What I do is add this extension to my code (at the top level of a file):
extension CGRect {
    var center : CGPoint {
        return CGPoint(x:self.midX, y:self.midY)
    }
}

A: There is no center property in CGRect, hence the error. It's a property of UIView.
You could do:
var position = CGPoint(x: layoutCircleFrame.midX, y: layoutCircleFrame.midY)

Or, as seen here, you can add a center property to CGRect via an extension.


text:
Q: Is there still documentation or support for https://api.projectoxford.ai/vision/v1? I am trying to find more information, but I cannot get access to the API portal page https://www.projectoxford.ai/vision . Do you know if Microsoft is planning to remove the API?

A: ProjectOxford was deprecated in favor of Cognitive Services
The Vision API have the following main paths
Computer Vision

Analyze content in images and video.

Custom Vision

Customize image recognition to fit your business needs.

Face

Detect and identify people and emotions in images.

Form Recognizer

Extract text, key-value pairs, and tables from documents.

Video Indexer

Analyze the visual and audio channels of a video, and index its content.

DEV API reference of all services ➡ https://eastus.dev.cognitive.microsoft.com/docs/services/


text:
Q: AND occasionally produces wrong result on shell and node native driver I've built a dynamic query generator to create my desired queries based on many factors, however, in rare cases it acted weird. After a day on reading logs I found a situation that can be simplified in this:
db.users.find({att: 'a', att: 'b'})

What I expect is that mongodb by default uses AND, so above query's result should be an empty array. However, it's not!
But when I use AND explicitly, the result is an empty array
db.users.find({$and: [{att: 'a'}, {att: 'b'}]})

A: In javascript object's keys should be unique, otherwise the value will be replaced by the latest value
(also mongodb shell is based on js, so it follows some rules of js)

const t = {att: 'a', att: 'b'};
console.log(t);

So in your case your query is acting like this:
db.users.find({att: 'b'})

You've to handle this situation on your code if you want the result be empty in the  mentioned condition


text:
Q: Using NetworkManager (nmcli) to create an hotspot broadcasting an hidden SSID as described in the subject I was wondering if I can hide the SSID of my freshly created hotspot by means of two simple nmcli commands :
Code:
nmcli device wifi hotspot ifname wlan0 con-name Hotspot ssid MySsid band bg channel 11 password 'mypassword'
nmcli con modify Hotspot ipv4.method shared ipv4.addresses 192.168.240.1/24
nmcli con up Hotspot

any pointers about that ? I still can't find the right option to add while creating the network...
Kind Regards

A: On recent versions of NetworkManager set wifi.hidden property.
Note that hidden networks don't increase security, but rather require the clients to actively scan for the network (by setting wifi.hidden on their side). That makes the client machine trackable by having rather unique scan requests, not only when you are in rangez but all the time (because NM Scans for the network wherever you are). See man nm-settings about that.

A: I see, the fact is that those commands seems to set this property by default...take a look at the configuration file :
[connection]
id=Hotspot
uuid=9f655aa4-6c63-4549-8da8-3ea1ab6112ec
type=wifi
autoconnect=false
permissions=
timestamp=1567000798

[wifi]
band=bg
channel=11
hidden=true
mac-address=00:00:00:00:00:00
mac-address-blacklist=
mode=ap
seen-bssids=00:00:00:00:00:00;
ssid=MYAP

[wifi-security]
group=ccmp;
key-mgmt=wpa-psk
pairwise=ccmp;
proto=rsn;
psk=mypass

[ipv4]
address1=192.168.240.1/24
dns-search=
method=shared

[ipv6]
addr-gen-mode=stable-privacy
dns-search=
method=ignore

the only modification I can think of after your suggestion is this one :
# creating the actual hotspot with SHARED address
nmcli device wifi hotspot ifname wlan0 con-name Hotspot ssid arty-$SSID_SUFFIX band bg channel 11 password 'arancino'
nmcli con modify Hotspot ipv4.method shared ipv4.addresses 192.168.240.1/24 802-11-wireless.hidden 'TRUE'
nmcli con up Hotspot

anyway, although supported by nm (my operating version is release v1.6), it doesn't seem to have any effect on the final result....any pointers ?


text:
Q: TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array I want to write a function that randomly picks elements from a training set, based on the bin probabilities provided. I divide the set indices to 11 bins, then create custom probabilities for them.
bin_probs = [0.5, 0.3, 0.15, 0.04, 0.0025, 0.0025, 0.001, 0.001, 0.001, 0.001, 0.001]

X_train = list(range(2000000))

train_probs = bin_probs * int(len(X_train) / len(bin_probs)) # extend probabilities across bin elements
train_probs.extend([0.001]*(len(X_train) - len(train_probs))) # a small fix to match number of elements
train_probs = train_probs/np.sum(train_probs) # normalize
indices = np.random.choice(range(len(X_train)), replace=False, size=50000, p=train_probs)
out_images = X_train[indices.astype(int)] # this is where I get the error

I get the following error:
TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

I find this weird, since I already checked the array of indices that I have created. It is 1-D, it is integer, and it is scalar.
What am I missing?
Note : I tried to pass indices with astype(int). Same error.

A: Perhaps the error message is somewhat misleading, but the gist is that X_train is a list, not a numpy array. You cannot use array indexing on it. Make it an array first:
out_images = np.array(X_train)[indices.astype(int)]

A: I get this error whenever I use np.concatenate the wrong way:
>>> a = np.eye(2)
>>> np.concatenate(a, a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<__array_function__ internals>", line 6, in concatenate
TypeError: only integer scalar arrays can be converted to a scalar index

The correct way is to input the two arrays as a tuple:
>>> np.concatenate((a, a))
array([[1., 0.],
       [0., 1.],
       [1., 0.],
       [0., 1.]])

A: A simple case that generates this error message:
In [8]: [1,2,3,4,5][np.array([1])]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-55def8e1923d> in <module>()
----> 1 [1,2,3,4,5][np.array([1])]

TypeError: only integer scalar arrays can be converted to a scalar index

Some variations that work:
In [9]: [1,2,3,4,5][np.array(1)]     # this is a 0d array index
Out[9]: 2
In [10]: [1,2,3,4,5][np.array([1]).item()]
Out[10]: 2
In [11]: np.array([1,2,3,4,5])[np.array([1])]
Out[11]: array([2])

Basic python list indexing is more restrictive than numpy's:
In [12]: [1,2,3,4,5][[1]]
....
TypeError: list indices must be integers or slices, not list

edit
Looking again at
indices = np.random.choice(range(len(X_train)), replace=False, size=50000, p=train_probs)

indices is a 1d array of integers - but it certainly isn't scalar.  It's an array of 50000 integers.  List's cannot be indexed with multiple indices at once, regardless of whether they are in a list or array.

A: Another case that could cause this error is
>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index

Using the actual shape will fix it.
>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>

A: Check that you're passing the right arguments. Similar to Simon, I was passing two arrays to np.all when it only accepted one array, meaning that the second array was interpreted to be an axis.

A: Try to use x_train.shape[] instead.


text:
Q: Vaadin Flow: How to tell if a Component is attached How does one reliably find out if a given Component is actually present in the DOM?
Until now I used Component.getUI().isPresent() which is supposed to able to determine if the Component is attached to a UI.
It also might be that I ran into an edge case as the Components in question are encapsulated in a ComponentRenderer which is managed by a Grid.
I need to access these Componets via JavaScript like this:
void setValue(Component comp, Value value){
  Runnable callJs = comp.getUI().ifPresent(ui -> ui.getPage().executeJs("someCall($0)", value));

  if(comp.isAttached()){
    // execute it right away
    callJs.run();
  } else {
    // execute onAttach
    comp.addAttachListener(evt -> callJs.run());
  }
}

A: After some digging I stumbled across the StateNode API:
comp.getElement().getNode().isAttached()


text:
Q: SpecialCells(xlCellTypeConstants) results unexpected result on just one cell as the base range To summarize: if the base range of the SpecialCells is just one cell, then the result of range.SpecialCells(xlCellTypeConstants, xlNumbers) yields not just that cell or nothing.
I supposed, SpecialCells should yield a range inside that object it is applied... or am I wrong?
I've "developed" a little new excel book, just to show what I don't understand, as follows:

*

*Created a new excel book

*Filled the A1:B3, as follows:
   A   B   ...
 1 1  12
 2 2  22
 3 3  32
 .

All the other cells of the sheet are untouched.

*Inside a new module I've added the following code:
Private Sub test()

    Dim oSet As Range, oSpec As Range, oUsed As Range

    Worksheets("Sheet1").Activate

    Set oSet = ActiveSheet.Range("A1:A1")
    Set oSpec = oSet.SpecialCells(xlCellTypeConstants, xlNumbers)
    Set oUsed = ActiveSheet.UsedRange

    Set oSet = Nothing
    Set oSpec = Nothing
    Set oUsed = Nothing

End Sub

*Running the subroutine, and stopping it at the first range reset, it yields:
oSet.Address = "$A$1"
oSpec.Address = "$A$1:$B$3" ' this seems to be wrong; should it be just "$A$1" ?
oUsed.Address = "$A$1:$B$3"

*Having been changed the value of A1 to A, rerun the sub, and stop at the same place, it gives (consistently with the previous, which shows it works consequtively):
oSet.Address = "$A$1"
oSpec.Address = "$B$1","$A$2:$B$3" ' this seems to be wrong; should oSpec be nothing ?
oUsed.Address = "$A$1:$B$3"

*However, resetting the value of  A1 to the original 1, but changing the range of the first Set operation in the Subroutine from just the cell "A1" to a true range of cells "A1:A2", then rerun the sub, and stop at the place, it gives very different (and more expected) result:
oSet.Address = "$A$1:$A$2"
oSpec.Address = "$A$1:$A$2" ' this is good
oUsed.Address = "$A$1:$B$3"

I would appreciate, if somebody would explain the results. Thanks ahead.

A: This is happening because in case of one cell, it considers UsedRange instead.
References:
1) Super secret SpecialCells
2) Using SpecialCells in Excel VBA
As a helpful note, I will give you my wrapper function for SpecialCells and its helper method (in C#, not in VBA):
    /// <summary>
    /// <para>Wrapper for SpecialCells function.</para>
    /// </summary>
    /// <param name="inputRange"></param>
    /// <param name="cellType"></param>
    /// <returns></returns>
    /// <remarks>Throws null when there are no cells in <paramref name="inputRange"/> corresponding to <paramref name="cellType"/>, unlike SpecialCells which throws exception</remarks>
    public static Range GetRangeSpecialCells(this Microsoft.Office.Interop.Excel.Range inputRange, XlCellType cellType)
    {
        try
        {
            if (inputRange.Cells.Count == 1)
            {
                if (cellType == XlCellType.xlCellTypeComments)
                {
                    if (inputRange.Comment != null)
                    {
                        return inputRange;
                    }
                    else
                    {
                        return null;
                    }
                }
                else if (cellType == XlCellType.xlCellTypeFormulas)
                {
                    if (inputRange.HasFormula == true)
                    {
                        return inputRange;
                    }
                    else
                    {
                        return null;
                    }
                }
                else if (cellType == XlCellType.xlCellTypeBlanks)
                {
                    if (string.IsNullOrEmpty(inputRange.Value2) == true)
                    {
                        return inputRange;
                    }
                    else
                    {
                        return null;
                    }
                }
                else if (cellType == XlCellType.xlCellTypeLastCell)
                {
                    return inputRange;
                }
                else
                {
                    // since inputRange has a single cell, SpecialCells will apply to entire worksheet
                    // this range has all cells from worksheet (UsedRange) of type provided: cellType
                    Range temp = inputRange.SpecialCells(cellType);

                    // intersect range with single cell (inputRange) with above range
                    Range rangeOverlap = Intersect(inputRange, temp);

                    // if range with single cell is contained in that intersection, then this cell is of type xlCellTypeConstants
                    if (rangeOverlap.Count == inputRange.Count && rangeOverlap.Rows.Count == inputRange.Rows.Count && rangeOverlap.Columns.Count == inputRange.Columns.Count)
                    {
                        return inputRange;
                    }
                    else
                    {
                        return null;
                    }
                }
            }
            else
            {
                return inputRange.SpecialCells(cellType);
            }
        }
        catch (System.Runtime.InteropServices.COMException ex)
        {
            return null;
        }
    }

    /// <summary>
    /// <para>Customized function for intersection of two ranges (<paramref name="rangeA"/> ∩ <paramref name="rangeB"/>)</para>
    /// </summary>
    /// <param name="rangeA"></param>
    /// <param name="rangeB"></param>
    /// <returns>Range corresponding to intersection of the two provided ranges</returns>
    /// <remarks>This function returns null if any of provided ranges is null or malformed, unlike Application.Intersect which throws exception</remarks>
    public static Range Intersect(Range rangeA, Range rangeB)
    {
        Range rngIntersect;
        if (rangeA == null)
        {
            rngIntersect = null;
        }
        else if (rangeB == null)
        {
            rngIntersect = null;
        }
        else if (rangeA.Worksheet != rangeB.Worksheet)
        {
            rngIntersect = null;
        }
        else
        {
            try
            {
                rngIntersect = Globals.ThisAddIn.Application.Intersect(rangeA, rangeB);
            }
            catch (Exception ex)
            {
                rngIntersect = null;
            }
        }

        return rngIntersect;
    }


text:
Q: Georeferencing in R Based on the Four Corners I have a raster image (photograph) that was taken from a helicopter.  Along with that raster image, the system also tells me the positions of the four corners of the image in a different file.  I have imported the image into R but it does not have any georeferencing builtin to it.  I would like to find a way to tell R what each of the corners are so that I can plot it on a map and perform different types of spatial analysis work on the image.
Most posts on this subject specify that all I need to do is tell R about the bounding box and everything will be good to go.  The issue there is that the image can have an arbitrary orientation and is not necessarily parallel to, well a parallel.
I am sure that there is an easy way to do this but I am very new to this type of work.

A: I' think it is not a matter of R ..only. Here a small sketch howto realize the referencing stuff under Linux. You can use GDAL to create a georeferenced axis parallel image from your heli position data, assuming, that your image has the dimension width and height and the bounding box is given by may be GPS-coodinates stored in UTM-33 shown in this table:
 image-x  image-y     world-x   world-y
 --------------------------------------
     0       0         ulx       uly
     0      height     llx       lly
   width     0         urx       ury
   width    height     lrx       lry

where variable names are:
  ulx - upper left corner x
  uly - upper left corner y
  llx - lower left corner x
  lly - lower left corner y
  urx - upper right corner x
  ury - upper right corner y
  lrx - lower right corner x
  lry - lower right corner y

of the in the world turned and shifted bounding box. With GDAL you need two steps to get the image into an axis parallel form.

*

*Create a new image with pass point and coordinate system infos using gdal_translate.

*Recalculate the axis parallel image with gdalwarp.
Here a small bash pseudo code:
   sid=32633 # Datum for UTM-33

   hg=<IMAGE_HEIGHT>
   wd=<IMAGE_WIDTH>
   ulx=<corner-x from gps>
   uly=<corner-y from gps>
   ...

   gsd=10 # Target resolution lets say 10m

   # 1. Step
   gdal_translate -of GTiff\
    -gcp   0     0 $ulx   $uly \
    -gcp   0   $hg $llx   $lly \
    -gcp $wd     0 $urx   $ury \
    -gcp $wd   $hg $lrx   $lry \
    -a_srs epsg:$sid\
     in.tif out-pp.tif

    # 2. Step resampling
    gdalwarp -of GTiff  -r bilinear \
             -tr $gsd out-pp.tif out-ref.tif

With the tool gdalinfo you can read the info tags of the new georeferenced axis parallel image. An example
  $ gdalinfo out-ref.tif
  Driver: GTiff/GeoTIFF
  Files: out-ref.tif
  Size is 5001, 6868
  Coordinate System is:
  PROJCS["WGS 84 / UTM zone 33N",
      ...
     AUTHORITY["EPSG","32633"]]
  Origin = (370000.000000000000000,6068670.000000000000000)
  Pixel Size = (9.998000399920016,-9.998543972044263)
  ...

From here you get the info offsX/Y and pixSizeX/Y, as you see it is not exaclty 10m scaled. You can switch between the both worlds (axis parallel image and real world) using the following functions and go on in R.
  calcWorldPos <- function (pixX ,pixY, offsX, offsY, pixSizeX, pixSizeY)

     X = offsX + pixX * pixSizeX;
     Y = offsY - pixY * pixSizeY;

     return c(x,y);
  }

  calcPixPos <- function( worldX, worldY, offsX, offsY, pixSizeX, pixSizeY) {

     pixX = floor(( worldX - offsX ) / pixSizeX );
     pixY = floor(( offsY - worldY ) / pixSizeY );

     return c(pixX, pixY);
  }

There is also a package rgdal to work with georeferenced images in a more closed form and without leaving R but I miss the convenient tools gdalinfo, gdal_translate and gdalwarp.

A: I think you would be far better off georeferencing your image in QGIS. R can do a lot of things, but its not yet a full replacement GIS. The georeferencing system in QGIS is very simple to use, free, and you can throw in some streaming satellite imagery and/or other free map data like OpenStreetMap in the background to help you position the image as correctly as possible. Your description doesn't sound like a proper airphoto, so expect to have to use a lot of control points, especially towards the edges of the image. Make sure the coordinates you were given are used for the first four control points, and then add as many as you need. Experiment with the transformation algorithms, more become available as you add more points.


text:
Q: .objects.all() returns nothing its my first time to ask hope I can find solution to my problem. Am trying to display the courses in an html page using objects.all() but it returns nothing and the page remain empty, even though records do exist in the database. I tried the same method for other pages and it worked, idk what am doing wrong here :(
in view.py
def viewCourse(request):
    corlist = Course.objects.all()
    #print(muffin)
    #course.count()
    context = {'corlist':corlist}
    return render(request, 'LogInApp/ViewCourse.html', context)

in model.py
class Course(models.Model):
    COURSES = (
        ('Data Structure','Data Structure'),
        ('Computer Network','Computer Network'),
        ('Web Design','Web Design'),
        ('Internet of Things','Internet of Things'),
        ('Artificial Intelligence','Artificial Intelligence'),
        ('Artificial Intelligence-Tut', 'Artificial Intelligence-Tut'),
    )
    course_id = models.AutoField(primary_key=True)
    course_name = models.CharField(max_length=100, null=True, choices= COURSES)
    fk_lecturer_id = models.OneToOneField(Lecturer, on_delete=models.CASCADE)  # foreign key
    date = models.DateField(max_length=20, null=True)
    time = models.TimeField(max_length=20, null=True)

    def __str__(self):
        return '{} {}'.format(self.course_id, self.course_name)

    @property
    def lecturerid(self):
        return self.fk_lecturer_id.lecturerid

in ViewCourse.html

                        Course ID
                        Course Name
                        Course Lecturer
                        Date
                        Time

                    {% for co in corlist %}

                         {{ co.course_id }}
                         {{ co.course_name }}
                         {{ co.fk_lecturer_id }}
                         {{ co.date }}
                         {{ co.time }}

                    {% endfor %}


text:
Q: How to work around cross-frame cross-origin scripting protection in an extension? I use currently the --disable-web-security and the --disable-site-isolation-trials flags to do cross-frame cross-origin scripting in Chrome. As far as I know Chrome developers will remove that feature soon and there is no guarantee I can use anything after that. I am looking for alternatives and I am curious if I can use Chrome or Firefox extensions to completely override a page on the target origin? E.g. the target is https://example.com and I want to override https://example.com/script.runner/ to load my content from a Karma server maybe through the extension somehow. That way I could do cross-frame same-origin scripting, which is allowed by the browser. Is this possible?
Note:
If you want to write about postMessage in your answer, then rather close this tab.


text:
Q: How to get id from one page to another page in Laravel I have a page to get some data from a user, this data will save in first_forms table, but I have other fields in the table for next page and they are null.
this is first_forms table :

In this table, project_name, customer_name, buyer, response, model will be saved in the first step in the first page choose.blade.php
This is store function in the controller:
FirstForm::create([
   'model' => $request['model'],
   'project_name' => $request['project_name'],
   'customer_name' => $request['customer_name'],
   'buyer' => $request['buyer'],
   'response' => $request['response'],
]);
return view('Form2.firstForm');

As you can see other fields in first_forms table will be null. After this user redirect to next page firstForm. Now in this page users have to complete other fields like: airflow, tcp, compress_number, etc. I want when user click on submit in this page, new fields in this page save in the previous row in first_forms table who complete in the previous page, how can I do this?
I think I have to get the id of who completes he previous page and update row with new fields in a new page, but I don't know how I can get the id and update row. Primary key is id.
This is first_forms table when user complete first page :

This is the data of who completed the first page. On the next page, those fields are null, have to be complete in this row.

A:
You can simply check that

$first = FirstForm::create([
  'model' => $request['model'],
  'project_name' => $request['project_name'],
  'customer_name' => $request['customer_name'],
  'buyer' => $request['buyer'],
  'response' => $request['response'],
]);

//Below line will re-retrieve the record along with primary key which is `id`
$first = $first->fresh();

return view('Form2.firstForm',compact('first'));

In view you can access inserted data like $first->id Now place your id in a hidden field of the nextform and update your record according to that id. You can even show the previously inserted record in readonly fields of the nextform
In your nextform view
<input type="hidden" name="update_id" value="{{ $first->id ?? '' }}" />

When you submit the nextform with all other fields, you will get the hidden id as well. So again in your controller method you will do something like
FirstForm::where('id',request('update_id'))->update([
   //here goes your other fields of the nextform
]);


text:
Q: overlapping appointments using the entity framework I am using the asp.net mvc with the Entity Framework.
I have a list of appointments with a startedat field, an endedat field and a roomid field (called SpaceConfigurationId) and would like to find the list of appointments that have been double booked for a given room. It is fine to assume that endedat is always after startedat.
There are 4 cases to would allow an appointment to be matched:

*

*appointment a starts before appointment b starts and ends after appointment b starts and before appointment b ends

*appointment a starts after appointment b starts and before appointment b ends and ends after appointment b ends

*appointment a starts before appointment b starts and ends after appointment b ends

*appointment a starts after appointment b starts and before appointment b ends and ends after appointment b starts and before appointment b ends
I would like the list of appointments that meet any of those requirements. It seems simple but is actually a bit of a mind game. I had a look at intersect but didn't seem to get anywhere.
I have the following variable defined and would like to return a list.
IQueryable<Appointment> appointments = Repository.ReadAppointments();
... insert code here ...
return appointments.ToList();

Here is some SQL which is really slow but may help to outline the problem
select COUNT(*)
from appointment a
    cross join appointment b
where
    not a.Id = b.Id
    AND
    a.SpaceConfigurationId = b.SpaceConfigurationId
    AND
    (
        (a.StartedAt < b.StartedAt and a.EndedAt > b.StartedAt and a.EndedAt < b.EndedAt)
        OR
        (a.StartedAt > b.StartedAt and a.StartedAt < b.EndedAt and a.EndedAt > b.EndedAt)
        OR
        (a.StartedAt < b.StartedAt and a.EndedAt > b.EndedAt)
        OR
        (a.StartedAt > b.StartedAt and a.StartedAt < b.EndedAt and a.EndedAt > b.StartedAt and a.EndedAt < b.EndedAt)
    )

A: *

*Define indexes on SpaceConfigurationId and date columns.

*There are 2 cases when appointments don't match:

*

*When a ends before b.

*When a starts after b.

So..
select COUNT(*)
from appointment a
join appointment b
on
    (not a.Id = b.Id)
    AND
    (a.SpaceConfigurationId = b.SpaceConfigurationId)
    AND
    NOT (a.EndetAt < b.StartedAt)
    AND
    NOT (a.StartedAt > b.EndetAt)

So...
repository.ReadAppointments().Where(a => repository.ReadAppointments().
     Any(b =>
         !(b.ID == a.ID) &&
         (a.SpaceConfigurationId == b.SpaceConfigurationId) &&
         !(a.EndetAt < b.StartedAt) &&
         !(a.StartedAt > b.EndetAt))).
     Select(t => t.ID).ToList();

It doesn't generate the same SQL. It actually uses EXISTS, but with proper indexes should work ok.


text:
Q: Custom enumerate environment inside Fancybox I would like to put a enumerate environment (customized with the enumitem package) inside of a shadowbox created from the Fancybox package. Here's my MWE:
\documentclass[letterpaper,10pt,american]{article}
\usepackage[left=1 in, right=1 in, top=1 in, bottom=1 in]{geometry}
\usepackage{amsmath,amsfonts,amssymb,amsthm,color,hyperref,enumitem}
\usepackage{setspace}
\usepackage{caption}
\usepackage{pgf,tikz}
\usetikzlibrary{automata,arrows,positioning,calc,decorations.pathreplacing}
\usepackage{fancybox}
\begin{document}
\shadowbox{
\begin{enumerate}[before=\itshape,font=\normalfont,label=\textbf{ABC.\arabic*}]
\item Item 1
\item Item 2
\item Item 3
\end{enumerate}}
\end{document}

However, the customization of my enumerate environment doesn't show up: only numbers 1., 2., 3. are displayed, rather than ABC.1, ABC.2, ABC.3. Am I doing something wrong? What's causing enumitem customization not to work inside fancybox?
EDIT: We've almost solved the issue! But there's still one small obstacle remaining to fix: When you have ten or more items in the list, then ABC.10, ABC.11, ABC.12, etc. will leak outside of the box.

A: Here's a breakable version with tcolorbox as an alternative:
\documentclass[letterpaper,10pt,american]{article}
\usepackage[left=1 in, right=1 in, top=1 in, bottom=1 in]{geometry}
\usepackage{amsmath,amsfonts,amssymb,amsthm,color,enumitem}

\usepackage{setspace}
\usepackage{caption}
\usepackage{pgf,tikz}
\usetikzlibrary{automata,arrows,positioning,calc,decorations.pathreplacing}
%\usepackage{fancybox}
\usepackage[most]{tcolorbox}
\usepackage{xpatch}

\newtcolorbox{enumshadebox}[1][]{breakable, enhanced jigsaw,sharp corners, colframe=black,drop shadow,boxsep=5pt,#1}
\usepackage{hyperref}

\begin{document}

\begin{enumshadebox}
\begin{enumerate}[leftmargin=50pt,before=\itshape,font=\normalfont,label=\textbf{ABC.\arabic*},widest={ABC.100}]
\foreach \x in {1,...,60} {%
  \item \x
}
\end{enumerate}
\end{enumshadebox}

\end{document}

A: You have to use enumerate inside a minipage. If you want a tight box, use varwidth package. Use leftmargin=* in addition.
\documentclass[letterpaper,10pt]{article}
\usepackage[left=1 in, right=1 in, top=1 in, bottom=1 in]{geometry}
\usepackage{enumitem}
\usepackage{fancybox}
\usepackage{varwidth}
\begin{document}
\shadowbox{%
\begin{varwidth}{\linewidth}
\begin{enumerate}[before=\itshape,leftmargin=*,font=\normalfont,label=\textbf{ABC.\arabic*}]
\item Item 1
\item Item 2
\item Item 3
\end{enumerate}
\end{varwidth}
}
\end{document}

A: Some improvements to @Harish Kumar's solution: enumitem has the tools to solve the leak problem for long labels: the key wide= and widest=.
There is also a problem in case of long items: the box leaks into the right margin. I propose 3 solutions for 3 different layouts: one with an indent on both sides, another where only the shadow leaks into the right margin, and no leak at all. Also, I simplified your code for the margins, since they're all equal, and used the showframe option to demonstrate what happens:
\documentclass[letterpaper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[margin=1 in, showframe]{geometry}
\usepackage{enumitem}
\usepackage{fancybox}
\usepackage{varwidth}
\begin{document}

\shadowbox{%
  \begin{varwidth}{\dimexpr\linewidth-2\fboxsep-\shadowsize-\parindent\relax}
    \begin{enumerate}[before=\itshape,wide = 0pt, font=\normalfont,label=\textbf{ABC.\arabic*}]
      \item Item 1\setcounter{enumi}{99}
      \item Item 2 \emph{This one's a very long item. This one's a very long item. This one's a very long item. This one's a very long item.}
      \item Item 3
    \end{enumerate}
  \end{varwidth}
}
\vskip1cm
\noindent\shadowbox{%
  \begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\shadowsize\relax}
    \begin{enumerate}[before=\itshape,wide = 0pt, font=\normalfont, leftmargin =*, label=\textbf{ABC.\arabic*},widest =999]
      \item Item 1\setcounter{enumi}{99}
      \item Item 2. \emph{This one's a very long item. This one's a very long item. This one's a very long item. This one's a very long item.}
      \item Item 3
    \end{enumerate}
  \end{varwidth}
}
\vskip1cm
\noindent\shadowbox{%
  \begin{varwidth}{\dimexpr\linewidth-2\fboxsep-\shadowsize\relax}
    \begin{enumerate}[before=\itshape,wide = 0pt, font=\normalfont, leftmargin =*, label=\textbf{ABC.\arabic*},widest =999]
      \item Item 1\setcounter{enumi}{99}
      \item Item 2. \emph{This one's a very long item. This one's a very long item. This one's a very long item. This one's a very long item.}
      \item Item 3
    \end{enumerate}
  \end{varwidth}
}
\end{document}


text:
Q: How to map a Spring Data JPA repository entity into a view model? Here is the situation, I want to fetch an entity from database and map it to a new view domain model which has more or less properties, if this view model has more properties, signs the extra properties with default value. I want a map technique in JPA to complete this, which is similar to MyBatis mapping mechanism.
So how to do it?

A: Just load the entity, copy it over in the new entity, fill the unset properties with the desired default values and store it using JPA (possibly via Spring Data JPA).
For copying over the data from one entity to another you might want to look int Dozer or similar libraries.
You could also misuse Spring Data's projection support to query the original entity, but return it as the target entity with methods similar to the following:
interface SourceRepository<Source, Long> extends CrudRepository<Source, Long> {
    List<Target> findTargetBy();
}

The resulting Target entities then could be stored again using another repository (you might have to set version and id properties to null to make it clear to the framework that these are new entities.


text:
Q: Magento 2 : Edit Welcome Message For Logged Users In template /Magento_Theme/templates/html/header.phtml I need change welcome message for logged users. Now it looks like:
<?php switch ($block->getShowPart()):
case 'welcome': ?>

        <span data-bind="text: new String('<?php echo $block->escapeHtml(__('Welcome, %1!', '%1'));?>').replace('%1', customer().firstname)">

<?php break; ?>

<?php case 'other': ?>
    <?php echo $block->getChildHtml(); ?>
<?php break; ?>

How I can get customer last name and gender. In the finally I want to have message:
Welcome, Man Jon Dough

A: replace customer().firstname by customer().fullname

A: Edit in  whatever you want -
<span data-bind="text: new String('<?php echo $block->escapeHtml(__('Welcome, %1!', '%1'));?>').replace('%1', customer().firstname)">


text:
Q: Bootstrap - collapsible row - hide show row which we are expanding I am having one table with list of expanded row
My One
 is parent and next is child which I am expanding
I want to hide the second row when it is not expanded.
Below is the code which I am using
I have also added image: The red
 I want to hide.. You can also see the expanded
 in next rows:

    joed123@yahoo.com
    WD154590
    2/1/2017
    Yes

                        Application
                        App Role
                        Workflow Status

                        Portal
                        User
                        Pending Approval

                        SSR
                        User
                        Provisioned

A: You should try to use JQuery if possible here. That way you can use JS to manage the state of showing / hiding your elements, and you can save the state in your browser.


text:
Q: Using looping for searching data on Leaflet Is there a way to find data from different layers and different propertyNames? I have several GeoJSON data files, with different properties. At this moment I can only search one GeoJSON.
For looping and calling the data I am using this code:
maplink_var = [source1.geojson,source2.geojson,etc];

var <?= $i['maplink_var']; ?> = new L.GeoJSON(<?= $i['maplink_var']; ?>, {
  style: function(feature) {
      ...
    },
  onEachFeature: function(feature, marker) {
      ...
    }
});

and below is the code to find data:
var searchControl = new L.Control.Search({
  layer: source1,source2,source3,
  propertyName: ['propNameSource1','propNameSource2','propNameSource3'],
  marker: false,
  moveToLocation: function(latlng, title, map) {
    var zoom = map.getBoundsZoom(latlng.layer.getBounds());
    map.setView(latlng, zoom); // access the zoom
  }
});

searchControl.on('search:locationfound', function(e) {
  e.layer.setStyle({fillColor: '#3f0', color: '#0f0'});
  if(e.layer._popup) e.layer.openPopup();
}).on('search:collapsed', function(e) {
  featuresLayer.eachLayer(function(layer) {
    featuresLayer.resetStyle(layer);
  });
});

map.addControl( searchControl );

I get an error if I give array on property name, stack on loading, and none of the data appears.

A: As explained in the documentation layer is a L.LayerGroup. Thus you can pass multiple layers like this (source):
var searchControl = new L.Control.Search({
  layer: L.layerGroup([source1, source2, source3]),
  ...
})

As for the propertyName: The property name must be the same for all GeoJSON files. Try this when you create the L.GeoJSON (not tested):
onEachFeature: function(feature, layer) {
  const p = feature.properties
  p.title = p.propNameSource1 || p.propNameSource2 || p.propNameSource3 //create new property 'title'
}

title is the default for propertyName so you won't even have to set it when you create L.Control.Search.


text:
Q: Is this an example of a basic/simple higher-order function in javascript? While reading Eloquent Javascript (Chapter 6) I am trying to grasp fundamental concepts. There is discussion about Higher-Order functions in Javascript. Is the function processNumbers() in the following code a Higher-Order function?
function addNumbers(number1, number2) {
  return (number1 + number2);
}

function processNumbers(action, number1, number2) {
  return action(number1, number2);
}

document.write(processNumbers(addNumbers, 2, 10));

A: From Wikipedia:

In mathematics and computer science, a higher-order function (also functional form, functional or functor) is a function that does at least one of the following:

*

*take one or more functions as an input

*output a function

So yes, processNumbers is a higher-level function as it takes in a function as input via the action parameter.


text:
Q: Convert rows to columns in SQL Server 2008 We have one table called Licenses. This is what it looks like:

CustNum
LicenseAddress
License
ExpiryDate

155
123
Y32CA
12/31/2018

155
998
Y32CB
12/31/2020

155
568
Y32CC
12/31/2022

Here is what I want it to look like:

LicAddr1
Lic1
ExpiryDate1
LicAddr2
Lic2
ExpiryDate2
LicAddr3
Lic3
ExpiryDate3

123
Y32CA
12/31/2018
998
Y32CB
12/31/2020
568
Y32CC
12/31/2022

Here is the query I have currently, however it's only returning NULLs:
SELECT LicAddr1,
       Lic1,
       ExpiryDate1,
       LicAddr2,
       Lic2,
       ExpiryDate2,
       LicAddr3,
       Lic3,
       ExpiryDate3
FROM (SELECT CustNum, LicenseAddress, License, ExpiryDate FROM Licenses) d
PIVOT (
       MAX(ExpiryDate)
       FOR CustNum IN (LicAddr1, Lic1, ExpiryDate1, LicAddr2, Lic2, ExpiryDate2, LicAddr3, Lic3, ExpiryDate3)
      ) piv

What am I doing wrong?

A: PIVOT isn't really what you're after, especially since you're trying to get multiple values from each row (which doesn't work very well with the aggregation PIVOT tries to offer).
I'm assuming here you want the most recent three licenses, in which case we can apply a row number per CustNum, ordered by ExpiryDate (newest first), then flip them so they are left-to-right oldest-to-newest:
;WITH cte AS
(
  SELECT CustNum, LicenseAddress, License, ExpiryDate,
    rn = ROW_NUMBER() OVER (PARTITION BY CustNum ORDER BY ExpiryDate DESC)
  FROM dbo.Licenses
)
SELECT CustNum,
  LicAddr1    = MAX(CASE WHEN rn = 3 THEN LicenseAddress END),
  Lic1        = MAX(CASE WHEN rn = 3 THEN License        END),
  ExpiryDate1 = MAX(CASE WHEN rn = 3 THEN ExpiryDate     END),
  LicAddr2    = MAX(CASE WHEN rn = 2 THEN LicenseAddress END),
  Lic2        = MAX(CASE WHEN rn = 2 THEN License        END),
  ExpiryDate2 = MAX(CASE WHEN rn = 2 THEN ExpiryDate     END),
  LicAddr3    = MAX(CASE WHEN rn = 1 THEN LicenseAddress END),
  Lic3        = MAX(CASE WHEN rn = 1 THEN License        END),
  ExpiryDate3 = MAX(CASE WHEN rn = 1 THEN ExpiryDate     END)
FROM cte
GROUP BY CustNum;

Results:

CustNum
LicAddr1
Lic1
ExpiryDate1
LicAddr2
Lic2
ExpiryDate2
LicAddr3
Lic3
ExpiryDate3

155
123
Y32CA
2018-12-31
998
Y32CB
2020-12-31
568
Y32CC
2022-12-31

*

*Example db<>fiddle


text:
Q: ebproof undefined control sequence \hypo I'm trying to use the ebproof package with the following MWE:
\documentclass[12pt, letterpaper]{report}
\usepackage[utf8]{inputenc}
\usepackage{ebproof}

\begin{document}

\begin{prooftree}
    \hypo{ x {:} \sigma \in \Gamma }
    \infer1[var]{ \Gamma \vdash x {:} \sigma}
\end{prooftree}

\end{document}

(taken from this question)
However when I try to compile it to a pdf I get the following error:
$ pdflatex test.tex
This is pdfTeX, Version 3.14159265-2.6-1.40.16 (TeX Live 2015/Debian) (preloaded format=pdflatex)
 restricted \write18 enabled.
entering extended mode
(./test.tex
LaTeX2e <2016/02/01>
Babel <3.9q> and hyphenation patterns for 81 language(s) loaded.
(/usr/share/texlive/texmf-dist/tex/latex/base/report.cls
Document Class: report 2014/09/29 v1.4h Standard LaTeX document class
(/usr/share/texlive/texmf-dist/tex/latex/base/size12.clo))
(/usr/share/texlive/texmf-dist/tex/latex/base/inputenc.sty
(/usr/share/texlive/texmf-dist/tex/latex/base/utf8.def
(/usr/share/texlive/texmf-dist/tex/latex/base/t1enc.dfu)
(/usr/share/texlive/texmf-dist/tex/latex/base/ot1enc.dfu)
(/usr/share/texlive/texmf-dist/tex/latex/base/omsenc.dfu)))
(/usr/share/texlive/texmf-dist/tex/latex/ebproof/ebproof.sty
(/usr/share/texlive/texmf-dist/tex/latex/pgf/utilities/pgfkeys.sty
(/usr/share/texlive/texmf-dist/tex/generic/pgf/utilities/pgfkeys.code.tex
(/usr/share/texlive/texmf-dist/tex/generic/pgf/utilities/pgfkeysfiltered.code.t
ex)))) (./test.aux)
! Undefined control sequence.
<recently read> \hypo

l.8     \hypo
             { x {:} \sigma \in \Gamma }
? q
OK, entering \batchmode⏎

I have no idea what I'm doing wrong :/
I'm using TeX Live on Linux Mint 18.1 and it is updated to the latest version through Mint's package manager.

A: Version 1.1 of the ebproof package (March 13, 2015) uses \Hypo and \Infer rather than \hypo and \infer. Thanks to marmot for suggesting that I used texdoc ebproof.
As a workaround I've added this to my preamble:
\newcommand\hypo{\Hypo}
\newcommand\infer{\Infer}

(This will make it easy to update to ebproof v2.0 or TeXLive 2017 in the future without breaking my LaTeX document.)
Alternatively installing TeXLive 2017 from a PPA would fix the issue via version 2.0 of ebproof which uses lowercase commands. (I did not actually try this approach myself).


text:
Q: .Net Unicode character mapping Let's assume we have following two classes
Typeface
GlyphTypeface

We can create instance of GlyphTypeface class via Typeface.TryGetGlyphTypeface method,
but before creating object for GlyphTypeface we create object of Typeface using following
constructor
public Typeface(FontFamily fontFamily, FontStyle style, FontWeight weight, FontStretch stretch);

When we create object fontFamily we hard coded fontName(for example Calibri).
.Net auto populated property CharacterToGlyphMap of GlyphTypeface  for glyph indexes.
I want to know population if the CharacterToGlyphMap depends on fontName (calibri)?
Actual problem is that when we use fontname(calibri) and try to get the value from CharacterToGlyphMap by hindi symbols we get 'an error key not found'.


text:
Q: Send multiple images to web server with input source of imagepicker. I've used UIImagePicker to upload two images into UIImageViews. Then I sent the Two images to web server. but instead of two different images one image saving two times.
No problem with code what i written to send multiple images to web server.I mistaken at UIImagePicker only.This is the First time am using UIImagePicker. check the code for image picker what i written in my Project
- (void)takePhoto:(UIButton *)sender {

if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

    UIAlertView   *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                          message:@"Device has no camera"
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles: nil];

    [alertView show];

}

else{

    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    [self presentViewController:picker animated:YES completion:NULL];

}

}
- (void)selectPhoto:(UIButton *)sender {

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];

}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

chosenImage = info[UIImagePickerControllerEditedImage];
chosenImage1=info[UIImagePickerControllerEditedImage];
chosenImage2=info[UIImagePickerControllerEditedImage];

imageView.image = chosenImage;

frstCmpImgView.image= chosenImage1;
scndCmpImgView.image=chosenImage2;

if ([self.navigationItem.title  isEqual: @"CLOTHING"]) {
    NSLog(@"cloth page");
    [self clothview];
}
else if([self.navigationItem.title  isEqual: @"FACE PHOTO"]){

    [self hideButtns];

    NSLog(@"face page");

}

else{
    //----compare object--

    if ([cmparObjLabel.text isEqualToString:@"Choose the 1st Object"]) {
        [self afterUploadFrstCmpObj];

    }
    else if ([cmparObjLabel.text isEqualToString:@"Choose the 2nd Object"])
    {

        [self afterUploadScndCmpObj];
    }
}
[picker dismissViewControllerAnimated:YES completion:NULL];

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

[picker dismissViewControllerAnimated:YES completion:NULL];

}

Thanks in advance for every one.


text:
Q: How to setup complex project with Visual Studio 2022? I have project that I was developing for years in Linux.
It depends on MKL, libxml++, GSL and armadillo library.
Its installation structure is done in CMake and project is formed by building a shared library and couple of executables that link to it. There are about 20 classes in the library.
Project structure is:
--src
  --executable1.cpp
  --executable2.cpp
  --mysharedlib
    --class1.h
    --class1.cpp
    --...

My question is how to install and run this code in Visual Studio in Windows.
I never used VS before and am still going through tutorials. I managed to run my code by installing Ubuntu on WSL, but I I'd like a VS solution as it'd be handy to pass to user not familiar with Linux.
I tried opening the project directory with VS, hoping CMAKE would do all the magic, but expectedly it cannot locate the dependent libraries, so I am now going through web looking how to integrate each to VS. I managed to find armadillo and mkl guide, but I am lost on how to link these libraries to my project codes and whether I should abandon its current cmake setup and start building the code structure differently in VS.
Any links to useful VS tutorials and advices how to this are greatly appreciated.

A: VS does have support for CMake, although I have no idea how well VS integrates CMake. If you're not set on using VS, you might want to look into an IDE that uses CMake at it's core, Clion comes to mind. That being said, when coming from Linux you don't have the (initial) luxury of simply installing all the dependencies via a preinstalled package manager.
In order for CMake to find your dependencies (assuming you've configured them by using find_package()) you should add the sources of your dependencies to your project in a thirdparty folder (name is up to you) and add these dependencies using add_subdirectory() instead. This will compile all your dependencies from source, so you might have to configure these dependencies yourself (look into the documentation of your dependencies on how to build them from source).
Another way is to use a package manager that is available on Windows to download, compile and provide your dependencies to your build tools. vcpkg comes to mind, claiming to integrate well with CMake by providing a toolchain file that you can pass to CMake when building your project. You might even be able to configure VS to automatically pass this toolchain to CMake whenever it's invoked.
From personal experience, there is no need to convert an existing project to the VS project structure. There's plenty of available solutions and tools available on Windows to work with CMake projects. Going with the cross-platform approach should be preferred unless you're only targeting Windows, using VS to it's fullest then might give you some additional quality of life.
If you have more specific questions regarding this, I suggest that you update your original post or to create separate, specific questions regarding the processes involved in setting up an existing CMake project on Windows.


text:
Q: PHP script keeps sending Email evertime the page is loaded I have put together a simple contact form for my website. Using PHP to POST the data and send directly to my email address. But for some reason every time I visit the page on my website. I still get the test message Displaying under the Form. Then when I reload the website and visit the link again it still displays the thank you message. and automatically sends an email. Im still in testing mode 2 days before my launch and I need this figure out. Considering I am novice to php I dont know what goes where....  check out my website to get a live view https://trillumonopoly.com  (click "Contact Us" link in menu) I would like for the contact form to disappear and echo the thank you message once sent. And reset after the page is reloaded. I am also using Jquery ajax to load all my pages into a div container. So I would like to keep the content inside that div without forwarding to the Echo message page, leaving my index page
Heres My ajax code
$(document).ready(function () {
    loadMainContent('main');

    $('body').delegate('.navMenu', 'click', function (event) {
        event.preventDefault();
        loadMainContent($(this).attr('href'));
    });
});

function loadMainContent(page) {
    $('#main').load('pages/' + page + '.php');
}

here is html for the form:

Contact Us

                <form action="pages/mail.php" method="GET" class="box2">
                    NAME:
                    <input type="text" name="name" placeholder="YOUR NAME HERE" required>

                    EMAIL:
                    <input type="email" name="email" placeholder="YOUR EMAIL HERE" required>

                    MESSAGE:

                    <textarea name="message" rows=10 cols=23 placeholder="YOUR MESSAGE HERE" required></textarea>

                    <button type="submit" value="Message Sent" class="btn btn-danger btn-lg" style="background-color:"red">SUBMIT</button
                </form>
                <?php include('mail.php'); ?>

Here is My simple PHP:
<?php

$name = $POST['name'];
$email = $POST['email'];
$message = $POST['message'];

mail("info@trillumonopoly.com","ILLUMONOPOLY WEB Contact", $message,"From: $email\r\n");

echo "Thank You For Contacting Us!";

?>

A: Better than check everything before send mail.
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])){
    $name = $POST['name'];
    $email = $POST['email'];
    $message = $POST['message'];

    mail("info@trillumonopoly.com","ILLUMONOPOLY WEB Contact", $message,"From: $email\r\n");

    echo "Thank You For Contacting Us!";
}

And send POST request to the index, not mail.php.
<form action="" method="POST">
    ...

So the user can see your message at the end of contact form.


text:
Q: Generate timestamp (unix format) with intervals I'm quite new to TypeScript and I know it's built on top of JavaScript, but for some reason I keep getting errors so I'm kinda stuck.
I want to create a function that generates a timestamp with the unix format which has intervals of random numbers. For better explanation:
The starting timestamp should be Date.now()  which should give something like 1669111677979.
The next step should be adding random numbers ranging from 60 to 120 on top of the Date.now for maybe 15 times.
How can I achieve this? Thanks in advance!
I tried using for loops but that didn't quite solve my issue.
import { faker } from '@faker-js/faker';
import { IDeviceData } from '@backend/data';

export function generateFakeData(): IDeviceData {
  for(let interval = 0; interval < 15; interval+20){
    console.log(interval);
    }

  return {
    id: faker.datatype.uuid(),
    imei: faker.datatype.uuid(),
    sensorPayload: 'test',
    temperature: faker.datatype.number({ min: -40, max: 70 }),
    humidity: faker.datatype.number({ max: 100 }),
    carbondioxide: faker.datatype.number({ max: 1000000 }),
    timestamp: Date.now()+interval.toString()
  };
}

UPDATE
I did some more digging into the code and somewhere else it's generating data with a for loop. It runs the code 15 times and pushes it to the devices array.
const [devices, setDevices] = useState([] as IDeviceData[]);

useEffect(() => {
    if (environment.production === false) {
      const fakeData = [];
      for (let i = 0; i < 15; i++) {
        fakeData.push(generateFakeData());
      }
      setDevices(fakeData);

    } else {...}
}

Now how can I make sure that the timestamp adds a few seconds on every push of code into the array?

A: You just need some sort of pseudorandom integer generation function. Here's an example:
TS Playground
/** Generate a random integer (inclusive of min/max) */
function getRandomInt (min = 0, max = 1): number {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

let ts = Date.now();
const timestamps: number[] = [];

for (let i = 0; i < 15; i += 1) {
  ts += getRandomInt(60, 120);
  timestamps.push(ts);
}

console.log(timestamps); // array of 15 "random" millisecond timestamps, each 60–120 ms apart

Compiled JS from the TS playground:

"use strict";
/** Generate a random integer (inclusive of min/max) */
function getRandomInt(min = 0, max = 1) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
let ts = Date.now();
const timestamps = [];
for (let i = 0; i < 15; i += 1) {
    ts += getRandomInt(60, 120);
    timestamps.push(ts);
}
console.log(timestamps); // array of 15 "random" millisecond timestamps, each 60–120 ms apart


text:
Q: Difference between sibling namespaces in nested vs global context I have some C++ libraries that are written using nested namespaces. These libraries use many mathematical functions that, for readability, are better off read without explicitly specifying namespaces. Right now, a simplified version of the code would look like this.
namespace Base::Sibling1 {
  float cos(float x) { return cosf(x); }
};

namespace Base::Sibling2 {
  using namespace Sibling1;
  float f(float x) { return cos(x); }
};

We wanted to move to use flatter namespaces mostly to make it easier to extend the library with sibling code. We had hoped that a simple change like this would work:
namespace Sibling1 {
  float cos(float x) { return cosf(x); }
};

namespace Sibling2 {
  using namespace Sibling1;
  float f(float x) { return cos(x); }
};

Instead this fails now since Sibling2::f() calls cos(x) that is now ambiguous.
I have two questions

*

*why is it ambiguous now and not int the first version?

*is it possible to obtain the behavior we had before without listing all functions explicitly using using Sibling1::cos?

A: The problem cannot be reproduced as you describe it. Moreover, there is no reason that the flattening alone introduces ambiguities, if you use expose in the siblings the same names you introduced in Base.  So, the root cause is probably in some parts of the code you are not showing.
The second version does not define cosf(), so you probably are using some namespace.  If in that namespae there is also a cos() you create an ambiguity between the two overloads.  I could reproduce this by using namespace std:
#include <iostream>
#include <cmath>
using namespace std;
namespace Sibling1 {
  float cos(float x) { return cosf(x); }
}
namespace Sibling2 {
  using namespace Sibling1;
  float f(float x) { return cos(x); }
}

Online demo: the compilation error indicates which are the candidates behind the ambiguity.  If you now comment the using namespace out, the ambiguity goes away, and the code compiles.  Online proof.
Namespaces are meant to avoid naming conflicts and keep control of  ambiguities:

*

*Creating a namespace and systematically using namespace everywhere defeats the whole purpose.

*On the other side, long using lists are painful to maintain, especially if you have to repeat them in several sibling namespaces.  This is probably why the Base and the nesting were created in the first place.

In the first version, you do not show what's in Base.  It is possible that some more tailored using clauses are used therein instead of full namespaces: if selectively injecting the really required functions in the Base namespace, they are made available within the siblings avoiding ambiguity that can be introduced by injecting the name of unnecessary functions.

A: The ambiguity is due to how using directives work.

[namespace.udir] (emphasis mine)
2 A using-directive specifies that the names in the nominated
  namespace can be used in the scope in which the using-directive
  appears after the using-directive. During unqualified name lookup
  ([basic.lookup.unqual]), the names appear as if they were declared in
  the nearest enclosing namespace which contains both the
  using-directive and the nominated namespace. [ Note: In this context,
  "contains" means "contains directly or indirectly". — end note ]
3 A using-directive does not add any members to the declarative
  region in which it appears. [ Example:
namespace A {
  int i;
  namespace B {
    namespace C {
      int i;
    }
    using namespace A::B::C;
    void f1() {
      i = 5;        // OK, C::i visible in B and hides A::i
    }
  }
  namespace D {
    using namespace B;
    using namespace C;
    void f2() {
      i = 5;        // ambiguous, B::C::i or A::i?
    }
  }
  void f3() {
    i = 5;          // uses A::i
  }
}
void f4() {
  i = 5;            // error: neither i is visible
}

— end example ]

So given your structure of namespaces, according to bit I made bold in paragraph 2, when you write
using namespace Sibling1;

It kinda translates to this
namespace /* Enclosing */ {

    using Sibling1::cos;

    namespace Sibling2 {
      float f(float x) { return cos(x); }
    };

}

The namespace I marked as enclosing is either Base or the global namespace. The "kinda" bit (according to paragraph 3) is that it's not an actual declaration being added. I.e. if something named cos already exists in /* Enclosing */, it's not a re-declaration. This is by design, because using directives can potentially bring a lot of names in, and so it shouldn't cause an error when the names they bring are not actually used.
In your case however, the name brought in is used.
When /* Enclosing */ is Base, it matches only one declaration, the one in Sibling1, as-if it was declared in Base.
When /* Enclosing */ is the global namespace, it matches the actual declaration there too, presumably the one brought in by math.h (you seem to be using that). So you get an ambiguity (the name refers to two potential entities).
So on the whole, compilers that reject this code are behaving as expected. While I understand your plight, I don't think there's really a problem for you to solve here. If client code finds Base::Sibling1::cos too verbose, it itself can employ a using directive of the form using namespace Base;. Or using a namespace alias to shorten things namespace sib1 = Base::Sibling1;.


text:
Q: Hyperlink in Eclipse is not working on click So, I just want to open a simple link in Eclipse. What I did:
final Hyperlink link = new Hyperlink(group, SWT.WRAP);
            link.addHyperlinkListener(new HyperlinkAdapter(){
                public void linkActivated(HyperlinkEvent e) {
                    System.out.println("test");

            });
            link.setEnabled(true);
            link.setToolTipText("Test tooltip!");
            link.setForeground(new Color(null, 0, 0, 250));
            link.setText("Text");

All nice and good, the text appear in my color, but when I click the text I never get the System.out.println("test")...I see the tooltip also. But never enters in the linkActivated method.
Where I'm wrong ?
Additional info: this is done in a Dialog->Composite->Group
Thank you in advance!
LE: So sorry for that, the problem was that Eclipse imported automated  javax.swing.event.HyperlinkEvent when I really needed org.eclipse.ui.forms.events.HyperlinkEvent.
Again sorry for spam, but it took me some time to find out this.

A: Copied from above:

The problem was that Eclipse imported automated javax.swing.event.HyperlinkEvent when I really needed org.eclipse.ui.forms.events.HyperlinkEvent.


text:
Q: Pagination with custom field I've got a little (big) problem.
Is there a solution to show only posts that have not the same custom field value (from a specific custom field key) ?
I have some post with a manual ID as custom field, and I don't want to show them into my loop, and keep a good pagination.
It's easy to skip this post (that have the same manual ID) but I cannot get a good pagination because I use continue; to skip them.

A: As I stated in comments, you need pre_get_posts and a meta_query to exclude posts from a certain custom field with a certain value from the main query. It is really in your best interest to read up on the before mentioned. Just remember, all parameters in WP_Query works on pre_get_posts as WP_Query uses pre_get_posts to alter the query parameters, and the main query uses WP_Query
In short, you can try the following: (REQUIRES PHP 5.4+ and the code is untested)
add_action( 'pre_get_posts', function ( $q )
{
    if (     !is_admin() // Targets the front end only, we don't need this for is_home()
          && $q->is_home() // Change this to the appropriate page, here we only target the home page
          && $q->is_main_query() // Target the main query only
    ) {
        $meta_query = [
            [
                'key' => 'Custom_ID',
                'compare' => 'NOT IN' // Do not get posts from this spoecific key/value pair
            ]
        ];
        $q->set( 'meta_query', $meta_query );
    }
});


text:
Q: how to find unique word in text file and then store unique words in text file using powershell I am using PowerShell. Here I want to remove duplicate words from the text file and then store the unique words in the text file. What I do is here.
$A = $( foreach ($line in Get-Content C:\Test1\File1.txt) {
    $line.tolower().split(" ")
  }) | Sort-Object | Get-Unique
$A | export-csv "somefile.csv"

Here is my file.

A: PowerShell can use a dotnet type called a hashset which is perfect for doing exactly this, and at the figurative speed of light too!
First we read the file into memory in PowerShell and assign it to a variable called $lines.
Next, we split into just the unique $words.
Finally, we create a hashset which will only allow unique words or items.
$lines = get-content "C:\Users\Stephen\OneDrive\Documents\quotes.txt"
[string[]]$words = $lines.Split()
$uniqueWords = [System.Collections.Generic.HashSet[string]]::new($words)

Here's some info on how this works, we're using the hashset constructor which accepts an input value.
But its FAST!
It is amazingly fast to use a hashset too! I measured the performance on a reasonably sized file of 10MB of text from samplefile.com with a number of famous quotes and other info.
Method           TotalMs
------           -------
Get-Unique    21484.4956
Using Hashset  1840.7407

Get hashset is dramatically faster.  It's an order of magnitude faster in the worst case, and I've seen it be two orders of magnitude or more before.

A: Or simply as one-liner
(Get-Content 'C:\Test1\File1.txt' -Raw) -split '\W' | Sort-Object -Unique | Set-Content -Path 'C:\Test1\File2.txt'

\W is regex for a Non-Word character like space, comma, etc.

A: The main issue with your example was that you weren't processing the returned array from the split function:
Get-Content hello.txt | ForEach-Object { $wrds=$_.Split(" "); foreach ($i in $wrds) {  Write-Output $i } } | Sort-Object | Get-Unique

Split each line into the array wrds and then loop on the contents to write the output before performing the sort and processing the duplication.


text:
Q: Element of fraction field integral over ring of integers In Mollin's Algebraic Number Theory, the author states "Since $F$ is the quotient field of $\mathfrak{O}_F$ [the ring of integers for $F$] then any $\alpha\in F$ is integral over $\mathfrak{O}_F$."
This is part of proving the fact that the ring of integers of a number field is a Dedekind Domain. In particular, it aims to prove that $\mathfrak{O}_F$ is integrally closed.
However, unless I'm missing something, the statement appears false. $\mathbb{Q}$ is the fraction field for $\mathbb{Z}$, which is in turn the ring of integers for $\mathbb{Q}$. However, not every element of $\mathbb{Q}$ is integral (the solution to a monic polynomial with coefficients in $\mathbb{Z}$. Am I missing something?


text:
Q: Restore lost bootloader on a luks partition I need an advice about a bad situation.
I was installing a new linux ditro by using my main PC. I booted with the ISO and then installed the distro on /dev/sdc, which was an external USB drive.
My bad, I didn't realized when installing, that I didn't change the boot loader installation on the same drive, but I left on /dev/sda, which holds my main operating system (LUKS encrypted).
Obviuosly after this, the main operating system is not booting any more, and I see an errror message from GRUB saying:
error: no such cryptodisk found

Now, I have a clonezilla backup of my /dev/sda/, and in the file list, among other files, I see
12/04/2022  04:59 AM                10 parts
12/03/2022  11:41 PM                38 sda-chs.sf
12/03/2022  11:41 PM         1,048,064 sda-hidden-data-after-mbr
12/03/2022  11:41 PM               512 sda-mbr
12/03/2022  11:41 PM               391 sda-pt.parted
12/03/2022  11:41 PM               338 sda-pt.parted.compact
12/03/2022  11:41 PM               267 sda-pt.sf
12/03/2022  11:41 PM       118,196,482 sda1.ext4-ptcl-img.gz.aa
12/04/2022  04:59 AM               512 sda2-ebr

I hope some of these backups can help me in restore the situation (may be sda-mbr and sda-hidden-data-after-mbr?), but I'd like to ask your help before doing anything, in order to avoid more damage.
Anyone can advice how to recover the situation?
Thanks so much!!

A: UEFI or BIOS installs. Looks more like BIOS as you have MBR and maybe grub's core.img which is in the sectors after the MBR. Most systems now are UEFI and prefer gpt partitioning.
If you plug in external drive, does it boot?
Update it to see encrypted install.
sudo apt-get update && sudo apt-get install lvm2 cryptsetup
sudo modprobe dm-crypt
sudo cryptsetup luksOpen /dev/sdXY my-crypt
sudo os-prober
sudo update-grub

And then install grub from external drive to external drive's MBR.
And from encrypted install install grub to sda. So internal drive boots normally.
Also what version of grub?
Nowadays GRUB (v2.06) allows to boot Linux from a LUKS-encrypted /boot partition (even one inside a LVM) with the GRUB_ENABLE_CRYPTODISK=y key and the appropriate LUKS or LUKS2 modules loaded.
Otherwise you can use live installer.
https://askubuntu.com/questions/63594/mount-encrypted-volumes-from-command-line
http://askubuntu.com/questions/719409/how-to-reinstall-grub-from-a-liveusb-if-the-partition-is-encrypted-and-there-i?rq=1

A: OK, I was able to solve with the following commands:
sudo -i
apt-get update
apt-get install cryptsetup lvm2
fdisk -l
cryptsetup luksOpen /dev/sda? TAG
vgchange -ay
vgscan
vgchange -ay [VOLUME GROUP NAME]           # From the above command
lvscan
mount /dev/[VOLUME GROUP NAME]/[LOGICAL VOLUME NAME] /mnt          # LOGICAL VOLUME NAME from above command

cd /mnt
mount /dev/sda1 /mnt/boot
for i in /dev /dev/pts /proc /sys /sys/firmware/efi/efivars /run; do sudo mount -B $i /mnt$i; done

chroot /mnt

grub-install /dev/sda
update-grub

for i in /dev /dev/pts /proc /sys /sys/firmware/efi/efivars /run; do sudo umount /mnt$i; done

umount /mnt
vgchange -an
cryptsetup luksClose TAG

Now I have to solve a kind of mixup with devices, but I'm able to boot up the system.
Thanks a lot for the help @oldfred


text:
Q: PHP : get parent child value I have an array like this
array (
  0 =>
  array (
    'id' => '1',
    'job_id' => 'J1',
    'parent_id' => '0',
  ),
  1 =>
  array (
    'id' => '2',
    'job_id' => 'J2',
    'parent_id' => '0',
  ),
  2 =>
  array (
    'id' => '3',
    'job_id' => 'J3',
    'parent_id' => '1',
  ),
  3 =>
  array (
    'id' => '4',
    'job_id' => 'J4',
    'parent_id' => '2',
  ),
  4 =>
  array (
    'id' => '5',
    'job_id' => 'J5',
    'parent_id' => '3',
  ),
  5 =>
  array (
    'id' => '6',
    'job_id' => 'J6',
    'parent_id' => '1',
  ),
  6 =>
  array (
    'id' => '8',
    'job_id' => 'J8',
    'parent_id' => '7',
  ),
)

I am showing child record where parent_id is mention with it's parent records
Output
Array
(
[1] => Array
    (
        [job_id] => J1
        [parent_id] => 0
        [children] => Array
            (
                [0] => Array
                    (
                        [job_id] => J3
                        [parent_id] => 1
                        [children] => Array
                            (
                                [0] => Array
                                    (
                                        [job_id] => J5
                                        [parent_id] => 3
                                    )
                            )
                    )

                [1] => Array
                    (
                        [job_id] => J6
                        [parent_id] => 1
                    )

            )

    )

[2] => Array
    (
        [job_id] => J2
        [parent_id] => 0
        [children] => Array
            (
                [0] => Array
                    (
                        [job_id] => J4
                        [parent_id] => 2
                    )
            )
    )

)

Now I want - if parent_id mentioned but it's not available in given array then want to show records in main array in output not as child array
expecting output
Array
(
[1] => Array
    (
        [job_id] => J1
        [parent_id] => 0
        [children] => Array
            (
                [0] => Array
                    (
                        [job_id] => J3
                        [parent_id] => 1
                        [children] => Array
                            (
                                [0] => Array
                                    (
                                        [job_id] => J5
                                        [parent_id] => 3
                                    )

                            )

                    )

                [1] => Array
                    (
                        [job_id] => J6
                        [parent_id] => 1
                    )

            )

    )

[2] => Array
    (
        [job_id] => J2
        [parent_id] => 0
        [children] => Array
            (
                [0] => Array
                    (
                        [job_id] => J4
                        [parent_id] => 2
                    )

            )

    )
[3] => Array
    (
        [id] => 8
        [job_id] => J8
        [parent_id] => 7
    )
 )

Here id 7 is not exist in error i want it as parent records with id as key. How to find that?
Code
function buildTree( $ar, $pid = 0 ) {
        $op = array();
        foreach( $ar as $item ) {
            echo '<pre>';
            //print_r($item);echo '<br>';//exit;
            if( $item['parent_id'] == $pid ) {
                $op[$item['id']] = array(
                    'job_id' => $item['job_id'],
                    'parent_id' => $item['parent_id']
                );
                // using recursion
                $children =  buildTree( $ar, $item['id'] );
                //print_r($children);
                $children = array_values($children);
                if( $children ) {
                    $op[$item['id']]['children'] = $children;
                }
            }
        }
        return $op;
 }

A: You can add the pid in a new array just above :

$op = array;
  So everytime buildtree is called the pid is added to the new array.
  You can add other arrays in the resultant $op array after it is returned.

This should be done outside buildtree method:
Check if there is any element whose parent_id is not in the new array that was created if yes then add that element to $op as per the requirement.
Hope that helps.