text:
Q: Installing Windows 8 Consumer Preview returns an error I always get "A DVD driver your PC needs is missing." Then I click "Ok" and "No device drivers were found." pops up.
This occurs right after I select my language and keyboard. How do I fix it?
I'm installing the 32-bit consumer preview on VMware player on a 32-bit Windows 7.

A: VMware says it could be a corrupted ISO file:
http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1032711

A: I can confirm that in my case it was due to a corrupted download of the ISO file. The size of my file was not correct; and it gave the error mentioned in the question above, here on my VMware vSphere 5.0.
Use a download manager (e.g. Orbit Downloader) and compare the SHA-1 hash of the downloaded file with the SHA-1 value published at Microsofts download page. (Install HashTab, right-click the iso file and click the tab File Hashes) Or download from msdn.microsoft.com, as they use a buildin download manager which checks the integrity of the file.
Both Windows Server 8 Beta and Windows 8 Beta seems to run without any problems at my VMware vSphere 5.0 here.

A: In my case it was an incomplete download by Google Chrome. So effectively a corrupt ISO as Peter said. Downloading the ISO again solved the issue. I used Safari and curl to have 2 horses in the race and they both worked just fine.
Compare the SHA1 hash provided by MS on the ISO download page to ensure you have the whole thing. The hash is E91ED665B01A46F4344C36D9D88C8BF78E9A1B39.


text:
Q: Controller namespace not routing correctly So I am using MVC 5, and is getting this error. This is because I have two areas and they both have a controller with the same name and same method name.
Multiple types were found that match the controller named 'controller1'.
This can happen if the route that services this request ('{controller}/{action}/{id}') does not
specify namespaces to search for a controller that matches the request.
If this is the case, register this route by calling an overload of
the 'MapRoute' method that takes a 'namespaces' parameter.

So I understand that I need to add name spaces to my routing. So in Route.config.cs I added this
 routes.MapRoute(
   name: "Default",
   url: "{controller}/{action}/{id}",
   defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
   namespaces: new[] { "webApp.Controllers" }
 );

Then in the application_start() function in global.asax I added ControllerBuilder.Current.DefaultNamespaces.Add("webApp.Controllers");
Then in my areas, where my error is coming from. I have 2 areas, admin and myportal. Both have a AreaRegistration.cs file. In AdminAreaRegistration.cs I have this added
public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Admin_default",
            "Admin/{controller}/{action}/{id}",
           defaults: new { action = "Index", id = UrlParameter.Optional },
           new[] { "webApp.Areas.Admin.Controllers" }
        );
    }

In MyPortalAreaRegistration.cs I have this added
 public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "MyPortal_default",
            "MyPortal/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional },
            new[] { "webApp.Areas.MyPortal.Controllers" }
        );
    }

From the client side I am making a post call
 const otherParams = {
        headers: {
            "content-type": "application/json; charset=UTF-8"
        },
        body: JSON.stringify(product),
        method: 'POST'
    };
    console.log(otherParams);
    const response = await fetch('/Item/GetDetailPageURL', otherParams)
        .then(response => {
            response.json();
            console.log(response);
            window.open(response.url, "_blank");
        })
        .then(data => console.log(data));

From what I understand this is all I needed to get it work, but it is still complaining about the namespace. Am I misunderstanding/ missing something?

A: You shouldn't need to change your RouteConfig.cs
All you need to do is to register your area (inside the area folder):
In this example, the area name is admin. You need to write your area registration code inside adminAreaRegistration.cs file which is inside admin folder:

public class adminAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "admin";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "admin_default",
            "admin/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

And then add AreaRegistration.RegisterAllAreas(); to your Global.asax.cs

A: Besides area registration like Hooman Bahreini said, try to setup your default name spaces as well in the application start.

*

*Try this

 protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        // in you application start register your default or whatever makes sense Portal Controllers
  ControllerBuilder.Current.DefaultNamespaces.Add("webApp.Areas.MyPortal.Controllers");
    }

*TRUST ME ON THIS -- go to your bin folder and blow away any old dll's "bin" folder completely manually. Sometimes there are stale dll's and don't get cleaned

*your routes seem fine, but double check your routes with this answer on routes...

A: Use Attribute Routing in ASP.NET MVC 5:
[RoutePrefix("reviews")]
public class ReviewsController : Controller
{

Somewhere else:
[RoutePrefix("otherreviews")]
public class ReviewsController : Controller
{

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python CGI scripts using GET values I have a CGI script in python. I want to know how to run the CGI script itself alongside a normal python script (in this case a file writing device) using the variables received through the GET method. Here is the code:
window.location.href = "http://[URL]/python_scripts/get.py?first_name=mlb&last_name=406"

This is in the main script, the get.py file looks like this:
#!/usr/bin/python

# Import modules for CGI handling
import cgi, cgitb

# Create instance of FieldStorage
form = cgi.FieldStorage()

# Get data from fields
first_name = form.getvalue('first_name')
last_name  = form.getvalue('last_name')

print "Content-type:text/html\r\n\r\n"
print ""
print ""
print "
Hello %s %s
" % (first_name, last_name)
print ""
print ""

f = open("/var/www/data.txt", w)
f.write("Hello from %s %s") % (first_name, last_name)
f.close()

in the error.log file it says:
[Tue Jun 23 19:07:07 2015] [error] (13)Permission denied: exec of '/var/www/python_scripts/get.py' failed
[Tue Jun 23 19:07:07 2015] [error] [client [IP]] Premature end of script headers: get.py, referer: http://[URL]/python_scripts/testScript.py

EDIT
The script runs fine without the f=open etc part, making me suspect a permission error
EDIT
Now solved. I needed to apply "chmod 777" permissions to the function file, the file performing the operation, and the text file itself. Thanks for all the help


text:
Q: Excess colomns in the query result I'm trying to write a simple interface for a list of companies using MySQL and PHP.  So, I want to fetch some information from my database.
Here are my tables:

*

*companies_data - only for system information.

*corporate_data - here I want to keep information about big companies.

*individual_data - and here I want to keep information about little companies.

So, here is the tables

And here is the query that I've written:
SELECT
    a.id,
    a.user_id,
    a.added,
    a.`status`,
    a.company_id,
    a.company_type,
    a.deposit,
    a.individual_operations_cache,
    a.corporate_operations_cache,
    a.physical_operations_cache,
    b.full_name,
    b.tax_number,
    b.address,
    b.statement_date,
    b.psrn,
    c.full_name,
    c.tax_number,
    c.address,
    c.statement_date,
    c.psrn
FROM
    companies_data a
    LEFT OUTER JOIN corporate_data b
        ON (a.company_id = b.id) AND a.company_type = 0
    LEFT OUTER JOIN individual_data c
        ON (a.company_id = c.id) AND a.company_type = 1
WHERE
    a.user_id = 3

This is just the code for a test, I'll expand it soon.

As you see, I've got result with extra fields like %field_name%1, %another_field_name%1 and so on. Of course it is not the mysql error - what I've asked that I've got - but I want to remove this fields? It's possible or I must convert this output on the application side?

A: thos %field_name%1, %another_field_name%1 , are visible since you are selecting them in your query:
            b.full_name,
            b.tax_number,
            b.address,
            b.statement_date,
            b.psrn,
            c.full_name,
            c.tax_number,
            c.address,
            c.statement_date,
            c.psrn
When you use fields with the same name in distinct tables, then the result column name come with this identifier field1, field2, fieldn... in order to distinguish from which table does the field come from.
If you want to avoid this names, you can use aliases as follows:
           [...]
            b.full_name as corporate_full_name,
           [...]
Probably, if every common fields are coincident, you won´t need to show them all, so just remove them from the select.
Hope being usefull for you.
Br.


text:
Q: Eigenvalues of a compact operator with modulus greater than $\epsilon$ is finite Consider the following fragments from Murphy's "$C^*$-algebras and operator theory":

In the above proof of theorem 2.4.5., how does theorem 1.4.11 imply that the set $S$ is finite? I guess it has something to do with the non-zero points of $\sigma(u)$ being isolated?

A: Let $x_n$ be a sequence in $S$. Since $S$ is bounded in $\Bbb C$ it is a bounded sequence and as such admits a convergent subsequence, so assume it converges. Further $|x_n|≥\epsilon$ for all $n$ so $x_n$ cannot converge to $0$. Since $S=\sigma(u)\cap \{ x\in\Bbb C\mid |x|≥\epsilon \}$ is closed the limit must also lie in $S$. But every point of $S$ is isolated and as such cannot be the limit of other points and $x_n$ must be eventually constant (ie $S$ is discrete in $\Bbb C$).
This implies $S$ is finite, for otherwise there must be a sequence without a constant subsequence.


text:
Q: How are the "limits" of infinite intersections and unions defined? How are the "limits" of infinite intersections and unions defined?
That's,
What can I use to infer what kind of set is spanned by e.g.
$$\bigcup_{i=1}^{\infty} [2 + 1/i, 5 - 1/i]$$
since to know this one would somehow have to infer the $\infty$ -limit of the above intersection, right?

A: The "limit" just is the union (or intersection). Another way, and IMO the less silly way, the above expression could be written is $\bigcup\{[2+1/i,5-1/i]:i\in \mathbb{N}\}$ (assuming $i$ ranges over $\mathbb{N}$). The notation used in your post is, I think, meant to somehow make the concept of arbitrary union or intersection familiar by analogy with the extension of ordinary addition to $\Sigma$-summation, but there's nothing deeper at work here than the notions of union/intersections themselves.


text:
Q: Appending to a line I have a certain string fruits as such:
Apples
Bananas
Pineapples

There is a carriage return \r at the end of each line, as well as at the beginning and end of the string. Using RegEx, how would I go about appending : 1 to the end of the first line Apples? I have tried the following to no avail:
re.sub("Apples(\r)", "\1:1", fruits)

My thinking was that \1 should replace what's in the brackets (\r), however everything in the pattern is being replaced.

A: What you are doing is matching "Apples\r", capturing the "\r" in the process, and then replacing the entire match with "\r:1".
For this simple example, there's no need to capture matches to \r, anyway, since the only thing that will match it is \r. You can hard code that into the replacement string.
I'll assume you want the resulting string to be "\rApples: 1\rBananas\rPineapples\r.
You can use a lookbehind so that Apples is not consumed (though I hear that consuming one a day keeps the doctor away):
re.sub("(?<=Apples)\r", ": 1\r", fruits)

But you could also just do:
re.sub("Apples\r", "Apples: 1\r", fruits)

The lookbehind would be more useful if you wanted to add : 1 after each fruit:
re.sub("(?<=[^\r])\r", ": 1\r", fruits)

The above says find every \r that follows a character that isn't an \r, and replace them with : 1\r. The result would then be:
# \rApples: 1\rBananas: 1\rPineapples: 1\r\r

A: If you do
re.sub("A(B)", "\1C", "AB")

you will get BC, because \1 is replaced by what is in the bracket.
To get AC, you should do:
re.sub("(A)B", "\1C", "AB")

A: Having \r as your fruit separator makes it awkward to print things out; so for the purposes of this answer I am going to use the @ character in its place.  The code that follows works just the same if you assign \r to my separator variable and use your actual \r separated string for fruit_str.
Some explanation follows the code.
import re

def updateFruitQuantity(the_fruit, the_quantity, fruit_str, separator):
    re_1 = r"(" + the_fruit + r")(:.*?|)" + separator
    re_2 = r'\1:' + str(the_quantity) + separator
    fruit_str = re.sub(re_1, re_2, fruit_str)
    return(fruit_str)

separator = "@"
fruit_str = "@Apples@Bananas@Pineapples@"
print(fruit_str)

fruit_str = updateFruitQuantity("Pineapples", 25, fruit_str, separator)
print(fruit_str)
fruit_str = updateFruitQuantity("Bananas", 17, fruit_str, separator)
print(fruit_str)
fruit_str = updateFruitQuantity("Pineapples", 3, fruit_str, separator)
print(fruit_str)
fruit_str = updateFruitQuantity("Apples", 94, fruit_str, separator)
print(fruit_str)
fruit_str = updateFruitQuantity("Apples", 102, fruit_str, separator)
print(fruit_str)

And here is the code's output:
@Apples@Bananas@Pineapples@

@Apples@Bananas@Pineapples:25@
@Apples@Bananas:17@Pineapples:25@
@Apples@Bananas:17@Pineapples:3@
@Apples:94@Bananas:17@Pineapples:3@
@Apples:102@Bananas:17@Pineapples:3@

I am building separate regular expressions for the target text and for the replacement text.
These target expression assumes that each fruit:quantity is followed by the separator.  There are two capture groups in the target expression -- each is surrounded by parenthesis.  The second grouping is important in the target expression because it sweeps up any :quantity element that might be present.
The replacement expression starts with \1 which stands for the text matched by the first grouping in the target expression (eg "Apples").  That is followed by the colon and then the quantity string to be used.  Doing it this way ensures that any existing :quantity is properly replaced with the new quantity and that it also works in the case where there were no existing :quantity.  So for example in our third change you see the quantity for Pineapples go back from 25 to 3.
You will need another mechanism for adding new types of fruit to fruit_str as time went on.


text:
Q: IndexError: list index out of range when if len(listx[i]) > n I apologize in advance if my question is too basic. I have also tried to find answers in previous posts, but they are not exactly what I am looking for.
I am struggling with this exercise :
Write a program that analyzes all the elements of a word list one by one (for example
example: ['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra']) for
generate two new lists. One will contain words with less than 6 characters,
the other is words of 6 characters or more.
liste1 = ['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra']

moins6 = []
plus6 = []
i = 0

while i <= 13 :

