text:
Q: DB2 driver class connot be resolved in persistence.xml and getting entityManager exception I am given a project and I have to make it run in my local machine.
It has actually many projects that compile into jar files and a main project that compiles to ear including those jars.
The application is run on WebSphere server and although it runs I eventually get an error concerning the entity manager. Logs are not displaying anything but after debugging, when calling a method from a class from a specific jar, I am getting the following exception:

javax.el.ELException: javax.ejb.EJBException:
      The com.xxx.xxx.managers.xxxManager/entityManager reference of type
      javax.persistence.EntityManager for the XXXManager component in the
      xxx-managers.jar module of the XXXPortal_ear application cannot be resolved.

After inspecting further I saw that IntelliJ marks my persistence.xml with some errors:
<!-- Hibernate -->
<!-- <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.WebSphereExtendedJTATransactionLookup"/> -->
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.WebSphereJtaPlatform" />
<property name="hibernate.default_schema" value="XXX_TRANSACTIONS"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.DB2Dialect"/>
<property name="hibernate.connection.driver_class" value="com.ibm.db2.jcc.DB2XADataSource"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.max_fetch_depth" value="3"/>
<property name="hibernate.default_batch_fetch_size" value="100"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
<!-- OpenJPA -->
<property name="openjpa.jdbc.Schema" value="XXX_TRANSACTIONS"/>
<property name="openjpa.ConnectionDriverName" value="com.ibm.db2.jcc.DB2XADataSource"/>
<property name="openjpa.ConnectionFactoryProperties" value="PrintParameters=True, PrettyPrint=true" />
<property name="openjpa.Log" value="DefaultLevel=DEBUG, Runtime=TRACE, Tool=INFO, Query=TRACE, JDBC=ERROR, SQL=ERROR" />

The XXX_TRANSACTIONS values of the property hibernate.default_schema is marked with red and hovering displays:

Cannot resolve schema 'XXX_TRANSACTIONS'

Also, at the hibernate.connection.driver_class property, part of the value "com.ibm.db2.jcc.DB2XADataSource" is marked red (only db2.jcc.DB2XADataSource is red).
Hovering displays:

Cannot resolve class 'DB2XADataSource'

I tried importing db2jcc.jar but then I get

com.ibm.db2.jcc.DB2XADataSource' is not assignable to 'java.sql.Driver'

at the driver class property.
There might be a chance that I messed something up in the WebSphere configuration.
I can provide further information if needed.
Please help. Thanks in advance.
EDIT:
Those are lines from the persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="XxxModel">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>XxxDatasource</jta-data-source>
        <mapping-file>META-INF/orm.xml</mapping-file>
        <class>...

I am also posting the General properties of the JDBC provider of WebSphere:

@Andy Guibert: sadly I cannot upgrade the Hibernate version, it could cause problems when we redeploy to the customer so I cannot perform major changes.
I have to mention that the application works on an other machine. It is opened in the Rational Application Developer Studio (eclipse version for IBM). I am trying to setup on my local machine on IntelliJ IDEA Ultimate Edition. One difference that I spotted is that the jar created in my environment did not include the persistence.xml and other resource files of that particular module. I used the maven resources plugin to included in my jar:
    <resources>
      <resource>
          <directory>src/main/java/META-INF</directory>
      </resource>
  </resources>

Despite that, the problem persist and while debbuging I am still getting the exception that I wrote at the original post.

A: I believe that the hibernate.connection.driver_class property is for your JDBC driver's implementation class of the java.sql.Driver class, but you have listed com.ibm.db2.jcc.DB2XADataSource, which is DB2's implementation of java.sql.XADataSource, not its implementation of java.sql.Driver.
In any case, I would not recommend that you configure Hibernate this way on WebSphere, because when you configure Hibernate to look directly at a driver class it will bypass WebSphere's connection pool and you will have lesser performance.
Instead, I would recommend configuring a DataSource in WebSphere, and then reference the DataSource JNDI name in your persistence.xml like this:
<persistence ...>

  <persistence-unit name="SOME_PU" transaction-type="JTA">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <jta-data-source>jdbc/YOUR_DATASOURCE</jta-data-source>
  </persistence-unit>

</persistence>

Note that as of Hibernate 5.2.17.Final, Hibernate has a new transaction integration class that is capable of fully integrating with the WebSphere (traditional or Liberty) transaction manager.  If you are using this version or newer, then it is not necessary to hibernate.transaction.jta.platform


text:
Q: MongoDB timeout Exception (C#) We're developing a chatbot using microsoft framework (v3) along with cosmos's mongo API. We've had no issues up until recently when the bot suddenly stopped working locally. On further inspection, we found that we were getting a timeout exception.

"A timeout occured after 30000ms selecting a server using
  CompositeServerSelector{ Selectors =
  MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector,
  LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000
  } }. Client view of cluster state is { ClusterId : "1", ConnectionMode
  : "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers :
  [{ ServerId: "{ ClusterId : 1, EndPoint :
  "Unspecified/hakeemdb.documents.azure.com:10255" }", EndPoint:
  "Unspecified/hakeemdb.documents.azure.com:10255", State:
  "Disconnected", Type: "Unknown" }] }. "

Interestingly enough the bot still works when it is deployed to skype, the problem only seems to occur locally. When querying to database directly, queries run without a hitch, it only seems to be a problem when running the bot locally. We've had updated all our mongo drivers to the most up to date stable versions with no luck.
We've also tried solutions from the following links:
MongoDB C# 2.0 TimeoutException
https://jira.mongodb.org/browse/CSHARP-1302
https://jira.mongodb.org/browse/CSHARP-2540
I also found this stack overflow post:
MongoDB C# driver timeout
but I'm a little unsure if what it means, although it seems to be very close to the issue we are having.
I haven't included any code because I don't think it's a code issue as it started without any change to any of the code.
Another point that could be important is that recently all our resources in azure were moved to a new region so something could have changed during that. We thought that maybe some securities settings had been changed during the migration and the IP of our workplace was being blocked but the database seems to be set to allow connections from all sources so I'm not sure if that's the issue
Any advice or ideas would be greatly appreciated

A: In the end the wifi network at my work updated their firewall settings and one of the ports we were using for Mongo was blocked. We bypassed the port restrictions by connecting to the physical local network and it worked after that

redpajama_set_name: RedPajamaStackExchange


text:
Q: EntityExistsException when creating new element Here is my bean :
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "cl_id")
private Long clId;

@JoinColumn(name = "zip_id", referencedColumnName = "zip_id")
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private Zip zipId;
@JoinColumn(name = "city_id", referencedColumnName = "city_id")
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private City cityId;
@JoinColumn(name = "street_id", referencedColumnName = "street_id")
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private Street streetId;

My problem is, whenever I try to insert a new client that uses
an already existant zip, city or street I get this error :
Exception in thread "AWT-EventQueue-0" javax.persistence.EntityExistsException:
Exception Description: Cannot persist detached object [bean.Zip[zipId=17]].
Class> com.jresto.common.bean.Zip Primary Key> [17]
at  oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.persist(EntityManagerImpl.java:208)

It doesn't consider the CascadeType.MERGE part.

A: You're persisting a new Bean (assuming that's the name of your entity). And you told Hibernate that whenever you persist a Bean, persist() must also be called on the zip of the Bean. And the bean contains a zip which has an ID of a zip which already exists in the database. So obviously, you get this exception.
Either use merge() instead of persist, or look up the zip from the session, attach the retrieved persistent zip to the bean, and persist the bean.
Cascading a ManyToOne association is a bit strange. You have several bean instances sharing a single zip, and whenever you modify one of the beans, the zip is modified for all the other beans.


text:
Q: How do I capture the response of URL every-time new tab opens I'm trying to develop a web-scraping project, in which I am scraping a website called Startup India, which you can use for connecting with startups. Here, I have clicked based on some filters I selected , and clicked on every startup and when I click on every startup, I have to go inside that startup and scrape it.  But I can't scrape the data because I'm not able to capture the response for scraping profiles in startup India.
import scrapy
from selenium import webdriver
import os
import logging
class ProductSpider(scrapy.Spider):
    name = "product_spider"
    allowed_domains = ['https://www.startupindia.gov.in/']
    start_urls = ['https://www.startupindia.gov.in/content/sih/en/search.html?industries=sih:industry/advertising&states=sih:location/india/andhra-pradesh&stages=Prototype&roles=Startup&page=0']

    def __init__(self):
        cwd = os.getcwd()
        self.driver = webdriver.Chrome("C:/Users/RAJ/PycharmProjects/WebCrawler/WebCrawler/WebCrawler/spiders/chromedriver.exe")

    def parse(self, response):
        self.driver.get(response.url)

        next = self.driver.find_elements_by_xpath("//*[@id='persona-results']//a[@class='img-wrap']")

        logging.info(next)

        for i in next:
            try:
                logging.info(i.click())
                logging.info(response.url)

                # get the data and write it to scrapy items
            except:
                print("Yolo")

Code will be appreciated

A: I have setup scrapy project and run  scrapy crawl product_spider and it gives URL of new tab open after clicking on an element.
import scrapy
from selenium import webdriver
import os
import logging
from selenium.webdriver.chrome.options import Options as ChromeOptions

CHROME_DRIVER_UBUNTU_PATH = "your chrome driver path"

class ProductSpider(scrapy.Spider):
    name = "product_spider"
    allowed_domains = ['https://www.startupindia.gov.in/']
    start_urls = [
        'https://www.startupindia.gov.in/content/sih/en/search.html?industries=sih:industry/advertising&states=sih:location/india/andhra-pradesh&stages=Prototype&roles=Startup&page=0']

    def __init__(self):
        cwd = os.getcwd()
        opts = ChromeOptions()
        opts.add_argument("--headless")  # for headless browser it's not necessary

        self.driver = webdriver.Chrome(executable_path=CHROME_DRIVER_UBUNTU_PATH, chrome_options=opts)

    def parse(self, response):
        self.driver.get(response.url)

        next = self.driver.find_elements_by_xpath("//*[@id='persona-results']//a[@class='img-wrap']")

        for i in next:
            try:
                i.click()  # click on image in page
                # move to new tab open
                self.driver.switch_to.window(self.driver.window_handles[next.index(i) + 1])
                logging.info(self.driver.current_url)

                self.driver.switch_to.window(self.driver.window_handles[0])
                # get the data and write it to scrapy items
            except Exception as e:
                print(e)


text:
Q: Performing a keyword search across all open excel workbooks VBA I've been working on a lot of Excel VBA Macros codes and have achieved a lot. I've run into an issue, where I wish to perform a search for a keyword that may be available in one of the open Excel Workbooks, like - ABC12345 and I want the criteria to be met if "ABC" is found in cell B2.
My code so far:
Sub ABC_Upload()
Sheets("Add File Here").Select
If IsEmpty(Range("A1")) Then
  Worksheets("Master Mapper").Activate

  Dim answerABC As Integer
