text:
Q: Setting dllimport programmatically in C# I am using DllImport in my solution.
My problem is that I have two versions of the same DLL one built for 32 bit and another for 64 bit.
They both expose the same functions with identical names and identical signatures.
My problem is that I have to use two static methods which expose these and then at run time use IntPtr size to determine the correct one to invoke.
private static class Ccf_32
{
    [DllImport(myDllName32)]
    public static extern int func1();
}

private static class Ccf_64
{
    [DllImport(myDllName64)]
    public static extern int func1();
}

I have to do this because myDllName32 and myDllName64 must be constant and I have not found a way to set it at run time.
Does anyone have an elegant solution for this so I could get rid of the code duplication and the constant IntPtr size checking.
If I could set the file name, I would only have to check once and I could get rid of a ton of repeated code.

A: I prefer to do this by using the LoadLibrary call from kernel32.dll to force a particular DLL to load from a specific path.
If you name your 32-bit and 64-bit DLLs the same but placed them in different paths, you could then use the following code to load the correct based on the version of Windows you are running.  All you need to do is call ExampleDllLoader.LoadDll() BEFORE any code referencing the ccf class is referenced:
private static class ccf
{
    [DllImport("myDllName")]
    public static extern int func1();
}

public static class ExampleDllLoader
{
    [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
    private extern static IntPtr LoadLibrary(string librayName);

    public static void LoadDll()
    {
        String path;

        //IntPtr.Size will be 4 in 32-bit processes, 8 in 64-bit processes
        if (IntPtr.Size == 4)
            path = "c:/example32bitpath/myDllName.dll";
        else
            path = "c:/example64bitpath/myDllName.dll";

        LoadLibrary(path);
    }
}

A: Why not wrap them into a method?
private static class ccf_32_64
{
    private static class ccf_32
    {
        [DllImport(myDllName32)]
        private static extern int func1();
    }

    private static class ccf_64
    {
        [DllImport(myDllName64)]
        private static extern int func1();
    }

    public static int func1()
    {
        if (32bit)
        {
            return ccf_32.func1();
        }
        else
        {
            return ccf_64.func1();
        }
    }
}

A: One alternative option is to have both the 32- and 64-bit versions of the unmanaged DLL have the same name, but have them live in separate folders in your build output (say, x86\ and x64\).
Then, your installer or however else you're distributing this is updated so it knows to install the proper DLL for the platform it's installing on.

A: You can probably achieve this with the #if keyword. If you define a conditional compiler symbol called win32, the following code will use the win32-block, if you remove it it will use the other block:
#if win32
    private static class ccf_32
    {
        [DllImport(myDllName32)]
        public static extern int func1();
    }
#else
    private static class ccf_64
    {
        [DllImport(myDllName64)]
        public static extern int func1();
    }
#endif

This probably means that you can remove the class wrapping that you have now:
    private static class ccf
    {
#if win32
        [DllImport(myDllName32)]
        public static extern int func1();
#else
        [DllImport(myDllName64)]
        public static extern int func1();
#endif
    }

For convenience, I guess you could create build configurations for controlling the compilation symbol.

A: I know this is a really old question (I'm new - is it bad to answer an old question?), but I just had to solve this same problem.  I had to dynamically reference a 32-bit or 64-bit DLL based on OS, while my .EXE is compiled for Any CPU.
You can use DLLImport, and you don't need to use LoadLibrary().
I did this by using SetDLLDirectory.  Contrary to the name, SetDLLDirectory adds to the DLL search path, and does not replace the entire path.  This allowed me to have a DLL with the same name ("TestDLL.dll" for this discussion) in Win32 and Win64 sub-directories, and called appropriately.
public partial class frmTest : Form
{
    static bool Win32 = Marshal.SizeOf(typeof(IntPtr)) == 4;
    private string DLLPath = Win32 ? @"\Win32" : @"\Win64";

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool SetDllDirectory(string lpPathName);
    [DllImport("TestDLL.dll", SetLastError = true)]
    static extern IntPtr CreateTestWindow();

    private void btnTest_Click(object sender, EventArgs e)
    {
        string dllDir = String.Concat(Directory.GetCurrentDirectory(), DLLPath);
        SetDllDirectory(dllDir);

        IntPtr newWindow = CreateTestWindow();
    }
}

A: you can create two methods and choose one in a runtime, so you can keep Any CPU
public static class Ccf
{
    [DllImport(myDllName32)]
    private static extern int func32();

    [DllImport(myDllName64)]
    private static extern int func64();

    public static int func()
    {
        if(Environment.Is64BitProcess)
        {
            return func64();
        }
        return func32();
    }

}

A: You can't do this the way you want. You need to think of the DllImport attribute as metadata that is used at compile time. As a result you can't change the DLL it is importing dynamically.
If you want to keep your managed code targeted to "Any CPU" then you either need to import both the 32-bit and 64-bit libraries wrapped as two different functions that you can call depending on the runtime environment or use some additional Win32 API calls to late-load the correct version of the unmanaged assembly at runtime and additional Win32 calls to execute the required methods. The drawback there is that you won't have compile time support for any of that type of code for type safety, etc.

A: Hmm, I'm wondering if you could create an interface and then a class with the methods based on the 32 bit and 64 bit dlls.
I'm not sure if there is an explicit method to determine if you are running 64 bit, but the following might work: allow unsafe code and have an unsafe function that gets a pointer to some address and then determine whether the pointer is 4 or 8 bytes in size.  Based on the result determine which implementation of the interface to create.

A: You can determine whether you are running 64Bits or not by checking the size of the IntPtr type (which is called native int anyways).
Then you can load the approriate DLL using an imported LoadLibraryW call, get the function pointer using GetProcAddress, and then, check out Marshal.GetDelegateForFunctionPointer
This not nearly as complicated as it might look like. You have to DllImport both LoadLibraryW and GetProcAddress.


text:
Q: Resend Confirmation Email if not sent to customers I have the code that is sending confirmation email to customers on new account registration. I want the button on my page that customers can use to resend email confirmation link to their email if email previously not received by them
Not tried yet I'm new to .NET MVC, it's NopCommerce based.
public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {

        // Plug in your email service here to send an email.
        string text = message.Body;
        string html = message.Body;
        //do whatever you want to the message
        MailMessage msg = new MailMessage();
        msg.From = new MailAddress("support@easypostagelabels.com");
        msg.To.Add(new MailAddress(message.Destination));
        msg.Subject = message.Subject;
        msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
        msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));

        SmtpClient smtpClient = new SmtpClient("easypostagelabels.com", 25);// Convert.ToInt32(25));//587
        smtpClient.EnableSsl = false;
        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("support@easypostagelabels.com", "Admin@1234");
        smtpClient.Credentials = credentials;
        try
        {

            smtpClient.Send(msg);
            string texterr = "success";
            // WriteAllText creates a file, writes the specified string to the file,
            // and then closes the file.    You do NOT need to call Flush() or Close().
            System.IO.File.WriteAllText(HttpContext.Current.Server.MapPath("/Content/error.txt"), texterr);
        }
        catch (System.Net.Mail.SmtpException E)
        {
            string texterr = E.Message;
            // WriteAllText creates a file, writes the specified string to the file,
            // and then closes the file.    You do NOT need to call Flush() or Close().
            System.IO.File.WriteAllText(HttpContext.Current.Server.MapPath("/Content/error.txt"), texterr);
        }
        return Task.FromResult(0);
    }
}

guide me about code that customers use to resend email confirmation link

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use cppunit just like junit --- two mains I know that the unit test for Java is very simple. We just need use JUnit and run test classes as JUnit test.
Now I'm working with C++ and I find a test library: cppunit.
It seems that I need to run my test with a specific function main.
However, a cpp project can have ONLY ONE main.
What should I do? I have to switch mains when I do my test and when I run my project?

A:
What should I do? I have to switch mains when I do my test and when I run my project?

You should separate the code to test into a library project, that can be linked from your target application and the unit test runner.
Then have two more projects providing a main() function:

*

*one for the target app, that just forwards main() implementation to a call of a MyTargetApp class member function, e.g. MyTargetApp::run()

*one for the unit testing, that calls a TestRunner, and contains all of the test suite and fixture classes (including these for the MyTargetApp).

The target application project can be configured without linking against the cppunit library and your test suite/fixture implementations (which will certainly reduce the final artifacts footprint).

However, a cpp project can have ONLY ONE main.