    if len(liste1[i]) > 6:
        moins6.append(liste1[i])

    else:
        plus6.append(liste1[i])

    i +=1

I receive the error " IndexError: list index out of range "
Could you suggest me the right way to write it (with while loop)
Many thanks in advance

A: liste1 = ['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra']

moins6 = []
plus6 = []

for word in liste1:
    if len(word) > 6:
        moins6.append(word)
    else: plus6.append(word)
print(moins6)
print(plus6)

output:
['Maximilien', 'Brigitte', 'Jean-Pierre']
['Jean', 'Sonia', 'Sandra']

A: according to your code your value of i is going from 0 to 13
while there are only 6 elements in your input list
so your value of i should go from 0 to 5
if you didn't know what your input size will be, you can use len() to find out
liste1 = ['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra']

moins6 = []
plus6 = []
i = 0

while i < len(liste1) : # here is your error

    if len(liste1[i]) > 6:
        moins6.append(liste1[i])

    else:
        plus6.append(liste1[i])

    i +=1
print(liste1, moins6, plus6)

['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra']
['Maximilien', 'Brigitte', 'Jean-Pierre']
['Jean', 'Sonia', 'Sandra']

A: You can iterate over the list, find the len of each elem, and append it to the appropriate list:
liste1 = ['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra']

moins6 = []
plus6 = []

for elem in liste1:
    if len(elem) < 6:
        moins6.append(elem)
    else:
        plus6.append(elem)

print(plus6)
print(moins6)

OUTPUT:
['Maximilien', 'Brigitte', 'Jean-Pierre', 'Sandra']
['Jean', 'Sonia']


text:
Q: The POST method is not supported for this route. Supported methods: GET, HEAD in Laravel Inertia I am creating a simple CRUD application for Laravel Inertia. I am using Laravel v8.24.0 (PHP v7.3.26). I try to search on internet but some of them are encounter it updating/edit data.
Lead.vue
<script>
import Layout from "../../Shared/Layout";
export default {
components: {
   Layout,
},
data() {
return {
  lead: {
    name: "",
    email: "",
    phone: "",
    dob: "",
    package: "",
  },
};
},
methods: {
async handleSubmit() {
  let res = await this.$inertia.post("/leads/save", this.lead);
},
},
};

web.php
Route::get('/', [WelcomeController::class, 'index']);
  Route::group(['middleware' => 'auth'], function () {
  Route::get('/dashboard', [DashboardController::class, 'index'])->name('dash');
  Route::get('/leads/add', [LeadController::class, 'create']);
  Route::get('/leads/save', [LeadController::class, 'store']);
});

LeadController
public function store(Request $request)
{
    $postData = $this->validate($request, [
        'name' => 'required',
        'email' => "required|email",
        'phone' => "required|phone",
        'dob' => "required|date"
    ]);
    $package = "";
    if ($request->has('package')) {
        $package = $request->input('package');
    }
    Lead::create([
        'name' => $postData['name'],
        'email' => $postData['email'],
        'phone' => $postData['phone'],
        'dob' => $postData['dob'],
        'branch_id' => 1,
        'age' => 1,
        'added_by' => Auth::user()->id,
        'interested_package' => $package
    ]);

    return redirect()->route('dash');
}

But upon saving I got an error

A: Route::post('/leads/save', [LeadController::class, 'store']);
here get to post fix this


text:
Q: dateByAddingTimeInterval method availability I use dateByAddingTimeInterval method. I checked this method on iPhone with iOS 3.1 and it's worked! But in documentation said that this method available in iOS 4.0. Why this method worked in iOS 3.1?

A: It looks like an error in the documentation. The header specifies:
- (id)dateByAddingTimeInterval:(NSTimeInterval)ti NS_AVAILABLE(10_5, 2_0);

So it's available in 10.5, and iOS 2.0. That's why it is present in iOS 3 and later.


text:
Q: SQLite OLE DB driver for C++ (MFC) I am looking for OLE DB driver to acces SQLite. Is there any? I need it to use under MFC, not .NET.
I have found this but it is .NET driver: http://CherryCitySoftware.com/ccs/Home/Default.aspx
and this but I have no references to this: http://www.newobjects.com/product.asp?Category=71
Thanks

A: You may try SQLite ODBC together with the OLE DB Provider for ODBC.


text:
Q: Не удается подключить базу данных к серверу Не удалось подключить базу данных Postgres к серверу Tomcat 10.0.27. Вот код DBConnection:
public class DBConnection {

    public static Connection getConnectionToDatabase() {
        Connection connection = null;

        try {
            System.out.println("MySQL JDBC Driver Registered!");

            connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/hplus", "postgres", "");
        }

        catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();

        }

        if (connection != null) {
            System.out.println("Connection made to DB!");
        }
        return connection;
    }

}

Вот код, где я пытаюсь получить соединение:
public class ApplicationDao {

    public List<Product> searchProducts(String searchString) {
        Product product = null;
        List<Product> products = new ArrayList<>();
        try{
            Connection connection = DBConnection.getConnectionToDatabase();

            String sql = "select * from products where product_name like '%"+searchString+"%'";

            Statement statement = connection.createStatement();

            ResultSet set = statement.executeQuery(sql);

            while(set.next()){
                product= new Product();
                product.setProductId(set.getInt("product_id"));
                product.setProductImgPath(set.getString("image_path"));
                product.setProductName(set.getString("product_name"));
                products.add(product);

            }

        }
        catch(SQLException exception){
            exception.printStackTrace();
        }
        return products;
    }

}

Вот что я получаю:
HTTP Status 500 – Internal Server Error
Type Exception Report

Message Cannot invoke "java.sql.Connection.createStatement()" because "connection" is null

Я попытался отладить код, в логах появляется следующая ошибка:
HTTP Status 500 – Internal Server Error
Type Exception Report

Message java.lang.ClassNotFoundException: com.example.jdbc.Driver

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

java.lang.RuntimeException: java.lang.ClassNotFoundException: com.example.jdbc.Driver
    com.example.demo.dao.DBConnection.getConnectionToDatabase(DBConnection.java:14)
    com.example.demo.dao.ApplicationDao.searchProducts(ApplicationDao.java:19)
    com.example.demo.servlets.SearchServlet.doGet(SearchServlet.java:30)
    jakarta.servlet.http.HttpServlet.service(HttpServlet.java:683)
    jakarta.servlet.http.HttpServlet.service(HttpServlet.java:792)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

java.lang.ClassNotFoundException: com.example.jdbc.Driver
    org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1449)
    org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1257)
    java.base/java.lang.Class.forName0(Native Method)
    java.base/java.lang.Class.forName(Class.java:383)
    java.base/java.lang.Class.forName(Class.java:376)
    com.example.demo.dao.DBConnection.getConnectionToDatabase(DBConnection.java:12)
    com.example.demo.dao.ApplicationDao.searchProducts(ApplicationDao.java:19)
    com.example.demo.servlets.SearchServlet.doGet(SearchServlet.java:30)
    jakarta.servlet.http.HttpServlet.service(HttpServlet.java:683)
    jakarta.servlet.http.HttpServlet.service(HttpServlet.java:792)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.