answerABC = MsgBox("Please check the Data Sheet. No value found in first row! Do you wish to find XYZ file in open workbooks and start process?", vbYesNo + vbQuestion, "Review & Proceed")
If answerABC = vbYes Then

    'Starts here
    Dim wSheet As Worksheet
    Dim wBook As Workbook
    Dim XYZFound As Range
    Dim xFound As Boolean
    Dim lngLastRow2 As Long

    On Error Resume Next
    For Each wBook In Application.Workbooks
        For Each wSheet In wBook.Worksheets
            Set XYZFound = Nothing
            Set XYZFound = wSheet.Cells.Find(What:="ABC", After:=wSheet.Cells(1, 1), _
            LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
            SearchDirection:=xlNext, MatchCase:=True)
            'Set XYZFound = wSheet.Cells.Find(What:="BIC", After:=wSheet.Cells(1, 1), _
            LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
            SearchDirection:=xlNext, MatchCase:=False)

            'XYZFound.Cells.Select
            If Not XYZFound Is Nothing Then
                xFound = True
                Application.Goto XYZFound, True
            'Rows(1, 2).EntireRow.Hidden = True
            lngLastRow2 = Cells(Cells.Rows.Count, "B").End(xlUp).Row
            Range("A1:E" & lngLastRow2).Copy
            ThisWorkbook.Worksheets("Add File Here").Activate
            Range("A1").Select
            ActiveSheet.Paste
            Application.CutCopyMode = False

            End If

        Next wSheet
        If xFound Then Exit For
        Next wBook

If XYZFound Is Nothing Then
MsgBox "No open file for XYZ Meetings Found. Make sure the most recent XYZ Excel WB is open!", vbCritical + vbOKOnly
Exit Sub
End If
    'Ends Here

Sheets("Add File Here").Select
Columns("A").Replace _
 What:=";", Replacement:=""
Columns("A").Replace _
 What:=":", Replacement:=""
Columns("A").Replace _
 What:=",", Replacement:=""
Columns("A").Replace _
 What:="(", Replacement:=""
Columns("A").Replace _
 What:=")", Replacement:=""
Columns("A").Replace _
 What:="{", Replacement:=""
Columns("A").Replace _
 What:="}", Replacement:=""
Columns("A").Replace _
 What:="[", Replacement:=""
Columns("A").Replace _
 What:="]", Replacement:=""
Columns("A").Replace _
 What:="~+", Replacement:=""
Columns("A").Replace _
 What:="~*", Replacement:=""
Columns("A").Replace _
 What:="~?", Replacement:=""
Columns("A").Replace _
 What:="_", Replacement:=""
Columns("A").Replace _
 What:=".", Replacement:=""
Columns("A").Replace _
 What:="'", Replacement:=""
Columns("A").Replace _
 What:="\", Replacement:=""
Columns("A").Replace _
 What:="/", Replacement:=""
Columns("A").Replace _
 What:=".", Replacement:=""
Columns("A").Replace _
 What:="@", Replacement:=""
Columns("A").Replace _
 What:=Chr(34), Replacement:=""

Columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("C1").Value = "Client ID"
Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("D1").Value = "Client Name"
Columns("E:E").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("E1").Value = "Planner Name"
Columns("I:I").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("I1").Value = "External System Name"
Dim rng As Range
    Dim i As Long

    'Set the range in column A you want to loop through
    Set rng = Range("B2:B100")
    For Each cell In rng
        'test if cell is empty
        If cell.Value <> "" Then
            'write to adjacent cell
            cell.Offset(0, 1).Value = "Company ID"
        End If
    Next
Dim rngC As Range
    Dim Ci As Long

    'Set the range in column A you want to loop through
    Set rngC = Range("C2:C100")
    For Each cell In rngC
        'test if cell is empty
        If cell.Value <> "" Then
            'write to adjacent cell
            cell.Offset(0, 1).Value = "Company"
        End If
    Next
Dim rngP As Range
    Dim Pi As Long

    'Set the range in column A you want to loop through
    Set rngP = Range("D2:D100")
    For Each cell In rngP
        'test if cell is empty
        If cell.Value <> "" Then
            'write to adjacent cell
            cell.Offset(0, 1).Value = "NA"
        End If
    Next
Dim rnEP As Range
    Dim Ei As Long

    'Set the range in column A you want to loop through
    Set rngE = Range("H2:H100")
    For Each cell In rngE
        'test if cell is empty
        If cell.Value <> "" Then
            'write to adjacent cell
            cell.Offset(0, 1).Value = "Company"
        End If
    Next
'MsgBox "File has been formatted for XYZ and is ready for MMS upload.", vbOKOnly
Dim answer As Integer
answer = MsgBox("Temporary File Prepared for XYZ. Do you wish to proceed with MMS_NewMtgs file creation?", vbYesNo + vbQuestion, "Review & Proceed")
If answer = vbYes Then
    Call Prepare_OutputFile
Else
    MsgBox "Output file not created!! Please select - Click to create MMS Formatted File from Master Mapper.", vbOKOnly
End If
End If
End If
ThisWorkbook.Saved = True
End Sub

Any suggestions would be greatly appreciated.
Thanks!

A: Aside from what @nwhaught said, there is a problem in If xFound = 1 Then Exit For. Your xFound is declared as Boolean and despite you set a value of 1 (one) to it, the real value is True. Now, for VBA True is not equal 1 and your If condition is always False. The value of True in VBA is -1, but you don't need this. Just use If xFound Then Exit For, as checking a value of boolean is enough, there's no need to compare it with another boolean.

A: Your issue is that you don't exit your inner for loop in time.  You exit the outer for after processing all of the sheets, which is setting XYZfound back to nothing.
If you only need to find this thing once, then move your 'exit for' up a couple of lines, and terminate the loop before processing the next sheet in the workbook.

A: you can shorten the search lines by using this:
    Columns("A").Replace ";", ""
    Columns("A").Replace ":", ""
    Columns("A").Replace ",", ""
    Columns("A").Replace "(", ""
    Columns("A").Replace ")", ""
    Columns("A").Replace "{", ""
                 .
                 .
                 .
                 .

this is an example of a good reason to use the With command
    With Columns("A")
        .Replace ";", ""
        .Replace ":", ""
        .Replace ",", ""
        .Replace "(", ""
        .Replace ")", ""
        .Replace "{", ""
                 .
                 .
                 .
    End With