Another option is to use just one project with a narrow main() function that can be compiled using a conditional preprocessor statement (as from their example on the TestRunner class):
 #ifdef TESTING
 int runUnitTests(int argc, char* argv[]);
 #endif

 int main(int argc, char* argv[]) {

 #ifdef TESTING
     // run the unit tests
     // -----------------------------------------------------------------
     return runUnitTests(argc,argv);
 #else
     // run the application
     // -----------------------------------------------------------------
     MyTargetApp app;
     return app.run(argc,argv);
 #endif

 #ifdef TESTING
 int runUnitTests(int argc, char* argv[]) {
   std::string testPath = (argc > 1) ? std::string(argv[1]) : "";

   // Create the event manager and test controller
   CppUnit::TestResult controller;

   // Add a listener that colllects test result
   CppUnit::TestResultCollector result;
   controller.addListener( &result );

   // Add a listener that print dots as test run.
   CppUnit::TextTestProgressListener progress;
   controller.addListener( &progress );

   // Add the top suite to the test runner
   CppUnit::TestRunner runner;
   runner.addTest( CppUnit::TestFactoryRegistry::getRegistry().makeTest() );
   try {
     std::cout << "Running "  <<  testPath;
     runner.run( controller, testPath );

     std::cerr << std::endl;

     // Print test in a compiler compatible format.
     CppUnit::CompilerOutputter outputter( &result, std::cerr );
     outputter.write();
   }
   catch ( std::invalid_argument &e ) {
     // Test path not resolved
     std::cerr  <<  std::endl
                <<  "ERROR: "  <<  e.what()
                << std::endl;
     return 0;
   }

   return result.wasSuccessful() ? 0 : 1;
 }
 #endif

Then have 2 different project configurations, one that defines TESTING and one without.
One disadvantage of this solution is though, you'll get all the unit test suites and fixtures left in your program, because cppunit macros will register and instantiate them automatically, regardless if the will be called from the execution path.


text:
Q: How to distribute a survey form through WhatsApp? How can I send this survey form link to many WhatsApp contacts (mainly small business owners and shop-keepers)

A: I've been able to do this successfully by simply adding the URL of the survey into a WhatsApp message. This isn't the most efficient option for a large survey audience but it will solve the problem. Using the WhatsApp Web interface made this easier than doing it on a phone/tablet.
Also, these resources might be useful:

*

*https://faq.whatsapp.com/iphone/how-to-link-to-whatsapp-from-a-different-app

*https://developers.facebook.com/docs/whatsapp/


text:
Q: Scrapy: How to limit number of urls scraped in SitemapSpider I'm working on a sitemap spider. This spider gets one sitemap url and scrape all urls in this sitemap. I want to limit the number of urls to 100.
I can't use CLOSESPIDER_PAGECOUNT because I use XML export pipeline.
It seems that when scrapy gets to the pagecount, it stops everything including XML generating. So the XML file is not closed etc. it's invalid.
class MainSpider(SitemapSpider):
    name = 'main_spider'
    allowed_domains = ['doman.com']
    sitemap_urls = ['http://doman.com/sitemap.xml']

    def start_requests(self):
        for url in self.sitemap_urls:
            yield Request(url, self._parse_sitemap)

    def parse(self, response):
        print u'URL: {}'.format(response.url)
        if self._is_product(response):
            URL = response.url
            ITEM_ID = self._extract_code(response)

    ...

Do you know what to do?

A: If you are using SitemapSpider, you can use sitemap_filter, which is a proper way to filter entries.
    limit = 5  # Limit to 5 entries only
    count = 0  # Entries counter

    def sitemap_filter(self, entries):
        for entry in entries:
            if self.count >= self.limit:
                continue
            self.count += 1
            yield entry

A: Using on return was not enough for me, but you can combine it with the CloseSpider  exception :
# To import it :
from scrapy.exceptions import CloseSpider

#Later to use it:
raise CloseSpider('message')

I posted the whole code combining both on stackoverflow here

A: Why not have a count property on the spider initialized to 0, and the on your parse method you can
def parse(self, response):
    if self.count >= 100:
         return
    self.count += 1
    # do actual parsing here


text:
Q: Drupal app development name = MagApp 1.0
description = Magapp module that enables MagApp powered publications.
core = 7.x
php = 5.1
package = MagApp
dependencies[] = references
dependencies[] = node_reference
dependencies[] = magapp_core_content_types
version = "7.x-2.0"

I have been created a module and the info file is written above is there any problem while changing the php version , Because i did it before months , so i have to update this module , Can i add dependencies directly without using modules .

A: Search the source of /modules for admin/structure and check how they built that *_menu() hook.
If you have access to the server and it's running *NIX you could do:
grep -ri 'admin/structure' your_site_directory/modules/*

And then you can implement your own hook_menu() in your own module. Might also be possible in the Structure -> Menu system of the web UI. I don't recall.


text:
Q: object inside object first one feemap is static one inside that uuid will be given by dynamically and it is a object that one will act like value "feeMap": {
      "6874597a-3b20-40ea-bfa3-08358ad19793": {
        "id": "6874597a-3b20-40ea-bfa3-08358ad19793",
        "name": "visnhuuuu666",
        "description": "One Time fee",
        "cost": 13,
        "isOneTimeFee": true,
        "isProrated": false,
        "prorateToDay": false,
        "discountable": true,
        "prepayable": true
      }
    }
    inside feemap that id is a uuid how can do like that. this "6874597a-3b20-40ea-bfa3-08358ad19793": uuid is acts like object and that uuid only act as inner id value also how can I do like that dynamically is it possible. please help me this problem

I want feemap inside object should be given dynamically that is uuid and that one acts like object and also inside that object for id value also that same object uuid will add here

A: you can use strings for field name sin JS and access them too like so:

let feeMap = {};
feeMap["6874597a-3b20-40ea-bfa3-08358ad19793"] = {};
feeMap["6874597a-3b20-40ea-bfa3-08358ad19793"].id = "6874597a-3b20-40ea-bfa3-08358ad19793";
feeMap["6874597a-3b20-40ea-bfa3-08358ad19793"].name = "visnhuuuu666";
//and so on....

Please refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#accessing_properties


text:
Q: Flatlist - lista subindo e invadindo espaço do menu Boa noite, estou com um problema em minha aplicação em react, minha lista (flatlist) quando fica com muitos itens, a lista acaba subindo na página e invadindo o espaço do menu de minha aplicação que esta inserido acima dela.
index.js (Home)
import { StyleSheet, Text, View } from 'react-native';

import Header from '../../components/Header';
import Actions from '../../components/Actions';
import List from '../../components/list';

export default function Home() {
  return (
    <View style={styles.container}>
        <Header name="Olá, usuário." />

        <Actions/>

        <Text style={styles.title}>Mapas:</Text>

        <List/>

    </View>

  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#fafafa',
  },
    title:{
    fontSize: 18,
    fontWeight: 'bold',
    margin: 14,
    marginEnd: 14,
  }
});

Conteúdo das configurações de index.js (List)
const styles = StyleSheet.create({
    container: {
      backgroundColor: '#fafafa',
    },
    list:{
      marginStart: 14,
      marginEnd: 14,
    }

Segue imagem do problema
Estou me embaralhando nesse ajuste, no mais esta tudo correto, alguém pode me explicar onde estou pecando?
Obrigado!

A: Consegui resolver, estava esquecendo que tinha definido uma animação nos ícones dos botões que acabei mudando de ideia, porém não tinha removido a seguinte linha:
   marginTop: 10,
    }

Ele estava empurrando minha lista pra cima do menu, após remover o marginTop consegui resolver o problema, fica a dica pra quem ter o mesmo descuido que tive.


text:
Q: questions about backbone.js integration with JQuery/JQueryUI I have just started using backbone (with requirejs for modules).
It seems to me that there is an overlap between what jQuery can do and what Backbone can do.  This leaves me wondering which option I should be using.
For example, I could listen to an even in the following ways:
$('selector').click( function(event) {...

or
var myView = Backbone.View.extend({
  events: {
    "click selector": "onClickSelector",
  }, ...

1) Which of the above options should I be using?
Jquery supports things that I just don't know how to manage with Backbone.  For example, the autocomplete function of JqueryUI:
$('selector').autocomplete({ ...

2) how might I implement autocomplete this using backbone?  Do I just do all this in a method after the view is rendered onPostRender()?
I find see a lot of example that seem to add new members to the View object.  For example:
var myView = Backbone.View.extend({
  events: {
    deletePressed: function() { ... },
    submitPressed: function() { ... },
    editPressed: function() { ... },
  }, ...

if the functionality of these events is simple, I can see that this makes sense, however, if there is more complexity to the behaviour the View object will get very complex.
3) Should I be implementing complex behaviour in the anonymous function or should I call a named function?
4) Kind of similar to the above, if I have a common function that is used by many events (such as resetForm()) should this be declared as a member of the View of a names function?
I am currently storing my jquery objects as variables in the module
var $mySelector = $(selector);

or I could attach them to the View
var myView = Backbone.View.extend({
  initialize: {
    this.mySelector = $(selector);
  }, ...

5) Should I be making my JQuery objects part of the View or part of the AMD module:

A: Here are answers to your questions:
1 : Go for the second option the one with events property in the view. Note : You can bind events using this approach to only those elements which are children of the element you specified as el in your view.
2: Yes you can do it in onPostRender().
3: If you want handleDeletePressed(), handleSubmitPressed() and handleEditPressed() to be reused or they have to do lot many things I suggest it is better to create named functions and specify them as :
events: {
    deletePressed: 'handleDeletePressed',
    submitPressed: 'handleSubmitPressed',
    editPressed: 'handleEditPressed',
  }

4: You can declare it as a member of view.
5: At any instance inside your view you can use this.$('selector'), to get jQuery object. If you want you can create jQuery objects as well.


text:
Q: Python list comprehension to map from flat list to mimic a nested structure In a recent question, thefourtheye showed a neat list comprehension to map a list to a nested list:
list1 = [1, 2, 3, 4, 5]
list2 = [[1, 2, 3], [5], [1, 6], [1, 0, 9, 10], [1, 5, 2]]
print [(item1, s) for item1, item2 in zip(list1, list2) for s in item2]

Output
[(1, 1), (1, 2), (1, 3), (2, 5), (3, 1), (3, 6), (4, 1), (4, 0), (4, 9), (4, 10), (5, 1), (5, 5), (5, 2)]

My question is related.
Is there a list comprehension to take a flat list of n elements, and map it into the structure of a nested list with n basic elements?:
list1 = [3, 5, 4, 1, 2, 6, 0, 7]
list2 = [ [0,1], [2,3,4], [5], [6,7] ]

output
[ [3,5], [4,1,2], [6], [0,7] ]

I have an ugly loop for it, but can't quite seem to make it come out in a comprehension.
ETA: Hmm.  I see some cool answers based on the integer type I used in the example.  I should have added that it needs to work on strings.
Let me be more transparent and precise.
I have a sentence that has been broken into space-based tokens and subtokens, and a flat list of replacement tokens.
list2 = [['This'], ['is'], ['a'], ['sentence'], ['I', "'d"], ['like'], ['to'], ['manipulate', '.']]
list1 = ['These', 'were', 'two', 'sentences', 'I', "'d", 'like', 'to', 'read'.]

output = [['These'], ['were'], ['two'], ['sentences'], [['I'], ["'d"]], ['like'], ['to'], ['read', '.']]

A: This method relies just on the "shape" of list2, not the contents
>>> list1 = [3, 5, 4, 1, 2, 6, 0, 7]
>>> list2 = [ [0,1], [2,3,4], [5], [6,7] ]
>>> it = iter(list1)
>>> [[next(it) for i in el] for el in list2]
[[3, 5], [4, 1, 2], [6], [0, 7]]

With the string example
>>> list2 = [['This'], ['is'], ['a'], ['sentence'], ['I', "'d"], ['like'], ['to'], ['manipulate', '.']]
>>> list1 = ['These', 'were', 'two', 'sentences', 'I', "'d", 'like', 'to', 'read','.']
>>> it = iter(list1)
>>> [[next(it) for i in el] for el in list2]
[['These'], ['were'], ['two'], ['sentences'], ['I', "'d"], ['like'], ['to'], ['read', '.']]

A: This seems to work.
>>> [[list1[i] for i in s] for s in list2]
[[3, 5], [4, 1, 2], [6], [0, 7]]

A: Use a nested list-comp to use the values from the second list to get the first:
list1 = [3, 5, 4, 1, 2, 6, 0, 7]
list2 = [ [0,1], [2,3,4], [5], [6,7] ]
list3 = [[list1[i] for i in el] for el in list2]
# [[3, 5], [4, 1, 2], [6], [0, 7]]

A: Maybe you can try this:
list1 = [3, 5, 4, 1, 2, 6, 0, 7]
list2 = [ [0,1], [2,3,4], [5], [6,7] ]
print([list1[l[0] : l[0] + len(l)] for l in list2])


text:
Q: How to access dropdown in static method I have taken a DropDownList in my home.aspx  and in home.aspx.cs page I want to access it within a static method. How it possible? I can't access it in static method. Please help me..

A: No it isn't possible.
This is a fundamental rule of many languages. Static methods cannot access anything that is instance-specific. An instance of a DropDownList on an ASP.NET is exactly that.. an instance variable. A static method is across all instances.
To get what you want.. you need to pass an instance into it. Something like this:
public class ObjectA {
    public string Name { get; set; }

    public static string GetName(ObjectA instance) {
        return instance.Name;
    }
}

(Yes, that's a horrible example.. )
So, with an ASP.NET page.. you might do something like this:
public void Page_Load(object sender, EventArgs e) {
    doSomethingWith(dropDownList1);
}

public static void doSomethingWith(DropDownList dropDown) {
    // use the dropdown variable here
}

A: Pass the DropDownList as a parameter of your static method, then you could call the method of this instance from your static.


text:
Q: Pulling text out of a string in SQL I have been assigned with the task of getting part numbers out of a string in our database. I know that the part will be between the first and second comma in the string but I have no idea how to go about doing this. Any one have any suggestions? This is an example of the string I will be working with LEL,SPEC2078,14 CUT LEADS,#18 1/32

A: No problem! Might be best to write a function if you have to do this for several different items inside a CSV string.
SELECT 'LEL,SPEC2078,14 CUT LEADS,#18 1/32'

SELECT SUBSTRING('LEL,SPEC2078,14 CUT LEADS,#18 1/32',1,CHARINDEX(',','LEL,SPEC2078,14 CUT LEADS,#18 1/32',1)-1) -- Get's the first value
SELECT SUBSTRING('LEL,SPEC2078,14 CUT LEADS,#18 1/32',CHARINDEX(',','LEL,SPEC2078,14 CUT LEADS,#18 1/32',2) + 1, CHARINDEX(',','LEL,SPEC2078,14 CUT LEADS,#18 1/32',2) + CHARINDEX(',','LEL,SPEC2078,14 CUT LEADS,#18 1/32',1)) -- Get's the next value

A: You will want to use Substring to pull out certain strings and CharIndex to find the position of the commas.

A: assuming the partno is in a column called p and the name of your table is products:
select SUBSTRING(p, charindex(',',p,1)+1, case when charindex(',',p,charindex(',',p,1)+1) = 0 then len(p)-charindex(',',p,1) else charindex(',',p,charindex(',',p,1)+1) end)
from products

A: Thanks for all your help this was my final solution.
select inm.fpartno, SUBSTRING(inm.fdescript, charindex(',',inm.fdescript,1)+1,

case when charindex(',',inm.fdescript,charindex(',',inm.fdescript,1)+1) = 0
then len(inm.fdescript)-charindex(',',inm.fdescript,1)
else CharIndex(',', inm.fdescript, CharIndex(',', inm.fdescript) + 1) - CharIndex(',', inm.fdescript) - 1 end)
from Database.dbo.inmast as inm`


text:
Q: tensorflow lite program crashing with kivy on buildozer I tried running this github program https://github.com/tito/experiment-tensorflow-lite
It is basically about running tensorflow lite using kivy on android.
I tried running the program on my pc but I got this error``
STDOUT:
patching file jnius/jnius_jvm_android.pxi
Hunk #1 FAILED at 1.
1 out of 1 hunk FAILED -- saving rejects to file jnius/jnius_jvm_android.pxi.rej
patching file jnius/env.py
Hunk #1 FAILED at 185.
1 out of 1 hunk FAILED -- saving rejects to file jnius/env.py.rej

  STDERR:

[INFO]:    STDOUT:
    patching file jnius/jnius_jvm_android.pxi
Hunk #1 FAILED at 1.
1 out of 1 hunk FAILED -- saving rejects to file jnius/jnius_jvm_android.pxi.rej
patching file jnius/env.py
Hunk #1 FAILED at 185.
1 out of 1 hunk FAILED -- saving rejects to file jnius/env.py.rej
[INFO]:    STDERR:
Traceback (most recent call last):
  File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/home/pls/experiment-tensorflow-lite/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 1276, in <module>
    main()
  File "/home/pls/experiment-tensorflow-lite/.buildozer/android/platform/python-for-android/pythonforandroid/entrypoints.py", line 18, in main
    ToolchainCL()
  File "/home/pls/experiment-tensorflow-lite/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 725, in init
    getattr(self, command)(args)
  File "/home/pls/experiment-tensorflow-lite/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 153, in wrapper_func
    build_dist_from_args(ctx, dist, args)
  File "/home/pls/experiment-tensorflow-lite/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 212, in build_dist_from_args
    build_recipes(build_order, python_modules, ctx,
  File "/home/pls/experiment-tensorflow-lite/.buildozer/android/platform/python-for-android/pythonforandroid/build.py", line 573, in build_recipes
    recipe.apply_patches(arch)
File "/home/pls/experiment-tensorflow-lite/.buildozer/android/platform/python-for-android/pythonforandroid/recipe.py", line 560, in apply_patches
    self.apply_patch(
  File "/home/pls/experiment-tensorflow-lite/.buildozer/android/platform/python-for-android/pythonforandroid/recipe.py", line 263, in apply_patch
    shprint(sh.patch, "-t", "-d", build_dir, "-p1",
  File "/home/pls/experiment-tensorflow-lite/.buildozer/android/platform/python-for-android/pythonforandroid/logger.py", line 167, in shprint
    for line in output:
  File "/usr/local/lib/python3.8/dist-packages/sh-1.14.1-py3.8.egg/sh.py", line 911, in next
    self.wait()
  File "/usr/local/lib/python3.8/dist-packages/sh-1.14.1-py3.8.egg/sh.py", line 841, in wait
    self.handle_command_exit_code(exit_code)
  File "/usr/local/lib/python3.8/dist-packages/sh-1.14.1-py3.8.egg/sh.py", line 865, in handle_command_exit_code
    raise exc
sh.ErrorReturnCode_1:

  RAN: /usr/bin/patch -t -d /home/pls/experiment-tensorflow-lite/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/pyjnius-sdl2/armeabi-v7a__ndk_target_21/pyjnius -p1 -i /home/pls/experiment-tensorflow-lite/.buildozer/android/platform/python-for-android/pythonforandroid/recipes/pyjnius/sdl2_jnienv_getter.patch

  STDOUT:
patching file jnius/jnius_jvm_android.pxi
Hunk #1 FAILED at 1.
1 out of 1 hunk FAILED -- saving rejects to file jnius/jnius_jvm_android.pxi.rej
patching file jnius/env.py
Hunk #1 FAILED at 185.
1 out of 1 hunk FAILED -- saving rejects to file jnius/env.py.rej

I used the same buildozer.init file on the github
Python version: 3.8.10
I ran the program on ubuntu virtual machine using virtual box

A: Just use command:
buildozer android clean

before:
buildozer android debug


text:
Q: Bison in the plural form I just realized that we should say "bison are this and that" without the plural "s". I've checked its definition in a dictionary and it's a countable noun. I've seen in a textbook "Bison are..." and on the same page in the same textbook "Chimpanzees are..." so what am I missing?

A: Sometimes they are just like that. I'm not sure why, but I've learned to accept how they are, learn them that way and move on. I've been told that English has many rules but does not keep to them.


text:
Q: Azure Data Factory V2 Dynamic Content Long story short, I have a data dump that is too large for an azure function. So we are using Data Factory.
I have tasked another function to generate an access token for an API and output it as part of a json. I would like to set that token to a variable within the pipeline. So far I have this:

I'm attempting to use the Dynamic Content "language" to set the variable:
@activity('Get_Token').output

I'd like something like pythons:
token = data.get('data', {}).get('access_token', '')

As a secondary question, my next step is to use this token to call an API while iterating over another output, so perhaps this exact step can be added into the ForEach?

A: Looks like the variable should be @activity('Get token').output.data.access_token as others have indicated but, as you've guessed, there's no need to assign a variable if you only need it within the foreach.  You can access any predecessor output from that successor activity.  Here's how to use the token while iterating over another output:

*

*Let's say your function also outputs listOfThings as an array
within the data key. Then you can set the foreach activity to
iterate over @activity('Get token').output.data.listOfThings.

*Inside the foreach you will have (let's say) a Copy activity with a
REST dataset as the source.  Configure the REST linked service
with anonymous auth ...

*... then you'll find a field called Additional
Headers in the REST dataset where you can create a key Authorization
with value as above, Basic @activity('Get token').output.data.access_token

*The thing that you said you want to iterate over (in the listOfThings JSON array) can be referenced inside the foreach activity with
@item() (or, if it's a member of an item in the listOfThings
iterable then it would be @item().myMember)

To make #4 explicit for anyone else arriving here:

*

*If listOfThings looks like this, listOfThings: [ "thing1", "thing2", ...]

*for example, filenames: ["file1.txt", "file2.txt", ...]

*then @item() becomes file1.txt etc.
whereas

*

*If listOfThings looks like this, listOfThings: [ {"key1":"value1", "key2":"value2" ... }, {"key1":"value1", "key2":"value2" ... }, ...]

*for example. filenames: [ {"folder":"folder1", "filename":"file1.txt"}, {"folder":"folder2", "filename":"file2.txt"}, ... ]

*then @item().filename becomes file1.txt etc.


text:
Q: Dynamic alerts with radio buttons I have this HTML form below (radio buttons) which is having 3 questions with answers A, B and C.
<fieldset>
<legend>Question 1:</legend>
<input type="radio" value="1" name="first" />A

<input name="first" type="radio" value="2" />B

<input name="first" type="radio" value="3" />C

</fieldset>

<fieldset>
<legend>Question 2:</legend>
<input type="radio" value="1" name="second" />A

<input name="second" type="radio" value="2" />B

<input type="radio" value="3" name="second" />C

</fieldset>

<fieldset>
<legend>Question 3:</legend>
<input type="radio" value="1" name="third" />A

<input name="third" type="radio" value="2" />B

<input type="radio" value="3" name="third" />C

</fieldset>

Please answer all the questions

What I need here is a jQuery script to display 3 answers dynamically. The 3 answers should be like below:

*

*Answer 1 (if 2 or more answers are A)

*Answer 2 (if 2 or more answers are B)

*Answer 3 (if 2 or more answers are C)
Nothing is displayed if the answers are A, B and C.
I'm not a jQuery pro but I just have the script (below) to check if the answers are completed or not. Can anyone help me with this?
$('input:radio').click(
function() {
    var q = $('fieldset').length;
    console.log('q: ' + q + '; checked: ' + $('input:radio:checked').length);
    if ($('input:radio:checked').length == q){
        $('#display').text('You\'ve completed all questions!');
    }
    else {
        $('#display').text('You\'ve not yet finished...');
    }
});

Thanks in advance.
JSFiddle Demo - http://jsfiddle.net/BhanuChawla/KSd3M/

A: Here is one possible solution:
var answers = {
    "1": "Answer 1",
    "2": "Answer 2",
    "3": "Answer 3"
};

$("input[type='radio']").on("click", function() {
    var vals = $("fieldset input:checked").map(function() {
        return this.value;
    }).get().sort();
    for (var i = 0; i < vals.length; i++) {
        if (vals[i] == (vals[i + 1] || null)) {
            $("#display").text(answers[vals[i]]);
            break;
        }
    }
});

DEMO: http://jsfiddle.net/mLnWP/

A: Here i have done complete bins for above issue. you can check demo link too.
Demo: http://codebins.com/bin/4ldqp74
HTML
<fieldset>
  <legend>
    Question 1:
  </legend>

    <input type="radio" value="1" name="first" />
    A

    <input name="first" type="radio" value="2" />
    B

    <input name="first" type="radio" value="3" />
    C

</fieldset>

<fieldset>
  <legend>
    Question 2:
  </legend>

    <input type="radio" value="1" name="second" />
    A

    <input name="second" type="radio" value="2" />
    B

    <input type="radio" value="3" name="second" />
    C

</fieldset>

<fieldset>
  <legend>
    Question 3:
  </legend>

    <input type="radio" value="1" name="third" />
    A

    <input name="third" type="radio" value="2" />
    B

    <input type="radio" value="3" name="third" />
    C

</fieldset>

  Please answer all the questions

JQuery
$(function() {

    var answers = Array();
    $("input:radio").click(function() {
        var index = 0;
        if ($(this).is(":checked")) {
            index = $(this).closest("fieldset").index();
            answers[index] = $(this).val().trim();
        }
        for (var i = 0; i < answers.length; i++) {
            if ($("input:radio[value=" + answers[i] + "]:checked").length > 1) {
                $("#display").text("Max Answers Selected:" + answers[i]);
                break;
            } else if ($("input:radio:checked").length >= 3) {
                $("#display").text("All have different Answers..!");
            }
        }

    });

});

CSS
label{
  float:left;
  margin-left:10px;
  font-size:14px;
}

#display{
  margin-top:10px;
  border:1px solid #335599;
  padding:5px;
  font-size:14px;
  background:#a4a1df;
}

Demo: http://codebins.com/bin/4ldqp74


text:
Q: Почему возникает ошибка Parse error: syntax error, unexpected 'exit' (T_EXIT)? Необходимо получить и отдать картинку пользователю.
Вместо этого, при полностью нормальном коде выдается такая фигня:

Parse error: syntax error, unexpected 'exit' (T_EXIT) in
  E:\OpenServer\domains\easy\test.php on line 6

Все бы ничего, но вроде никаких запятых не пропустил...
$img = 'http://mirgif.com/KARTINKI/kosmos/kosmos-81.jpg';
$headers = get_headers($img,true);
$headers = $headers['Content-Type'];
header("Content-Type: $headers");
$img = file_get_contents($img);
exit($img);

A: Как уже говорили выше, код рабочий. Возможно ошибка появляется из-за неправильного конца строки. Проверьте , возможно что после <?php нет символа конца строки \n или он в неправильном формате . Символы конца строки должны быть UNIX Format


text:
Q: while import resnet got error - ImportError: cannot import name '_obtain_input_shape'' I got an while importing resnet.
I tried removed latest version and install old version of keras==1.0.6 and it doesn't work. Also i did changes in resnet.py -->  "from keras_applications.imagenet_utils import _obtain_input_shape , i got an error an like "ImportError: cannot import name 'GlobalMaxPooling2D' "
from keras.applications.imagenet_utils import _obtain_input_shape
import os
import numpy as np
from pickle import dump
import resnet
import numpy as np
from keras.preprocessing.image import load_img, img_to_array
from keras.models import Model
from os import listdir
import cv2
from keras import applications

I need import all these without an error. kindly help me to sort this. Thanks in advance

A: Change
from keras.applications.imagenet_utils import _obtain_input_shape

with
from keras_applications.imagenet_utils import _obtain_input_shape


text:
Q: Karma test in Angular isn't doing what it is expected to My login controller is:
angular.module('mean').controller('LoginController', ['$scope', '$location', '$rootScope', 'UserService', function ($scope, $location, $rootScope, UserService) {
  $scope.init = function() {
    $scope.credentials = {};
    $scope.status_object = {
      text: '',
      class: '',
      show: false
    };
  }

  $scope.authenticate = function() {
    $scope.status_object = {
      text: 'Authenticating...',
      class: 'info',
      show: true
    };
    UserService.authenticate($scope.credentials).then(function(response) {
      if(response.data.status === 'error') {
        $scope.status_object = {
          text: response.data.error,
          class: 'danger',
          show: true
        };
      } else if(response.data.status === 'ok') {
        $rootScope.globals.logged_in = true;
        $location.path('/' + response.data.user.access);
      }
    });
  };
}]);

My test is:
  describe('LoginController', function() {
    beforeEach(module('mean'));

    var scope, rootScope, LoginController, $httpBackend, $location;

    beforeEach(inject(function($controller, $rootScope, _$httpBackend_, _$location_) {
      scope = $rootScope.$new();
      rootScope = $rootScope.$new();

      LoginController = $controller('LoginController', {
        $scope: scope,
        $rootScope: rootScope
      });

      $httpBackend = _$httpBackend_;

      $location = _$location_;
    }));

    it('should show danger when wrong credentials are used', function() {
      scope.credentials = {
        email: 'test@email.com',
        password: 'password'
      }

      $httpBackend.expectPOST('/api/v1/user/auth').respond({
        status: 'error',
        error: 'Invalid User'
      });

      console.log(scope.status_object);
      scope.authenticate();
      $httpBackend.flush();

      expect(scope.status_object).toEqualData({text: 'Invalid User', class: 'danger', show: true});
    });
  });

In my view, I have an ng-init="init()". Everything works smoothly on the front end, but when running my test, I get:
PhantomJS 1.9.7 (Mac OS X) LoginController should show danger when wrong credentials are used FAILED
  TypeError: 'undefined' is not a function (evaluating 'expect(scope.status_object).toEqualData({text: 'Invalid User', class: 'danger', show: true})')
      at /myapp/test/karma/unit/controllers/login.spec.js:43
PhantomJS 1.9.7 (Mac OS X): Executed 4 of 4 (1 FAILED) (0.135 secs / 0.043 secs)

Not sure what my test is doing wrong. Any ideas?

A: Yes, you need to define toEqualData first, for example, the way the Angular tutorial does it:
  beforeEach(function(){
    this.addMatchers({
      toEqualData: function(expected) {
        return angular.equals(this.actual, expected);
      }
    });
  });

A: Turns out the line: expect(scope.status_object).toEqualData({text: 'Invalid User', class: 'danger', show: true}); was causing the error. There is no toEqualData, so I'm using toEqual instead and it's working now


text:
Q: ADFS on same server setup SSO I am in the process of configuring my AFDS. The two applications I am attempting to have trust  each other are on the same server, under the same doamin. I was wondering if anybody has any particular experience with configuring ADFS on a single server with the applications on the same server as well.
Thanks!
Are there any guides to this, or any special configurations I need for my situation? Do I need to do anything special with the certificates, since both applications and ADFS are on the same server?

A: I have no clue why you would do such a thing - it's a bit too much for a single server as I understand it. However, I would suppose you need to configure the trusts just as you would with a two server setup.
I have successfully configured it for sharepoint 2013 using this tutorial:
http://technet.microsoft.com/en-us/library/hh305235.aspx
Also, we have set up a custom login page using the following tutorial:
http://blog.helloitsliam.com/Lists/Posts/Post.aspx?ID=76
It's for sharepoint 2010 but everything is mostly the same. Please pay attention to copying the thumbprints to sharepoint's web.config - if you copy them straight from the window, an invisible unicode character is copied with them. You can't see it in a text editor but SharePoint most definitely sees it and will throw an ID4175 error.
If you stumble on any problems please don't hesitate to comment on this thread so I get a notification.


text:
Q: VS 2008 - Publish Web Site - Exclude App_Data How do I prevent Visual Studio 2008 (standard edition) from publishing the App_Data folder?  I can't have the contents of App_Data published because it ruthlessly overwrites the production data.

A: The publish dialog has a checkbox option at the bottom to "Include files from the App_Data folder".


text:
Q: AudioKit real-time recording and playback I'm trying to add a feature to my app where I can record audio from the phone's built-in microphone and then playback that audio through the phone's speakers at the same time.
Firstly, I want to know if this is possible through AudioKit?
Secondly, if it's possible, which playground/examples projects in AudioKit can I look through for reference on how to do this?
I know it's possible to record the audio to a file and then play that back and I saw it in the Recorder example project, but what I wanted was a real-time playback.
Would appreciate any guidance or help you can give me for this.

A: For any app that uses the device microphone, you need to add the NSMicrophoneUsageDescription key to Info.plist. Once that's taken care of you just route the microphone through the effects, and set the output to the end of the chain.
import UIKit
import AudioKit

class ViewController: UIViewController {

    var microphone = AKMicrophone()
    var reverb = AKReverb()

    override func viewDidLoad() {
        super.viewDidLoad()

        microphone >>> reverb
        AudioKit.output = reverb
        AKSettings.ioBufferDuration = 0.002 // Optional, set this to decrease latency
        AudioKit.start()
    }
}


text:
Q: How can a docker service know about all other containers of the same service? I'm working on a file sync Docker microservice.  Basically I will have a file-sync service that is global to the swarm (one on each node).  Each container in the service needs to peer with all the other containers on different nodes.  Files will be distributed across the nodes, not a complete duplicate copy.  Some files will reside on only certain nodes.  I want to be able to selectively copy a subset of the files from one node to another.
How can I get a list of the endpoints of all the other containers so the microservice can peer with the them?  This needs to happen programmatically.
On a related note, I'm wondering if a file-sync microservice is the best route for the solution I'm working on.
Basically I have some videos a user has uploaded.  I want to be able to encode them into different formats.  I was planning on having the video encoding node have the file-sync service pull the files, encode the videos, and then use the file-sync to push the encoded files back to the same server.  I know I can use some kind of object store but that isn't available to me with bare metal dedicated servers and I'd rather not deal with OpenStack if I don't need to.

A: Thanks to @johnharris85 for the above suggestion.  For anyone else that is interested I created a snippet that can be used in node.
https://gist.github.com/brennancheung/62d2abe16569e600d2be5e9495c85331
const dns = require('dns')

function lookup (serviceName) {
  const tasks = `tasks.${serviceName}`
  return new Promise((resolve, reject) => {
    dns.lookup(tasks, { all: true }, (err, addresses, family) => {
      if (err) {
        return reject(err)
      }
      const filtered = addresses.filter(address => address.family === 4)
      const ips = filtered.map(x => x.address)
      resolve(ips)
    })
  })
}

async function main () {
  const result = await lookup('hello')
  console.log(result)
}

main()


text:
Q: how to get selected value from combox in windows c# I am new in windows. I want to get selected item on index changed in combobox in windows c#, at page load it calls selectedindexchanged event. how it happens. so plz help me.
thanks in advance

A: Here is simple example :
int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;

MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "\n" +
                "Index: " + selectedIndex.ToString());

A: Assuming you are in the SelectedIndexChanged event:
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            MessageBox.Show("Selected Item Text: " + comboBox1.SelectedItem.ToString() + "\n" +
                            "Index: " + comboBox1.SelectedIndex.ToString());
        }


text:
Q: SQL query giving weird result - count This is my SQL query:
select
client_details.client_id,
count( PC.cheque_status ) as count_stat,
client_details.client_city,
client_details.account_created_on,
client_details.client_name,
SUM(PC.amount),
SUM(PNB.amount),
SUM(PCA.amount),
PC.cheque_status,
count(PNB.status),
count(PCA.status),
PSD.version
                      from `client_details` as `client_details`
                      inner join `products_sold_details` as `PSD` on `PSD`.`client_id` = `client_details`.`client_id` and PSD.version = 1
                      left join product_cheque_mapped PCM on PCM.product_sold_id = PSD.id
                      left join product_cash_mapped PCAM on PCAM.product_sold_id = PSD.id
                      left join product_neft_mapped PNM on PNM.product_sold_id = PSD.id
                      left join `product_cheques` as `PC` on (`PC`.`cheque_status` = 0 and PCM.product_cheques_id = PC.id)
                      left join `product_net_banking` as `PNB` on ( `PNB`.`status` = 0 and PNM.product_neft_id = PNB.id)
                      left join `product_cash` as `PCA` on ( `PCA`.`status` = 0 and PCAM.product_cash_id = PCA.id )
                      group by `client_details`.`client_id`, PCM.product_cheques_id having count( PC.cheque_status ) > 0

These are the table structures:
client_details:
client_id (PK);
client_name;

products_sold_details:
id (PK);
client_id (FK);
version;

product_cheques:
id (PK);
client_id (FK);
amount;
cheque_status;

product_net_banking:
id (PK);
client_id (FK);
amount;
status;

product_cash:
id (PK);
client_id (FK);
amount;
status;

products_sold_details has a many to many relation with product_cheques, product_net_banking, product_cash
client_details has many products_sold_details
client_details has many product_cheques, product_cash, product_net_banking
if there are two products for a client, and there is only one cheque for the combined product which has a status 0, then I should get count(PC.cheque_status) as 1
if there are 3 product for a client, and there are 3 cheques for that client which have status 0, then I should get the count(PC.cheque_status) as 3 for 3 cheques.
However, what I am getting is 9 as count(PC.cheque_status) in this case.
Also, the SUM(amount) is getting multiplied with the number of products.
Where am I going wrong here?


text:
Q: Debugging C++ DLL used by C# Project I have a C# project that uses a C++ DLL. I am trying to debug the DLL but Visual Studio is reporting that the "PDB does not match image" for my DLL.

*

*The C++ DLL is built by me, in the same solution which produces both the DLL and a full PDB.

*The C++ DLL is marked as a dependency of the C# project.

*The C# project it set up to copy the DLL file to the output directory if it is newer than the existing ones.

*The C# project has "Enable debugging of native code" enabled.

The symbol load information for the DLL under the modules window shows the correct PDB is found but complains that the "PDB does not match image". Even though this is the PDB built along side the DLL by Visual Studio.
Googling this error only provides people also asking what's going wrong but an answer is never provided.

A: The issue was the copying of the DLL.
I had added the DLL as an "Existing Item" to the C# project which apparently copies the file into the project directory as is. I had to add a post-build event to the C++ project to copy the DLL to the C# project's directory. Which will then copy the DLL to the output directory if it is newer.


text:
Q: I am confused about constant, constant references, references to constants, ... (including example code) I am trying to write a graph data structure implementation that I feel satisfied with. (Maintain adjacency lists as sets instead of linked lists.) Anyways, I tried to use references and iterators and wrote this:
#include <iostream>
#include <string>
#include <set>
#include <stack>

class Vertex {
    std::string name;
    std::set<Vertex> edges;
public:
    Vertex(std::string name) : name(name) {}

    std::string vertexName() const {
        return name;
    }

    std::set<Vertex> outEdges() const {
        return edges;
    }

    void addEdge(const Vertex& other) {
        edges.insert(other);
    }

    void removeEdge(const Vertex& other) {
        edges.erase(other);
    }

    int outDegree() {
        return edges.size();
    }
};

bool operator<(const Vertex& v1, const Vertex& v2) {
    return (v1.vertexName().compare(v2.vertexName()) < 0);
}

void DFS(const Vertex& v) {
    std::stack<Vertex*> stack;
    std::set<Vertex*> visited;

    stack.push(&v);             // error1
    visited.insert(&v);         // error2

    while (!stack.empty()) {
        Vertex* vert_ptr = stack.top();
        stack.pop();

        std::cout << vert_ptr->vertexName() << std::endl;

        //
        for (std::set<Vertex>::iterator iter = vert_ptr->outEdges().begin(); iter != vert_ptr->outEdges().end(); iter++) {
            if (visited.find(&(*iter)) != visited.end()) {      // error3
                stack.push(&(*iter));                           // error4
                visited.insert(&(*iter));                       // error5
            }
        }
    }
}

int main() {
    Vertex a = Vertex("a");
    Vertex b = Vertex("b");
    Vertex c = Vertex("c");

    DFS(a);

    getchar();
    return 0;
}

I am getting the following errors:

*

*error1: E0304    no instance of overloaded function "std::stack<_Ty, _Container>::push [with _Ty=Vertex *, _Container=std::deque<Vertex *, std::allocator<Vertex *>>]" matches the argument list

*error2: E0304    no instance of overloaded function "std::set<_Kty, _Pr, _Alloc>::insert [with _Kty=Vertex *, _Pr=std::less<Vertex *>, _Alloc=std::allocator<Vertex *>]" matches the argument list

*error3: E0304    no instance of overloaded function "std::set<_Kty, _Pr, _Alloc>::find [with _Kty=Vertex *, _Pr=std::less<Vertex *>, _Alloc=std::allocator<Vertex *>]" matches the argument list

*error4: E0304    no instance of overloaded function "std::stack<_Ty, _Container>::push [with _Ty=Vertex *, _Container=std::deque<Vertex *, std::allocator<Vertex *>>]" matches the argument list

*error5: E0304    no instance of overloaded function "std::set<_Kty, _Pr, _Alloc>::insert [with _Kty=Vertex *, _Pr=std::less<Vertex *>, _Alloc=std::allocator<Vertex *>]" matches the argument list
I am realizing that I do not understand references as well as I thought I did. I used google, and the hits I got reiterate what I understand about references, but do not touch on the part I do not understand (which is causing those errors).
I also dereferenced the iterators, and then used & to get the addresses of the actual objects the iterators are pointing to, and do not know if I am misunderstanding the way iterators work, or if it is just a problem with references.
I would appreciate it if someone could point me towards a good reference on all of this. :(

A: In your case void DFS(const Vertex& v) v is a reference to a var which is constant. In other words, you promised that the function will not modify the object.
std::stack<Vertex*> stack;
std::set<Vertex*> visited;

The above are containers of pointers to an object, which is not a constant and therefore is modifiable.
Here you are trying to violate an agreement. You are trying to allocate a pointer to a constant object v in a container which is intended for pointers to modifiable objects. If this is would have been allowed, you would be able to modify the value referenced by v through the pointer. So, it is not allowed and the compiler produces an error here.
stack.push(&v);             // error1
visited.insert(&v);         // error2

so, you needed to declare containers with pointers to the constants:
std::stack<const Vertex*> stack;
std::set<const Vertex*> visited;

now, the visited.find(&(*iter)) has to do with the implementation of the set::iterator. Apparently the value returned by operator '*' referenced a constant value, causing another conversion attempt from 'const' to non-const.
So, declaring stack and visited with const Vertex * argument should solve your compilation issues.


text:
Q: Finding the correct units for the energy-momentum tensor? I'm trying to understand the energy-momentum tensor $T^{\mu\nu}$ but I'm confused about the units. My textbook says the components of $T^{\mu\nu}$ are $\mathrm{Jm^{-3}}$. Four-momentum is is given by$$P^{\mu}=\left(E/c,\mathbf{p}\right)=\left(E/c,p_{x},p_{y},p_{z}\right)$$
The $E/c$ component of $P^{\mu}$ has units $\mathrm{Jsm^{-1}}$. The definition of $T^{\mu\nu}$ is "the rate of flow of the $\mu$ component of four-momentum across a surface of constant $\nu$." Using this definition, how do you get the rate of flow of the $E/c$ component of four-momentum across a surface of constant time (ie the $T^{00}$ component) to have the correct units of $\mathrm{Jm^{-3}}$? Surely you need to multiply $E/c$ by something with $\mathrm{s^{-1}m^{-2}}$ units, but what exactly?
Thank you

A: You say

The definition of $T^{\mu\nu}$ is "the rate of flow of the $\mu$
  component of four-momentum across a surface [of unit area] of constant $\nu$."

which means that the dimensions of $T^{\mu\nu}$ ought to be
$$\frac{Momentum}{Area \, \times \, Time.}$$

A: Notation: I will denote SI units between brackets, not to be confused with a multiplication.
Lets start by a well known case, the stress tensor of a perfect fluid:
$$ T^{\alpha \beta} \, = \left(\rho + {p \over c^2}\right)u^{\alpha}u^{\beta} + p g^{\alpha \beta} $$
from it, we could say that stress energy tensor units are from momentum density ($\rho u^\alpha$) multiplied by velocity $u^\beta$ (momentum flow), or pressure $p$ multiplied by metric $g^{\alpha\beta}$.

*

*When spacetime basis is $(ct,x,y,z)$, all stress energy tensor components (in contravariant and covariant form) have the same units
$$ T^{\alpha\beta} \left[ \left( \frac{kg\,m}{s} \frac{1}{m^3} \right) \frac{m}{s} = \frac{kg}{ms^2} \right] $$ equal to pressure units or energy density [ $ \frac{J}{m^3}=Pa=\frac{kg}{ms^2}$ ]. It corresponds to what is said in the book that is mentioned at the question.

*When spacetime basis is $(t,x,y,z)$ we have (assume $i,j \in \{1,2,3\}$):
$T^{00} \left[kg/m^3\right]$ : mass spatial density.
$T^{0j}, T^{i0} \left[ \frac{kg}{m^3} \frac{m}{s} = \frac{kg}{m^2s} \right]$ : momentum per unit of space volume.
$T^{ij} \left[ \frac{kg}{m^3} \frac{m}{s} \frac{m}{s} = \frac{kg}{ms^2} \right]$ : energy per unit of space volume.
These units corresponds to wikipedia paragraphs about stress energy tensor.

A: According to http://en.wikipedia.org/wiki/Stress-energy_tensor#Identifying_the_components_of_the_tensor $T_{00}$ is the density of relativistic mass not energy, so you have to divide by $c^2$.
For the momentum components:
$$\frac{dp^\alpha}{dV} = -T^\alpha _\beta u^\beta$$
giving you units of density.


text:
Q: Issue with Html.EditorFor on MVC3 I have a view with a form that's is typed to a viewmodel called AddEditItemVM. This viewmodel has the following property:
public List<Category> Categories{get;set;}

What im trying is two things:

*

*Render a checkbox foreach Category in the generic category list of my viewmodel.

*Make that when the form is posted receive, in my controller action, the property Categories instantiated (into the instance of AddEditItemVM)
About the first point, i would like to use any helper (if exists) that renders a group of checkboxes using lambda expressions like (m=>m.Categories), instead to render the checkbox with a foreach into the view.
About the second point, i read that there is one feature in MVC called Custom Model Binders. These get values from ValueProviders (querystring, cookies, or Form values) and creates the necessary instances passing it to specific action called after a form was posted. Should i create one custom model binder in order to receive my property Categories instantiated?

A: This might work
CheckboxList in MVC3.0


text:
Q: Store multiple values in a file - best format? I want to store multiple values (String, Int and Date) in a file via Java in Android Studio.
I don't have that much experience in that area, so I tried to google a bit, but I didn't get the solution, which I've been looking for. So, maybe you can recommend me something?
What I've tried so far:

*

*Android offers a SharedPreferences feature, which allows a user to save a primitive value for a key. But I have multiple values for a key, so that won't work for me.

*Another option is saving data on an external storage medium as file. As far as good. But I want to keep the filesize at minimum and load the file as fast as possible. That's the place, where I can't get ahead. If I directly save all values as simple text, I would need to parse the .txt file per hand to load the data which will take time for multiple entries.
Is there a possibility to save multiple entries with multiple values for a particular key in an efficient way?

A: No need to reinvent a bicycle. Most probably the best option for your case is using the databases. Look into Sqlite or Realm.

A: You don't divulge enough details about your data structure or volume, so it is difficult to give a specific solution.
Generally speaking, you have these three choices.
Serialize a collection

I have multiple values for a key

You could use a Map with a List or Set as its value.  This has been discussed countless times on Stack Overflow.
Then use Serialization to write and read to storage.
Text file
Write a text file.
Use Tab-delimited or CSV format if appropriate. I suggest using the Apache Commons CSV library for that.
Database
If you have much data, or concurrency issues with multiple threads, use a database such as the H2 Database Engine.


text:
Q: Помогите с ширеной меню на сайте помогите пожалуйста с меню, нужно что бы на всех экранах оно было равно ширине 70% то есть на всю область сайта.
Как можно это реализовать ?? давать новые классы дополнительным ul ??
http://www.samodelkin66.ru/shop/mekhanizirovannye-instrumenty


text:
Q: Help wanted achieving cryogenic temperatures My son's science project involves liquifying air.  I found the Linde process which is the way it was done first.  We are trying and not getting very far so I am looking for advice.
I have an air compressor good to 150psi.  We are slowly ramping up the pressure in the system.  We are currently testing at 80psi.  We pressurize 20 feet of copper tube bent in a coil running through an ice bath.  The tube exits and goes into the bottom of a thermos.
The end of the tube is capped, and we allow a small leak so that pressure drops from 80psi to 1atm.
We insulated the few inches between the ice bath and the thermos. We do not yet have a double walled tube, but we taped the thermos so all the air coming out is exiting through the insulation.
When we run, the thermos drops from room temperature (about 68F in the basement) to our best of 45F.  I'm quoting in Fahrenheit right now because the boys are very obnoxious about not wanting to use a temperature system they aren't comfortable with, and I just haven't been able to convince them that they are being unreasonable.
The point is, we are not even achieving the temperature of the ice bath.  Incidentally, as measured with my multimeter, the ice bath is always 3C.  I'm curious about that too, but that will be a separate question. Needless to say, we are not achieving any refrigeration.
The next step we will increase the leak so that the flow through the system is much higher. And we will start trying to use a Peltier cooler so we can have an intermediate stage that is 20C or so cooler than the ice bath.
Obviously we can up the pressure, but I would think we should see something more than we are getting.  Any suggestions?  Should I take a picture of our setup?


text: Q: Error in uploading file to 000webhost I'm new to php and this is my first time trying to hosting an website. I'm using codeigniter as my framework. I would like to hosting my website however it give me this kind of error.  It is because my index.php and .htaccess file is wrong? If yes, can I get the right one ? My question may be duplicate from before, and i'm asking it because i could not understand the solution or could'n find an appropriate solution. Thanks in advance ]1


text:
Q: Firebase In-App Messaging cause java.lang.RuntimeException: Internal error in Cloud Firestore (21.4.1) Getting runtime exception while trying to use Firebase Auth and In-App Messaging. As soon as I try to authenticate user with Firebase getting following exception -
I/FIAM.Headless: Starting InAppMessaging runtime with Installation ID dT********Gl49TUSZRKMx

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: buzz.anusmarak, PID: 24274
    java.lang.RuntimeException: Internal error in Cloud Firestore (21.4.1).
        at com.google.firebase.firestore.util.AsyncQueue.lambda$panic$3(com.google.firebase:firebase-firestore@@21.4.1:534)
        at com.google.firebase.firestore.util.AsyncQueue$$Lambda$3.run(com.google.firebase:firebase-firestore@@21.4.1)
        at android.os.Handler.handleCallback(Handler.java:754)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:163)
        at android.app.ActivityThread.main(ActivityThread.java:6361)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
     Caused by: java.lang.ExceptionInInitializerError
        at com.google.firestore.v1.ListenRequest.getDefaultInstance(com.google.firebase:firebase-firestore@@21.4.1:915)
        at com.google.firestore.v1.FirestoreGrpc.getListenMethod(com.google.firebase:firebase-firestore@@21.4.1:408)
        at com.google.firebase.firestore.remote.WatchStream.<init>(com.google.firebase:firebase-firestore@@21.4.1:61)
        at com.google.firebase.firestore.remote.Datastore.createWatchStream(com.google.firebase:firebase-firestore@@21.4.1:115)
        at com.google.firebase.firestore.remote.RemoteStore.<init>(com.google.firebase:firebase-firestore@@21.4.1:167)
        at com.google.firebase.firestore.core.FirestoreClient.initialize(com.google.firebase:firebase-firestore@@21.4.1:280)
        at com.google.firebase.firestore.core.FirestoreClient.lambda$new$0(com.google.firebase:firebase-firestore@@21.4.1:108)
        at com.google.firebase.firestore.core.FirestoreClient$$Lambda$1.run(com.google.firebase:firebase-firestore@@21.4.1)
        at com.google.firebase.firestore.util.AsyncQueue.lambda$enqueue$2(com.google.firebase:firebase-firestore@@21.4.1:436)
        at com.google.firebase.firestore.util.AsyncQueue$$Lambda$2.call(com.google.firebase:firebase-firestore@@21.4.1)
        at com.google.firebase.firestore.util.AsyncQueue$SynchronizedShutdownAwareExecutor.lambda$executeAndReportResult$1(com.google.firebase:firebase-firestore@@21.4.1:322)
        at com.google.firebase.firestore.util.AsyncQueue$SynchronizedShutdownAwareExecutor$$Lambda$2.run(com.google.firebase:firebase-firestore@@21.4.1)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at com.google.firebase.firestore.util.AsyncQueue$SynchronizedShutdownAwareExecutor$DelayedStartFactory.run(com.google.firebase:firebase-firestore@@21.4.1:229)
        at java.lang.Thread.run(Thread.java:760)
     Caused by: java.lang.RuntimeException: Unable to get message info for com.google.firestore.v1.ListenRequest
        at com.google.protobuf.GeneratedMessageInfoFactory.messageInfoFor(GeneratedMessageInfoFactory.java:62)
        at com.google.protobuf.ManifestSchemaFactory$CompositeMessageInfoFactory.messageInfoFor(ManifestSchemaFactory.java:143)
        at com.google.protobuf.ManifestSchemaFactory.createSchema(ManifestSchemaFactory.java:55)
        at com.google.protobuf.Protobuf.schemaFor(Protobuf.java:93)
        at com.google.protobuf.Protobuf.schemaFor(Protobuf.java:107)
        at com.google.protobuf.GeneratedMessageLite.makeImmutable(GeneratedMessageLite.java:171)
        at com.google.firestore.v1.ListenRequest.<clinit>(com.google.firebase:firebase-firestore@@21.4.1:911)
        at com.google.firestore.v1.ListenRequest.getDefaultInstance(com.google.firebase:firebase-firestore@@21.4.1:915)
        at com.google.firestore.v1.FirestoreGrpc.getListenMethod(com.google.firebase:firebase-firestore@@21.4.1:408)
        at com.google.firebase.firestore.remote.WatchStream.<init>(com.google.firebase:firebase-firestore@@21.4.1:61)
        at com.google.firebase.firestore.remote.Datastore.createWatchStream(com.google.firebase:firebase-firestore@@21.4.1:115)
        at com.google.firebase.firestore.remote.RemoteStore.<init>(com.google.firebase:firebase-firestore@@21.4.1:167)
        at com.google.firebase.firestore.core.FirestoreClient.initialize(com.google.firebase:firebase-firestore@@21.4.1:280)
        at com.google.firebase.firestore.core.FirestoreClient.lambda$new$0(com.google.firebase:firebase-firestore@@21.4.1:108)
        at com.google.firebase.firestore.core.FirestoreClient$$Lambda$1.run(com.google.firebase:firebase-firestore@@21.4.1)
        at com.google.firebase.firestore.util.AsyncQueue.lambda$enqueue$2(com.google.firebase:firebase-firestore@@21.4.1:436)
        at com.google.firebase.firestore.util.AsyncQueue$$Lambda$2.call(com.google.firebase:firebase-firestore@@21.4.1)
        at com.google.firebase.firestore.util.AsyncQueue$SynchronizedShutdownAwareExecutor.lambda$executeAndReportResult$1(com.google.firebase:firebase-firestore@@21.4.1:322)
        at com.google.firebase.firestore.util.AsyncQueue$SynchronizedShutdownAwareExecutor$$Lambda$2.run(com.google.firebase:firebase-firestore@@21.4.1)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at com.google.firebase.firestore.util.AsyncQueue$SynchronizedShutdownAwareExecutor$DelayedStartFactory.run(com.google.firebase:firebase-firestore@@21.4.1:229)
        at java.lang.Thread.run(Thread.java:760)
     Caused by: java.lang.UnsupportedOperationException
        at com.google.firestore.v1.ListenRequest.dynamicMethod(com.google.firebase:firebase-firestore@@21.4.1:903)
        at com.google.protobuf.GeneratedMessageLite.dynamicMethod(GeneratedMessageLite.java:252)
        at com.google.protobuf.GeneratedMessageLite.buildMessageInfo(GeneratedMessageLite.java:280)
E/AndroidRuntime:     at com.google.protobuf.GeneratedMessageInfoFactory.messageInfoFor(GeneratedMessageInfoFactory.java:60)
            ... 25 more

Following dependencies are being used -
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.3.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

    implementation 'androidx.navigation:navigation-fragment:2.3.0'
    implementation 'androidx.navigation:navigation-ui:2.3.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.squareup.picasso:picasso:2.71828'

    //firebase Analytics
    implementation 'com.google.firebase:firebase-analytics:17.5.0'
    // FirebaseUI for Cloud Firestore
    implementation 'com.firebaseui:firebase-ui-firestore:6.2.1'
    // FirebaseUI for Firebase Auth
    implementation 'com.firebaseui:firebase-ui-auth:6.2.1'
    //Firebase Storage
    implementation 'com.google.firebase:firebase-storage:19.2.0'
    //Firebase Cloud Messaging
    implementation 'com.google.firebase:firebase-messaging:20.3.0'
    //Firebase In-App Messaging
    implementation 'com.google.firebase:firebase-inappmessaging-display:19.1.1'
    implementation 'com.google.firebase:firebase-inappmessaging:19.1.1'

    //AdsMob
    implementation 'com.google.android.gms:play-services-ads:19.4.0'

    //Preferences Screen
    implementation 'androidx.preference:preference:1.1.1'

    //Kotlin extension
    implementation 'androidx.core:core-ktx:1.3.1'

    //circular images
    implementation 'com.mikhaellopez:circularimageview:4.2.0'

    //lottie animation
    implementation 'com.airbnb.android:lottie:3.4.1'

    // Room components
    implementation "androidx.room:room-runtime:2.2.5"
    annotationProcessor "androidx.room:room-compiler:2.2.5"
    androidTestImplementation "androidx.room:room-testing:2.2.5"

    //Joda Time
    implementation 'net.danlew:android.joda:2.10.6'

    //Image Cropper
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.+'

    //Calendar View
    implementation 'com.applandeo:material-calendar-view:1.7.0'

    //Work Manager
    implementation "androidx.work:work-runtime:2.4.0"

    //Guava error
    implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava'

    //Custom Preference Library
    implementation 'com.takisoft.preferencex:preferencex:1.1.0'
    implementation 'com.takisoft.preferencex:preferencex-datetimepicker:1.1.0'
    implementation 'com.takisoft.preferencex:preferencex-colorpicker:1.1.0'
    //https://github.com/Gericop/Android-Support-Preference-V7-Fix/wiki/Preference-types#timepickerpreference

    //Color Picker
    implementation 'com.github.rtugeek:colorseekbar:1.7.7'
    //https://github.com/rtugeek/ColorSeekBar
}

If I remove following dependency from build.gradle file

implementation 'com.google.firebase:firebase-inappmessaging-display:19.1.1'
implementation 'com.google.firebase:firebase-inappmessaging:19.1.1'

then exception is resolved, but I want to use Firebase In-App Messaging feature in my app. Any help or suggestions are welcome.

A: java.lang.RuntimeException: Internal error in Cloud Firestore

Seems like bug for this version. You can raise an issue @Google or @Github for this.

The Android Issue Tracker contains a list of pending technical tasks
across a variety of topics, information relevant to those tasks, and
information about progress on those tasks, including which ones might
get worked on in the short term.

You should upgrade your FirebaseUI for Android version. FirebaseUI for Android v6.3.0 is a minor release containing new features and bug fixes. Read v6.3.0.
   implementation 'com.firebaseui:firebase-ui-firestore:6.3.0'
   implementation 'com.firebaseui:firebase-ui-auth:6.3.0'

FYI
If same issues still coming then You can downgrade your version for now
   implementation 'com.google.firebase:firebase-inappmessaging-display:19.1.0'
   implementation 'com.google.firebase:firebase-inappmessaging:19.1.0'


text:
Q: Why do the Matrix machines not implement a backup system? In the first movie, we see Agents possessing several bluepills to be able to communicate with the Matrix. Every time something that is incompatible with survival happens, that bluepill's RSI is restored; that is, the Agents stop possessing people when they die. However, said person is still a viable source of energy, and that person was just flushed down the toilet (literally).
My question is, why didn't the machines do something to prevent that? For example, for the time that the RSI is in use, put the person in a coma. Or create a layered structure: the bluepills are in a sort of Construct, and that Construct is used as a proxy to the Matrix; whenever the person dies in the Matrix due solely to reasons simulated by the Matrix (for example, being shot), that person is then connected to a different RSI: of someone else of the same age who has died, for instance, or a new one altogether. (I believe something similar had happened with Trinity in Reloaded: she was killed within the Matrix and subsequently revived within the Matrix. She was a redpill, however, and wasn't generating energy for the machines, and was anyway on a hovercraft during the time, so that doesn't count.)
And yes, I am aware of this question, but mine is about the bluepills and not the redpills.

A: Agents don't (usually) die.

Morpheus: ...Every single man or woman who has stood their ground, everyone who
has fought an agent, has died. I've seen an Agent punch through a
concrete wall. Men have emptied entire clips at them and hit nothing
but air
The Matrix: Agents

Hence the need for a system that preserves the host body in the event of Agent death is essentially worthless.

You may also wish to note that although we spend a lot of time watching them, there are relatively few Zionese rebels and even fewer Agents. The general population (of several billion) can easily stand to lose a few people without even noticing the loss.

A:
Every time something that is incompatible with survival happens, that bluepill's RSI is restored; that is, the Agents stop possessing people when they die. However, said person is still a viable source of energy, and that person was just flushed down the toilet (literally).

Actually, the dead bluepill would not be flushed down the toilet, literally or figuratively. According to Morpheus the dead bluepill would be used to feed living bluepills:

There are fields, endless fields, where human beings are no longer born. We are grown. For the longest time I wouldn't believe it, and then I saw the fields with my own eyes. Watch them liquefy the dead so they could be fed intravenously to the living.
The Matrix (transcript)

The scheme you suggest sounds rather complicated -- the machines would have to plant false memories into a bluepill who happened to "die" along with all the other bluepills who knew/know the bluepill (both in his former life and his newly constructed one). It's probably not worth it to the machines considering

*

*the rarity of an Agent's death (usually only when fighting the One, or possibly when a redpill gets a lucky kill)

*the fact that the loss of one bluepill among billions constitutes an insignificant loss of power

*the machines can and do recycle dead bluepills to feed living ones (it's not a total loss)


text:
Q: Issues opening projects on my Teacher's computer I am a high school student working in Visual Basic on VS2019 and using .NET 5.0, my teacher is using VS2015 and using .NET 4.5.2, we are having difficulties opening my projects on his computer. This is the error in the output log

The default XML namespace of the project must be the MSBuild XML
namespace. If the project is authored in the MSBuild 2003 format,
please add xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
to the  element. If the project has been authored in the old
1.0 or 1.2 format, please convert it to MSBuild 2003 format.  D:\DiceRoll03\DiceRoll03\DiceRoll03.vbproj

If anyone understands this or has seen this problem before, any help would be appreciated.

A: Net 5.0 projects only be supported on at least VS2019 16.8.  See this document.

It means the vs versions before that do not support NET 5.0 including VS2015.
So you should let your teacher's computer download the latest VS2019 community free version and then you can work with that.


text:
Q: How can I create my own Error messages form firebase login/register page. For Example, If password/email is invalid Currently it shows the below error messages when either entering invalid email or invalid password,

how can i customize it to my own error messages?
below is my sigin function.
function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const { setTimeActive } = useAuthValue();
  const navigate = useNavigate();

  const login = (e) => {
    e.preventDefault();
    signInWithEmailAndPassword(auth, email, password)
      .then(() => {
        if (!auth.currentUser.emailVerified) {
          sendEmailVerification(auth.currentUser)
            .then(() => {
              setTimeActive(true);
              navigate("/verify-email");
            })
            .catch((err) => alert(err.message));
        } else {
          navigate("/");
        }
      })
      .catch((err) => setError(err.message));
  };


text:
Q: What happens to temperature as volume increases (charles law) Let us take Boyles law to start.
Assumptions:

*

*Gas is perfect.

*In a massless piston that can be expanded with no friction

*Adiabatic

If we were to decrease the volume of the piston, the pressure inside would go up because the gas molecules would be hitting the sides more often.
If we were to increase the outside pressure on the piston, the volume of the piston would go down until the internal pressure matched the external pressure.
We see here that Boyle's law is perfectly explained by the kinetic model of gases (T held constant).

Let's look at Charles law (P held constant)
If we were to increase the temperature of the molecules, their kinetic energy would increase and would therefore hit the piston with greater force and increase the volume of the piston until the internal and external pressures are equal.
But if we were to spontaneously increase the volume of the piston, the temperature would NOT increase as a result (to maintain the increased volume against the constant external pressure) because heat doesn't spontaneously arise.
So it seems that Charles law only works one way, but not the other. And that T and V are not intrinsically linked like P and V are in Boyles law. Is this true?

A: The answer itself is hidden in the second part of your question. P in any gas law refers to the pressure inside the volume of the container [ which is always equal to the external pressure on the container ]
Now, in the second part of your question, the statements

(P held constant)

&

if we were to spontaneously increase the volume of the piston

cannot be true simultaneously.
As soon as you want to increase the volume of the container (irrespective of the method of achieving such a change -- whether by a reversible piston process or via irreversible free expansion), you have to reduce the external pressure on the piston & thereby the pressure inside the container also reduces & then you can apply kinetic theory accordingly [ Note that unless these two P's are equal, you cannot apply any gas law because they are valid only for equilibrium situations. It's very important to keep this condition in mind when you are thinking about such thought experiments. ]
To conclude, all gas laws work irrespective of whether the change in the variables are positive or negative as long as you are being careful to satisfy all conditions including the condition of equilibrium & reversibility.

A: Compressing a gas that is not at absolute zero will increase its temperature because a finite volume of gas at a finite temperature has a set amount of heat energy. when that set amount of heat energy occupies a smaller space its temperature rises. Conversely when it occupies a larger space its temperature goes down. so both laws are reversible.


text:
Q: Save product attribute where value contains umlaut I have an issue where I have multiple values in German containing umlauts and other special characters - Portionsgröße: 30g (ein großer Portionslöffel).
$var = Portionsgröße: 30g (ein großer Portionslöffel);

If I do $product->setData('attribute_name', $var); it only saves part of the text. So in this case it would return - echo $product->getData('attribute_name') - Portionsgr
htmlspecialchars and htmlentities doesn't fix the issue. Any advice

A: I can't imagine how the variable assignment worked. You should have gotten a syntax error (syntax error, unexpected ':').
Please put single quotes around the value:
$var = 'Portionsgröße: 30g (ein großer Portionslöffel)';

A: I achieved the desired result in the end by using the php function utf8_encode(data).


text:
Q: Does a connection specific dns suffix dictate which DNS servers are queried on Windows? Scenario:

*

*Windows 10 client machine

*Adapter #1 has subnet 192.168.1.0/24 with dns server of 192.168.1.1 and a DNS suffix of test.local

*Adapter #2 (software vpn) has subnet of 10.10.10.0/24 with dns server of 10.10.10.5 and DNS suffix of lan.company.net

*company.net is split horizon and resolves differently on the open wan as opposed to the corporate lan.

*local routing table dictates 192.168.1.1 as the default gateway

So, if the client were to query host1.local.company.net, would windows query 10.10.10.5? Maybe it would query both? If so, what would dictate the order? If it queries both simultaneously, is there a race condition here due to the split horizon config?
Thanks,
D


text:
Q: Cyrillic does not show in MySQL When I insert cyrillic text through PHP it inserts a row but with empty records:
<?php

$link = new mysqli('localhost', 'xxx', 'xxx', 'xxx');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* change character set to utf8 */
if (!mysqli_set_charset($link, "utf8")) {
    printf("Error loading character set utf8: %s\n", mysqli_error($link));
} else {
    printf("Current character set: %s\n", mysqli_character_set_name($link));
}

if($link->connect_errno > 0){
    die('Unable to connect to database [' . $link->connect_error . ']');
}

mysqli_query($link, "INSERT INTO applications (firstname, lastname, university, specialty, course, hobby, motivation, phone, email) VALUES ('да', 'да', 'да', 'да', 'да', 'да', 'да', 'да', 'да')");

mysqli_close($link);

?>

When I remove the /* change character set to utf8 */ the entries are symbols... Where is the problem?

A: Call this after you connect to your database:
mysql_query("SET NAMES UTF8");

Source


text:
Q: What do you mean by in the mirror world? I was trying an attempt to replicate Wu experiment mentally when I heard the term mirror world kept popping ups, why should we care what happens inside the mirror world? Is it a math thing?

A: Yes, it's a math thing. However, since physics is about describing the world as it is, and since physicists use mathematics to "understand" the laws of nature, the implications matter: If we include this "thing" in our mathematics to describe nature, we alter our predictions about nature.
Symmetries and conservation laws are fundamental in physics, because they tell us much about nature. E.g. we "know" that the momentum is conserved in a collision of two particles, and we "know" that fermions have an anti-symmetric wave function. These laws help us to predictable the outcome of experiments and to cross-check our calculations: If I do some calculation and obtain a non-symmetric (neither symmetric nor anti-symmetric) wave function of a fermion, I better redo my calculation. The same is true if I try to formulate an equation: If we use an equation which is not invariant under Lorentz transformation, we "know" that it probably only an approximation -- I use quotations marks for the word know, because this is still only an educated guess.
The same is true for parity. Parity is a fundamental symmetry. It is quite "natural" for us to assume that it is conserved. Thus, it was rather shocking when Wu published her finding and proved that the weak interaction does not conserve parity.
In order to put this into some perspective, let's consider modern assumptions. Today, "we" believe that CPT (charge, parity, time) is a conserved quantity under inversion. It is a valuable assumption, because it helps to sort our list of theories according to their probability of correctness: A theory which does not conserve CPT is generally considered to be less probable true than a theory which conserves CPT. Thus, this CPT "math thing" has implications: Physicists around the world use it to modify their theories.
The math of parity is defined here, while the Wikipedia article about Wu's experiment provides a simple example to the topic. Consider a 2D clock (left picture) and it's mirror (right picture)

In a world which conserves parity and were a "left clock" rotates clockwise, the mirror image of the clock rotates anti-clockwise, see upper image. However, if we would observe that the mirror image of the clock rotates clockwise as well,

we would conclude that parity is not conserved.

A: The mirror universe is a universe in which the arrow time is pointing opposite to the time arrow in our universe (in reality the mirror should be 4-dimensional). Both arrows start at the big bang. Things happening in that mirror universe are happening at the same time as things over here, but "on the other side" of the big bang. I'm not so sure that things happening in that universe are identical to things happening here. I don't hope so, because I don't believe there is an anti-copy of me somewhere. Though an anti-me could be fun!
Here is a picture of the evolution of our universe since the big bang.

When you put a mirror at the flashing bang (perpendicular to it), then you will see in this mirror, well, a mirrored universe. A mirror universe. Identical to ours but the arrow of time, space (together spacetime), and matter and anti-matter are in(re)versed. I think this doesn't correspond to reality though. We will never be sure though.
As an aside
It's my guess there does exist a kind of mirror universe, but with the mirror placed parallel to our universe. The arrow of time is pointed there in the same direction as in our universe.
In the rishon model matter and anti-matter are present in equal amounts in our universe. In this mirror universe also, but nevertheless what we call here matter (quarks, electrons, protons, etc.), is "over there" anti-matter (anti-quarks, anti-electrons, anti-protons, etc.). Not because of the mirror but because of the rishons are anti-rishons over there. Things over there don't have to happen identically to things happening here, but the rishon content is the same.
And here, too, we never will be sure. We *can** however, investigate if rishons exist.

A: Parity (aka reflection aka the mirror world) is when you switch coordinates from $x, y, z$ to $-x, -y, -z$.
This looks so much like a simple coordinate transform that we would instinctively expect it to lead to the same physics, except it doesn't.


text:
Q: Beautifulsoup doesn't reach a child element I wrote the following code trying to scrape a google scholar page
import requests as req
from bs4 import BeautifulSoup as soup

url = r'https://scholar.google.com/scholar?hl=en&q=Sustainability and the measurement of wealth: further reflections'

session = req.Session()
content = session.get(url)
html2bs = soup(content.content, 'lxml')
gs_cit = html2bs.select('#gs_cit')
gs_citd = html2bs.find('div', {'id':"gs_citd"})
gs_cit1 =  html2bs.find('div', {'id':"gs_cit1"})

but the gs_citd gives me only this line

 and doesn't reach any level beneath it. Also gs_cit1 returns a None.
As appearing in this image

I want to reach the highlighted class to be able to grab the BibTeX citation.
Can you help, please!

A: Ok, so I figured it out. I used the selenium module for python which creates a virtual browser if you will that will allow you to perform actions like clicking links and getting the output of the resulting HTML. There was another issue I ran into while solving this which was the page had to be loaded otherwise it just returned the content "Loading..." in the pop-up div so I used the python time module to time.sleep(2) for 2 seconds which allowed the content to load in. Then I just parsed the resulting HTML output using BeautifulSoup to find the anchor tag with the class "gs_citi". Then pulled the href from the anchor and put this into a request with "requests" python module. Finally, I wrote the decoded response to a local file - scholar.bib.
I installed chromedriver and selenium on my Mac using these instructions here:
https://gist.github.com/guylaor/3eb9e7ff2ac91b7559625262b8a6dd5f
Then signed by python file to allow to stop firewall issues using these instructions:
Add Python to OS X Firewall Options?
The following is the code I used to produce the output file "scholar.bib":
import os
import time
from selenium import webdriver
from bs4 import BeautifulSoup as soup
import requests as req

# Setup Selenium Chrome Web Driver
chromedriver = "/usr/local/bin/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)

# Navigate in Chrome to specified page.
driver.get("https://scholar.google.com/scholar?hl=en&q=Sustainability and the measurement of wealth: further reflections")

# Find "Cite" link by looking for anchors that contain "Cite" - second link selected "[1]"
link = driver.find_elements_by_xpath('//a[contains(text(), "' + "Cite" + '")]')[1]
# Click the link
link.click()

print("Waiting for page to load...")
time.sleep(2) # Sleep for 2 seconds

# Get Page source after waiting for 2 seconds of current page in Chrome
source = driver.page_source

# We are done with the driver so quit.
driver.quit()

# Use BeautifulSoup to parse the html source and use "html.parser" as the Parser
soupify = soup(source, 'html.parser')

# Find anchors with the class "gs_citi"
gs_citt = soupify.find('a',{"class":"gs_citi"})

# Get the href attribute of the first anchor found
href = gs_citt['href']

print("Fetching: ", href)

# Instantiate a new requests session
session = req.Session()

# Get the response object of href
content = session.get(href)

# Get the content and then decode() it.
bibtex_html = content.content.decode()

# Write the decoded data to a file named scholar.bib
with open("scholar.bib","w") as file:
    file.writelines(bibtex_html)

Hope this helps anyone looking for a solution to this out.
Scholar.bib file:
@article{arrow2013sustainability,
  title={Sustainability and the measurement of wealth: further reflections},
  author={Arrow, Kenneth J and Dasgupta, Partha and Goulder, Lawrence H and Mumford, Kevin J and Oleson, Kirsten},
  journal={Environment and Development Economics},
  volume={18},
  number={4},
  pages={504--516},
  year={2013},
  publisher={Cambridge University Press}
}

A: You can parse BibTeX data using beautifulsoup and requests by parsing data-cid attribute which is a unique publication ID. Then you need to temporarily store those IDs to a list, iterate over them, and make a request to every ID to parse BibTeX publication citation.

Example below will work for ~10-20 requests then Google will throw a CAPTCHA or you'll hit the rate limit. The ideal solution is to have a CAPTCHA solving service as well as proxies.
Code and full example in the online IDE:
from bs4 import BeautifulSoup
import requests, lxml

params = {
    "q": "samsung",
    "hl": "en"
}

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3538.102 Safari/537.36 Edge/18.19582",
    "server": "scholar",
    "referer": f"https://scholar.google.com/scholar?hl={params['hl']}&q={params['q']}",
}