Добавил dependency в pom, также создал дирекорию lib в папке WEB-INF и добавил туда postgres.jar, также добавил postgres.jar в директорию tomcat/lib/, но ничего из вышеперечисленного не помогло

A: Не совсем понятно, почему в качестве драйвера для постгреса ваш код пытается загрузить явно "учебный" класс com.example.jdbc.Driver.
Попробуйте по старинке загрузить конкретный класс JDBC драйвера, для постгреса это org.postgresql.Driver:
public class DBConnection {
    static {
        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
// ...
}

Также можно попробовать отменить регистрацию "учебного" драйвера:
static {
    java.util.Enumeration<Driver> drivers =  DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver bad = drivers.nextElement();
        if (bad.getClass().getName().equals("com.example.jdbc.Driver")) {
            try {
                DriverManager.deregisterDriver(bad);
            } catch (SQLException e) {
                throw new RuntimeException("Could not deregister com.example.jdbc.Driver", e);
            }
            break;
        }
    }
}


text:
Q: Convert function pointer to std::uintptr_t at compile time I'd like to convert a constant expression function pointer to a std::uintptr_t at compile time.  How can I do this?
Here's a minimal example:
#include <cstdint>
void fn() {}
int main(int argc, char** argv) {
  constexpr void* ptr = (void *) fn;
  constexpr std::uintptr_t idx = reinterpret_cast<std::uintptr_t>(fn);
  return 0;
}

GCC 7/8/9 are currently giving me the error "conversion from pointer type to arithmetic type std::uintptr_t in a constant expression."  However, my understanding was that std::uintptr_t should be able to hold any pointer type, meaning this should be able to be done in a constant expression.
Background
To give a bit of background as to why I need this, I want to (1) retrieve the address of a function pointer at compile time, (2) convert it to a std::uintptr_t, then (3) pass it as a template parameter so it can be baked into a function at compile time.
This is meant to be part of an RPC engine, similar to this code, which produces a very similar error:
#include <cstdio>
#include <cstdint>

template <std::uintptr_t FnPtr, typename Fn>
void fn_handler() {
  ((Fn *) FnPtr)();
}

int main(int argc, char** argv) {
  auto lel = []() {
    printf("Hi, fam!\n");
  };
  // Note that +lel is an implement 0+lel, converting
  // the lambda to a fn ptr.
  constexpr void* ptr = reinterpret_cast<void*>(+lel);
  constexpr std::uintptr_t idx = reinterpret_cast<std::uintptr_t>(ptr);

  fn_handler<idx, decltype(lel)>();
  return 0;
}

A:
However, my understanding was that std::uintptr_t should be able to hold any pointer type, meaning this should be able to be done in a constant expression.

Sure. But reinterpret_cast is never allowed in a constant expression. And since that's the only way to convert a pointer into an integer, that's not something you can do at compile time.
If you want to pass a function pointer as a template parameter, then just do that:
int func() {return 0;}

template<int (*pfn)()>
int fn_handler()
{
  return pfn();
}

...

fn_handler<&func>();

If you want to make the type of the function a template parameter, then pre-C++17, you can use the old trick like this:
template<typename Fn, Fn pfn>
decltype(auto) fn_handler()
{
  return pfn();
}

...

fn_handler<decltype(&func), &func>();

C++17 lets us just use auto:
template<auto pfn>
decltype(auto) fn_handler()
{
  return pfn();
}

...

fn_handler<&func>();


text:
Q: ModuleNotFoundError: No module named 'tensorflow' error in vscode terminal while running fine in wsl I installed tensorflow using conda in wsl, and now I'm using it through Jupyter notebook and it's working fine. I also write codes in vscode and then run it through wsl using python3 filename.py and it works fine too.
the problem is when I try to run the code using the 'running' option of vscode and then I get the error ModuleNotFoundError: No module named 'tensorflow' in terminal.
I checked my environments and I only have 'base' environment so the packages should be installed there and I also tried 'conda ...' in vscode terminal and it didn't recognize conda either.
what can be the problem with my vscode?
also I have to say that numpy and matplotlib packages are running fine using vscode itself but tensorflow and some other modules are not identified

A: You need to create a new virtual environment in anaconda to install Tensorflow and can access the Visual Studio code from the same virtual environment.
Open anaconda prompt and type below code to create virtual environment
conda create -n tf tensorflow
conda activate tf

install TensorFlow in that "tf" virtual environment
pip install tensorflow

launch VS code by selecting the same "tf" virtual environment in anaconda navigator.
Now, type the below code to check if TensorFlow installed successfully in VS code.
import tensorflow as tf
print(tf.__version__)

Likewise, you can install other required packages in the same virtual environment.
pip install <package-name>


text:
Q: Replacing question mark with exclamation mark and vice versa I need to write a function that receives a sentence string and a true/false 'shouting' argument. It should return the string, replacing any question marks with exclamation marks and vice versa. If 'shouting' is true, all letters should be in uppercase.
function changeIntonation(str, isShouting) {
let myString = '';
let regExcl = /\!/;
let regQmark = /\?/;

let qMarkStr = str.replace(regQmark, '!');
let finalStr = qMarkStr.replace(regExcl, '?');

let newArr = finalStr.split('');

if(isShouting === true) {
  let upperCaseArr = newArr.map(function(char){
    return char.toUpperCase();
  })
  myString = upperCaseArr.join('');
}
return myString;

}
My code works when I try to convert Hey! How are you? to HEY?HOW ARE YOU!, but when I test Hey? How are you! it just makes it upper case and the exclamation and question mark remain unchanged.
Also !?  to ?! fails.
Any ideas? Thank you.

A: The problem is when you try to replace ! with ? and then replace ? with !, you risk replacing, by mistake, original ! and ? that existed.
To work around that, you have to replace ! and ? in one command, like (using a function argument on String#replace()):
let finalStr = str.replace(/[!?]/g, function(c) { return c === '?' ? '!' : '?'; });

Also you don't need to call .toUpperCase() on each char, you can use it on the string:

function changeIntonation(str, isShouting) {
  let finalStr = str.replace(/[!?]/g, function(c) { return c === '?' ? '!' : '?'; });

  if (isShouting === true) {
    return finalStr.toUpperCase();
  } else {
    return finalStr;
  }
}
console.log(changeIntonation("Hey! How are you?", true));
console.log(changeIntonation("Hey! How are you?", false));
console.log(changeIntonation("Hey? How are you!", true));
console.log(changeIntonation("Hey? How are you!", false));

A: Thanks to @acdcjunior, who answered just before me and I didn't notice he already answered! My code looks like his, but is a little bit more compact.
function changeIntonation(str, isShouting) {
    str = str.replace(/\?|\!/g, function(match) {
        return match == "?" ? "!" : "?";
    });
    return isShouting ? str.toUpperCase() : str;
}

First of all I noticed you're making single characters upper-case to then join them all in a whole string. Why? I just made the whole string directly upper-case.
Then I understood the problem is that when you replace question marks with exclamation marks both those before were question and exclamation marks now are only exclamation marks, so if you try replacing exclamation marks with question ones, you'll replace them all.
So I choosed to replace with a callback both question and exclamations marks and check in the callback if the occurrence is the one or the other to replace correctly.


text:
Q: How to send custom claims from Duende IdentityServer to Blazor WASM Hosted app I'm creating a Hosted Blazor WASM app that is connecting to a Duende IdentityServer app for authentication and authorization. The Blazor Server part is functioning as BFF.
The user is assigned a role and a role has permissions. I want to add those permissions as a claim so I can use it for authorization purposes in Blazor app. I'm adding the permissions in a "PermissionsClaimsPrincipalFactory". In the "PermissionClaimProfileService" I'm adding all claims off the user to the context.IssuedClaims.
When I click "Login" in the Blazor App, I'm redirected to the login page on the IdentityServer App. After login I'm redirected to Blazor and I see the claims assigned to my user. But the claims I add in my Profile Service are not shown on that page.
In my logs I can see that my Profile Service is returning all claims. But then I don't see them on the client side.
I've tried several things, but I don't see what I'm doing wrong.
This is what I see in the logs:

Profile service returned the following claim types: sub preferred_username name amr auth_time idp email AspNet.Identity.SecurityStamp http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier TenantKey Permissions email_verified

These are the claims shown in the browser:
amr
   pwd
sid
   5BB444DB7141399BFA6ED4D1A65B1AE6
sub
   5c009dae-d118-44e1-9a46-c119dcc31ff9
auth_time
   1662538078
idp
   local
name
    {Name}
email
    {Email}
bff:logout_url
    /bff/logout?sid=5BB444DB7141399BFA6ED4D1A65B1AE6
bff:session_expires_in
    1209598
bff:session_state
    EvCMn29HkOmdDzxlAqvwUGfj3u0DgxHCymQtn1tOw0U.4F818675DFBEC4B689B4E3159633443A

Blazor APP Uri: https://localhost:7111
IdentityServer Uri: https://localhost:7193
IdentityServer Client Configuration
"BlazorClient": {
   "AlwaysSendClientClaims": true,
   "ClientId": "app-blazor",
   "ClientSecrets": [
      "SuperSecretPassword"
   ],
   "ClientName": "App",
   "ClientUri": "https://localhost:7111/",
   "AllowedGrantTypes": [
      "authorization_code"
   ],
   "AllowOfflineAccess": true,
   "RedirectUris": [
      "https://localhost:7111/signin-oidc"
   ],
   "FrontChannelLogoutUri": "https://localhost:7111/signout-oidc",
   "PostLogoutRedirectUris": [
      "https://localhost:7111/signout-callback-oidc"
   ],
   "AllowedScopes": [
      "openid",
      "profile",
      "api1"
   ]
}

Identity Server Resources
 public static IEnumerable<IdentityResource> IdentityResources =>
    new List<IdentityResource>
    {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile()
    };

 public static IEnumerable<ApiScope> ApiScopes =>
    new List<ApiScope>
    {
            new ApiScope("api1", "MyAPI")
    };

Identity Server Profile Service
public class PermissionClaimProfileService : ProfileService<ApplicationUser>
{
    public PermissionClaimProfileService(UserManager<ApplicationUser> userManager, IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory,
        ILogger<ProfileService<ApplicationUser>> logger) : base(userManager, claimsFactory, logger)
    {
    }

    public override async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        await base.GetProfileDataAsync(context);

        var existingClaims = context.IssuedClaims;
        foreach(var claim in context.Subject.Claims)
        {
            if (!existingClaims.Select(c => c.Type).ToList().Contains(claim.Type))
                existingClaims.Add(claim);
        }
        context.IssuedClaims = existingClaims.ToList();
    }
}