or this:
    Dim badText As Variant
    For Each badText In Array(";", ":", ",", _
                               "(", ")", "{", "}", "[", "]", _
                               "~+", "~*", "~?", "_", ".", _
                               "'", "\", "/", "@", """")       ' chr(34) = " (quote), in VBA string it must be escaped by doubling it up

        Columns("A").Replace badText, ""
    Next badText

another place to simplify:
the two range content checks where you put the text "Company" beside each non-empty cell
Set rngC = Range("C2:C100")
For Each cell In rngC
         .
         .
Set rngE = Range("H2:H100")
For Each cell In rngE
         .

the two For loops can be combined into one that starts with this line:
For Each cell In Range("C2:C100, H2:H100")


text:
Q: How to get a particular frameset functionality in asp.net I'm coding a page for a company website. We want to be able to click a link in the sidebar and have it open in the same window, beside the sidebar.
This is possible using frames, however I'm using Visual Studio to code the site with ASP.net, and ASP isn't accepting the frameset model. Moreover, I know that frames are generally frowned upon and for good reason.
Is there a way to code the page within ASP to do what we need? I've spent a couple of hours searching and I can find a bunch of ways to set a page up without using frames (which I already knew), but haven't yet seen anything that mentions a way to get a menu selection on the left to open in the column on the right.
Any help?


text:
Q: StackExchange.Redis.IDatabase.StringSetAsync stops setting data in cache Stackoverflow!
Please, help me to find an error in my services. The story:
I have very simply .net 5 console app that periodically makes web request to external resource and stores data in Redis cache via StackExchange.Redis so at any moment the cache contains actual value.
internal class TimedService : BackgroundService
{
    readonly ILogger<TimedService> _logger;
    readonly IServiceScopeFactory _services;
    readonly RedisStore _redisStore;

    public TimedService(
        ILogger<TimedService> logger,
        IServiceScopeFactory services,
        RedisStore redisStore)
    {
        _logger = logger;
        _services = services;
        _redisStore = redisStore;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await UpdateBinanceRates();
            await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
        }
    }

    async Task UpdateBinanceRates()
    {
        using var scope = _services.CreateScope();
        var binanceAdapter = scope.ServiceProvider.GetRequiredService<IBinanceRatesAdapter>();

        var rate = await binanceAdapter.GetPriceAsync(Currency.USDT, Currency.BTC);
        if (rate.IsFailure)
        {
            _logger.LogError($"Unable to receive rate from binance.");
            return;
        }

        try
        {
            var settingResult = await _redisStore.SetObjectAsync(RedisSharedKeys.BinanceKey, rate.Value, TimeSpan.FromSeconds(20));
            if (!settingResult)
                _logger.LogError($"Unable to cache Binance rate");
            else
                _logger.LogInformation($"Binance rate updated");
        }
        catch (AggregateException aex)
        {
            _logger.LogError(aex, "Exception while caching Binance rate");
        }
    }

Where SetObjectAsync is an extension method:
    public static async Task<bool> SetObjectAsync<T>(this RedisStore cache, string key, T value, TimeSpan? timeSpan = null)
    {
        var stringValue = JsonConvert.SerializeObject(value);
        return await SetStringAsync(cache, key, stringValue, timeSpan);
    }

and
    public static async Task<bool> SetStringAsync(this RedisStore cache, string key, string value, TimeSpan? timeSpan = null)
    {
        return await cache.RedisCache.StringSetAsync(key, value, timeSpan);
    }

RedisStore injected as a singleton:
        services.AddSingleton(sp =>
        {
            var redisSettings = sp.GetRequiredService<IOptions<RedisSettings>>();
            return new RedisStore(redisSettings.Value);
        });

My other service gets the cached data. Everything works fine after service starts, but about 12 hours later the service stops store data in the cache - service works, but i see no data in cache (i use RedisInsigth-v2 to check the cache). Also, there is no error in logs that means that RedisCache.StringSetAsync returns true all times and no exception throwed. I'm using "StackExchange.Redis" Version="2.2.4" and Redis v6.0.6 in Docker. Interesting, that with other keys rarely saved in Redis i dont have any troubles.

A: You're probably encountering an exception somewhere in UpdateBinanceRates, most likely when you are trying to hit Redis on that string set, it's probably a timeout or something, it's possible it's some json convert issue impossible to say for certain given the nature of this issue.
You aren't seeing it because you are trying to catch an AggregateException. Most likely the exception is getting out of UpdateBinanceRates, and because your while loop isn't wrapped with any kind of try/catch the exception escapes and your background service just dies (hence no more updates). You might try wrapping the inner part of the while loop with a try/catch with a very generic exception (probably just Exception) to see if the next time you encounter this behavior if it is an exception escaping. That's most likely your problem.


text:
Q: Detecting different heat element power I have a range of heating elements with different power ratings (i.e. different resistances). Is there a way for my microcontroller to detect what power they are so I can use the microcontroller and a Triac to modulate the power to a specific power?

A: Yes. You just need to measure the voltage across the element and the current through the element. Multiply these to get instantaneous power, take enough samples and you can estimate the average power. Control the triac as desired to regulate the power consumption.
If you are asking if the Arduino can determine the power rating of the elements, then there is no obvious way to do this based only on the information you have provided.

A: Assuming these heater elements are lines powered (110V/220V) single phase heaters, you can use a current transformer to measure the current safely and you can assume that the voltage is whatever the line voltage is.
Something like this:
https://www.amazon.com/JANSANE-SCT-013-000-Non-invasive-Split-Core-Transformer/dp/B07D8SXQ13

This assumes you are doing a one-off non-commercial application.  If you need to build something that meets industrial safety requirements you should find someone with experience to help with the design.

A: you need several devices like :
1. a good Multimeter for reading low to mid resistance (Ohm)
2. either clamp meter for sensing current in AC or current transformer with panel meter,, they are many choices from analog to digital.
3. a good supply AC or DC.

*

*first you test with multitester, check how much resistance they have. ex: 26ohm
so if you connect to 110V it will gives you about 465W
you can try to connect it to 220/230V outlet but remember some heater designed with specific value of voltage and W/mm2 (surface area power) so it will not to be hot enough to be melt away for their application.

or to be safe you can try to connect it with 110V outlet if you have it (try to use line with fuse fast blow 5a or MCB 6a or 10a or more if your heater element big enough)

*reading the current with your clamp meter, if your meter reads 6a the power should be 660W for 110V outlet and 1320W for 220V outlet

you can try to use DC voltage if you are not sure how it works, with DC amperage meter. but i think the current will flow too small since the resistance stay the same.
the best way to do it to check with resistance value (with multimeter or specific ohm meter).


text:
Q: metric induced norm or norm induced metric I am always confused between whether metric induces norm or norm induces metric. Can someone clarify this relation a bit for me? Was there any intuition on which direction being true?

A: In a vector space, a norm can induce a metric.  For example, suppose that $u,v\in\mathbb{R}^n$ and let $||\cdot||$ be the Euclidean norm.  Then one can induce a metric $d(u,v):\mathbb{R}^n\times\mathbb{R}^n\rightarrow\mathbb{R}$ given by
$$
d(u,v)=||u-v||.
$$


text:
Q: Pegar valor de input HTML e passar para variável em PHP Possuo esse seguinte input:

Início do período:
 <input type="text" id="calendario">

necessito do valor que o usuário irá selecionar, como conseguiria colocar esse valor em uma variável php?

A: <input type="text" id="calendario" name="calendario">

Adicione um name a seu  campo
no  php  você pode pegar  via $_POST ou $_GET depende do metodo que vai enviar para o  serivodor
<?php
if(isset($_POST['calendario'])){
    $calendario = $_POST['calendario'];
}
?>

Seu formulario deve ficar parecido com isso
<form method="post" action="urlp do seu site">
    <input type="text" id="calendario" name="calendario">
    <input type="submit" value="enviar">
</form>


text:
Q: Arduino alternative for delays? What I wanted to do is to run 2 traffic lights simultaneously(ex. North and South).Is there an alternative for delay besides millis? I tried to use Blinkwithoutdelay but as a newbie its very complicated for me to use it.
    digitalWrite(greenled, HIGH); //Green on for 1 seconds
    delay(greenDuration);
    digitalWrite(greenled, LOW); //Green off, yellow on for 1 seconds
    digitalWrite(yellowled, HIGH);
    delay(1000);
    digitalWrite(yellowled, LOW); //yellow off, red on for 1 seconds
    digitalWrite(redled, HIGH);
    delay(1000);
    digitalWrite(redled, LOW); //Red off

    digitalWrite(greenled2, HIGH); //Green on for 1 seconds
    delay(1000);
    digitalWrite(greenled2, LOW); //Green off, yellow on for 1 seconds
    digitalWrite(yellowled2, HIGH);
    delay(1000);
    digitalWrite(yellowled2, LOW); //yellow off, red on for 1 seconds
    digitalWrite(redled2, HIGH);
    delay(1000);
    digitalWrite(redled2, LOW); //Red off

Complete code:
int beam = 2;//Beam sensor
int greenled = 4;
int redled = 7;
int yellowled = 13;
int greenDuration =1000;    //normal time
int greenShortDuration = 1000;
int greenIncrement = 5000; //5 seconds
void setup()
{
  // set the digital pin as output:
  pinMode(greenled, OUTPUT);
  pinMode(redled, OUTPUT);
  pinMode(greenled, OUTPUT);
  pinMode(beam,INPUT);
  Serial.begin(9600);
}

void loop()
{
            Serial.println("Status:low");
            digitalWrite(greenled, HIGH); //Green on for 5 seconds
            delay(greenDuration);
            digitalWrite(greenled, LOW); //Green off, yellow on for 2 seconds
            digitalWrite(yellowled, HIGH);
            delay(1000);
            digitalWrite(yellowled, LOW); //yellow off, red on for 5 seconds
            digitalWrite(redled, HIGH);
            delay(1000);
            digitalWrite(redled, LOW); //Red and Yellow off

    digitalWrite(greenled2, HIGH); //Green on for 1 seconds
    delay(1000);
    digitalWrite(greenled2, LOW); //Green off, yellow on for 1 seconds
    digitalWrite(yellowled2, HIGH);
    delay(1000);
    digitalWrite(yellowled2, LOW); //yellow off, red on for 1 seconds
    digitalWrite(redled2, HIGH);
    delay(1000);
    digitalWrite(redled2, LOW); //Red off
  if(digitalRead(beam)==HIGH){
    for(int i=1; i<=10; i++){
      Serial.println(i);

      while(i>=10){
          Serial.println("Motion Detected");
          greenDuration +=greenIncrement; //Add 5 seconds everytime
          Serial.println(greenDuration);

        break;
      }

      }

    }
         if(!digitalRead(beam)==HIGH){
        Serial.println("hey"); //indication of code is working
        greenDuration=greenShortDuration;
        return;

}

}

A:
I tried to use Blinkwithoutdelay but as a newbie its very complicated
  for me to use it.

You have to try harder :)
Imagine loop() isn't the "program" but a description of any moment.
In general it detects that neither time for a change nor a new pushbutton request has come, so loop exits immediately.
Even if something should have happened, any new reaction does not take any time, and loop exits immediately.

A: There is a simple solution to solve the given traffic lights sample.
Instead of calling the delay function you could call your special delay-function:
int globalFlagSomeonePressedBeam = false;  // store global if someone pushed the beam button

void delay_and_check_for_beam (int msDelay) {
    for (int i=0; i<msDelay; ++i) {
        if(digitalRead(beam)==HIGH){ // check beam button
            globalFlagSomeonePressedBeam = true; // store information
        }
        delay(1);
    }
}

Between the calls to your delay function you set the right lights (digital outs)
After you check your globalFlagSomeonePressedBeam you need to set it back to false

A: Solution by OP.
unsigned long curGoStopDuration, defGoStopDuration = 5000, maxGoStopDuration = 30000;
unsigned long currentMillis;

#pragma region SensorFields
int durationIncrement = 2500;
unsigned long greenPrevMillis;
float DetectionTime = 2500;
bool triggered;
#pragma endregion

enum LightState { Green, Yellow, Red };

class Stoplight
{
private:
    int greenLed, yellowLed, redLed;
    unsigned long previousMillis;
    float CurInterval;
    LightState state;
public:
    unsigned long GreenDuration = 5000;
    unsigned long RedDuration = 5000;
    int YellowDuration = 1000;

    Stoplight(int gLed, int yLed, int rLed) :greenLed(gLed), yellowLed(yLed), redLed(rLed)
    {
        pinMode(greenLed, OUTPUT);
        pinMode(redLed, OUTPUT);
        pinMode(yellowLed, OUTPUT);
    }

    void Loop()
    {
        if (currentMillis - previousMillis >= CurInterval)
        {
            previousMillis = currentMillis;
            //Transitions
            switch (state)
            {
                case Green:
                    ToYellow();
                    break;
                case Yellow:
                    ToRed();
                    break;
                case Red:
                    ToGreen();
                    break;
            }
        }
    }

    void ToGreen()
    {
        digitalWrite(redLed, LOW);
        digitalWrite(greenLed, HIGH);
        CurInterval = GreenDuration - YellowDuration;
        state = Green;
    }

    void ToYellow()
    {
        digitalWrite(greenLed, LOW);
        digitalWrite(yellowLed, HIGH);
        CurInterval = YellowDuration;
        state = Yellow;
    }

    void ToRed()
    {
        digitalWrite(yellowLed, LOW);
        digitalWrite(redLed, HIGH);
        CurInterval = RedDuration;
        state = Red;
    }

};

Stoplight SL_01(2, 3, 4), SL_02(5, 6, 7);
int beamSensor = 8;

void setup()
{
    //Set default values
    curGoStopDuration = defGoStopDuration;

    SL_01.ToGreen();
    SL_02.ToRed();

    pinMode(beamSensor, INPUT);
    Serial.begin(9600);
}

void loop()
{
    currentMillis = millis();
    Sensor();

    //Manipulate durations
    SL_01.GreenDuration = curGoStopDuration;
    SL_02.RedDuration = curGoStopDuration;
    SL_01.Loop();
    SL_02.Loop();
}

void Sensor()
{
    //If sensor detects something
    if (digitalRead(beamSensor) == HIGH)
    {
        if (!triggered)
        {
            greenPrevMillis = currentMillis;
            triggered = true;
        }

        if (currentMillis - greenPrevMillis >= DetectionTime)
        {

            if(curGoStopDuration < maxGoStopDuration)
                curGoStopDuration += durationIncrement; //Add seconds

            greenPrevMillis = currentMillis;

            Serial.print("Green light duration is now: ");
            Serial.println(curGoStopDuration);
        }
    }
    else  //No detection
    {
        curGoStopDuration = defGoStopDuration;
        triggered = false;
    }
}

A: You need interrupt on your beam, fast one, just counter, but its necessary for more precise counting (traffic =) )... this works for me just fine:
#define redPin1 40
#define yellowPin1 41
#define greenPin1 42
#define beamPin1 21
#define redDuration 1000
#define yellowDuration 1000
#define greenDuration 1000
#define durationIncrement 500

byte carCounter1 = 0;
byte state1 = 1;

void setup()
{
    pinMode(redPin1, OUTPUT);
    pinMode(yellowPin1, OUTPUT);
    pinMode(greenPin1, OUTPUT);
    pinMode(beamPin1, INPUT);

    attachInterrupt(digitalPinToInterrupt(beamPin1), beamCount1, RISING);
}

void beamCount1()
{
     carCounter1++;
}

void wait(long duration)
{
    int wait = 0;
    long last = millis();
    while (wait == 0)
    {
        long now = millis();

        if (now - last >= duration) { wait = 1;}
        else {}
    }
}

void redLight(byte redLightPin)
{
    digitalWrite(redLightPin, HIGH);
    wait(redDuration);
    state1 = 2;
}

void yellowLight1(byte redLightPin, byte yellowLightPin)
{
    digitalWrite(yellowLightPin, HIGH);
    wait(yellowDuration);
    digitalWrite(redLightPin, LOW);
    digitalWrite(yellowLightPin, LOW);
    state1 = 3;
}

void yellowLight2(byte yellowLightPin)
{
    digitalWrite(yellowLightPin, HIGH);
    wait(yellowDuration);
    digitalWrite(yellowLightPin, LOW);
    state1 = 1;
}

void greenLight(byte greenLightPin)
{
    digitalWrite(greenLightPin, HIGH);
    long incremented = greenDuration + (carCounter1 * durationIncrement);
    wait(incremented);
    digitalWrite(greenLightPin, LOW);
    carCounter1 = 0;
    state1 = 4;
}

void trafficLight(byte red, byte yellow, byte green)
{
    switch (state1){

    case 1:
      redLight(red);
      break;
    case 2:
      yellowLight1(red, yellow);
      break;
    case 3:
      greenLight(green);
      break;
    case 4:
      yellowLight2(yellow);
      break;
    }
}

void loop()
{
    trafficLight(redPin1, yellowPin1, greenPin1);
}

no delays, just wait function which makes track of millis... if you want more precision, count the time needed for each light and remove it from wait...


text:
Q: Why was Boromir allowed to join the Fellowship of the Ring? Why was Boromir allowed to join the Fellowship of the Ring after the Council of Elrond, where he succumbed to the Ring moments after first seeing it, and explicitly said that he wanted to use it himself?  It was made absolutely clear that he could not be trusted around the Ring, but no one spoke up to say "Maybe the guy who succumbed to the Ring within seconds shouldn't go on the mission to destroy said Ring".
Assuming that it was deemed necessary for the Fellowship to include a representative of Gondor (although Rohan didn't get a place in the Fellowship, for some reason), couldn't Aragorn fill that spot?  If not, wouldn't it have been worth the delay to send Boromir back to Gondor and request that Faramir (who later proved himself to be less susceptible to the Ring) take Boromir's place?  Granted, the Council had no way of knowing ahead of time that Faramir was stronger than Boromir, but it seems like Boromir was the worst possible choice, and anyone who wasn't Boromir would have been a better candidate.

Updated May 24:  I am finally reading The Return of the King, and the heated exchange between Denethor and Gandalf just before the siege of Minas Tirith seems to support my argument.  Denethor is angry at Gandalf for letting the Ring be sent to Mordor with Frodo, and says that it should have been carried to Gondor by Boromir instead, so it could be hidden.  Gandalf says that if Boromir had taken it, he would have been corrupted before he ever reached Gondor and Denethor would no longer recognize him.  Denethor accuses Gandalf of having stolen Faramir's loyalty and claims that the real reason Gandalf didn't trust Boromir was that Boromir followed Denethor's orders rather than Gandalf's; he says Gandalf doesn't trust Denethor's judgment..
Gandalf replies:

"... I do not trust you... And now hearing you speak I trust you less, no more than [I trusted] Boromir."
  - The Lord of the Rings;  The Return of the King, Book V, Chapter 4: "The Siege of Gondor"

There we have it- Gandalf never trusted Boromir, or at least didn't trust him by the time the Fellowship was being assembled.  Why, pray tell, was he allowed to go anywhere near the Ring, when the wisest person around didn't trust him to begin with?

A: Because he's going to Gondor, which is on the way to Mordor, and because Aragorn vouches for him.
Seriously, that's it (emphasis mine):

'And I will choose you companions to go with you, as far as they will or fortune allows. The number must be few, since your hope is in speed and secrecy. Had I a host of Elves in armour of the Elder Days, it would avail little, save to arouse the power of Mordor.
'The Company of the Ring shall be Nine; and the Nine Walkers shall be set against the Nine Riders that are evil. With you and your faithful servant, Gandalf will go; for this shall be his great task, and maybe the end of his labours.
'For the rest, they shall represent the other Free Peoples of the World: Elves, Dwarves, and Men. Legolas shall be for the Elves; and Gimli son of Glóin for the Dwarves. They are willing to go at least to the passes of the Mountains, and maybe beyond. For men you shall have Aragorn son of Arathorn, for the Ring of Isildur concerns him closely.'
'Strider!' said Frodo.
'Yes,' he said with a smile. 'I ask leave once again to be your companion, Frodo.'
'I would have begged you to come,' said Frodo, 'only I thought you were going to Minas Tirith with Boromir.'
'I am,' said Aragorn. 'And the Sword-that-was-Broken shall be reforged ere I set out to war. But your road and our road lie together for many hundreds of miles. Therefore Boromir will also be in the Company. He is a valiant man.'
Fellowship of the Ring Book 2 Chapter 3: "The Ring Goes South"

A: I think because Boromir was "given" his mystical dream or dreams, presumably by Eru or by some lower god, Gandalf and Elrond assumed that Boromir had some part to play which only the gods could sense; so he was included in the partnership. Gandalf did sometimes make choices against prevailing wisdom.

A: Within the film script, it's made clear that Boromir has been invited to the Council of Elrond to represent Gondor, one of the "superpowers" of Middle-earth. On top of that he's the Steward's son, no less and an awesome warrior in his own right. Additionally, he's someone who has a reasonable level of knowledge about Mordor, having lived on its borders his entire life.
Refusing him membership to the Fellowship simply because he thought that it would be a good idea to use the Ring of Power against their common enemy would make things difficult for the Fellowship, if not downright awkward. On top of that, they may need to travel through territory loyal to Gondor so they want to maintain strong relations.
Frankly, there's no sensible reason to not include him and several excellent reasons why they should do so:

BOROMIR: You carry the fate of us all, little one.
Boromir looks towards Elrond and Gandalf.
BOROMIR: If this is indeed the will of the Council, then Gondor will
see it done.
Frodo stares in wonder as the Greatest Fighters in all Middle-earth stand at his side.

A: Things working for Boromir:

*

*He is going the same direction.  (Mentioned above)

*He is a good warrior. (mentioned above)

*He is the son/heir of the Steward of Gondor. (mentioned above)

*Represents humans within the Fellowship. (mentioned above)

*He came with "Boromir's riddle", accredited to the Vala Irmo Lórien, where he is directed to "Seek for the Sword that was broken."

Things working against Boromir:

*

*The Ring took him immediately.  (Is the speed of capture related to the 9 rings?)

*Sauron already had hooks in his father through the Palantír.

*Gondor, his destination, was the front-lines of the battle.  It is a bad idea to put the strategic goal of the enemy at the center of the focus of their exercise of strength.

*Gondor also had its back against a wall.  The number of opportunities, open doors to accommodate changes in direction decreases as the Fellowship approaches Gondor - it makes them less nimble.

Thoughts:

*

*It seems that Boromir is a "member of convenience" and not a "strategic asset".

*It may be that nobody realized 1) that the Ring got him, 2) how quickly the Ring took him, and 3) how completely the Ring took him. One of the best ways to keep the truth from being acted on is to keep it from being known.  The ring took Sméagol in a moment and he did what he would not have normally done - he killed to get it.  Boromir, while equally taken, was in the company of such great power that had he tried to take it by force in front of others, he would have been struck down.  Just because he intended to go to Gondor with it does not mean it did not take him - it is how he rationalized what the Ring wanted him to do.

*There is an irony in his entry versus his exit.  While his entry was more convenience, his exit was profoundly impactful.  He transformed the Fellowship.  He galvanized Frodo, and Aragorn in ways they did not expect.  Frodo started out passive, waiting for leadership and relying on the strength of others, and after the the ring took Boromir, he took the initiative and acted courageously relying on his own strength.  Aragorn started out rejecting a crown and much of the civilization of men, but at the noble and heroic death of Boromir, he swore to protect the great city, and to see to it that humanity was not lost.

*He was essential for the survival of the team on Caradhras, in Moria, and at Sarn Gebir.  He and Aragorn carried the hobbits who would have been killed by Saruman's storms.  He fought hard in the burial room of Balin, and as one of the best human warriors on the planet, he made a critical difference and without him they would have died. He and Aragorn also carried Frodo who would have run toward the Balrog.  He warned them of the rapids of Sarn Gebir where the party stopped.

*The belt from Galadriel says something interesting about her evaluation of Boromir, and indirectly indicates what Gandalf may also have seen but not communicated.  Tolkien knows the three treasured possessions of Thor were Mjolnir (the hammer), Jarngreipr (the gloves), and Megingjord (the belt) which doubles Thor's strength.  The gifted belt could be an allusion to Megingjord, imparting an elvish strength of character that transformed Boromir's final battle.

*The words of Gandalf to Denethor are toward Denethor and not necessarily the whole story.  In game theory what Gandalf has put in front of Denethor exactly what Denethor just put in front of him, and as such can see the reaction Denethor expected to elicit.

A: At the Council of Elrond, Boromir is clearly tempted by the Ring. This is not the same as succumbing to its influence.
In fact, everyone is tempted by the Ring -- the hobbits least of all, but even Frodo is gradually corrupted by its influence.
For powerful beings such as Gandalf, the temptation is severe. In the books (Book 1, Chapter 2, "The Shadow of the Past"), Frodo offers Gandalf the Ring. Gandalf is horrified and tells Frodo not to tempt him. Similarly, when Frodo offers the Ring to Galadriel, she spends a few moments contemplating how she could use its power to become a goddess.
So it is not surprising when Boromir suggests using the Ring to overthrow Sauron. That's how the temptation of the Ring works. It seems like a perfectly logical idea, unless you really understand the Ring's corrupting power. In both books and film, Boromir is persuaded to go along with the Council's belief that the Ring is too dangerous to use.
The Council took a risk in sending Frodo out with powerful companions -- not just Boromir, but Aragorn, Gandalf and the rest. At any time, one of them could have been overcome by desire for the Ring and tried to seize it. On the other hand, they needed Frodo to reach Mordor. The hobbits nearly didn't make it to Rivendell, even with help from Aragorn and Glorfindel/Arwen (in the book/film respectively). So, the Council decided Frodo needed a strong escort.
As it happens, Boromir breaks first, but this was not foreseen by the Council. Later on, Aragorn remarks that it was a "sore trial" for Boromir, who was a "warrior, and a Lord of Men", but that is no more than hindsight.

A: In point of fact, Boromir did not succumb to the Ring moments after first seeing it, nor did he explicitly want to use it himself at the Council.  He only questioned the wisdom of trying to destroy the Ring rather than using it as a weapon against Sauron.  It was only after spending several months in proximity to the Ring that, after leaving Lórien, he finally begins to yield to its temptation.
From the Tale of Years, the Council was October 25, 3018.  The Company left Rivendell two months later, on December 25th, passed through Moria and arrived at Lórien, leaving there on February 16, 3019.  It's 10 days later that he finally gives in to the temptation.


text:
Q: Embedded Javascript code to Flutter Mobile I have to add a script code for spinner of javascript inside the flutter code for mobile Application.
I tried several approaches to implement the script by using WebView and also I put the script directly in JS file then put it in HTML file but non of these approaches run the javascript code on mobile app.
Question
Is there any way to embed the javascript code inside the flutter code?

A: Yes you can, without webviews, check out this package
https://pub.dev/packages/flutter_js

A: There are several plugins for this but Personality I prefer this one
https://pub.dev/packages/flutter_webview_plugin/example
this plugin allows you embbed javaScript code


text:
Q: Reading ionic www/config.xml file from device I am having trouble reading the www/config.xml file from Android device. I tried two different approaches. First, I tried using the $http service which was recommended in another thread to do. When that did not work I then tried to use the Cordova file plugin. The reason I am doing this is to try to get the version number from the www/config.xml file in the app.  Below are both approaches:
1) $http.get()
 url = 'file:///android_asset/www/config.xml'
 $http.get(url)
    .then ((data) ->
      versionNumber = data.data.match(/<widget\s.*?\sversion=['"]([^'"]+)['"]/)
      verNum = versionNumber[1]
    ), (err) ->
    # {"data": null, "status": 0, .....}
      alert JSON.stringify err

2)  Cordova file plugin
   if ionic.Platform.isAndroid()
    path = 'file:///android_asset/www/'
    file = 'config.xml'
    $cordovaFile.readAsText(path, file)
      .then ((data) ->
        alert JSON.stringify data
        return
      ), (error) ->
        # I alert { code: 5 } which is an ENCODING_ERR
        alert JSON.stringify error

A: Take a look to the folder platforms/android and you can see that the file 'android_asset/www/config.xml' don't exists.
You could try reading the file '/res/xml/config.xml' or you could try a different approach for example creating a Cordova Hook.

Cordova Hooks:
Cordova Hooks represent special scripts which could be added by
  application and plugin developers or even by your own build system to
  customize cordova commands.

You could adapt the replace text hook from this article or this build number hook based on the same hook.
UPDATE
To get only the version number of your app you could use this plugin:

Cordova AppVersion plugin
Cordova plugin to return the version number of the current app
https://github.com/whiteoctober/cordova-plugin-app-version

Is available also with ngCordova

A: ngCordova has a great set of plugins when working with ionic.
To get the app version use this one: http://ngcordova.com/docs/plugins/appVersion/
I wanted to display the version number in my splash screen, so I used their example and added an event:
Inside $ionicPlatform.ready callback:
$cordovaAppVersion.getVersionNumber().then(function (version) {
    $rootScope.$broadcast("appVersionResolved", { version: appVersion });
}

In the splash screen controller:
$rootScope.$on("appVersionResolved", function(event, args) {
    $scope.appVersion = args.version;
});


text:
Q: pymupdf detect two paragraph which text blocks coordinates is closed as one I face a problem that When I use fitz to detect pdf layout. The two paragraph will be detect as one textblock if the two block as a close line margin.

for example. I want detect the text and the isolated formula as to text blocks. but for now fitz detect them as one text block.How could i handdle this.
Shoud I detect words coordinates and sort it with normal reading order or some methods like this.

A: PyMuPDF also has ways to adjust the granularity of text extraction: there are more levels between and beyond block extraction and word extraction.
You can extract by line, by text span (both are a higher level than word) and by character (level below word). And all of them deliver wrapping rectangles of the respective text, plus a plethora of text font proprerties (font size, font weight, font style, font color), writing direction.
Here is an example that extracts lines of text:
details = page.get_text("dict", flags=fitz.TEXTFLAGS_TEXT)  # skips images!
for block in details["blocks"]:  # delivers the block level
    for line in block["lines"]:  # the lines in this block
        bbox = fitz.Rect(line["bbox"])  # wraps this line
        line_text = "".join([span["text"] for span in line["spans"]])

Please do have a look at this picture in the documentation - it shows an overview of the dictionary layout: https://pymupdf.readthedocs.io/en/latest/_images/img-textpage.png.


text:
Q: MIPS errors and operation #if true perform matrix operation
mul.s $f7, $f5, $f6 #m * a[d][c]
add.s f7, $f7, $f5 #add (m*a[d][c])+col c

div.s $f5, $f4, $f2 #divide -a[r][d]/a[d][d] and store to m
move $f3, $zero #setting [r][d] = 0

I'm receiving errors on my add.s and mov register lines. Any help?

A: You're missing a $-sign on the line add.s f7, $f7, $f5. It should be add.s $f7, $f7, $f5.
I don't know how your assembler handles move instructions with floating-point registers (or if it does), but I'd suggest using mtc1 $zero,$f3 instead. Normally you'd follow that with a cvt.s.w or cvt.d.w to convert the value to floating point, but in the case of 0 that isn't necessary.


text:
Q: export als recommendation model to a file I am new to Apache Spark. I ran the sample ALS algorithm code present in the examples folder. I gave a csv file as an input. When I use model.save(path) to save the model, it is stored in gz.parquet file.
When I tried to open this file, I get these errors
Now I want to store the recommendation model generated in a text or csv file for using it outside Spark.
I tried the following function to store the model generated in a file but it was useless:
model.saveAsTextFile("path")

Please suggest me a way to overcome this issue.

A: Lest say you have trained your model with something like this:
val model = ALS.train(ratings, rank, numIterations, 0.01)

All that you have to do is:
import org.apache.spark.mllib.recommendation.ALS
import org.apache.spark.mllib.recommendation.MatrixFactorizationModel
import org.apache.spark.mllib.recommendation.Rating
// Save
model.save(sc, "yourpath/yourmodel")
// Load Model
val sameModel = MatrixFactorizationModel.load(sc, "yourpath/yourmodel")

A: As it turns out saveAsTextFile() only works on the slaves.Use collect() to collect the data from the slaves so it can be saved locally on the master. Solution can be found here


text:
Q: how to match list of dictionaries to another list of dictionaries value where key is different? I have an issue where matching two list of dictionaries. Below the code i tried to match.
listDict1= [
    '{"weightMax":150, "weightMin":100, "date":"2017-07-05 12:16:06"}',
    '{"weightMax":150, "weightMin":100, "date":"2017-07-05 12:17:06"}',
    '{"weightMax":0, "weightMin":0, "date":"0"}']

listDict2= [
    '{"Weight":"138.0","unit":"Kg",
      "measurementTime":"2017-07-05 12:15:06",
      "receiptTime":"2017-06-30T15:16:09.009-07:00",
      "date":1498860969000,"model":"2011",
      "manufacturer":"CONTINUA","serialnumber":"SN_WEIGHT082"}',
    '{"Weight":"138.0","unit":"Kg",
      "measurementTime":"2017-07-05 12:16:06",
      "receiptTime":"2017-06-30T15:16:09.009-07:00",
      "date":1498860969000,"model":"2011",
      "manufacturer":"CONTINUA","serialnumber":"SN_WEIGHT082"}',
    '{"Weight":"188.0","unit":"Kg",
      "measurementTime":"2017-07-05 12:17:06",
      "receiptTime":"2017-06-30T15:16:09.009-07:00",
      "date":1498860969000,"model":"2011",
      "manufacturer":"CONTINUA","serialnumber":"SN_WEIGHT082"}']

I need to match listDict1['date'] value with listDict2['measurementTime']
I tried the code below, but it matches as per the list index
def matchValValues(listDict1, listDict2):
    val1 = []
    rpm = []

    for i in range(len(listDict1)):
        j = dict((k, v) for k, v in ast.literal_eval(listDict1[i]).iteritems())
        k = dict((k, v) for k, v in ast.literal_eval(listDict2[i]).iteritems())
        #for i in j.keys():
        val = j['date']
        we = k['measurementTime']
        if val in we :
            val2 = float(k['Weight'])
            max=  float(j['weightMax'])
            min = float(j['weightMin'])
            print "True"
            if val2 <= max and val2 >= min:
                print "pass"
                val1.append(str(j['weightMax'])+'|'+str(j['weightMin']))
                rpm.append(k['Weight'])
            else:
                val1.append(j.copy())
                rpm.append(k.copy())
        else:
            val1.append(j.copy())
            rpm.append(k.copy())
    print val1
    print rpm

expected output:
if there is a match append only weight and measurementTime value in rpm
if there is a match append only weightmax, weightmin and date value in val1
else append whole unmatched dict in rpm and val1 corresponding.
current output:
[{'date': '2017-07-05 12:16:06', 'weightMax': 150, 'weightMin': 100},
 {'date': '2017-07-05 12:17:06', 'weightMax': 150, 'weightMin': 100},
 {'date': '0', 'weightMax': 0, 'weightMin': 0}]

[{'Weight': '138.0', 'measurementTime': '2017-07-05 12:15:06',
  'serialnumber': 'SN_WEIGHT082', 'date': 1498860969000L,
  'model': '2011', 'receiptTime': '2017-06-30T15:16:09.009-07:00',
  'unit': 'Kg', 'manufacturer': 'CONTINUA'},
 {'Weight': '138.0', 'measurementTime': '2017-07-05 12:15:06',
  'serialnumber': 'SN_WEIGHT082', 'date': 1498860969000L,
  'model': '2011', 'receiptTime': '2017-06-30T15:16:09.009-07:00',
  'unit': 'Kg', 'manufacturer': 'CONTINUA'},
 {'Weight': '188.0', 'measurementTime': '2017-07-05 12:16:06',
  'serialnumber': 'SN_WEIGHT082', 'date': 1498860969000L,
  'model': '2011', 'receiptTime': '2017-06-30T15:16:09.009-07:00',
  'unit': 'Kg', 'manufacturer': 'CONTINUA'}]

A: It matches per the list index, because that's exactly what you told it to do.  Computers are annoying in this respect.
Don't use the index for choosing the needed listDict2 entry.  Instead, fetch the date from listIndex1[i] and search listDict2[<all>]['measurementTime'] for that value.  If the lists are large, you might want to build a reverse dictionary of <time stamp> : index to make your work easier.
Does that get you moving?


text:
Q: iTextSharp produces invalid PDF Using itextsharp 4.2.0, I have made the following function to generate a dummy PDF in memory and send it back to the client:
internal override byte[] GeneratePDFDocument(pdfContent content)
{
    Document document = new Document(PageSize.A4, 30f, 30f, 30f, 30f);

    MemoryStream output = new MemoryStream();
    PdfWriter writer = PdfWriter.GetInstance(document, output);
    document.Open();
    document.Add(new Paragraph("Hello World"));
    byte[] response = output.ToArray();
    document.Close();
    return response;
}

which is called from a static function:
public static byte[] Print(string jsonData)
{
    PDFGeneratorBase generator;
    generator = new ITextSharpGenerator();
    return generator.GeneratePDFDocument(view.GetViewData());
}

which is called from a WebAPI controller:
public HttpResponseMessage PrintPDF(HttpRequestMessage req)
{
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    byte[] pdfData = PrintReport.Print(printJobString);
    result.Content = new ByteArrayContent(pdfData);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = "PrintPDF.pdf";
    return result;
}

If I open the resulting PDF in Foxit Reader 7.2, the error message is "Format error: not a PDF or corrupted".
What am I doing wrong here?

A: You need to close the document before grabbing the byte array. Closing the document flushes the internal buffers of "finishes" the document. Swap this:
byte[] response = output.ToArray();
document.Close();

With this:
document.Close();
byte[] response = output.ToArray();


text:
Q: Assigning percentages to different causes There was recently a celebrated spat between Cathy Newman, one of the main presenters of Channel 4 News in the UK, and Jordan Peterson, a well-known academic and clinical psychologist, on the causes of the gender pay gap. You can listen to it on YouTube, where it has been viewed over 9 million times. Peterson says that "statistics show" that only x% of the gender pay gap is due to prejudice against women. The exact value of x is not relevant to my question.
I recently read a discussion about whether human intelligence is inherited or acquired, with the conclusion that it's 50% nature and 50% nurture.
What would it mean, if anything, to say "The taste of a cake is 10% due to the proportion of flour to butter and 20% due to the freshness of the eggs."
My question is When is it sensible to assign percentages to the causes of some phenomenon? What kinds of statistical or scientific model are being assumed and what kinds of evidence could be adduced that such a model is appropriate? This is a big topic, so I would welcome pointers to clearly written articles on the subject, and also pointers to relevant books.

A: What you are seeing is usually some form of effect size.
For a notable and commonly used example, you may perform an ANOVA and calculate $\eta^2$ ("eta squared") which is described here as

"the proportion of variance associated with or accounted for
  by each of the main effects, interactions, and error in an ANOVA study"

Which is quite literally a percentage assigned to causes of some phenomena.


text:
Q: Generacion de base de datos Hibernate 5.4 Estoy usando hibernate 5.4 (previamente usaba hibernate 4) y al parecer han cambiado la manera de impactar las clases de java en la base de datos.
Alguien sabe como impactar en la base de datos las clases de java con hibernate 5.4??

A: Para crear tablas usando Hibernate tenemos varias opciones a usar: Hibernate Tools, archivos xml, anotaciones, etc.
Supongamos que quiero crear una Entidad llamada Alumno con cuatro atributos(id, nombre, telefono, fecha).
Con archivos XML tendríamos algo como esto:
Alumno.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 <hibernate-mapping>
 <class name="com.codes.Alumno" table="Alumno" >
 <id column="Id" name="id" type="integer"/>
 <property name="nombre" column="nombre" />
 <property name="telefono" column="telefono" />
 <property name="fecha" column="fecha" />
 </class>
</hibernate-mapping>

Y la clase Alumno.java
package com.codes.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Setter;
import lombok.ToString;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.time.LocalDate;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Alumno implements java.io.Serializable{
    private static final long serialVersionUID = 7526472295622776147L;

    @Getter @Setter public int id;
    @Getter @Setter public String nombre;
    @Getter @Setter public String telefono;
    @Getter @Setter public LocalDate fecha;
}

hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/curso</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="show_sql">true</property>
        <property name="current_session_context_class">thread</property>

        <!-- archivo de mapeo -->
        <mapping resource="Alumno.hbm.xml" />

    </session-factory>
</hibernate-configuration>

Con anotaciones(@) mi clase Alumno.java se vería así:
package com.codes.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Setter;
import lombok.ToString;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.GenerationType;
import javax.persistence.Table;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Table(name="alumno")
@Entity(name="Alumno")
public class Alumno implements java.io.Serializable{
    private static final long serialVersionUID = 7526472295622776147L;

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Getter @Setter public int id;
    @Column(name="nombre")
    @Getter @Setter public String nombre;
    @Column(name="telefono")
    @Getter @Setter public String telefono;
    @Column(name="fecha")
    @Getter @Setter public LocalDate fecha;
}

Además de no olvidar el archivo hibernate.cfg.xml para ambos casos:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/curso</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="show_sql">true</property>
        <property name="current_session_context_class">thread</property>

        <!-- clase con anotaciones --->
        <mapping class="org.codes.Alumno" />

    </session-factory>
</hibernate-configuration>

Links:
http://www.mkyong.com/hibernate/how-to-generate-code-with-hibernate-tools/
http://hibernate.org/tools/
https://www.onlinetutorialspoint.com/hibernate/generator-classes-in-hibernate.html
http://www.cursohibernate.es/doku.php?id=unidades:02_hibernate:02_entidad


text:
Q: How to know which version of an image a container is running? Suppose I have one running container:
CONTAINER ID   IMAGE            COMMAND   CREATED       STATUS       PORTS                  NAMES
59f00e5c96d6   me/myapp:latest  "bash"    9 hours ago   Up 7 hours   127.0.0.1:80->80/tcp   bashapp

Suppose I found a mysterious docker image archive file me-myapp-latest.tar.gz out of nowhere. I want to know, relative to the image used to start the running container, whether that file contains an older or newer version of the image.
I load the archive into docker using docker load --input me-myapp-latest.tar.gz. docker images now shows:
REPOSITORY   TAG      IMAGE ID        CREATED           SIZE
me/myapp     latest   fe22fc800843    12 hours ago      123MB

This gives no indication of whether or not the me/myapp:latest shown by docker images is the same as that shown by docker ps -a. They are both named me/myapp:latest, but they could be different.
How can I determine if the images are the same, or if they're not the same, which one is newer and which is older?

A: In general, you can check if the imageId of your container matches the one of your image:
docker inspect -f '{{ .Image }}' bashapp

As you won't be able to remove an image that is still used, you should be able to find the image of your container with the following command:
docker images | grep $(docker inspect -f '{{ .Image }}' bashapp | cut -d ":" -f 2 | head -c 12)

If you know which image is used, you should also be able to tell whether the image is newer or not.


text:
Q: Xamarin connect to Web Api I am new to using Xamarin, Web APIs and HttpClient.
I have an app, I am trying to retrieve a message from a local Web Service I am running using HttpClient and display it as a simple basic start.
Here is my 'Login' button code:
    private async void Login_Clicked(object sender, EventArgs e)
    {

        var txtEmail = this.FindByName<Entry>("txtEmail");
        var txtPassword = this.FindByName<Entry>("txtPassword");

        if ( txtEmail.Text == null )
        {
            await DisplayAlert("Email", "Please enter your email address!", "OK");
            return;
        }

        if (txtPassword.Text == null)
        {
            await DisplayAlert("Password", "Please enter your password!", "OK");
            return;
        }

        using (var request = new HttpRequestMessage())
        {
            request.RequestUri = new Uri("http://82.68.3.61/api/ping");
            request.Method = HttpMethod.Get;
            request.Headers.Add("Accept", "application/json");

            using (var client = new HttpClient())
            {
                HttpResponseMessage response = await client.SendAsync(request);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    await DisplayAlert("Success", json, "OK");
                }

            }
        }

    }

Here is my Web Application Controller code:
public class LoginController : Controller
{

    [HttpGet]
    [Route("api/ping")]
    public IActionResult Ping()
    {
        return Ok("Pong!!");
    }
}

If I use the following: https://localhost:44309/api/ping I get the message Pong!! back, but the app doesn't do anything when I press login, why?

A: That IP seems like a public IP, you probably don't have the correct rules in your firewall/router to allow external access.
If your app runs in an emulator you can use 10.0.2.2 instead of localhost to reach your host machine.
Otherwise, if you are running on a device on the same network as your host computer, then use the local IP address. Often these are in the 192.168.x.x or 10.x.x.x ranges.
Also, you should not use HttpClient in a using statement like:
using (var client = new HttpClient())

It should be considered as a shared resource per app instance. Otherwise you will experience that you leak TCP sockets, which can result in you not being able to make new requests.


text:
Q: Spring Security back channel SAML SOAP Authentication I have a Spring Security app that uses SAML.  It is working fine.  I go to a secured page, I get redirected to the IDP, login... success.
Now I want to have the login done "in house" as it were, with no redirection.
I want to have a login page that takes username/pass - then -- well I don't know. :)
Is there anyway to NOT have the user's browser go to the IDP,  either POST the form to the IDP and then redirect back to my app?
I read in the documentation about back-channel SOAP calls, and that sounds like exactly what I want, but I can't find anything on it.  Does anyone have an example of how this would be achieved?


text:
Q: how to draw a rectangle in an image using open cv? I want to draw a rectangle in an image using open cv c++?I read a function called CV::rectangle,can anyone explain how this function works?Or is there any other method which can be used to draw rectangle?

A: You are right, you can use cv::rectangle.
You should be able to draw something using this code
cv::rectangle( img, cv::Point2f( 10, 10 ), cv::Point2f(100, 100), cv::Scalar( 255, 0, 0 ) );

This will draw a red rectangle starting with top left at (10, 10) and bottom right at (100,100).
This also assumes that img has 3 channels of usigned int type, if the type is different, then you need to change the values in the Scalar.


text:
Q: tell Positive Definite Matrices by the sign of determinants This is from my textbook

I don't understand why it didn't mention the other situation which is $det(A_k) <0 $ for all k, and we stall have positive pivot because $\frac{negative}{negative}=positive$

A: If you take that equation seriously for $k=1$, you need to evaluate $\det A_0$, the determinant of an empty matrix. That's the sum over an empty product for all permutations of $0$ elements, of which there is $1$, so $\det A_0=1$. Thus the case $\det A_k\lt0$ is excluded. A more direct way might be to consider that equation to hold for $k\gt1$ and regard the first pivot $a_{11}=\det A_1$ as an initial value.


text:
Q: How to see the rest of screen visual studio phone Tell me how can i see the rest of the screen in my xaml? I added text block with height 2000 pixels, how can I see the rest?The second problem is, in my XAML my text is beautifully e.g. centered... But in emulator it's everything in single line.
<phone:PhoneApplicationPage
    x:Class="Excercises.Weider_s_six"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="#FF1FB0DB">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="PageTitle" Text="Weider's six" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" FontSize="64" />
        </StackPanel>

        <!--ContentPanel - place additional content here-->

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <ScrollViewer>
                <TextBlock Height="2000" HorizontalAlignment="Left" Margin="0,6,0,0" Name="TextBlock1" Text="Weider 6 pack Training is a perfect exercise for flat stomach.
    This easy training programme has many advantages.
    It's perfect for beginners and for experts – exercises are easy and begin with the basic level, so every beginner can use them but they get more complicated pretty fast so advanced sportsmen can also be interested in them.
    It helps not only carve your muscles but also burn fat – during the exercise you not only use your abdominal rectus but you also move your legs and arms. It is also because W6 puts pressure on the number of repetitions. It carves your muscles but also burns fat. You can train W6 for about 40 minutes without taking any breaks – you use up all glycogen in blood and start burning the fat.
    It is easy – it is a really easy training set which you can train almost anywhere. All you need is flat ground.
    It gives excellent results – if you want to have a flat stomach W6 is designed just for you. You can see the first effects after just a week and after a whole series it is really impressive.
    How to do Weider 6

    Starting Position

    Lay flat on the ground, hands along the body.
    1 – exercise 1

    Lift your right leg and bend your knee to right angle angle
    Lift your upper torso to contract abdominal muscles and hold the lifted knee with your hands.
    Hold still for 3 seconds.
    Return to the starting position.
    Repeat the exercise with the other leg
    2 – exercise 2

    Lift both legs and bend your knees to right angle
    Lift your upper torso to contract abdominal muscles and hold both knees
    Hold still for 3 seconds

    Return to the starting position" VerticalAlignment="Top" Width="450" />
        </ScrollViewer>
        </Grid>

    </Grid>

    <!--Sample code showing usage of ApplicationBar-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
                <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->

</phone:PhoneApplicationPage>

A: For the first part, include your textblock inside a scrollviewer and set its Width and Height to Auto.
Then, set TextWrapping="Wrap" in your textblock XAML and set TextAlignment property of textblock to required value to get required alignment.
And if you want formatted text, you can use something like this:
<TextBlock FontFamily="Arial" Width="Auto" Height="Auto" TextWrapping="Wrap">
<LineBreak/>
<Run Foreground="Maroon" FontFamily="Courier New" FontSize="40">
Some text 1
</Run>
<LineBreak/>
<Run text="Some Text 2"/>
<LineBreak/>
</TextBlock>

The <LineBreak/> corresponds to new line.
I think this will solve your all problems.
For further info, please refer this.


text:
Q: If I change a nameserver but preserve the MX record will it harm email? My client already has email setup with a provider but would like their website hosted by a different provider. Currently they just have a NS record pointed at the company that hosts their email. I used dig to grab their two MX records, otherwise they don't have any other records set. They are using Network Solutions as their domain registrar so I'll have to use Network Solutions advanced DNS tool to make the changes.
I was planning on doing the following:
1. Change the NS to point at Network Solutions (this is a requirement of their Advanced DNS)
2. Make sure the MX records point at the old email host
3. Add A records for the new website host
When I click the edit advanced DNS button in the Network Solutions control panel it says the following:
"Please Note: When you Move Name Servers to Network Solutions, your Existing Name Servers will no longer be used. As a result, Web sites and E-mail from other providers will be lost."
That last word has me kind of concerned. Will all the previous emails actually be "lost" or are they saying that email sent during the change over might be lost?

A: Contrary to what Wooble says, the wording is quite sensible.  The case that it addresses, of course, is fairly obvious with a little thought: Someone adjusts the name server records to switch from another company's content DNS hosting service to Network Solutions' content DNS hosting service without copying any of the existing other records across, and all of a sudden HTTP and SMTP go awry, as the world at large is no longer told the right places to contact for these services.
Yes, people sometimes do not know that it's necessary to transfer the database across from one publisher to another when one switches publishers.
And contrary to what spacehunt says, things will not soft fail if you switch the servers before copying the database.  In the absence of MX resource records, SMTP Relay clients will fall back to A and AAAA resource records, per RFC 2821 § 5.  They won't be there, of course, since you haven't copied them over either.  The SMTP Relay clients will bounce all queued mail as undeliverable.  Soft failures occur in the event that DNS query resolution fails to get an answer at all, not in the event that query resolution succeeds and gives a zero records answer.
In a similar vein, do you know that it isn't necessary to switch DNS hosting companies if all that you want to do (This is what you've told us.) is point HTTP service somewhere else?  As you've explained it, what you're doing seems entirely unnecessary.  You have company A providing SMTP mail service and content DNS service for the client, and company B providing content HTTP service.  To make company B's services known to the world, it's not necessary at all to replace company A with a company C — Network Solutions.  Just go to the current content DNS service provider and enter the necessary A and AAAA resource records into the database.

A: As long as the MX records are not changed, no, your emails will not be lost.
At worst, the SMTP server that tries to send email to you won't be able to resolve your domain name's MX records for a while, but all that happens is that the emails get queued on their side to be retried again later.

A: Your DNS provider (unless you're using bundled services) has no control whatsoever over your actual web and email services; the wording there is incredibly stupid. You will not lose any data stored on other servers by changing your DNS.
If the new DNS host has the same A, CNAME, and MX records as the old provider, it's extremely unlikely you'd even have any connectivity problems; your hostnames will resolve to the same IPs before and after your change propagates. If you're using different DNS records on the 2 DNS hosts, it's possible some of your traffic may go to unexpected IPs for a time about equal to your TTL setting; you should be prepared to deal with traffic continuing to go to the old IPs for a short while.


text:
Q: How to get the data in front end when API calling returning data in [[101,4],[102,2],[103,1],[104,1],[105,1],[108,1],[109,1]] without key value pair? When I am calling API its giving data in [[101,4],[102,2],[103,1],[104,1],[105,1],[108,1],[109,1]] format which is only value. Is there any solution that how to get this data in UI in flutter?
Previously I have worked with below type of data coming from API.In this data can be accessed using key name but how to access value in [[101,4],[102,2],[103,1],[104,1],[105,1],[108,1],[109,1]] format when there is no key to access value in Flutter?
[{"activityId":101,"docId":90,"status":1},{"activityId":101,"docId":100,"status":0},{"activityId":101,"docId":159,"status":0},{"activityId":101,"docId":201,"status":0},{"activityId":1784,"docId":123,"status":1}]

A: This looks like basic List<List<int>> so if data is  [[101,4],[102,2],[103,1],[104,1],[105,1],[108,1],[109,1]] let's say you want to access number 4 from the start of the message you'd need to access it like:
final response = <List<int>> [[101,4],[102,2],[103,1],[104,1],[105,1],[108,1],[109,1]]

int four = response[0][1];

print('$four')

in terminal would print value 4


text:
Q: jquery Bootgrid: get all rows data I need to filter rows in my jQuery Bootgrid (with pagination).
How I can get ALL rows from grid?
When I try to do this $('#TableId').bootgrid().data('.rs.jquery.bootgrid')
it returns only rows in first page.

A: Almost there. Try this:
$('#TableId').bootgrid().data('.rs.jquery.bootgrid').rows

returns all rows data(array) that Bootgrid used right now.


text:
Q: directory created by GitBash doesn't appear in Windows explorer Hi I'm working with GitBash to create a directory for my project, and then to clone the project from GitHub.com/...
But the directory never appeared in Windows Explorer.
To be detailed:

*

*I create a directory using mkdir TestForStackOverFlow

*I clone the project from GitHub.com using git clone https://github.com/udacity/Sunshine-Version-2.git
but i can't access this directory with windows explorer.
Images proving:
Before mkdir TestForStackOverflow

After mkdir TestForStackOverflow

Any guess how to fix it?
Thanks in advance

A: Finally was the COMODO firewall (version 6.2.282872.2847) who "auto sandbox" the GitBash without asking me.
I mark C:/Program Files/Git folder as Trusted and everything runs fine!
To do this on COMODO there is the steps:

*

*Open COMODO firewall and move to Task by clicking the up-right Icon as showing in the next image (red arrow)

*In the Task screen choose Shadowbox Tasks and then click Open Advanced Settings

*In the new window on left menu choose File Rating -> Trusted Files. In the list will appear open the pop-up menu on the bottom of the list (the little up-arrow on the bottom).

*Choose Add > Folders, navigate to the Git Folder and press OK. Finally press OK to Advanced Settings window.

A: Try and see if the issue persists when using a more recent bash, namely the one package with the latest git-for-windows (successor to msysgit)
Unzip PortableGit-2.4.4.2-3rd-release-candidate-64-bit.7z.exe and launch its git-bash.exe.
You will be using Git 2.4.4. On Windows.


text:
Q: Problem with writing an infix macro in Clojure I'm trying to write a Clojure infix macro, but I get a compilation error which I don't understand.
It should produce function calls from the regular math expression syntax:
(macroexpand '(infix 3 * (2 + 1)))
;; => (* 3 (+ 2 1))

I tried to switch the list statement to a quote, but it didn't work.
The macro:
(defmacro functionize [macro]
  `(fn [& args#] (eval (cons '~macro args#))))

(defmacro infix
  ([n]
   (if (not (or (number? n) (fn? n)))
     `(~(apply (functionize infix) n))
     n))
  ([fir sec & res]
   (list sec (infix fir) (infix res))))

The error:
1. Caused by java.lang.IllegalArgumentException
   Don't know how to create ISeq from: clojure.lang.Symbol

The error is for the last line, for the first call for infix.

A: i can see at least one possible error in your code: [fir sec & res] should probably be [fir sec res], since you need the third arg, not the list of all args. It still doesn't fix the problems in your code. The main one, is that you are overthinking it (with eval and stuff)
I would probably use something like this:
(defmacro infix [n]
  (if (list? n)
    (let [[arg1 op arg2] n]
      `(~op (infix ~arg1) (infix ~arg2)))
    n))

user> (clojure.walk/macroexpand-all '(infix (1 + ((6 - (3 / 7)) * 3))))
;;=> (+ 1 (* (- 6 (/ 3 7)) 3))

user> (infix (1 + ((6 - (3 / 7)) * 3)))
;;=> 124/7

UPDATE
to omit parentheses you could update it this way:
(defn unwrap-arg [restargs]
  (if (= 1 (count restargs))
    (first restargs)
    restargs))

(defmacro infix [n]
  (if (list? n)
    (let [[arg1 op & arg2] n]
      `(~op (infix ~arg1) (infix ~(unwrap-arg arg2))))
    n))

user> (clojure.walk/macroexpand-all '(infix (1 + 2 + (10 - (4 / 10)) + (4 * 5))))
;;=> (+ 1 (+ 2 (+ (- 10 (/ 4 10)) (* 4 5))))

user> (infix (1 + 2 + (10 - (4 / 10)) + (4 * 5)))
;;=> 163/5


text:
Q: Getting undefined value while passing hidden value from jsp to servlet I have a hidden value in JSP.
<input type="hidden" name="selectedtxn" value="" />

And I access the value from servlet.
String selectedTxnNo = request.getParameter("selectedtxn");

But the value I get in servlet is undefined.
Am I doing anything wrong?

A: your hidden input field is empty  value="" thats why you are getting undefined.Give some value like value="test"


text:
Q: On mouse over show div not working properly I have a table on every table when I move my mouse to show a pop up will appear the thing is when I move my mouse on the first one it shows me all, would there be a possibility to show only the one on which mouse is hovered over? as of I want to when the user hover's it shows the pop up of the one which the mouse is hovering over, not all the pop up should be shown as of now

$(document).ready(function() {
  $('.fa-bar-chart').mouseover(function() {
    $(".bar_graph").show();
  });

  $('.fa-bar-chart').mouseout(function() {
    $(".bar_graph").hide();
  });
});
table {
  margin-top:80px;
}
i {
  position: relative;
}
.bar_graph {
    width: 200px;
    height: 200px;
    background-color: #efefef;
    position: absolute;
    top: 0;
    right: -200px;
    padding: 0;
    padding-right: 10px;
    display: none;
}

  Stock In Trade Show

2016

2015

2014

2013

2012

  Stock In Trade Show

2016

2015

2014

2013

2012

  Stock In Trade  Show

2016

2015

2014

2013

2012

  Stock In Trade Show

2016

2015

2014

2013

2012

A: The $(".bar_graph") selector will return all the elements with the class bar_graph,  You should use this to refer to the related bar_graph like :
$(".bar_graph",this).show();
//Or
$(this).find(".bar_graph").show();

Hope this helps.

$(document).ready(function() {
  $('.fa-bar-chart').mouseover(function() {
    $(".bar_graph", this).show();
  });

  $('.fa-bar-chart').mouseout(function() {
    $(".bar_graph", this).hide();
  });
});
table {
  margin-top:80px;
}
i {
  position: relative;
}
.bar_graph {
    width: 200px;
    height: 200px;
    background-color: #efefef;
    position: absolute;
    top: 0;
    right: -200px;
    padding: 0;
    padding-right: 10px;
    display: none;
}

  Stock In Trade Show

2016

2015

2014

2013

2012

  Stock In Trade Show

2016

2015

2014

2013

2012

  Stock In Trade  Show

2016

2015

2014

2013

2012

  Stock In Trade Show

2016

2015

2014

2013

2012


text:
Q: WinAPI: Correctly copying a HBITMAP to the clipboard I have some difficulties trying to copy a HBITMAP to the clipboard. My HBITMAP is created from a COLORREF array and I am able to display it correctly. Here is how it is created:
COLORREF* colors = new COLORREF[imageSize[0] * imageSize[1]];

for (int i = 0; i < imageSize[1]; i++) {
    for (int j = 0; j < imageSize[0]; j++) {
        colors[imageSize[0] * i + j] = RGB(/* ... */);
    }
}

// Create bitmap
HBITMAP hBitmap = CreateBitmap(imageSize[0], imageSize[1], 1, 32, (void*)colors);

delete[] colors;

In order to copy my bitmap to the clipboard, I use this small piece of code:
OpenClipboard(hWnd);
EmptyClipboard();

SetClipboardData(CF_BITMAP, hBitmap);

CloseClipboard();

When I execute my app, I am able to copy the bitmap and paste it somewhere, for example in MS Paint. But if I try to copy it a second time, the clipboard content can't be pasted anymore unless the first piece of code above is executed again.
In the MSDN documentation, it is said that

If SetClipboardData succeeds, the system owns the object identified by the hMem parameter.

I don't understand exactly what this means, but I guess it is the source of my problem. I found an example of a function which does what I want here, but it does not seem to use the same kind of variables. Another example, using strings this time, can be found here.
I am not too sure how to translate this last example to my case. Could you point me in the right direction?

A: A comment that was deleted helped me find the answer. I actually have to copy my HBITMAP to another HBITMAP before calling SetClipboardData. This way, the copied bitmap can be sent to the clipboard, and the original bitmap is kept for later.
To copy the bitmap, I used the code that can be found in Copying a Bitmap to another Bitmap. In my code, it looks like this:
// Create a new bitmap
HBITMAP hBitmap_copy = CreateBitmap(imageSize[0], imageSize[1], 1, 32, NULL);

// Copy the source bitmap to the new one
HDC srcDC = CreateCompatibleDC(GetDC(NULL));
HDC newDC = CreateCompatibleDC(GetDC(NULL));

HBITMAP srcBitmap = (HBITMAP)SelectObject(srcDC, hBitmap);
HBITMAP newBitmap = (HBITMAP)SelectObject(newDC, hBitmap_copy);

BitBlt(newDC, 0, 0, imageSize[0], imageSize[1], srcDC, 0, 0, SRCCOPY);

SelectObject(srcDC, srcBitmap);
SelectObject(newDC, newBitmap);

DeleteDC(srcDC);
DeleteDC(newDC);

// hBitmap_copy can now be copied to the clipboard
OpenClipboard(hWnd);
EmptyClipboard();

SetClipboardData(CF_BITMAP, hBitmap_copy);

CloseClipboard();

I can now copy the displayed bitmap as many times as I want!

A: // You can't pass hBitmap to SetClipboardData directly
OpenClipboard(NULL)
HBITMAP hBitmap = getBit(); // From somewhere

DIBSECTION ds;
::GetObject(hBitmap, sizeof(DIBSECTION), &ds);
//make sure compression is BI_RGB
ds.dsBmih.biCompression = BI_RGB;
HDC hdc = ::GetDC(NULL);
HBITMAP hbitmap_ddb = ::CreateDIBitmap(
    hdc, &ds.dsBmih, CBM_INIT, ds.dsBm.bmBits, (BITMAPINFO*)&ds.dsBmih, DIB_RGB_COLORS);
::ReleaseDC(NULL, hdc);

EmptyClipboard();
SetClipboardData(CF_BITMAP, hbitmap_ddb);
CloseClipboard();


text:
Q: Basic Javascript / jQuery Works jFiddle, but Not my Browser I am not new to programming but I am new to Javascript and jQuery.
In my attempts to write the most basic thing, I wrote the below.
If I copy the jQuery include + my javascript and the HTML  to jsFiddle, it works. When you select something on the dropdown you get the alert box.
But opening the .html file in my browser, it does not work. You can change the selection all day long and nothing happens.
I feel like this is the most basic thing but I haven't been able to figure it out. What dumb beginner mistake am I making? Javascript is client-side, so it should work I would think. I am using Chrome if it matters but same result in IE. Javascript is enabled in both.
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $('#selections').change(function() {
            alert('Test');
        });
    </script>
</head>

<body>

    <select id="selections">
        <option>Options...</option>
        <option value="zero">zero</option>
        <option value="one">one</option>
    </select>

</body>

</html>

A: You have to put your script inside a $(document).ready() function. In JQuery, this ensures that all the events are being attached after the elements of the page has been loaded. Please see revised code below:
$(document).ready(function() {
    $('#selections').change(function() {
        alert('Test');
    });
});

A: place script tag before closing tag of body, it doesn't work, because you are binding on element before it is rendered "#selections".
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</head>

<body>

    <select id="selections">
        <option>Options...</option>
        <option value="zero">zero</option>
        <option value="one">one</option>
    </select>

    <script>
        $('#selections').change(function() {
            alert('Test');
        });
    </script>
</body>

or if you need it to be in head, wrap it within $(document).ready, like this,
$(document).ready(function(){
    $('#selections').change(function() {
            alert('Test');
        });
});


text:
Q: Transposing in Pandas I am trying to transpose in pandas. I have something that looks like this:
A B C D E F G H I
1 2 3 4 5 6 7 8 9
I want it to look like this:
A 1
B 2
C 3
D 4
E 5
F 6
G 7
H 8
I 9

A: You can use T or transpose:
df.T

or
df.transpose()

Input:
A B C D E F G H I
1 2 3 4 5 6 7 8 9

Output:
   0
A  1
B  2
C  3
D  4
E  5
F  6
G  7
H  8
I  9


text:
Q: dateTime to Epoch and vice versa xslt I have been trying to convert a given dateTime to epoch time and also a given epoch time to dateTime. I am quite new to xslt and have been struggling with this quite for some time, it is not giving me back any results. Here is my xslt so far
    <xsl:stylesheet version="1.0"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:ns0="http://www.NoPreAuth.org"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                exclude-result-prefixes="xsi xsl ns0 xsd">
<xsl:template match="/">
<xsl:variable name="date1">
        <xsl:value-of select="/ns0:NoAuthInput/ns0:StartDate"/>
</xsl:variable>
<xsl:variable name="date2">
        <xsl:value-of select="/ns0:NoAuthInput/ns0:EndDate"/>
</xsl:variable>
<ns0:NoPreAuthInput>
<ns0:Product>
        <xsl:value-of select="/ns0:NoAuthInput/ns0:Product"/>
</ns0:Product>
<!-- datTime to epoch -->
<ns0:END_T>
  <xsl:value-of select= "(('$date1')  - xsd:dateTime('1970-01-01T00:00:00') )  div  xsd:dayTimeDuration('PT1S') "/>
</ns0:END_T>
<!-- epoch To datTime -->
<ns0:Closed_T>
  <xsl:value-of select= "(('$date2')  + xsd:dateTime('1970-01-01T00:00:00') )  *  xsd:dayTimeDuration('PT1S') "/>
</ns0:Closed_T>
</ns0:NoPreAuthInput>
</xsl:template>
</xsl:stylesheet>

and the xml which I am trying to convert is:
<?xml version="1.0" encoding="UTF-8" ?>
<NoAuthInput xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.NoAuth.org

 xmlns="http://www.NoAuth.org">
   <Product>ABC</Product>
   <StartDate>2015-10-05T15:52:40.782</StartDate>
   <EndDate>1444150760</EndDate>
</NoAuthInput>

any help on this much appreciated. Thanks

A: To convert Unix time to ISO 8601 date-time:
<xsl:value-of select="xs:dateTime('1970-01-01T00:00:00') + xs:dayTimeDuration(concat('PT', UnixTime, 'S'))"/>

To convert ISO 8601 date-time to Unix time;
<xsl:value-of select="floor((xs:dateTime(ISODateTime) - xs:dateTime('1970-01-01T00:00:00')) div xs:dayTimeDuration('PT1S')) "/>

Requires XSLT 2.0.
Working demo: http://xsltransform.net/94rmq5L

A: If you are trying to do this in XSLT 1.0 on MSXML (I know the original asker is not):
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:userCSharp="http://stackoverflow.com/xsltexample">
  <xsl:output method="xml" omit-xml-declaration="yes" indent="yes" />
  <xsl:template match="/">
    <xsl:value-of select="userCSharp:DateToEpoch('1970-01-02')" />
  </xsl:template>
  <msxsl:script language="CSharp" implements-prefix="userCSharp"><![CDATA[
     public string DateToEpoch(string s)
     {
         DateTime dt = DateTime.Parse(s);
         DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

         return (dt - epoch).TotalSeconds.ToString();
     }
   ]]></msxsl:script>
</xsl:stylesheet>

Replace the '1970-01-02' with whatever text node you want and this should work, as long as that node was a valid date time.  If not, it's easy enough to write up another simple method to do that using DateTime.Parse/TryParse.  The output of this template (against any valid XML) would be 86400.  Note that it's best to define methods in a CDATA node to avoid needing to escape quotes or angle brackets (this code doesn't happen to use any but might be extended to for some reason).