def cite_ids() -> list:
    response = requests.get("https://scholar.google.com/scholar", params=params, headers=headers, timeout=10)
    soup = BeautifulSoup(response.text, "lxml")

    # returns a list of publication ID's -> U8bh6Ca9uwQJ
    return [result["data-cid"] for result in soup.select(".gs_or")]

def scrape_cite_results() -> list:

    bibtex_data = []

    for cite_id in cite_ids():
        response = requests.get(f"https://scholar.google.com/scholar?output=cite&q=info:{cite_id}:scholar.google.com", headers=headers, timeout=10)
        soup = BeautifulSoup(response.text, "lxml")

        # selects first matched element which in this case always will be BibTeX
        # if Google will not switch BibTeX position.
        bibtex_data.append(soup.select_one(".gs_citi")["href"])

    # returns a list of BibTex URLs, for example: https://scholar.googleusercontent.com/scholar.bib?q=info:ifd-RAVUVasJ:scholar.google.com/&output=citation&scisdr=CgVDYtsfELLGwov-iJo:AAGBfm0AAAAAYgD4kJr6XdMvDPuv7R8SGODak6AxcJxi&scisig=AAGBfm0AAAAAYgD4kHUUPiUnYgcIY1Vo56muYZpFkG5m&scisf=4&ct=citation&cd=-1&hl=en
    return bibtex_data