Identity Server  Claims Principal Factory
public class PermissionClaimsPrincipalFactory<TIdentityUser> : UserClaimsPrincipalFactory<TIdentityUser>
    where TIdentityUser : IdentityUser
{
    private readonly IClaimsCalculator _claimsCalculator;

    ///
    /// Needs UserManager and IdentityOptions, plus the two services to provide the permissions and dataKey
    ///
    /// <param name="userManager"></param>
    /// <param name="optionsAccessor"></param>
    /// <param name="claimsCalculator"></param>
    public PermissionClaimsPrincipalFactory(UserManager<TIdentityUser> userManager, IOptions<IdentityOptions> optionsAccessor,
        IClaimsCalculator claimsCalculator)
        : base(userManager, optionsAccessor)
    {
        _claimsCalculator = claimsCalculator;
    }

    ///
    /// This adds the permissions and, optionally, a multi-tenant DataKey to the claims
    ///
    /// <param name="user"></param>
    /// <returns></returns>
    protected override async Task<ClaimsIdentity> GenerateClaimsAsync(TIdentityUser user)
    {
        var identity = await base.GenerateClaimsAsync(user);
        var userId = identity.Claims.GetUserIdFromClaims();
        var claims = await _claimsCalculator.GetClaimsForUser(userId);
        identity.AddClaims(claims);

        return identity;
    }
}

IdentityServer Registration
services.AddScoped<IClaimsCalculator, ClaimsCalculator>();
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, PermissionClaimsPrincipalFactory<ApplicationUser>>();
services
    .AddIdentityServer(options =>
        {
            options.KeyManagement.Enabled = true;
            options.Events.RaiseErrorEvents = true;
            options.Events.RaiseInformationEvents = true;
            options.Events.RaiseFailureEvents = true;
            options.Events.RaiseSuccessEvents = true;

            // see https://docs.duendesoftware.com/identityserver/v6/fundamentals/resources/
            options.EmitStaticAudienceClaim = true;
         })
     .AddConfigurationStore(options =>
         {
            options.ConfigureDbContext = builder => builder.UseSqlServer(Configuration.GetConnectionString("identityserver"), sql => sql.MigrationsAssembly(migrationsAssembly));
         })
     .AddOperationalStore(options =>
         {
             options.ConfigureDbContext = builder => builder.UseSqlServer(Configuration.GetConnectionString("identityserver"), sql => sql.MigrationsAssembly(migrationsAssembly));
             options.EnableTokenCleanup = true;
             options.TokenCleanupInterval = 1800;
         })
      .AddAspNetIdentity<ApplicationUser>()
      .AddProfileService<PermissionClaimProfileService>();

Blazor Server Startup Code
public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);

    // Add services to the container.

    var configuration = builder.Configuration;

    builder.Services.AddControllersWithViews();
    builder.Services.AddRazorPages();

    builder.Services.AddBff();

    builder.Services.AddAuthentication(options =>
    {
        options.DefaultScheme = "cookie";
        options.DefaultChallengeScheme = "oidc";
        options.DefaultSignOutScheme = "oidc";
    })
    .AddCookie("cookie", options =>
    {
        options.Cookie.Name = "__Host-blazor";
        options.Cookie.SameSite = SameSiteMode.Strict;
    })
    .AddOpenIdConnect("oidc", options =>
    {
        options.Authority = configuration.GetValue<string>("IdentityServer:Authority");

        options.ClientId = configuration.GetValue<string>("IdentityServer:ClientId");
        options.ClientSecret = configuration.GetValue<string>("IdentityServer:ClientSecret");
        options.ResponseType = "code";
        options.ResponseMode = "query";

        options.Scope.Clear();
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.Scope.Add("api1");

        options.MapInboundClaims = false;
        options.GetClaimsFromUserInfoEndpoint = true;
        options.SaveTokens = true;
    });

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseWebAssemblyDebugging();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();

    app.UseBlazorFrameworkFiles();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseBff();
    app.UseAuthorization();
    app.MapBffManagementEndpoints();

    app.MapRazorPages();
    app.MapControllers();
    app.MapFallbackToFile("index.html");

    app.Run();
}

Blazor Client Show Claims
<AuthorizeView>
  <Authorized>

        @foreach (var claim in @context.User.Claims)
        {

@claim.Type

@claim.Value

        }

    @if(context.User.HasPermission(Permissions.CompanyProfile_ManagePermissions)){

User has permissions to manage permissions for company profile

    }

    @if (context.User.HasPermission(Permissions.Property_Read))
    {

User has permissions to read properties

    }
  </Authorized>
  <NotAuthorized>

No session

  </NotAuthorized>
</AuthorizeView>

A: Via the related answers for this question I've found the solution for me. At least I get the claims now...
This answer led me to it: Custom Claims are not being accessed in client with identityserver 4 .Net core 2.0
AlwaysIncludeUserClaimsInIdToken = true


text:
Q: How to register a virtual card to alsa from user-space? I'm developing a virtual device from the user space
(using umview http://wiki.virtualsquare.org/wiki/index.php/UMview)
so, i need to register my device to the system's sound cards list
(I've never used alsa in a kernel module so I think that I need to call the snd_card_register() function)
but I can't find a way to do that from the userspace...
maybe I can write a syscall to do that?

A: I think you should stop bothering about overriding any particular file (i.e. stop using umview, it's not needed) and simply use the "file" plugin to create device in the ALSA config that will pipe the data to your virtual device over a named pipe in /var/run/virtualsound/output or somewhere like that.
Unlike the umview approach, this will work in all applications without having to run them in any special way.

A: I've solved this problem some times ago,
Alsa user-space lib simply open every /dev/snd/controlC# from 0 to 32 and launch
ioctl(SNDRV_CTL_IOCTL_CARD_INFO, ...);

in order to build a list with the installed sound-cards
if we mount our UmView module on /dev/snd/control# and we hijack the ioctl and answer to it, our module will be identified as a sound-card by ALSA
I've created a virtual sound device with that technique, you can find it at
https://github.com/berdav/umdevaudio
this is a simple way to build a simple user-space driver.


text:
Q: Spring Integration. Gateway reply error on outbound exception I have the next configuration:
Inbound
<int:gateway id="inGateway" service-interface="XXX"
    error-channel="errorChannel"
    default-request-channel="requestChannel"
    default-reply-channel="replyChannel" />

Outbound:
<ws:outbound-gateway id="ws-outbound-gateway"
request-channel="inbound" reply-channel="outbound"      uri="XXX" />

Chain 1:
<int:chain input-channel="requestChannel" output-channel="inbound">
XXX </int:chain>

Chain 2:
<int:chain input-channel="outbound" output-channel="replyChannel"> XXX
</int:chain>

Error:
<int:chain input-channel="errorChannel" output-channel="replyChannel">

        <int:transformer ref="logicTransformers" method="errorTransformerMethod"></int:transformer>

    </int:chain>
</beans>

Java Transformer:
final GenericError errorCatalog = errorCatalog(errorMessage);
LOGGER.warn("Transformed error from catalog: {}", errorCatalog);
final MessageBuilder<Document> builder =
MessageBuilder.withPayload(XmlUtil.parseToDocument(errorCatalog)).copyHeaders(errorMessage.getHeaders()).copyHeadersIfAbsent(errorMessage.getHeaders());

When the webservice of outbound is down the error go into errorChannel transformer but to reponse we have the next error:

o.s.m.c.GenericMessagingTemplate$TemporaryReplyChannel#242  Reply
  message received but the receiving thread has exited due to an
  exception while sending the request message:GenericMessage
  [payload=[#document: null], headers={spanTraceId=8bf90ea9ff4266c8,
  spanId=598680bae5f913d5, spanParentSpanId=8bf90ea9ff4266c8,
  replyChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@76c751de,
  functionalId=PRUEBASOA12,
  errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@76c751de,
  messageSent=true, id=2108386f-99db-98b9-3d30-3bcf45335424,
  spanSampled=1, spanName=message:requestChannel}]

We don't understand... because we have the same flow with

A: In case of error on the service level the original message is wrapped to the MessagingException and the ErrorMessage with that payload  is sent to the errorChannel. Even if you use replyChannel explicitly, you still have to ensure the replyChannel header, which is populated by the inbound gateway. And exactly this header plays the main role in the request-reply behavior in that gateway.
That replyHeader is still present in your error flow, but it is already a part of the failedMessage in the MessagingException payload.
So, your logicTransformers.errorTransformerMethod should extract that replyChannel header for the real reply from this method to be sent to the explicit replyChannel. Or you can omit this replyChannel at all because any way the real sendAndReceive is based on the replyChannel header.
Please, read more info in the Reference Manual:
https://docs.spring.io/spring-integration/docs/4.3.11.RELEASE/reference/html/messaging-endpoints-chapter.html#gateway
https://docs.spring.io/spring-integration/docs/4.3.11.RELEASE/reference/html/configuration.html#namespace-errorhandler


text:
Q: What's 'the catch' with using MaxCDN for Bootstrap? So I understand the concept of a CDN (content delivery network) in the sense that that content is delivered in a smart fashion via a distributed network of servers.
I am currently learning bootstrap, and one method for implementing it uses CDNs for the style sheets and javascript. However, I'm trying to figure out what 'the catch' is when I use MaxCDN. Why would a company allow me to use their resources freely like this?
Does MaxCDN rate limit? What's the catch?

A: There is no catch as such. The companies in question that use a CDN generally want everyone to use their product and have it available quickly and 24/7 without having to maintain their own server parks to handle the loads, so they provide their files using a CDN (that they pay for).
Some folks have an issue with trusting third parties like CDNs for hosting files necessary for the functioning of their site ("what if they're down?") so they provide a local fallback, just in case. Some howto and backgrounds here

A: Like the other poster said, there is no catch. CDN providers have access to very cheap bandwidth and providing services like this doesn't really cost them anything.
Here is a good list of free CDNS that you can utilize in your projects: https://www.keycdn.com/blog/free-cdns/


text:
Q: os.remove() in windows gives "[Error 32] being used by another process" I know this question has been asked before quiet a lot on SO and elsewhere too. I still couldn't get it done. And im sorry if my English is bad
Removing file in linux was much more simpler. Just os.remove(my_file) did the job, But in windows it gives
    os.remove(my_file)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: (file-name)

my code :
line_count = open(my_file, mode='r')        #
t_lines = len(line_count.readlines())       # For total no of lines
outfile = open(dec_file, mode='w')
with open(my_file, mode='r') as contents:
    p_line = 1
    line_infile = contents.readline()[4:]
    while line_infile:
        dec_of_line = baseconvert(line_infile.rstrip(),base16,base10)
        if p_line == t_lines:
            dec_of_line += str(len(line_infile)).zfill(2)
            outfile.write(dec_of_line + "\r\n")
        else:
            outfile.write(dec_of_line + "\r\n")
        p_line += 1
        line_infile = contents.readline()[4:]
outfile.close()
os.remove(my_file)

Here my_file is a variable that contains complete path structure of a file. Like wise dec_file also contains path, but to a new file. And the file im trying to remove is the file that's being used under read mode. Need some help please.
my try's :

*

*Tried closing the file my_file.close(). The corresponding error i got was AttributeError: 'str' object has no attribute 'close'. I knew, when a file is in
read mode it automatically closes when it comes to the end of the
file. But still i gave it a try

*Also tried by os.close(my_file) as per https://stackoverflow.com/a/1470388/3869739. i got error as TypeError: an integer is required

*Or, am i getting this error just because i have opened the file
twice (for counting the line and to read the file content),..?

A: Pythonic way of reading from or writing to a file is by using a with context.
To read a file:
with open("/path/to/file") as f:
    contents = f.read()
    #Inside the block, the file is still open

# Outside `with` here, f.close() is automatically called.

To write:
with open("/path/to/file", "w") as f:
    print>>f, "Goodbye world"

# Outside `with` here, f.close() is automatically called.

Now, if there's no other process reading or writing to the file, and assuming you have all the permission you should be able to close the file. There is a very good chance that there's a resource leak (file handle not being closed), because of which Windows will not allow you to delete a file. Solution is to use with.

Further, to clarify on few other points:

*

*Its the garbage collector that causes the closure of the stream when the object is destroyed. The file is not auto-closed upon complete reading. That wouldn't make sense if the programmer wanted to rewind, would it?

*os.close(..) internally calls the C-API close(..) that takes an integer file descriptor. Not string as you passed.


text:
Q: set cache-control in asp.net How can I set cache-control to "no-cache,no-store" in ASP.NET? Do I have to implement a cache module which caches every response, or can it be done using OutputCache in ASPX page itself?

A: Response.CacheControl = "no-cache";

Response.AddHeader("Pragma", "no-cache");

Response.AddHeader("Pragma", "no-store");

Response.AddHeader("cache-control", "no-cache");

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.Cache.SetNoServerCaching();


text:
Q: How to reorder Empathy IM Client Contact List Groups? Does anyone know how to manually rearrange the default contact list groups so they aren't in alphabetical order?
I'm using Empathy 2.30.0.1 Ubuntu 10.04.

A: I upgraded to Ubuntu 10.04 yesterday and am currently beginning to use Empathy as it is the default Ubuntu IM client now.
In the display menu of the contact list window you can sort your contacts by name or status (online, etc.).
Edit : for group sorting : select a contact in your list, edit it (right-click -> edit or edit menu -> contact -> modify or something like this, my menus are in french). You have a group section in the pop-up window to define new groups or assign a user to existing groups. I did not notice it the first time ! Not so user-friendly...
Although Empathy is new in the Ubuntu default configuration, I really appreciate the support of so many IM protocols and the gnome integration. Personally I would like to sort my contacts by IM protocol and/or groups (edit: found how to !). I'm sure we can now except lot of user feedback in the following months which will boost Empathy development : Ubuntu and Linux users community is still growing !
As it is open source, you are able to contribute to the Empathy development, at least with your user feedback. As I never did that, I cannot explain you how to do it but some nice people are certainly ready to help you !
Cheers :-)


text:
Q: RMagick convert problem In linux i'm doing the below to convert a multipage PDF into images resized and with a high resolution:
convert -verbose -colorspace RGB -resize 800 -interlace none -density 300 -quality 80 test.pdf test.jpg

For the life of me, i can't seem to reproduce this EXACT command using RMagick. I tried something like this below but the image doesn't have the size/resolution i want. Any ideas?
Magick::ImageList.new('test.pdf').each_with_index { |img, i|
  img.resize_to_fit!(800, 800)
  img.write("test-#{i}.jpg") {
    self.quality = 80
    self.density = '300'
    self.colorspace = Magick::RGBColorspace
    self.interlace = Magick::NoInterlace
  }
}

Cheers,
G.

A: Use block with quality options for method new instead of method write:
Magick::ImageList.new('test.pdf') do
  self.quality = 80
  self.density = '300'
  self.colorspace = Magick::RGBColorspace
  self.interlace = Magick::NoInterlace
end.each_with_index do |img, i|
  img.resize_to_fit!(800, 800)
  img.write("test-#{i}.jpg")
end

Not sure actually about colorspace and interlace options,
but it definitely works for quality and density.


text:
Q: error: cannot find symbol @TypeConverters({Converters_kotlin.class}) into a Room Database I was developing an App where I have the intention to keep data into a RoomDatabase.
I get the erro on the title when I try to sart my App.
I don't know if it for using a kotlin class in combination with other java class.
My kotlin file is the Converters.class with I use to keep Image into the database.
Converters.kotlin

class Converters_kotlin {

    @TypeConverter
    fun fromBitmap(bitmap:Bitmap): ByteArray{

        val outputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)

        return outputStream.toByteArray()
    }

    @TypeConverter
    fun toBitmap(byteArray: ByteArray):Bitmap{

        return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)

    }
}

Birddb.java
@Database(
        entities = {BirdRoom.class},
        version = 1
)
@TypeConverters({Converters_kotlin.class})
public abstract class Birddb extends RoomDatabase {
    private static volatile Birddb INSTANCE;
    private static final int NUMBER_OF_THREADS = 1;
    static final ExecutorService databaseWriteExecutor = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
    public abstract BirdDAO birdDAO();

    public static Birddb getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (Birddb.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            Birddb.class, "user_database")
                            .build();
                }
            }
        }
        return INSTANCE;
    }
}

And the fragment where I call the database:
CaptureFragment.java
public class CaptureFragment extends Fragment {

    private CaptureViewModel mViewModel;
    private ImageButton btnCamara;
    private ImageView mPhotoImageView;

    public static final int REQUEST_CODE_TAKE_PHOTO = 0 /*1*/;
    private String mCurrentPhotoPath;
    private Uri photoURI;
    private EditText Ettitulo;

    public static CaptureFragment newInstance() {
        return new CaptureFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        Ettitulo = (EditText) container.findViewById(R.id.EtInstantanea);

        mPhotoImageView = (ImageView) container.findViewById(R.id.imgCapture);
        mPhotoImageView.setImageDrawable(null);

        btnCamara = (ImageButton) container.findViewById(R.id.btnCapture);
        btnCamara.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //1.Open the camera.

                if (v == mPhotoImageView) {

                    if (ContextCompat.checkSelfPermission(getContext(),
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getContext(),
                            Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED) {

                        if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getContext(),
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                        } else {
                            ActivityCompat.requestPermissions((Activity) getContext(),
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    225);
                        }

                        if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getContext(),
                                Manifest.permission.CAMERA)) {

                        } else {
                            ActivityCompat.requestPermissions((Activity) getContext(),
                                    new String[]{Manifest.permission.CAMERA},
                                    226);
                        }
                    } else {
                        dispatchTakePictureIntent();
                    }
                }

                //2. Recover the photo and write into internal storage.
                //TODO: Use AlerrtDiolog para solicitar nombre de la foto.
                DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which){
                            case DialogInterface.BUTTON_POSITIVE:

                                //Send the Jornal, and keep into DB.

                                String titulo = Ettitulo.getText().toString();

                                Bundle bundle = new Bundle();
                                bundle.putString("edtValue", titulo);
                                bundle.putString("image", mCurrentPhotoPath);

                                //Swicth the () -> fragment
                                FragmentManager manager=getFragmentManager();
                                FragmentTransaction transaction=manager.beginTransaction();
                                JournalFragment jf = new JournalFragment();
                                jf.setArguments(bundle);
                                transaction.replace(container.getId(),jf);
                                transaction.commit();

                                break;

                            case DialogInterface.BUTTON_NEGATIVE:
                                //No button clicked

                                Toast.makeText(getContext(), "Foto NO añadida a su diario personal.", Toast.LENGTH_LONG).show();
                                break;
                        }
                    }
                };

                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
                        .setNegativeButton("No", dialogClickListener).show();

                Intent intento1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File foto = new File(getActivity().getExternalFilesDir(null), mCurrentPhotoPath);
                intento1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(foto));
                startActivity(intento1);

                //3. Set the photo into the ImageView,
                Bitmap bitmap1 = BitmapFactory.decodeFile(getActivity().getExternalFilesDir(null)+"/"+Ettitulo.getText().toString());

                Drawable d = new BitmapDrawable(getResources(), bitmap1);

                mPhotoImageView.setImageDrawable(d);

                //4. Ask if the user want to keep that pjoto into his jornal.

                AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
                builder1.setMessage("¿Le gustaría guardar esta foto en su diario?");
                builder1.setCancelable(true);

                builder1.setPositiveButton(
                        "Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                                //Instancio la BBDD local..
                                Birddb db = Room.databaseBuilder(getContext(),
                                        Birddb.class, "database-name").build();

                                //Añado el objeto Bird a la BBDD local.
                                BirdDAO birdDAO = db.birdDAO();
                                //List<Bird> users = userDao.getAll();
                                AsyncTask.execute(new Runnable() {
                                    @Override
                                    public void run() {

                                        //Guardar Objeto Bird en la BBDD.

                                        String descripcion = Ettitulo.getText().toString();
                                        BirdRoom bird = new BirdRoom(descripcion, mCurrentPhotoPath);
                                        Birddb.getDatabase(getContext()).birdDAO().insertBird(bird);
                                        Toast.makeText(getContext(), "Ejemplar añadido correctamente a su diario", Toast.LENGTH_LONG).show();
                                    }
                                });
                            }
                        });

                builder1.setNegativeButton(
                        "No",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Toast.makeText(getContext(), "No se ha añadido la foto actual a su diario", Toast.LENGTH_LONG).show();
                                dialog.cancel();
                            }
                        });

                AlertDialog alert11 = builder1.create();
                alert11.show();

            }
        });

        return inflater.inflate(R.layout.fragment_capture, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(CaptureViewModel.class);

    }

    private void checkExternalStoragePermission() {

        if (ContextCompat.checkSelfPermission((Activity)getContext(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            Log.e(TAG, "Permission not granted WRITE_EXTERNAL_STORAGE.");
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getContext(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            } else {
                ActivityCompat.requestPermissions((Activity) getContext(),
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        225);
            }
        }if (ContextCompat.checkSelfPermission(getContext(),
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            Log.e(TAG, "Permission not granted CAMERA.");
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getContext(),
                    Manifest.permission.CAMERA)) {

            } else {
                ActivityCompat.requestPermissions((Activity) getContext(),
                        new String[]{Manifest.permission.CAMERA},
                        226);
            }
        }

    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {

                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.TITLE, "MyPicture");
                values.put(MediaStore.Images.Media.DESCRIPTION, "Photo taken on " + System.currentTimeMillis());
                photoURI = getActivity().getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

                //Uri photoURI = FileProvider.getUriForFile(AddActivity.this, "com.example.android.fileprovider", photoFile);

                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PHOTO);

            }
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_TAKE_PHOTO && resultCode == RESULT_OK) {

            Bitmap bitmap;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), photoURI);
                mPhotoImageView.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