Alternatively, you can achieve the same thing using Google Scholar API from SerpApi without the need to figure out what proxy provider provides good proxies as well as with the CAPTCHA solving service, besides figuring out how to scrape the data from the JavaScript without using browser automation.
Example to integrate:
import os
from serpapi import GoogleSearch

def organic_results() -> list:
    params = {
        "api_key": os.getenv("API_KEY"),
        "engine": "google_scholar",
        "q": "samsung",  # search query
        "hl": "en",      # language
    }

    search = GoogleSearch(params)
    results = search.get_dict()

    return [result["result_id"] for result in results["organic_results"]]

def cite_results() -> list:

    citation_results = []

    for citation in organic_results():
        params = {
            "api_key": os.getenv("API_KEY"),
            "engine": "google_scholar_cite",
            "q": citation
        }

        search = GoogleSearch(params)
        results = search.get_dict()

        for result in results["links"]:
            if "BibTeX" in result["name"]:
                citation_results.append(result["link"])

    return citation_results

If you would like to parse the data from all available pages, there's a dedicated blog post Scrape historic Google Scholar results using Python at SerpApi which is all about scraping historic 2017-2021 Organic, Cite results to CSV and SQLite using pagination.

Disclaimer, I work for SerpApi.


text:
Q: Does anyone know what "discoverd" daemon is? Saw this process running in Activity Monitor.  Not sure what it does...anyone seen this before?
Tried searching for list of "normal" mac os daemons but most lists are incomplete.  Have not found any sites which listed "discoverd" as one of the standard daemons.  Is this a malware?

A: https://launchpad.net/discoverd:

DiscoverD is a collection of discovery and monitoring daemons to scan
  and collect all information available about any active host running on
  your network. This collection of daemons comes with an optional web
  front-end running on a classic LAMP stack (Apache2, PHP5) to configure
  the various options and to watch the monitoring results.

A: Your version of OS X would help, but discoverd is a standard daemon. It replaces the old MDNS responder for use with bonjour on OS X 10.10.
There's no need to worry