Ìf you guess how to solve it, take thanks for advance!
[EDIT]
Add a capture of the error return by Android Studio.


text:
Q: Add reseting index to spark dataframe I have a dataframe I would like to add an index column to reset based on one of the columns
--------------------
|  ColA   |  ColB  |
====================
|  G1     |  10    |
--------------------
|  G1     |  20    |
--------------------
|  G2     |  50    |
--------------------
|  G2     |  10    |
--------------------
|  G2     |  70    |
--------------------

I would like the result to be
-----------------------------
|  ColA   |  ColB  |  ColC  |
=============================
|  G1     |  10    |   1    |
-----------------------------
|  G1     |  20    |   2    |
-----------------------------
|  G2     |  50    |   1    |   <== reset because ColA changed
-----------------------------
|  G2     |  10    |   2    |
-----------------------------
|  G2     |  70    |   3    |
-----------------------------

Is there anything like
df.withColumn("id", monotonicallyIncreasingId)
that would be appropriate?

A: Use Window to make partitions for the column colA.
import org.apache.spark.sql.expressions.Window

val w = Window.partitionBy("ColA").orderBy("ColB")
df.withCloumn("id", row_number.over(w))

Or, if you want to keep the original order of rows,
import org.apache.spark.sql.expressions.Window

val w = Window.partitionBy("ColA").orderBy("temp")
df.withColumn("temp", monotonically_increasing_id)
  .withCloumn("id", row_number.over(w))
  .drop("temp")


text:
Q: Can any (web) application tell that the web browser is accesed from a different host via vnc or apra? If I access the desktop of a remote Lubuntu 18.04 via vnc or xpra, start a web browser in it, and open some URL to run some web applications in the browser,

*

*can any web application tell that I am accessing it from a   host different from the host running the browser?

*can any web application tell when I switch the cursor focus away from the vnc or xpra window or move other applications' windows above to partially hide its window  on my local host, while the web browser window is always on top and in focus on the remote host?
Thanks.


text:
Q: Java: GC Overhead when handling multiple files and best way to store them I have two questions here. We store a huge amount of xml files in a postgres database, as bytea. For small users, there is no problem and we can handle all the files
A user can download all his xml's in a zip file. We then retrieve all files from database (around 5000 xml files with 15kb each), zip all the files and return to frontend.
The problem is that for that amount of files we are having GC Overhead, and the system goes down sometimes.
Is there a better way to handle those files?
If it is ok, how can we avoid the GC Overhead when retrieving all files?
Thanks in advance!


text:
Q: How can this table possibly be converted to a MySql table? I got a TABLE in Excel format like:

This is a STEN TABLE containing FACTORS (A,B,C,D,E....etc)
Each Factor is like a separate test.
Each Factor i.e. Factor A has a [Raw Score] and a [Sten]
Supposing Factor A, had a question like:
-----------------------------------

Why do humans have Eyes?
The answer options could be like:

a) To Watch movies =  [Raw Score] -> 10,
b) To Read Novels  =  [Raw Score] -> 5,
c) To close them while sleeping = [Raw Score] ->0

So if they Chose a) then, the system will go to the STEN TABLE to get the STEN Equivalent under Factor A, in this case, the sten equivalent will be 4. (See Factor A->Row score 10-> Sten column)
What could be the most practical way to have this STEN TABLE with Factors and their Raw Scores and Stens created?
Smothing like
              **STEN TABLE**
                         |
                         |
                **FACTORS (A,B,C,D...)**
                      /     \
                     /       \
                    /         \
                   /           \
                  /             \
            **[Raw Score]      [Sten]**

EDIT 1:

To See a larger image, please click here: http://ctrlv.in/459785

Please note that, the stens are not equal for all Factors, though the Raw Scores are the same. i.e. in Factor A, [Raw Score]->3 = [sten]->2 but in Factor C [Raw Score]->3  = [sten]->1 and in Factor F [Raw Score]->1 [sten]->2 whereas in Factor E [Raw Score]->1 = [sten]->1.
Thank you.
Any Suggestion is highly honored.

A: I'd pull this data into two tables: Factor's and STEN Lookup's.
Your Factors table would look like:
Factor_ID(PK) | Factor_Name
--------------|------------
  1           |      A
  2           |      B
  3           |      C
  4           |      D

Your `STEN_Lookup'
Factor_ID(FK) | Score_Value | STEN_Value
--------------|-------------|-------------
  1           |       0     |       1
  1           |       1     |       1
  1           |       2     |       1
  1           |       3     |       2
  1           |       4     |       2
  2           |       0     |       8
  2           |       1     |       9
  2           |       2     |       11
.....

I'd suggest you do some reading on normalization, as it helps massivly when designing your tables. A great Video Resource is MVA, (Video 2 on this hyperlink).


text:
Q: Getting the ip address of my machine in dotted decimal with C? I'm trying to get a string with the ip address in dotted decimal of my machine. What I do is trying to get the string from INADDR_LOOPBACK with the following code.
char addr[INET_ADDRSTRLEN];
struct in_addr *in_addr1 = malloc(sizeof(struct in_addr));
in_addr1->s_addr = INADDR_LOOPBACK;
inet_ntop(AF_INET, in_addr1, addr, INET_ADDRSTRLEN);
printf("addr: %s\n", addr);

Here's what I get from the printf:

1.0.0.127

*

*Why is it the localhost address reverse? Should it print
127.0.0.1?

*Honestly I was expecting to get the ip I would get calling for
example $ ifconfig... not the localhost! Did I misunderstand what INADDR_LOOBACK does?

A: INADDR_LOOPBACK is in host byte order, i.e. 0x7f000001. It is, incidentally, the IPv4 address 127.0.0.1.
in_addr1->s_addr must be in network byte order.
Your computer is a little-endian computer where the host byte order doesn't match the network byte order. You must use htonl to convert the loopback address to network byte order.


text:
Q: JavaScript error msg : Uncaught TypeError: Cannot set property 'onclick' of null The below javascript code is displaying nothing,although this code works by Fiddle perfectly. The javascript console gives me 2 error messages which I don't understand: Failed to load resource: net::ERR_FILE_NOT_FOUND and Uncaught TypeError: Cannot set property 'onclick' of null, so anyone understands the reason of the error messages and how can I get my code worked so it will calculate & display stuff that users will choose?
The code is:
var numericalValues = new Array();
numericalValues["Alot"]= 4;
numericalValues["NotMuch"]= 2;
numericalValues["NoSometimes"]= 3;
numericalValues["Hate"]= 0;
numericalValues["Chocolate"]= 4;
numericalValues["Carrot"]= 0;
numericalValues["Both"]= 2;
numericalValues["None"]= 0;

function getScoreChoco()
{
var scoreChoco = 0;
var form = document.forms["form"];
var choco = form.elements["choco"];
for(var i=0; i<choco.length; i++)
{
    if(choco[i].checked)
    {
    scoreChoco = numericalValues[choco[i].value];
    break;
    }

}
return scoreChoco;
}

function getScoreCake()
{
var scoreCake = 0;
var form = document.forms["form"];
var cake = form.elements["cake"];

for(var i=0; i<cake.length; i++)
{
  if(cake[i].checked)
  {
  scoreCake = numericalValues[cake[i].value];
  break;
  }

}
return scoreCake;
}

function getTotal()
{

var totalScore = getScoreCake() + getScoreChoco();

document.getElementById('result').innerHTML = "Your total score is: "+totalScore;

document.getElementById('calculate').onclick=getTotal;
}

Okay the HTML code for it:
<form id="form" name="form">
<fieldset id="controls">

Do you like chocolate?
Yes a lot
<input type="radio" name="choco" id="alot" value="Alot" checked="true">

Not that much
<input type="radio" name="choco" id="notMuch" value="NotMuch">
No, but still I don't mind eating it sometimes
<input type="radio" name="choco" id="noSometimes" value="NoSometimes">

 No, I hate it
<input type="radio" name="choco" id="hate" value="Hate">

Do you prefer chocolate cake or carrot cake?
chocolate
<input type="radio" name="cake" id="chocolate" value="Chocolate" checked="true">

Carrot
<input type="radio" name="cake" id="carrot" value="Carrot">

Both
<input type="radio" name="cake" id="both" value="Both">

None
<input type="radio" name="cake" id="none" value="None">

  <input type="button" name="Calculate" id="calculate" value="Calculate" />

    </form>

A: I'm guessing that your javascript code is located above the HTML code. Therefore, when you try to access document.getElementById('calculate'), the html code has not been parsed yet, so there is no element with id calculate yet, so it returns undefined. Try putting the javascript code at the end of the body tag instead of wherever it is (probably in the head tag, im guessing)


text:
Q: How to send CTRL+C to a VPS through JS I was wondering how I can send CTRL+C to my VPS by pressing a key such as V.
This is the code that I currently have for my userscript (tampermonkey):
       break;
        case 86:
            socket.emit("cmd", {
        "stop": "^C"

Currently, When the key V is pressed, it sends this line of text to my console :

{ stop: '^C' }

I want it to only send ^C (which is CTRL+C) so it will stop my script. is there a way I can do this? thanks!
EDIT
 i also have another .js file that connects to the userscript, and can send data that way!

A: How you connect with your VPS? By PUTTY or bash shell? If yes, there is shortcut ctrl + shift + c to copy resource.


text:
Q: Unable to do Stacking for a Multi-label classifier I am working on a multi-label text classification problem (Total target labels 90). The data distribution has a long tail and class imbalance and around 100k records. I am using the OAA strategy (One against all). I am trying to create an ensemble using Stacking.
Text features : HashingVectorizer(number of features 2**20, char analyzer)
TSVD to reduce the dimensionality (n_components=200).
text_pipeline = Pipeline([
    ('hashing_vectorizer', HashingVectorizer(n_features=2**20,
                                             analyzer='char')),
    ('svd', TruncatedSVD(algorithm='randomized',
                         n_components=200, random_state=19204))])

feat_pipeline = FeatureUnion([('text', text_pipeline)])

estimators_list = [('ExtraTrees',
                    OneVsRestClassifier(ExtraTreesClassifier(n_estimators=30,
                                                             class_weight="balanced",
                                                             random_state=4621))),
                   ('linearSVC',
                    OneVsRestClassifier(LinearSVC(class_weight='balanced')))]
estimators_ensemble = StackingClassifier(estimators=estimators_list,
                                         final_estimator=OneVsRestClassifier(
                                             LogisticRegression(solver='lbfgs',
                                                                max_iter=300)))

classifier_pipeline = Pipeline([
    ('features', feat_pipeline),
    ('clf', estimators_ensemble)])

Error
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-41-ad4e769a0a78> in <module>()
      1 start = time.time()
----> 2 classifier_pipeline.fit(X_train.values, y_train_encoded)
      3 print(f"Execution time {time.time()-start}")
      4

3 frames
/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py in column_or_1d(y, warn)
    795         return np.ravel(y)
    796
--> 797     raise ValueError("bad input shape {0}".format(shape))
    798
    799

ValueError: bad input shape (89792, 83)

A: StackingClassifier does not support multi label classification as of now. You could get to understand these functionalities by looking at the shape value for the fit parameters such as here.
Solution would be to put the OneVsRestClassifier wrapper on top of StackingClassifier rather on the individual models.
Example:
from sklearn.datasets import make_multilabel_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.svm import LinearSVC
from sklearn.ensemble import StackingClassifier
from sklearn.multiclass import OneVsRestClassifier

X, y = make_multilabel_classification(n_classes=3, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size=0.33,
                                                    random_state=42)

estimators_list = [('ExtraTrees', ExtraTreesClassifier(n_estimators=30,
                                                       class_weight="balanced",
                                                       random_state=4621)),
                   ('linearSVC', LinearSVC(class_weight='balanced'))]

estimators_ensemble = StackingClassifier(estimators=estimators_list,
                                         final_estimator = LogisticRegression(solver='lbfgs', max_iter=300))

ovr_model = OneVsRestClassifier(estimators_ensemble)

ovr_model.fit(X_train, y_train)
ovr_model.score(X_test, y_test)

# 0.45454545454545453


text:
Q: issue with javascript condition I am fetching rank count from Html class and I want to show the result on base on rank count
there are 5 questions which  have these 4 options
which have Html like below

var $ = jQuery;
var rank = 0;
 var i;
var x = $(".que").toArray();
var length = x.length+1;
for (i = 1; i < length; i++) {

  var rank_count = ($('.que' + i).find(".selected_answer").attr("class").split(/\s+/));
  //var rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_',''));

  if (i == 5 && rank_count[1] == 'rank_1') {
    rank = parseInt(16);
    //console.log(rank);
  } else {
    rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_', ''));
    //
    console.log(rank);
  }

}
// if rank between 0-4 then show this
if (rank >= parseInt(0) && rank <= parseInt(4)) {
  $('.result').find(".blog1").css('display', 'flex');
}
// if rank between 5-8 then show this
if (rank >= parseInt(5) && rank <= parseInt(8)) {
  $('.result').find(".blog2").css('display', 'flex');
}
// if rank between 9-12 then show this
if (rank >= parseInt(9) && rank <= parseInt(12)) {
  $('.result').find(".blog3").css('display', 'flex');
}
// if rank between 13-16 then show this
if (rank >= parseInt(13) && rank <= parseInt(16)) {
  $('.result').find(".blog4").css('display', 'flex');
}

question1

Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4

question2

Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4

question3

Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4

question4

Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4

question5

Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4

in this, I have set condition if que5 has selected answer rank_1 then set rank 16 else rank count as per selected answer.
but when I set the selected answer as per
if (i == 5 && rank_count[1] == 'rank_1')
    {
        rank = parseInt(16);
       console.log(rank);
    }else{
       rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_',''));
       console.log(rank);
    }

it is not showing proper result or showing 2 result blog3 or blog4
I don't know why is this happen
can anybody help me with this

A: Changes are needed at three places.
1. define length variable as var length = $("p[class^='que']").length;
2. In HTML
  tag should end after all span elements, only then $('.que' + i).find(".selected_answer") will be able to find span with .selected_answer class
3. condition inside for loop should include <= so that it reaches till 5

//var $ = jQuery;
var rank = 0;
var length = $("p[class^='que']").length;

for (i = 1; i <= length; i++) {

  var rank_count = ($('.que' + i).find(".selected_answer").attr("class").split(/\s+/));
  //var rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_',''));

  if (i == 5 && rank_count[1] == 'rank_1') {
    rank = parseInt(16);

    //console.log(rank);
  } else {
    rank = parseInt(rank) + parseInt(rank_count[1].replace('rank_', ''));
    //
    console.log(rank);
  }

}
alert(rank);
// if rank between 0-4 then show this
if (rank >= parseInt(0) && rank <= parseInt(4)) {
  $('.result').find(".blog1").css('display', 'flex');
}
// if rank between 5-8 then show this
if (rank >= parseInt(5) && rank <= parseInt(8)) {
  $('.result').find(".blog2").css('display', 'flex');
}
// if rank between 9-12 then show this
if (rank >= parseInt(9) && rank <= parseInt(12)) {
  $('.result').find(".blog3").css('display', 'flex');
}
// if rank between 13-16 then show this
if (rank >= parseInt(13) && rank <= parseInt(16)) {
  $('.result').find(".blog4").css('display', 'flex');
}

question1
Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4

question2
Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4

question3
Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4

question4
Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4

question5
Simple Blog 1
Simple Blog 2
Simple Blog 3
Simple Blog 4


text:
Q: Returning multiple rowsets from SQL Server using a stored procedure via an ASP.NET Core Web API I'm new to C#, .NET Core and middleware in general, just to manage the expectation of the code included.
Regardless I have managed to build a very basic API which takes in a param, runs a stored procedure using that param and returns a single 'table' result. The stored procedure produces two rowsets however, only one makes it all the way back through the API and I have not been able to figure out why.
The rowsets are not relational, one simply has values that were calculated using the raw data which is returned in the second one stored procedure output.
Have tried a few things including setting MultipleActiveResultSets=True but the issue is probably with the and I have not been able to find a solution that works for me. Would be great if someone was able to point me in the right direction.
API output
[
  {
    "pcd": "BA1 1UA",
    "crimesInArea": 711,
    "density": 37.1,
    "crimeScore": 1916
  }
]

ASP.NET Core 5 web app components
Connection string
"MyConn": "Server=Server,1433;Initial Catalog=HouseValueChecker;Persist Security Info=False;User ID=user;Password=password;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"

Output table mapping
[Keyless]
public class Outputs
{
    //[Key]
    public string pcd { get; set; }
    public int CrimesInArea { get; set; }
    public double Density { get; set; }
    public int CrimeScore { get; set; }
}

public class CrimeList
{
    public string Crime_Type { get; set; }
    public float Latitude { get; set; }
    public float Longitude { get; set; }
}

Context
public class CallSPDBContext : DbContext
{
    public CallSPDBContext(DbContextOptions<CallSPDBContext> options):base(options)
    {
    }

    public DbSet<MoveHereAPI.Models.DB.Outputs> Outputs { get; set; }
    public DbSet<MoveHereAPI.Models.DB.Outputs> CrimeList { get; set; }
}

Controller
[HttpPost]
public async Task<ActionResult<IEnumerable<Outputs>>> GetOutputs(Input input)
{
    string storedProc = "exec usp_GetCrimeData " + "@Postcode = '" + input.Postcode + "'";
    return await _context.Outputs.FromSqlRaw(storedProc).ToListAsync();
}

A: Try this
var postCodeParam = new SqlParameter("@Postcode",input.Postcode);

 return await _context.Outputs.FromSqlRaw("exec usp_GetCrimeData  @Postcode",postCodeParam).ToListAsync();


text:
Q: Re-using Total Commander's Viewer plugins in standalone applications outside TC - can it be done? Is there a way to use plugins written for Total Commander in my own C# application?
I'm specifically interested in, for example, the viewer plugins e.g. ImgView, ArcView and CAD View.

A: The easiest way how to use plugins originally written for Total Commander in your own C# application would certainly be the following:
See
http://www.ghisler.ch/board/viewtopic.php?t=25751&sid=23d738091055d84ee97d12cef09b82a7
for a detailed description of all of the plugin functions which the host application (usually being the Total Commander program) can call after loading the plugi DLL. Notice that despite of their somewhat unusual file name extensions (.wlx or .wfx or .wcx etc.) these TC plugins are just ordinary DLLs (dynamic link libraries) which have simply been renamed accordingly.
An example of calling TC plugin functions from other programs is the UniversalViewer program available for downlod from the  www.uvviewsoft.com  web site.
Good luck!
Michael Diegelmann
(author of the TC lister plugin ImgView)

A: If you know an API why not? As long as Total Commander uses those plugins theoretically you should be able to do the same as well.
Here is a good example of Writing a Total Commander plug-in in Visual Basic (or C#)
So perhaps, after a deep investigation, you will be able to write your own plugin?


text:
Q: Mongo import saves all data under a single object I ran a mongo import command to import my json file, but all the data got saved under a single object.
mongoimport -d DB NAME -c COLLECTION NAME --type json --file FILE PATH --host MY MONGO LAB HOST --port 27892 -u MYUSER -p MYPASSWORD

But now when i see the db in mongorobot

JSON
 {
"-Kbr7KouYOL_a9NIAyPV" : {
"correctas" : [ 1 ],
"creator_name" : "kk",
"game_name" : "Elrubius",
"jugado" : 62,
"opciones1" : [ "Por usar una pistola falsa" ],
"opciones2" : [ "Por matar" ],
"opciones3" : [ "Por robar" ],
"opciones4" : [ "Por estar tomando alcol" ],
"preguntas" : [ "Elrubius porque fue detenido" ],
"premium" : false
},
"-Kbr8RJMSCv95m6TS4Of" : {
"correctas" : [ 2 ],
"creator_name" : "CRIATURITA",
"game_name" : "ELRUBIOSOMG",
"jugado" : 34,
"opciones1" : [ "Carlos" ],
"opciones2" : [ "Ruben" ],
"opciones3" : [ "Jorge" ],
"opciones4" : [ "Chavez" ],
"preguntas" : [ "Como se llama elrubiusomg?" ],
"premium" : false
},

*

*Is wrong to store all the data under a single object?

*How can i avoid this?

Thanks

A: The issue is that you combined documents into a single document.
Your formatting (indentation) hides what you're doing. But... this is what you are using, in your question (with some properties removed for brevity):
{
    "-Kbr7KouYOL_a9NIAyPV": {
        "creator_name": "kk",
        "game_name": "Elrubius",
        "jugado": 62,
        "premium": false
    },
    "-Kbr8RJMSCv95m6TS4Of": {
        "creator_name": "CRIATURITA",
        "game_name": "ELRUBIOSOMG",
        "jugado": 34,
        "premium": false
    }
}

This is just going to give you one giant document with lots of subdocuments. And eventually, you will exceed the size of a single document.
Also, the way you constructed your JSON, it's creating unique property names for each document:

*

*-Kbr7KouYOL_a9NIAyPV

*-Kbr8RJMSCv95m6TS4Of
I doubt that was your intent; you'll never be able to query across that, since every document has a unique property name.
You need to fix your JSON to represent several separate documents. And fix that unique id so it's queryable. Something like:
{
    "id": "-Kbr7KouYOL_a9NIAyPV",
    "creator_name": "kk",
    "game_name": "Elrubius",
    "jugado": 62,
    "premium": false
}
{
    "id": "-Kbr8RJMSCv95m6TS4Of",
    "creator_name": "CRIATURITA",
    "game_name": "ELRUBIOSOMG",
    "jugado": 34,
    "premium": false
}

You can then import this set of documents.
Note that, in my example, I added an id property. MongoDB creates a unique _id property if you don't specify one. So, if you want to override MongoDB's guaranteed-unique property, you can replace id with _id in the example above.

A: I have quickly recognized that this is a Firebase database format. What a mess ? You pay them to extract your db and this is what they give you. I am in the same shoes with you :-( I can't fix a 2 GB json file to make it compatible with Mongo.


text:
Q: background thread blocks the UI thread for few seconds I'm working on an application, and I'm using esri mechanisms for mapping services. I created a background thread, that loops through layers, executing spatial query on each layer to get back a list of features. but the background thread seems to block the UI thread for a couple of seconds and then start executing as required.
and the background thread periodically updates the UI thread.
I'm using background worker for this operation. thanks in advance


text:
Q: Disable MaskedTextBox sound I use a MaskedTextBox control to facilitate the entry of dates in my project. I have mtb.BeepOnError set to false. However, it makes a generic beep whenever the 'Enter' key or 'Esc' key is pressed, and this is undesirable for my application.
This seems to be the default behaviour for the MTB, so is there any way to change that?

A: You can try something like this:
void mtb_KeyDown(object sender, KeyEventArgs e) {
  if (e.KeyCode == Keys.Enter | e.KeyCode == Keys.Escape) {
    e.SuppressKeyPress = true;
  }
}


text:
Q: Methods of approximation I am trying to approximate a point using the dataset below, this hypothetical sample shows fuel consumption at different speeds, suppose I would like to approximate fuel consumption at $80\,\mathrm{km}$ or $120\,\mathrm{km}$, I've read several tutorials on linear approximation but I only seem to confuse this more as I am not sure what the computed $\Delta$ should be when the rate of change is not a constant.
$$
\begin{array}{|c|c|c|c|}
\hline
\text{speed} & 50\,\mathrm{km} & 100\,\mathrm{km} & 150\,\mathrm{km} & 200\,\mathrm{km}  \\ \hline
\text{gas} & 12\,\mathrm{l} & 32\,\mathrm{l} & 56\,\mathrm{l} & 81\,\mathrm{l} \\ \hline
\end{array}
$$

A: Just use linear interpolation in the appropriate interval: $[50,100]$ for $80$ and $[100,150]$ for $120$.
For instance,
$$
f(80) = f(50) + (f(100-f(50))\frac{80-50}{100-50}
$$

A: When the rate of change is not a constant, you may want to model your data with a polynomial that is not linear, so it has an order greater than one.
Since the values of $x$ are equally spaced, Newton's method is well suited to find this interpolating polynomial $p(x)$. To fit four points, a third order polynomial will suffice.
We shall normalize the values of $x$ using $\dfrac{x}{50}$ instead, so as to work with small numbers.
Let us compute the first differences of $y$: $32-12, 56-32, 81-56$
$$20, 24, 25,$$
second differences $\dfrac{24-20}{2}, \dfrac{25-24}{2}$
$$2, \dfrac{1}{2}$$
and third difference $\dfrac{\dfrac{1}{2}-2}{3}$
$$ -\frac{1}{2}$$
to build the normalized polynomial
$$\begin{align}
p_n(x)&=12+20(x-1)+2(x-1)(x-2)-\frac{1}{2}(x-1)(x-2)(x-3)\\
&=-\frac{1}{2}x^3+5x^2+\frac{17}{2}x-1\\
\end{align}$$
and then undo the normalization with
$$p(x)=p_n\left(\frac{x}{50}\right),$$
so
$$p(x)=-\frac{1}{250000}x^3+\frac{1}{500}x^2+\frac{17}{100}x-1$$
We may want to check now that the polynomial is correct, so $p(50)=12, p(100)=32, p(150)=56$ and $p(200)=81$.
Finally, an estimated value of the function for $x=80$ is found to be
$$p(80)=-\frac{1}{250000}80^3+\frac{1}{500}80^2+\frac{17}{100}80-1=\frac{2919}{125}=23.352l$$


text:
Q: Run MSAccess pass through query thats runs SQL stored proc asynchronously As title says trying to run pass through query asynchrnously.
I have tried
db.Execute "QrySSRSOneParameter", dbRunAsync

but this doesnt work.
So I found this code that passes the SQL statement through.
I run the following code but a get a
Could not find stored procedure 'sptest'.

It does exist.
Set ws = DBEngine.CreateWorkspace("ODBCWorkspace", "LESTERASSOCIATE\Malcolm", "access", dbUseODBC)
Set myconn = ws.OpenConnection("TestConnection", dbRunAsync, False, connstring)
Set myqry = myconn.CreateQueryDef("", "EXECUTE sptest")
myconn.Execute "EXECUTE sptest", dbRunAsync
Set myconn = Nothing
Set ws = Nothing

A: just looking at this code briefly and one thing struck me.
you're setting your connection then creating a query def... then not using the query def
shouldn't the execute line read
myqry.execute(dbRunAsync)


text:
Q: How the precision for floating point numbers 0.1 and 0.5 varies in c I have attached two programs. I got the programs from a web portal. Could you tell the explanation for the same?
Program 1:
#include<stdio.h>

int main()
{
    float x = 0.4;
    if (x == 0.4)
        printf("\n if");
    printf("\n sizeof(0.4) : %d sizeof(x) : %d",sizeof(0.4) , sizeof(x));
    return 0;
}

Program 2:
#include<stdio.h>

int main()
{
    float x = 0.5;

    if (x == 0.5)
        printf("\n if") ;
    printf("\n sizeof(0.5) : %d sizeof(x) : %d",sizeof(0.5) , sizeof(x));
    return 0;
}

For Program 1, I got the output as:
sizeof(0.4) : 8 sizeof(x) :4

For Program 2, I got the output as:
if
sizeof(0.5) : 8 sizeof(x) :4

What is the difference between these two programs executions?
This is not a duplicate of the old posted question....
I need the explanation why if is condition got passed for the value of xin multiples of 5

A: if(x == 0.4) // here you are comparing float values with double
 printf("\n if") ;

so in this case implicit type casting will occur internally, at that time float value will converted in to double.(while converting float value into double it will put 0 for lower 32 bits. so condition fails)
if(x == 0.4f)
 printf("\n if") ; // now it will print if

Normally When you give sizeof(0.4), it will treat 0.4 as double. for float give sizeof(0.4f), Now it will give output sizeof(0.4): 4


text:
Q: therubyracer on windows - how to change gem file? I want to run a heroku server and after installing ruby and ruby gems, wanted to run ' bundle install'.
I received a compile error when trying to install therubyracer and realised it is because therubyracer does not run on windows from here. It is suggested on other several questions to change the gem file to not include therubyracer on windows, and instead use execjs. I downloaded execjs, but how do I change the gem file?
this is my current gem file:
source 'https://rubygems.org'

gem 'sinatra'
gem 'sinatra-contrib'
gem 'heroku'

group :development do
   gem 'less'
end

these are suggestions made here and here
gem 'therubyracer-heroku', '~> 0.8.1.pre3', :platform => :ruby
gem 'therubyracer', :platform => :ruby

I tried inserting either of these lines, which did not work (running 'bundle install' still attempted to install therubyracer and failed.) So I suspect I must add the :platform => :ruby else where.
Can anyone point me to how to modify my gem file to fix this problem?
Thank you!
ps: using Ruby 1.9.3.

A: If you are only using therubyracer for asset compilation, and you are deploying to cedar, then you can now leave both of those gems out of your Gemfile and heroku will do the right thing.
From the heroku documentation:

If you were previously using therubyracer or therubyracer-heroku,
  these gems are no longer required and strongly discouraged as these
  gems use a very large amount of memory.


text:
Q: What's the maximum value for major and minor for iBeacon transmitter? Question:
1) What's the maximum value for major and minor for iBeacon transmitter?
2) I'm using only one UUID, is there a limit for startRangingBeaconsInRegion to detect the major and minor value?

A: Both Major and Minor is 16bits. So the maximum major/minor is 65535.