text:
Q: How can I position multiple divs side by side? I have several div's that contain a floated image and an unordered list. I want both of these to be positioned side by side down the page.
The issue is, as the divs go down the page the whole thing falls apart. The images on the right start to go lower and lower and the list items go higher and higher up. Here is what I did.
    .imageleft  {
    float: left;
    margin-left: 0;
    margin-top: 0;
}

.container-right {
display:inline;
    padding-bottom: 10px;
    width: 500px;

}

.container-left {

    float:left;
    padding-bottom: 10px;
    width: 500px;

}

                Title

                Sub title:

                    List item

                    List item

                    List item

                    List item

                    List item

                    List item

                Title

                Sub heading

                    List item

                    List item

                    List item

                    List item

                    List item

                    List item

I tried adding a div around the 2 divs but it doesn't seem to help. How can I prevent this undesired behavior?
Thanks for any tips!

A: You mean like this http://jsfiddle.net/efVjj/

A: You really only need the .imageleft class. Apply to both divs and you're set.
Here's the code (I added a border to outline the divs):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Untitled Document</title>

                Title

                Sub title:

                    List item

                    List item

                    List item

                    List item

                    List item

                    List item

                Title

                Sub heading

                    List item

                    List item

                    List item

                    List item

                    List item

                    List item


text:
Q: Magento 1.13 Product URLs I have recently upgraded Magento  with the Latest Magento 1.13.1.0.
Now the issue is the URLS in older version are like
categroy1/subcategory1/test-product.html
category2/test-product.html
brand/test-product.html
brand/new-product.html

where the product is assgin to 3 different categories. But after upgrade and when i run the url_migration_to_1.13.php all the urls are updated and the new url are weird.
Some of the urls are like
test-product-1.html
new-product-1-395db788289ee286662bbcabe78d99da.html

My client do not want to lose any previous URLs from older Magento.
Can any one suggest me any idea?
Thanks

A: In admin panel, System->configuration->catalog(leftside)->catalog-> Search Engine Optimization , There is a field named as: Use Category Path for Product URL's. Make this option as "YES". Then it will display as previous with the category name also. Dont forget to Re-Index after making changes. Clear CACHE once your reindexing is successful..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generate bottom scroll on a live chat using jquery or js I have a trouble to generate a animation to the end of my live chat
I tried :
document.getElementById("chat-body").scrollTop = document.getElementById("chat-body").scrollHeight;

but with no result there is my html code for the chat:

                        <form id="send_message">

                                    <input type="text" id="message" placeholder="Enter your message">

                                    <button class="btn btn-success btn-sm btn-block" type="submit">Send</button>

                        </form>

I append elements to:

 and use this template : http://bootdey.com/snippets/view/messages-chat-widget
Thanks a lot for reply.

A: I think you want to use the .nano-content since it contains your ul and items:
var chat = $('.nano-content');
chat.scrollTop(chat.prop('scrollHeight'));

Or if you want to get fancy and animate the scroll:
chat.animate({scrollTop:chat.prop('scrollHeight')});

A: Solved by :
 var chat = $('.nano-content');
 var chatItems = $('.mar-btm').length;
 chat.animate({scrollTop: (chat.prop('scrollHeight') * chatItems)});

Thanks a lot @nfreeze


text:
Q: python + selenium: ChromeDriver only supports characters in the BMP I found the answer to this question in one of the post which worked for me in the following case:
<input class="some_class" value="test message">

JS_ADD_TEXT_TO_INPUT = """
            var elm = arguments[0], txt = arguments[1];
            elm.value += txt;
            elm.dispatchEvent(new Event('change'));
            """

message = ""
message_box = browser.find_element_by_xpath("xpath")
browser.execute_script(JS_ADD_TEXT_TO_INPUT, message_box, message)
message_box.send_keys(' ')
message_box.send_keys(Keys.ENTER)

but now I encountered different input style and above macro works no longer. When the message box is empty I can see the first statement. When I start to type to message box, "br" will change to "span"
1)

2)
       test message

message_box.send_keys('non-wide character message') works when applied to , macro does not work neither when applied to  nor . Any suggestions ? Thank you!


text:
Q: Maven error "Unable to initialize main class" when I try to run a jar file I just created I created a .jar file using Maven in the command line. It created the .jar file. When I tried to run it in the command line I got this error:
java -jar target\github-automation-1.0.0.jar
Error: Unable to initialize main class com.aking.app.Application
Caused by: java.lang.NoClassDefFoundError: org/openqa/selenium/WebDriver

I am not sure how to fix this issue. This is the file structure showing where important files are located (package is combined for the sake of typing):
- githubautomation (root directory)
    - pom.xml
    - src
        - main
            - java
                - com.aking.app
                    - Applicatoin.java

    - target
        - classes
            - com.aking.app
                - Application.class
        - github-automation-1.0.0.jar

My pom.xml (Edit: added suggested code)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <maven.compiler.release>11</maven.compiler.release>
        <start-class>com.aking.app.Application</start-class>
    </properties>

    <groupId>com.aking.app</groupId>
    <artifactId>github-automation</artifactId>
    <version>1.0.0</version>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.2.0</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.aking.app.Application</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

I also read something that there needs to be a main manifest attribute, but I'm not sure. I want to be able to have people run my program through the jar without relying on them to have an IDE.

A: You have to specify your start class in pom.xml.
In the properties section, include the below line
 <start-class>#path to your main class</start-class>

The path should be relative, i.e from the start of your package name.

A: This is the root cause of your problem:
Caused by: java.lang.NoClassDefFoundError: org/openqa/selenium/WebDriver

The class loader cannot find the WebDriver class.
Why?
Probably because the JAR file containing the class is not on the runtime classpath.
So how do you get it on the classpath?
There are 3 ways:

*

*Use java -cp ... com.aking.app.Application where the ... has all of the JAR files that you need.  The Oracle documentation explains the syntax you need to use to express the classpath on the command line.
Note: on Linux and Mac OS, the classpath separator is : not ;.

*Modify your JAR file to include a Class-Path attribute in its MANIFEST.MF file.

*Create an "UberJAR" that contains an exploded copy of all dependent JARs.
Variations 2 and 3 can be done using Maven.


text:
Q: All queries of Internet Explorer are slowed after a proxy is applied (including those bypassed directly)
I have set up an internet access limited PC for the special demand of our company, setting up a non-existent proxy server address of IE and adding those bypass sites to the excluded lists; however, after this proxy is applied, accessing any sites in IE have slowed down significantly, including some local webpages.

*

*Although this method can meet the requirement, the user experience is badly affected:
Reg Add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d 1 /f

Reg Add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyServer /t REG_SZ /d "0" /f

Reg Add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyOverride /t REG_SZ /d "*.speci-addr.com;<local>;" /f

What can I do about this?


text:
Q: Create ZipArchive of Excel XLSX file with EPPLUS C# I have the folowing function to return a FileStreamResult for my ASP.NET MVC application.
/// <summary>
/// Generates a FileStreamResult containing a zip file with the EXCEL file in it
/// </summary>
/// <typeparam name="T">Type of object in the object list parameter</typeparam>
/// <param name="objectList">The object list enumerable. This contains the data for the EXCEL file</param>
/// <param name="fileName">The file name of the EXCEL</param>
/// <returns>FileStreamResult</returns>
public FileStreamResult CreateZipFileFileStreamResult<T>(IEnumerable<T> objectList, string fileName)
{
    var ms = new MemoryStream();

    var contentType = System.Net.Mime.MediaTypeNames.Application.Zip;

    ExcelPackage excelPackage = null;

    ZipArchive archive = null;

    try
    {
        excelPackage = new ExcelPackage(ms);

        var workSheet1 = excelPackage.Workbook.Worksheets.Add("Sheet1");

        workSheet1.Cells["A1"].LoadFromCollection<T>(objectList, true);

        excelPackage.SaveAs(ms);

        ms.Seek(0, SeekOrigin.Begin);

        archive = new ZipArchive(excelPackage.Stream, ZipArchiveMode.Create, true);

        var newEntry = archive.CreateEntry(fileName, System.IO.Compression.CompressionLevel.Fastest);

        var newEntryStream = newEntry.Open();

        var fsr = new FileStreamResult(excelPackage.Stream, contentType);
        fsr.FileDownloadName = fileName + ".zip";

        return fsr;
    }
    catch (Exception ex)
    {
        if (archive != null)
            archive.Dispose();

        if (excelPackage != null)
            excelPackage.Dispose();

        if (ms != null)
            ms.Dispose();

        throw;
    }
}

The function returns something, but is is in a split XML fashion rather that one XLSX file.
I want it to a return a ZIPPED single file.
This is what the current result looks like.

Having used the help given by @kuujinbo I have created this function.
Please note that for some reason FileContentResult works and FileStreamResult does not work.
        /// <summary>
        /// Generates a FileStreamResult containing a zip file with the EXCEL file in it
        /// </summary>
        /// <typeparam name="T">Type of object in the object list parameter</typeparam>
        /// <param name="objectList">The object list enumerable. This contains the data for the EXCEL file</param>
        /// <param name="fileName">The file name of the EXCEL</param>
        /// <returns>FileStreamResult</returns>
        public FileContentResult CreateZipFileFileContentResult<T>(IEnumerable<T> objectList, string fileName)
        {
            var contentType = System.Net.Mime.MediaTypeNames.Application.Zip;

            using (var memoryStream = new System.IO.MemoryStream())
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    using (var package = new OfficeOpenXml.ExcelPackage())
                    {
                        var workSheet1 = package.Workbook.Worksheets.Add("Sheet1");
                        workSheet1.Cells["A1"].LoadFromCollection<T>(objectList, true);

                        var firstRow = workSheet1.Row(1);
                        if (firstRow != null)
                            firstRow.Style.Font.Bold = true;

                        zip.AddEntry(fileName, package.GetAsByteArray());
                        zip.Save(memoryStream);
                        var fcr = new FileContentResult(memoryStream.ToArray(), contentType); //NOTE: Using a File Stream Result will not work.
                        fcr.FileDownloadName = fileName + ".zip";
                        return fcr;
                    }
                }
            }
        }

A: Since EPPlus internally uses a version of DotNetZip , (take a look at the source code) try and do the same. IMHO their design decision tells a lot about why some choose not to use ZipArchive.
class TestObject
{
    public int Id { get; set; }
    public string Name { get; set; }
}

IEnumerable<TestObject> objectList = new List<TestObject>()
{
    { new TestObject() {Id = 0, Name = "zero" } },
    { new TestObject() {Id = 1, Name = "one" } }
};
string ExcelName = "test.xlsx";
string ZipName = "test.zip";

public ActionResult DotnetZip()
{
    using (var stream = new MemoryStream())
    {
        using (ZipFile zip = new ZipFile())
        {
            using (var package = new ExcelPackage())
            {
                var sheet = package.Workbook.Worksheets.Add("Sheet1");
                sheet.Cells["A1"].LoadFromCollection<TestObject>(objectList, true);
                zip.AddEntry(ExcelName, package.GetAsByteArray());
                zip.Save(stream);
                return File(
                    stream.ToArray(),
                    System.Net.Mime.MediaTypeNames.Application.Zip,
                    ZipName
                );
            }
        }
    }
}

Tested and working:


text:
Q: Deploy latest build from repository to tomcat What I want to achieve is two step build automation
Step A - Build & Upload to artifact repo

*

*Create build job in Jenkins which will create build after every check-in

*Upload every successful build on Archiva server

Step B - Get latest artifact & deploy on required servers

*

*After every desired interval, get latest build from Archiva

*Deploy build uploaded in Step A.2 to dev/qa/stg server by unzipping its content in web server directory.

I was able to do achieve Step A by using maven goals in my project pom.xml but any idea/suggestions/best practices for Step B.
I understand/agree, I would need two different jobs having different pom.xml, question remains how will we get latest war from repo in pom and how will be deploy that latest war on remote server by unzipping it, as tomcat there does not have admin module.

A: I would deploy not a jar/war artifact on step 2, but would create a RPM that contains a needed files structure.
With maven it's quite easy to do with a maven rpm plugin
3-4. Nexus has built in YUM repository support, so you can use yum to install the latest rpm version

A: So I've always found it better to separate the builds and the deploys.
The schedule for those can be independently managed then.
Assuming you are using linux on the servers you could use the ssh-plugins in jenkins to download the artifact in archiva

wget http://server/repository/internal/group/artifact/version/artifact-version.jar

As for the deploy, you could sftp them over to the deploy server also using jenkins SFTP plugin.


text:
Q: jQuery.ajax chama webmethod(c#) com SpeechSynthesizer Eu tenho um método javascript que verifica se existe uma mensagem não lida. Se existir exibe a imagem de um envelope.
O metodo executa um jQuery.ajax que chama um WebMethod que retorna a quantidade de mensagens não lida.
Porém agora preciso adicionar no WebMethod o SpeechSynthesizer(C#) para falar as mensagens não lida. Porém quando adiciono essa funcionalidade o success, complete ou erro do jQuery.ajax não são executados, e eu não sei como resolver.

A: Consegui resolver dessa forma:
$.ajax({url: "seu WebMethod ", success: function(result){
   if('speechSynthesis' in window){
      var speech = new SpeechSynthesisUtterance(result);
      speech.lang = 'pt-BR';
      window.speechSynthesis.speak(speech);
    }
}});


text:
Q: How to handle auto number (index) on large amount of data? I have a table on my database (SQL Server 2014) and it has a auto number column as my index column.
I have a lot of data insertions on a day and i was thinking how can i handle my db after a year , I mean that auto number column are limited to a number at last.
If i need to change my database's  architecture or design , where can i
    found the reference to do it?

A: Sql server's int data type top limit is 2^31-1 (2,147,483,647).
Even if you insert 100,000 rows per day, it would take more then 50 years to reach the max limit. I'm guessing in that time, should your application live that long, sql server 2014 would be so outdated that someone will re-write the application at least once.
If you don't think that's enough, you can use BigInt data type, that has a top limit of  2^63-1 (9,223,372,036,854,775,807).
Also, note that nothing is stopping you from using the negative numbers as well, and if you do this, you have a range of 4,294,967,296 for a regular int. That's going to be very hard to use up in any application lifetime.
From the relevant MSDN page:
Data type   Range                                                                       Storage
bigint      -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807)    8 Bytes
int         -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)                            4 Bytes
smallint    -2^15 (-32,768) to 2^15-1 (32,767)                                          2 Bytes
tinyint     0 to 255                                                                    1 Byte

A: your ever increasing column is probably an INT which has a limit of  2,147,483,647..If you are sure ,your table can grow beyond this number
Then try BIGINT which has a limit of 9,223,372,036,854,775,807 and read as
nine quintillion two hundred twenty-three quadrillion three hundred seventy-two trillion thirty-six
Here is how you can change an Identity column from INT to BIGINT
Replace identity column from int to bigint

A: If you feel like int is going to be too small for the primary key (max 2,147,483,647), try using bigint (9,223,372,036,854,775,807). That should be sufficient for most of the tables.

A: What you are referring to is a primary key, likely the clustered index.  Using Identity is a standard practice as this will put new records 'at the end'.  You will want other indexes for other queries.
As for a limitation, the bar is pretty high.
Data type   Range   Storage
bigint  -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807)    8 Bytes
int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)    4 Byte


text:
Q: How to find the number of arbitrary constants in solution of a given differential equation? How to find the number of arbitrary constants in solution of a given differential equation ?

A: In general, the number of arbitrary constants of an ordinary differential equation (ODE) is given by the order of the highest derivative.
e.g. $$y\color{red}'=f(x)$$ has $\color{red}{\text{one}}$ constant of integration, $$y\color{red}{''}+y'=f(x)$$ has $\color{red}{\text{two}}$, $$y\color{red}{'''}+y''=f(x)$$ has $\color{red}{\text{three}},$ etc..
To generalise, suppose we've an ODE of the form $$a_ny^{(\color{green}{n})}+a_{n-1}y^{^{(n-1)}}+\cdots+a_2y''+a_1y'+a_0y=f(x), $$ where $a_i$ is a function of $x$.
Then the number of arbitrary constants in the general solution to this equation is $\color{green}{n}.$

Notation: $y^{(n)}=\frac{d^ny}{dx^n}$


text:
Q: stripe create user firebase cloud functions I am attempting to create a stripe user upon user creation for firebase, I keep receiving this error (error displayed below). the code for the function is also displayed below. if I need to post the database structure I will do so, I currently do not have any structure for stripe customer (this might be where issue occurs). if anyone can assist I would greatly appreciate it.
Error:
Error: Reference.child failed: First argument was an invalid path = "/stripe_customers/${data.uid}/customer_id". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"
at Object.exports.validatePathString (/user_code/node_modules/firebase-admin/node_modules/@firebase/database/dist/cjs/src/core/util/validation.js:282:15)
at Object.exports.validateRootPathString (/user_code/node_modules/firebase-admin/node_modules/@firebase/database/dist/cjs/src/core/util/validation.js:293:13)
at Reference.child (/user_code/node_modules/firebase-admin/node_modules/@firebase/database/dist/cjs/src/api/Reference.js:72:30)
at Database.ref (/user_code/node_modules/firebase-admin/node_modules/@firebase/database/dist/cjs/src/api/Database.js:60:54)
at stripe.customers.create.then (/user_code/index.js:41:29)
at tryCatcher (/user_code/node_modules/stripe/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/user_code/node_modules/stripe/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/user_code/node_modules/stripe/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/user_code/node_modules/stripe/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/user_code/node_modules/stripe/node_modules/bluebird/js/release/promise.js:693:18)
at Async._drainQueue (/user_code/node_modules/stripe/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/user_code/node_modules/stripe/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues (/user_code/node_modules/stripe/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:672:20)
at tryOnImmediate (timers.js:645:5)
at processImmediate [as _immediateCallback] (timers.js:617:5)

Functions:
'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const logging = require('@google-cloud/logging')();

admin.initializeApp(functions.config().firebase);

const stripe = require('stripe')(functions.config().stripe.token);
const currency = functions.config().stripe.currency || 'USD';

//[START chargecustomer]
//charge the stripe customer whenever an amount is written to the realtime       database
exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/charges/{id}').onWrite((event) => {
  const val = event.data.val();

  if (val === null || val.id || val.error) return null;

  return     admin.database().ref(`/stripe_customers/${event.params.userId}/customer_id`).once('value').then((snapshot) => {
return snapshot.val();
  }).then((customer) => {
const amount = val.amount;
const idempotency_key = event.params.id;
let charge = {amount, currency, customer};
if (val.source !== null) charge.source = val.source;
return stripe.charges.create(charge, {idempotency_key});
  }).then((response) => {
return event.data.adminRef.set(response);
  }).catch((error) => {
return event.data.adminRef.child('error').set(userFacingMessage(error));
  }).then(() => {
return reportError(error, {user: events.params.userId});
  });
});
// [end chargecustomer]]

// when user is created register them with stripe
exports.createStripeCustomer = functions.auth.user().onCreate((event) => {
  const data = event.data;
  return stripe.customers.create({
    email: data.email,
  }).then((customer) => {
    return    admin.database().ref(`/stripe_customers/${data.uid}/customer_id`).set(customer.id);
  });
});

// add a payment source (card) for a user by writing a stripe payment source   token to realtime database
exports.addPaymentSource =.  functions.database.ref('/stripe_customers/{userId}/sources/{pushId}/token').onWrite((event) => {
  const source = event.data.val();
  if (sourve === null) return null;
  return     admin.database.ref(`/stripe_customers/${event.params.userId}/customer_id`).once('value').then((snapshot) => {
return snapshot.val();
  }).then((customer) => {
return stripe.customers.createSource(customer, {source});
  }).then((response) => {
return event.data.adminRef.parent.set(response);
  }, (error) => {
return event.data.adminRef.parent.child('error').set(userFacingMessage(error));
  }).then(() => {
return reportError(error, {user: event.params.userId});
  });
});

// when a user deletes their account, clean up after the
exports.cleanupUser = functions.auth.user().onDelete((event) => {
  return admin.database().ref(`/stripe_customers/${event.data.uid}`).once('value').then((snapshot) => {
return snapshot.val();
  }).then((customer) => {
return stripe.customers.del(customer.customer_id);
  }).then(() => {
return admin.database().ref(`/stripe_customers/${event.data.uid}`).remove();
  });
});

function reportError(err, context = {}) {
const logName = 'errors';
const lof = logging.log(logName);

const metadata = {
  resource: {
    type: 'cloud_function',
    labels: {function_name: process.env.FUNCTION_NAME},
  },
};

const errorEvent = {
  message: err.stack,
  serviceContext: {
    service: process.env.FUNCTION_NAME,
    resourceType: 'cloud_function',
  },
  context: context,
};

return new Promise((resolve, reject) => {
  log.write(log.entry(metadata, errorEvent), (error) => {
    if (error) {
      reject(error);
    }
    resolve();
  });
});
}
// end [reportError]

// sanitize the error message for the user
function userFacingMessage(error) {
  returnerror.type ? error.message : 'an error occurred, developers have been   altered';
}

Database Structure:

A: In your code you have this:
ref('/stripe_customers/${event.params.userId}/customer_id')

this ${event.params.userId} should give you the value of the wildcard, but since you are using ' it is including the $ in the path also. So you need to change it like this:
ref(`/stripe_customers/${event.params.userId}/customer_id`)

by changing ' to `


text:
Q: Faster grpstats on large dataset I have a large Matlab dataset (1,924,014 by 5; ~73.4 MB)
Date          id            a           b           c
...
733234        1467          1.2656      1.2718      51.16
733235        1467          1.2732      1.2794      51.16
733236        1467          1.2781      1.2844       51.5
733236        1467            1.26         NaN        NaN
733237        1467          1.3084         NaN        NaN
733237        1467          1.3205         NaN        NaN
733238        1467          1.3125      1.3188      53.85
733238        1467             1.3         NaN        NaN
...

Date is the date in datenum form.
I need to average (ignoring NaNs) the last three columns for unique Date+id pairs, as sometimes there is more than one row for a given Date+id pair.
The output I want is
Date          id            mean_a      mean_b      mean_c
...
735234        1467          1.2656      1.2718      51.16
735235        1467          1.2732      1.2794      51.16
735236        1467          1.2691      1.2844       51.5
735237        1467          1.3144         NaN        NaN
735238        1467          1.3062      1.3188      53.85
...

I expected to be able to use
grpstats(myDataset, {'Date', 'id'}, 'mean')

But it is prohibitively slow. I expect this task could be completed in under 60 seconds.  I think grpstats is adding a GroupCount column and adding names to each of the observations, things I don't need.
How can I do this quickly? I am open to ideas whether or not they use grpstats.

A: Group by Date and id with unique(...,'rows'), then produce accumulation subs for multiple columns with meshgrid(), or explicitly with repmat(), and finally take a @nanmean with accumarray():
% Group by date and id
[un,~,pos] = unique(db(:,1:2),'rows');

% Produce row, col subs
[col,row] = meshgrid(1:3,pos);

% Accumulate
[un accumarray([row(:), col(:)], reshape(db(:,3:5),[],1),[],@nanmean)]


text:
Q: Lint considers Kotlin MutableMap.forEach() as java.util.Map.forEach() I am using Kotlin's MutableMap in my Android project. And trying to do some action per item. So here is my code.
private val uris: MutableMap<String, Uri> = mutableMapOf()
// ... Fill the items here ...
uris.forEach {
    val ref = FirebaseFirestore.getInstanse().reference
    uploadFile(ref, it.value)
}

Everything just works fine at runtime, but my CI build fails with below lint error:
MyActivity.kt:142: Error: Call requires API level 24 (current min is 16): java.util.Map#forEach [NewApi]
              uris.forEach {
                   ~~~~~~~

I know we can't use JDK-8's Map for Android projects until the min sdk is 24. But why lint is considering it as JDK-8's Map?
For further information I tried getting the Java code from Kotlin Bytecode option in AS and found that forEach is replaced with while loop and iterator as expected.
So what could be reason and how to solve this? Any lead will be appreciated.

A: I think this is an import problem. Maybe you have used JDK 8's Map.forEach.
You have to use kotlin.collections.MutableMap.forEach
You can also check this blog:
http://blog.danlew.net/2017/03/16/kotlin-puzzler-whose-line-is-it-anyways/

A: There are two overloaded foreachs on Map:
Kotlin one:
uris.forEach { (key, value) -> // Do some Action }

Java8 one:
uris.forEach { key, value -> // Do some Action }

Confusing, isn't it?

A: Are you sure that you use forEach from Kotlin?
Because there are two forEach, one from Kotlin with Map.Entry as an argument and one from Java with two arguments: key and value.
Please, show full version of your code. If you use forEach without arguments, it means that you use Kotlin one (you have it implicit argument).
If you use Kotlin forEach and still have this warning you should report this issue to Android Issue Tracker


text:
Q: Get value of $\frac{a+c}{b+d}$ from the values of $\frac{a}b$ and $\frac{c}d$ So, this seems easy, but I cannot figure it out, and I haven't been able to find a similar problem when searching around.
Let $x=\frac{a}{b}$, $y=\frac{c}{d}$, and $z=\frac{a+c}{b+d}$, where $a,b,c,d >0$ are real numbers. If I know the values of $x$ and $y$ (i.e., not the numerators and denominators), can I get the value of $z$?
I've tried some different things without much success.

A: Let $x=\frac{1}{2}$ and $y=\frac{1}{3}$.  Then, $y=\frac{\lambda}{3\lambda}$ for any $\lambda\not=0$.  So, we can let $a=1$, $b=2$, $c=\lambda$, and $d=3\lambda$.  Observe that
$$
z=\frac{1+\lambda}{2+3\lambda}.
$$

*

*When $\lambda=1$, $z=\frac{2}{5}$.

*When $\lambda=2$, $z=\frac{3}{8}$.

Since the value of $z$ changes, depending on $\lambda$, then there's nothing that you can say without knowing more about $a$, $b$, $c$, and $d$.
If $x=y$, then this answer of mine shows that you can calculate $z$.

A: *

*If $x\le y$, I claim that $$x \le z \le y $$
To see it note that $x \le y$ is equivalent to $ad \le bc$.

Now $x \le z$ is just $\frac{a}{b} \le \frac{a+c}{b+d}$ which is just $ad\le bc$.
Similarly $z\le y$ is just $\frac{a+c}{b+d}\le \frac{c}{d} $, which is also $ad\le bc$.
However, as the other example shows, we can't determine the solution uniquely.


text:
Q: How do I put a previous game button for my tictactoe? I am currently working on a tictactoe game but there is a twist.
I need to have a button that show the previous game history or the winning pattern for the player.
what I am thinking is to manipulate the nth child of my data-cell so that it will be stored in a variable every time a player clicks on a cell on the board and when the previous game button is clicked, all the variables will be displayed again in the board.

 const X = 'x';
const CIRCLE = 'circle';
const WIN_COMB = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
]
var previousMoves = []

const cellElements = document.querySelectorAll('[data-cell]');
const board = document.getElementById('board');
const winnerDeclare = document.getElementById('winnerMsg');
const winnerMessage = document.querySelector('[data-winning-message-text]');
const xScore = document.getElementById('xScore');
const oScore = document.getElementById('oScore');
const drawScore = document.getElementById('draws');
const scoreReset = document.getElementById('resetScore');
const prevMatch = document.getElementById('previous');
const reset = document.getElementById('restart');
let circle;

var scoreX = 0;
var scoreO = 0;
var scoreDraw = 0;

gameStart()
reset.addEventListener('click', gameStart);
scoreReset.addEventListener('click', scoreClear);
// prevMatch.addEventListener('click', savedGame);

function gameStart(){
    circle = false;
    cellElements.forEach(cell => {
        cell.classList.remove(X);
        cell.classList.remove(CIRCLE);
        cell.removeEventListener('click', handleClick);
        cell.addEventListener('click',handleClick,{ once: true});
    })
    setHover();
    winnerDeclare.classList.remove('show');

}

function handleClick(e){
    // placing the mark on the board
    const cell = e.target;
    const currentClass = circle ? CIRCLE : X;
    placemark(cell,currentClass);
    if (checkwin(currentClass)){
        endGame(false);
    } else if(isDraw()) {
        endGame(true);
    } else {
        swapTurns();
        setHover();
    }
}

function endGame(draw){
    if (draw){
        winnerMessage.innerText = "DRAW!"
        // draw counter
        scoreDraw++;
        drawScore.innerHTML = scoreDraw;
    } else if (circle == true) {
        winnerMessage.innerText = "O is the winner!";
        scoreO++;
        oScore.innerHTML = scoreO;
    } else {
        winnerMessage.innerText = "X is the winner!"
        scoreX++;
        xScore.innerHTML = scoreX;
    }
    winnerDeclare.classList.add('show');

}

// declare draw
function isDraw() {
    return [...cellElements].every(cell =>{
        return cell.classList.contains(X) || cell.classList.contains(CIRCLE)
    })
}

function placemark(cell, currentClass) {
    cell.classList.add(currentClass);
    // previousMoves = cell.classList.add(currentClass);
}

// switching turns from X to O
function swapTurns(){
    circle = !circle;
}

// for hover effect
function setHover() {
    board.classList.remove(X);
    board.classList.remove(CIRCLE);

    if (circle) {
        board.classList.add(CIRCLE);
    } else {
        board.classList.add(X);
    }
}

// winner check
function checkwin(currentClass){
    return WIN_COMB.some(combination =>{
        return combination.every(index =>{
            return cellElements[index].classList.contains(currentClass);
        })
    })
}

// reset scoreboard
function scoreClear() {
    scoreX = 0;
    scoreO = 0;
    scoreDraw = 0;

    drawScore.innerText = "";
    oScore.innerText = "";
    xScore.innerText = "";
}

// // save previous game
// function saveTheGame(){
//     const cellHolder = []
//    for(x=0; x <= length.previousMoves;x++){
//        cellHolder[x] = document.getElementById("c" + [x]);
//        previousMoves[x] = cellHolder[x];
//    }

// }
// function savedGame() {
//   for(i=0; length.previousMoves;i++){
//       cellElements.innerHTML = previousMoves[i];
//   }
// }

A: You should use a global variable with the Array type, and any time a game ends, you would push there the game status. Maybe simply "O", "X" or "D" for draw, or if required, an object containing the endgame as one field and the entire board state as another field.
Then you'd read the last value in this array to display the last game, or do some computation across the entire array for statistics and patterns.
For Instance:

window.addEventListener('DOMContentLoaded', _e => {
  //Mimic your own variables
  const winnerMessage = document.querySelector('.winner-message');
  const winnerDeclare = winnerMessage;
  const xScore = document.querySelector('.x-score');
  const oScore = document.querySelector('.o-score');
  const drawScore = document.querySelector('.d-score');
  let circle = false;
  let scoreO = 0, scoreX = 0, scoreDraw = 0;

  //New one for storing endgame states
  const prevGames = [];

  function endGame(draw) {
    let gameResult;
    if (draw) {
      winnerMessage.innerText = "DRAW!"
      // draw counter
      scoreDraw++;
      drawScore.innerHTML = scoreDraw;
      gameResult = "D";
    } else if (circle == true) {
      winnerMessage.innerText = "O is the winner!";
      scoreO++;
      oScore.innerHTML = scoreO;
      gameResult = "O";
    } else {
      winnerMessage.innerText = "X is the winner!"
      scoreX++;
      xScore.innerHTML = scoreX;
      gameResult = "X";
    }
    winnerDeclare.classList.add('show');

    prevGames.push({
      result: gameResult,
      boardState: boardState()
    });
  }

  function boardState() {
    const res = new Array(9);
    document.querySelectorAll('.cell').forEach(cell => {
      id = cell.id;
      index = parseInt(id.substr(1));
      res[index] = cell.textContent;
    });
    return res;
  }

  document.querySelector('#btn-prevstate').addEventListener('click', e => {
    if (prevGames.length) {
      alert(JSON.stringify(prevGames[prevGames.length - 1]));
    } else {
      alert('No previous game');
    }
  });

  //For testing only
  document.querySelector('#btn-simgame').addEventListener('click', e => {
    circle = Math.random() < .5;
    document.querySelectorAll('.cell').forEach(cell => {
      cell.textContent = (Math.random() < .5) ? 'O' : 'X';
    });
    endGame(Math.random() < .5);
  });
});
#board {
  display: grid;
  grid-template-columns: repeat(3, 2em);
  grid-auto-rows: 2em;
  text-align: center;
}

.scores {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

0

0

0

  <button id="btn-simgame">Sim game</button>
  <button id="btn-prevstate">Show prev state</button>

Sorry, answer based on previous version of your question, but it still stands


text:
Q: What is the Difference Between Dyadic Pigeonhole Principle and the Pigeonhole Principle I have recently heard and read the term "dyadic pigeonhole principle" (e.g. see these posts by Terry Tao). However, is dyadic pigeonholing just a special case of "classical" pigeonholing where there are two (hence the word dyadic) holes?
Apologies in advance if this post is an overly trivial question.

A: As explained in Tao's paper, "dyadic pigeonholing" is a name he (Tao) gave to the following technique:

... dyadic decomposition is combined with the pigeonhole principle to
locate a single "good" scale in which to run additional arguments. We refer to this combination of dyadic decomposition and the pigeonhole principle as dyadic pigeonholing.

(Section 4., p. 5). It does not refer to the pigeonhole principle with two holes; perhaps more like $2^n$ holes.


text:
Q: HTML5 Canvas for 3D imported drawing from Catia dassault systemes I am looking for a way to insert 3D drawing made with Catia v5 into a HTML5 canvas!
Something that would let me drag the part and rotate it with a zoom in and out. Is there anything like that already out there??
Catia v5 is a software to draw complex part or assembly for planes in my case.


text:
Q: Darknet : No weights created after training custom objects The darknet training command does not produce any output and exits too early (compared to other CNN training projects)
I have followed the instructions for "how to train (to detect your custom objects)".
The yolo-obj.cfg is configured accordingly.
The darknet.exe has been compiled and build succesfully using MSVS 2017.
I have 3 new custom classes in:
obj.data file:
classes= 3
train = data/train.txt
valid = data/train.txt
names = data/obj.names
backup = backup/

obj.names file:
ring
watch
necklace

I ran the yolo_mark for approx 500 images for each class, resulting in the corresponding *.txt files.
I put all the jpg and txt files in the obj directory.
The train.txt file contains the path to the *.jpg files, e.g.: "data/obj/necklace 013311.jpg"
Downloaded and put the darknet53.conv.74 file in "x64" directory
Running the command (from virtual machine, hence no GPU) as admin:
C:\Users\claw\Downloads\darknet-master\darknet-master\build\darknet\x64>darknet_no_gpu.exe detector train data/obj.data yolo-obj.cfg darknet53.conv.74
yolo-obj

command line output:
layer filters size input output
0 conv 32 3 x 3 / 1 416 x 416 x 3 -> 416 x 416 x 32 0.299 BF
1 conv 64 3 x 3 / 2 416 x 416 x 32 -> 208 x 208 x 64 1.595 BF
2 conv 32 1 x 1 / 1 208 x 208 x 64 -> 208 x 208 x 32 0.177 BF
3 conv 64 3 x 3 / 1 208 x 208 x 32 -> 208 x 208 x 64 1.595 BF
4 Shortcut Layer: 1
5 conv 128 3 x 3 / 2 208 x 208 x 64 -> 104 x 104 x 128 1.595 BF
6 conv 64 1 x 1 / 1 104 x 104 x 128 -> 104 x 104 x 64 0.177 BF
7 conv 128 3 x 3 / 1 104 x 104 x 64 -> 104 x 104 x 128 1.595 BF
8 Shortcut Layer: 5
9 conv 64 1 x 1 / 1 104 x 104 x 128 -> 104 x 104 x 64 0.177 BF
10 conv 128 3 x 3 / 1 104 x 104 x 64 -> 104 x 104 x 128 1.595 BF
11 Shortcut Layer: 8
12 conv 256 3 x 3 / 2 104 x 104 x 128 -> 52 x 52 x 256 1.595 BF
13 conv 128 1 x 1 / 1 52 x 52 x 256 -> 52 x 52 x 128 0.177 BF
14 conv 256 3 x 3 / 1 52 x 52 x 128 -> 52 x 52 x 256 1.595 BF
15 Shortcut Layer: 12
16 conv 128 1 x 1 / 1 52 x 52 x 256 -> 52 x 52 x 128 0.177 BF
17 conv 256 3 x 3 / 1 52 x 52 x 128 -> 52 x 52 x 256 1.595 BF
18 Shortcut Layer: 15
19 conv 128 1 x 1 / 1 52 x 52 x 256 -> 52 x 52 x 128 0.177 BF
20 conv 256 3 x 3 / 1 52 x 52 x 128 -> 52 x 52 x 256 1.595 BF
21 Shortcut Layer: 18
22 conv 128 1 x 1 / 1 52 x 52 x 256 -> 52 x 52 x 128 0.177 BF
23 conv 256 3 x 3 / 1 52 x 52 x 128 -> 52 x 52 x 256 1.595 BF
24 Shortcut Layer: 21
25 conv 128 1 x 1 / 1 52 x 52 x 256 -> 52 x 52 x 128 0.177 BF
26 conv 256 3 x 3 / 1 52 x 52 x 128 -> 52 x 52 x 256 1.595 BF
27 Shortcut Layer: 24
28 conv 128 1 x 1 / 1 52 x 52 x 256 -> 52 x 52 x 128 0.177 BF
29 conv 256 3 x 3 / 1 52 x 52 x 128 -> 52 x 52 x 256 1.595 BF
30 Shortcut Layer: 27
31 conv 128 1 x 1 / 1 52 x 52 x 256 -> 52 x 52 x 128 0.177 BF
32 conv 256 3 x 3 / 1 52 x 52 x 128 -> 52 x 52 x 256 1.595 BF
33 Shortcut Layer: 30
34 conv 128 1 x 1 / 1 52 x 52 x 256 -> 52 x 52 x 128 0.177 BF
35 conv 256 3 x 3 / 1 52 x 52 x 128 -> 52 x 52 x 256 1.595 BF
36 Shortcut Layer: 33
37 conv 512 3 x 3 / 2 52 x 52 x 256 -> 26 x 26 x 512 1.595 BF
38 conv 256 1 x 1 / 1 26 x 26 x 512 -> 26 x 26 x 256 0.177 BF
39 conv 512 3 x 3 / 1 26 x 26 x 256 -> 26 x 26 x 512 1.595 BF
40 Shortcut Layer: 37
41 conv 256 1 x 1 / 1 26 x 26 x 512 -> 26 x 26 x 256 0.177 BF
42 conv 512 3 x 3 / 1 26 x 26 x 256 -> 26 x 26 x 512 1.595 BF
43 Shortcut Layer: 40
44 conv 256 1 x 1 / 1 26 x 26 x 512 -> 26 x 26 x 256 0.177 BF
45 conv 512 3 x 3 / 1 26 x 26 x 256 -> 26 x 26 x 512 1.595 BF
46 Shortcut Layer: 43
47 conv 256 1 x 1 / 1 26 x 26 x 512 -> 26 x 26 x 256 0.177 BF
48 conv 512 3 x 3 / 1 26 x 26 x 256 -> 26 x 26 x 512 1.595 BF
49 Shortcut Layer: 46
50 conv 256 1 x 1 / 1 26 x 26 x 512 -> 26 x 26 x 256 0.177 BF
51 conv 512 3 x 3 / 1 26 x 26 x 256 -> 26 x 26 x 512 1.595 BF
52 Shortcut Layer: 49
53 conv 256 1 x 1 / 1 26 x 26 x 512 -> 26 x 26 x 256 0.177 BF
54 conv 512 3 x 3 / 1 26 x 26 x 256 -> 26 x 26 x 512 1.595 BF
55 Shortcut Layer: 52
56 conv 256 1 x 1 / 1 26 x 26 x 512 -> 26 x 26 x 256 0.177 BF
57 conv 512 3 x 3 / 1 26 x 26 x 256 -> 26 x 26 x 512 1.595 BF
58 Shortcut Layer: 55
59 conv 256 1 x 1 / 1 26 x 26 x 512 -> 26 x 26 x 256 0.177 BF
60 conv 512 3 x 3 / 1 26 x 26 x 256 -> 26 x 26 x 512 1.595 BF
61 Shortcut Layer: 58
62 conv 1024 3 x 3 / 2 26 x 26 x 512 -> 13 x 13 x1024 1.595 BF
63 conv 512 1 x 1 / 1 13 x 13 x1024 -> 13 x 13 x 512 0.177 BF
64 conv 1024 3 x 3 / 1 13 x 13 x 512 -> 13 x 13 x1024 1.595 BF
65 Shortcut Layer: 62
66 conv 512 1 x 1 / 1 13 x 13 x1024 -> 13 x 13 x 512 0.177 BF
67 conv 1024 3 x 3 / 1 13 x 13 x 512 -> 13 x 13 x1024 1.595 BF
68 Shortcut Layer: 65
69 conv 512 1 x 1 / 1 13 x 13 x1024 -> 13 x 13 x 512 0.177 BF
70 conv 1024 3 x 3 / 1 13 x 13 x 512 -> 13 x 13 x1024 1.595 BF
71 Shortcut Layer: 68
72 conv 512 1 x 1 / 1 13 x 13 x1024 -> 13 x 13 x 512 0.177 BF
73 conv 1024 3 x 3 / 1 13 x 13 x 512 -> 13 x 13 x1024 1.595 BF
74 Shortcut Layer: 71
75 conv 512 1 x 1 / 1 13 x 13 x1024 -> 13 x 13 x 512 0.177 BF
76 conv 1024 3 x 3 / 1 13 x 13 x 512 -> 13 x 13 x1024 1.595 BF
77 conv 512 1 x 1 / 1 13 x 13 x1024 -> 13 x 13 x 512 0.177 BF
78 conv 1024 3 x 3 / 1 13 x 13 x 512 -> 13 x 13 x1024 1.595 BF
79 conv 512 1 x 1 / 1 13 x 13 x1024 -> 13 x 13 x 512 0.177 BF
80 conv 1024 3 x 3 / 1 13 x 13 x 512 -> 13 x 13 x1024 1.595 BF
81 conv 24 1 x 1 / 1 13 x 13 x1024 -> 13 x 13 x 24 0.008 BF
82 yolo
83 route 79
84 conv 256 1 x 1 / 1 13 x 13 x 512 -> 13 x 13 x 256 0.044 BF
85 upsample 2x 13 x 13 x 256 -> 26 x 26 x 256
86 route 85 61
87 conv 256 1 x 1 / 1 26 x 26 x 768 -> 26 x 26 x 256 0.266 BF
88 conv 512 3 x 3 / 1 26 x 26 x 256 -> 26 x 26 x 512 1.595 BF
89 conv 256 1 x 1 / 1 26 x 26 x 512 -> 26 x 26 x 256 0.177 BF
90 conv 512 3 x 3 / 1 26 x 26 x 256 -> 26 x 26 x 512 1.595 BF
91 conv 256 1 x 1 / 1 26 x 26 x 512 -> 26 x 26 x 256 0.177 BF
92 conv 512 3 x 3 / 1 26 x 26 x 256 -> 26 x 26 x 512 1.595 BF
93 conv 24 1 x 1 / 1 26 x 26 x 512 -> 26 x 26 x 24 0.017 BF
94 yolo
95 route 91
96 conv 128 1 x 1 / 1 26 x 26 x 256 -> 26 x 26 x 128 0.044 BF
97 upsample 2x 26 x 26 x 128 -> 52 x 52 x 128
98 route 97 36
99 conv 128 1 x 1 / 1 52 x 52 x 384 -> 52 x 52 x 128 0.266 BF
100 conv 256 3 x 3 / 1 52 x 52 x 128 -> 52 x 52 x 256 1.595 BF
101 conv 128 1 x 1 / 1 52 x 52 x 256 -> 52 x 52 x 128 0.177 BF
102 conv 256 3 x 3 / 1 52 x 52 x 128 -> 52 x 52 x 256 1.595 BF
103 conv 128 1 x 1 / 1 52 x 52 x 256 -> 52 x 52 x 128 0.177 BF
104 conv 256 3 x 3 / 1 52 x 52 x 128 -> 52 x 52 x 256 1.595 BF
105 conv 24 1 x 1 / 1 52 x 52 x 256 -> 52 x 52 x 24 0.033 BF
106 yolo

Total BFLOPS 65.304
Loading weights from darknet53.conv.74...
seen 64
Done!

Learning Rate: 0.001, Momentum: 0.9, Decay: 0.0005
If error occurs - run training with flag: -dont_show
Resizing
416 x 416

Cannot load image "data/img/ring chic-criss-cross-adjustable-ad-ring.jpg"
Loaded: 1.143984 seconds
Used AVX
Region 82 Avg IOU: 0.333570, Class: 0.602019, Obj: 0.402860, No Obj: 0.528741, .5R: 0.000000, .75R: 0.000000, count: 4
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.521660, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.514523, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 82 Avg IOU: 0.329878, Class: 0.570290, Obj: 0.611294, No Obj: 0.528309, .5R: 0.250000, .75R: 0.000000, count: 4
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.521499, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.514392, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 82 Avg IOU: 0.575794, Class: 0.539979, Obj: 0.316475, No Obj: 0.528604, .5R: 0.500000, .75R: 0.500000, count: 2
Region 94 Avg IOU: 0.312451, Class: 0.125449, Obj: 0.238739, No Obj: 0.521500, .5R: 0.000000, .75R: 0.000000, count: 1
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.514025, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 82 Avg IOU: 0.257590, Class: 0.547629, Obj: 0.447064, No Obj: 0.527685, .5R: 0.000000, .75R: 0.000000, count: 3
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.521665, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.515411, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 82 Avg IOU: 0.297573, Class: 0.436722, Obj: 0.389306, No Obj: 0.528302, .5R: 0.500000, .75R: 0.000000, count: 4
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.521452, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.513978, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 82 Avg IOU: 0.191856, Class: 0.645887, Obj: 0.364560, No Obj: 0.528137, .5R: 0.000000, .75R: 0.000000, count: 5
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.521575, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.514143, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 82 Avg IOU: 0.475039, Class: 0.419801, Obj: 0.578539, No Obj: 0.527876, .5R: 0.500000, .75R: 0.500000, count: 2
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.521085, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.514371, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 82 Avg IOU: 0.264798, Class: 0.416162, Obj: 0.462117, No Obj: 0.527412, .5R: 0.000000, .75R: 0.000000, count: 5
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.521446, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.514205, .5R: -nan(ind), .75R: -nan(ind), count: 0

1: 1003.093994, 1003.093994 avg loss, 0.000000 rate, 1056.320056 seconds, 64 images
Loaded: 0.000000 seconds
Cannot load image "data/img/necklace 570239071_2906.jpg"
Cannot load image "data/img/necklace 570239072_2906.jpg"
Cannot load image "data/img/necklace 10019367_no_place_like_roam_necklace_green_main.jpg"
Region 82 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.527527, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.521694, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.514430, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 82 Avg IOU: 0.213376, Class: 0.587271, Obj: 0.565966, No Obj: 0.528763, .5R: 0.000000, .75R: 0.000000, count: 5
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.522077, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.515318, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 82 Avg IOU: 0.314485, Class: 0.501796, Obj: 0.458959, No Obj: 0.528414, .5R: 0.000000, .75R: 0.000000, count: 2
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.521397, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.514781, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 82 Avg IOU: 0.278535, Class: 0.518696, Obj: 0.510300, No Obj: 0.528529, .5R: 0.000000, .75R: 0.000000, count: 5
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.521170, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.514448, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 82 Avg IOU: 0.270750, Class: 0.498121, Obj: 0.530221, No Obj: 0.528569, .5R: 0.000000, .75R: 0.000000, count: 2
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.521003, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.513312, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 82 Avg IOU: 0.235287, Class: 0.480098, Obj: 0.517194, No Obj: 0.527906, .5R: 0.000000, .75R: 0.000000, count: 4
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.521571, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.513103, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 82 Avg IOU: 0.368155, Class: 0.552764, Obj: 0.482865, No Obj: 0.528044, .5R: 0.200000, .75R: 0.000000, count: 5
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.521782, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.514365, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 82 Avg IOU: 0.393099, Class: 0.568679, Obj: 0.534074, No Obj: 0.528130, .5R: 0.000000, .75R: 0.000000, count: 2
Region 94 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.522459, .5R: -nan(ind), .75R: -nan(ind), count: 0
Region 106 Avg IOU: -nan(ind), Class: -nan(ind), Obj: -nan(ind), No Obj: 0.515186, .5R: -nan(ind), .75R: -nan(ind), count: 0

2: 1002.576904, 1003.042297 avg loss, 0.000000 rate, 1043.121191 seconds, 128 images
Loaded: 0.000000 seconds

After this I checked the backup directory, where only a *.tmp file was created (0 kb)
No weigth file was created...
What am I doing wrong ?

A: By default, the weights are recorded every 100 iterations. You have to wait to train YOLO for long hours (especially without GPU) before making inferences with your weights.

A: I do not think your training set is correctly configured.
Most of your results are -nan(ind)
There may be a problem with your train.txt.
1: 1003.093994, 1003.093994 avg loss, 0.000000 rate, 1056.320056 seconds, 64 images
^ This is the iteration number. By default darknet writes the weight to backup folder after 100 iterations.
If you want weights before that open your detector.c file in src and modify
    if (i % 1000 == 0 || (i < 1000 && i % 3 == 0)) {
    //if (i % 100 == 0) {
    //if(i >= (iter_save + 100)) {

line 204 like i have done for mine and make the number 1(instead of 3) if you want a weight on your first iteration
then build again.
Try training on a smaller net like yolo-voc like in this tutorial: https://timebutt.github.io/static/how-to-train-yolov2-to-detect-custom-objects/
Even i am facing a problem when using the yolov3.cfg based net (getting the same output)

A: The issue was that the object txt files (created by yolomarkup) were almost all empty. I had added 3 new objects; necklace, ring, watch and for each object approx 500 jpg images, which I used in yolomarkup.exe. For a lot of those marked up images the corresponding txt file was empty ! I dropped the training alltogether for those objects


text:
Q: How can I generate org.apache.spark.rpc.RpcTimeoutException during Spark Streaming I'm very new to spark and trying to test my spark streaming application for org.apache.spark.rpc.RpcTimeoutException.
How can I simulate a scenario where this exception is thrown for a streaming query.


text:
Q: How to send data from custom sp adapter to target application in ping federate I have searched entire documentation of ping federate but in vain.
I have an application running on localhost:8080.I have implemented a custom service provider adapter and deployed in ping federate server.I have configured the sp adapter to work with ssocircle idp.I am able to log the attributes from the idp in sp adapter in createAuthN method.I am initiating sso using /sp/ssostart.ping and sending a target resource.Now I want to send the attributes from the custom sp adapter to the target resource using post.

A:
I have configured the sp adapter to work with ssocircle idp.I am able
  to log the attributes from the idp in sp adapter in createAuthN
  method.

There may be a disconnect in what adapters do, versus connections, in PingFederate. A connection is a carrier of attributes to/from a partner outside your local "domain", while an adapter is a carrier of attributes between PingFederate and applications. That is, an IdP adapter is a method to get user attributes to PingFederate (after authentication), and an SP adapter is a method to get attributes from PingFed to an application (after SSO).

Now I want to send the attributes from the custom sp adapter to the
  target resource using post.

This is precisely the role of an adapter. What kind of adapter have you created? One that uses OpenToken? Reference adapter? Something else? If you have created something else, then your adapter is fully responsible for communicating the attributes to the SP Application (Target Resource). If you are using one of the integration kits we provide (like the Java Integration Kit, or the Agentless Integration Kit), we provide comprehensive examples of their use within their SDK directories.
If you are doing it from scratch, your code will be responsible for the entirety. We do have the standard sdk directory in the server install, along with the doc. Sending the attributes received via POST would be done with standard Java methods... You could consider reviewing this method here on StackOverflow:
How to send post form with java?
I would recommend using one of our adapters, frankly, because Ping has done the heavy lifting for you already. Personally, I am a big fan of the agentless integration kit (using the reference adapter), as I feel it is more secure. It captures the attributes sent in by the IdP connection, and then provides the target resource with a "reference". The application then retrieves the attributes from PingFederate by sending that reference to a special endpoint, and gets the attributes in a JSON format. Here is a link to sample Java code for our agentless integration.


text:
Q: @Html.CheckBoxFor onchange actionlink How can I make the code below an on change actionlink? So when I check the checkbox it will trigger an actionlink!
@Html.CheckBoxFor(c => OutOfBank.Available)

A: You can send an Ajax request when Checkbox changed, which triggers the action each time you check or uncheck the checkbox.
@Html.CheckBoxFor(c => OutOfBank.Available)

<script>
  $(function () {
     $('#Available').change(function () {
        $.ajax({
            url: '/example/@OutOfBank.Available',
            cache: false,
            method: 'GET',
            success: function (data) { alert('success'); },
            error: function () { alert('error'); }
          });
      });
  });
 </script>


text:
Q: splunk and ansi escape sequences? Is there any way to have ANSI color output on my logs and also consume them in splunk?
either having splunk show the color (ideal but highly unlikely) or apply a filter on splunk to remove the escape sequences?

A: It's pretty easy to remove unwanted text by using the SEDCMD attribute in props.conf.  If the unwanted text can be described by a regular expression then it can be eliminated and the rest of the event retained.
Add this to the relevant props.conf file stanza:
SEDCMD-noColor = s/\[36;3DEBUG\[38;8//

If the digits are not fixed then the regex will have to be adjusted accordingly.  Also, this regex does not account for the ESC character, if it's present in the data.


text:
Q: Testing on real devices We have recently bought ~20 different Android phones for testing (the emulators/online services just aren't good enough). When the phones are connected all at the same time the driver detects around half of them, but if I connect them one by one all are detected.
Is that a problem with the USB driver? Are there any alternative ways of doing this? I know that it is possible to run adb connect
[IP]:[PORT] but it seems like you need to root the phones for that.

A: I think you should be looking for a different means to get your apk onto your devices. I find myself testing on a similar number of devices, what I've gone to most recently is drop the apk inside dropbox and copy a link to it, then generate a QR that points to that link. Then I can just scan the QR with all of the devices I want it installed on. Bypasses the need for adb drivers too.

A: Yes , it's possbile, watch this url https://play.google.com/store/apps/details?id=com.tete.wifiadb


text:
Q: Facebook iOS SDK 4.x: changing the user to log in I'm upgrading Facebook SDK from 3.x to 4.x and need to log in as different Facebook users to my application (game) in order to check if FB requests work correct.
In 3.x login dialog switched to FB application, so I could change the user in the FB application and got new credentials for my login. Now I only got "You have already authorised..." message in a Safari-view login dialog.
I changed user in FB application several times as well as uninstalled my application in order to clean its local cache - nothing helps. My application always logs in as User 1, even if I logged in as User 2 in FB application.
How can I login as a different user (clear saved token, got a credentials dialog or something else)?

A: You need to log in fb from Safari and exit the user =)


text:
Q: What does 'xxx is a dog` mean? I just saw an sentence from here:

But the problem grows and the next thing you know your maven build is checking 50 repos for every artifact and build time is a dog

What does xxx is a dog mean here?

A: Dog can have several slang meanings.
In this case, it refers to another piece of slang, that is deemed to be quite offensive.
If something is really hard, really difficult or a pain in the backside, one may, very informally, express this as:

xxx is a (son of a) bitch.

(This can also be said about people, meaning that they are in one or several ways, not pleasant.)
This expression is, like I said, deemed very offensive in many situations (most, really).
If we take it literally, however, a bitch is a female dog, and her son would (bar Greek mythology) be a dog. Even if we refer directly to the bitch instead of her son, she's a dog.
So instead of the offensive (son of) a bitch, the author uses the euphemistic dog.


text:
Q: How to solve : [Errno 10060] A connection attempt failed while reading outlook email import email
import imaplib2
from collections import OrderedDict
import json

EMAIL_USER = 'client@apl.com'
EMAIL_PASSWORD = '*****'
EMAIL_SERVER = 'outlook.office365.com'

def read_mail_from_server():
    try:
        mail = imaplib2.IMAP4_SSL(EMAIL_SERVER, 993)
        mail.login(EMAIL_USER, EMAIL_PASSWORD)
        mail.select('INBOX')

        typ, raw_data = mail.search(None, 'ALL')
        ids_list = len(raw_data[0].split())
        print(ids_list)
        ...

I have written a python code to read outlook emails using imaplib. I'm getting the below error when I run it, but with the same code and with different credentials I was to able to read emails from another server. What could be the reason for getting this error?
[Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond


text:
Q: Modify the range of the color function in a StreamPlot, and add the corresponding ColorBar in the legend Hello I'm trying to manually clip the scale of the colors for the streamlines in StreamPlot. The problem is that at the origin the velocity goes to infinity and that throws off any attempt to rescaling. I've already tried modifying the RegionFunction... to no avail.
This is the default output:
StreamPlot[{-(y/(2 \[Pi] (x^2 + y^2))), x/(2 \[Pi] (x^2 + y^2))}, {x, -3, 3}, {y, -3, 3}, PlotLegends -> Automatic]

I have managed to somewhat achieve a working example:
StreamPlot[{-(y/(2 \[Pi] (x^2+y^2))),x/(2 \[Pi] (x^2+y^2))},{x,-3,3},{y,-3,3},RegionFunction->Function[{x,y,vx,vy,n},x^2 +y^2>0.1],PlotLegends->Automatic,StreamColorFunction->(ColorData["Rainbow"][Rescale[Norm[{#3,#4}],{0,0.00005}]]&),StreamColorFunctionScaling->False]

However I still had to fiddle with the Rescale values, 0.00005 is somewhat arbitrary and it does not tell me what is the actual value assigned to red or above. The plotlegend (ColorBar) then has to be inserted manually and I don't know how to do that. What I would like is a simple command to say:  "Set Color Range to -> {vmin,vmax}" in this case the values I'm interested are {0,0.35} and then display the color bar with correct values as well. Thank you!

A: One possible solution
bar = BarLegend[{(ColorData["Rainbow", #] &), {1/(2 Pi Sqrt[3^2] ),
    1/(2 Pi Sqrt[0.15^2])}}]; StreamPlot[{-(y/(2 \[Pi] (x^2 + y^2))),
  x/(2 \[Pi] (x^2 + y^2))}, {x, -3, 3}, {y, -3, 3},
 StreamColorFunction -> (ColorData["Rainbow", 1/( Norm[{#1, #2}])] &),
  PlotLegends -> Placed[bar, Below], StreamPoints -> 30,
 StreamColorFunctionScaling -> False]

A: If your plot spans several orders of magnitude, you might also consider using a logarithmic scale, as in these examples.
{min, max} = {1/100, 1};
sf = Log[#/min]/Log[max/min] &;
isf = InverseFunction@sf;

StreamPlot[
  {-(y/(2 \[Pi] (x^2 + y^2))), x/(2 \[Pi] (x^2 + y^2))},
  {x, -3, 3}, {y, -3, 3},
  StreamColorFunctionScaling -> False,
  StreamColorFunction -> Function[ColorData["Rainbow"][sf@#5]],
  PlotLegends ->
    BarLegend[{"Rainbow", {min, max}}, ScalingFunctions -> {sf, isf},
    ColorFunctionScaling -> True]
]

The options ScalingFunctions and ColorFunctionScaling are not officially supported for BarLegend, and are therefore higlighted red in notebooks (which was also seen in the answers of this post). However, at least in versions 12.0 and 13.0 they still work, as they are options of the internal Charting`iBarLegend.


text: Q: Как лучше подойти к реализации создания подключения к базе MySQL, ASP.NET Товарищи, хотелось бы испросить совета в следующем вопросе: Положим, у нас имеется ASP.NET проект, подгружающий данные из базы (MySQL). Как лучше реализовать это дело: создать статический класс, в котором будет статическая переменная подключения (то есть, условно, одно подключение для всех пользователей приложения), или же лучшим решением будет для каждого отдельного пользователя создавать своё подключение?


text:
Q: tlcockpit and tlmgr I hope that this question is suitable for this forum:
I have been experiencing difficulty with tlmgr generally. I found that there is a highly recommended GUI for tlmgr, tlcockpit. This was supposed to be part of the texlive distribution that I initially installed mid-December 2022, but it is not there. I then managed to use chown to gain access to the folder
/usr/share/texlive/texmf-dist/scripts
where I created the folder 'tlcockpit', and put the file 'tlcockpit.jar (all according to instructions at GIT website for tlcockpit. So far, so good. Or so it seemed.
When I launch the tlcockpit GUI, it tries its best to show the packages (installed ones) and the (possible) updates that are available. But the hamster wheel keeps spinning, and nothing is loaded.
It seems to me that there may be problems with the PATH or other environment variables. Maybe it cannot find its way...


text:
Q: javascript count objects in array of objects without null values Let's say we have array of objects:
const data = [
  {
    firstName: "Bruce",
    lastName: "Wayne",
    address: "Arkham 6",
    id: "1",
  },
  {
    firstName: "Peter",
    lastName: "Parker",
     address: "LA 54",
    id: "2"
  },
  {
    firstName: "Tony",
    lastName: "Stark",
    address: null,
    id: "3"
  }
];

and want to get length of the array but exclude counting of the objects which has null values (in example above, this is the last object with address property null) so that result of the counting of the example above would be 2.
objectsWithoutNull = data.reduce(function (r, a) {
    return r + +( a!== null);
}, 0);

I'm trying with reduce method, but got 0.
Where is the problem in iteration?

A: You can filter() the array and than get object values and check where not includes null.

const data = [
  {
    firstName: "Bruce",
    lastName: "Wayne",
    address: "Arkham 6",
    id: "1",
  },
  {
    firstName: "Peter",
    lastName: "Parker",
     address: "LA 54",
    id: "2"
  },
  {
    firstName: "Tony",
    lastName: "Stark",
    address: null,
    id: "3"
  }
];

const notNullable = data.filter(obj=>!Object.values(obj).includes(null));
console.log(notNullable)
console.log(notNullable.length)

More about Object Values Filter Includes

A: Reduce the array, for each object get the values with Object.values(), and check with Array.includes() if it contains a null value. Negate with ! the boolean result of inclues, and use the + operator to convert to number. Add the number to the accumulator.

const data = [{"firstName":"Bruce","lastName":"Wayne","address":"Arkham 6","id":"1"},{"firstName":"Peter","lastName":"Parker","address":"LA 54","id":"2"},{"firstName":"Tony","lastName":"Stark","address":null,"id":"3"}];

const result = data.reduce((r, o) =>
  r + +!Object.values(o).includes(null)
, 0);

console.log(result);

A: An option is to iterate over the object-values of a and test if the value is equal to null. If we found a null don't increase our counter.

const data = [
  {
    firstName: "Bruce",
    lastName: "Wayne",
    address: "Arkham 6",
    id: "1",
  },
  {
    firstName: "Peter",
    lastName: "Parker",
     address: "LA 54",
    id: "2"
  },
  {
    firstName: "Tony",
    lastName: "Stark",
    address: null,
    id: "3"
  }
];

let objectsWithoutNull = data.reduce(function (r, a) {
  let hasNull = false;
  const values = Object.values(a);
  values.map(v => {
    if (v === null) {
      hasNull = true;
    }
  });

  return r + !hasNull;
}, 0);

console.log(objectsWithoutNull);

A:   objectsWithoutNull = data.reduce(function (r, a) {
        return r + +( Object.values(a).indexOf(null) == -1);
    }, 0);

This will work if you want to check for all the properties!

A: You can use Array.prototype.every to check that all the values are not null
var length = data.filter(i => Object.values(i).every(i => i !== null)).length

A: If you are using lodash.
const data = [
      {
        firstName: "Bruce",
        lastName: "Wayne",
        address: "Arkham 6",
        id: "1",
      },
      {
        firstName: "Peter",
        lastName: "Parker",
         address: "LA 54",
        id: "2"
      },
      {
        firstName: "Tony",
        lastName: "Stark",
        address: null,
        id: "3"
      }
    ];

const counter = _.filter(data, ({address}) => {return address != null}).length;
console.log(counter);


text:
Q: Permission denied using mysql in Mac Terminal When attempting to do anything with mysql I am met with a

permission denied

For example
adamshaw$ mysql> -u root -p
-bash: -u: Permission denied

(base) Adams-MacBook-Pro:mysql adamshaw$ mysql> --skip-grant-tables
-bash: --skip-grant-tables: Permission denied

How do I grant myself permission to my own mysql?

A: Try adding chmod 755 to the beginning of the code line.
This helped me with trying to run python scripts via terminal.
May work for MySQL too.


text:
Q: Cordova InAppBrowser not working via build.phonegap.com I am working on an simple Phonegap App with Cordova InAppBrowser.  I am testing on my Android device.
In the config.xml I got the below code
....
<preference name="phonegap-version" value="cli-5.2.0" />
.....
<plugin name="cordova-plugin-whitelist" source="npm" />
<plugin name="org.apache.cordova.inappbrowser" source="pgb" />
.....
<access origin="*"/>

<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />

<allow-navigation href="http://*/*" />
<allow-navigation href="https://*/*" />
<allow-navigation href="data:*" />

....

In Javascript I got the below code when a button is clicked
....
var ref = cordova.InAppBrowser.open('http://google.com', '_blank', 'location=yes','fullscreen=no');
....

index.html
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=medium-dpi" />
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src * 'self' data:">

I use Phonegap Desktop App for testing purposes.  In that when the button is touched a browser window got opened and I could see the google.
But when I build the same via http://build.phonegap.com and install on my device.  Nothing opens after I touch the button.  Something goes wrong here.
Looks strange for me.  Any help is appreciated.

A: I posted the same question on Adobe Forums and got the solution for my problem.
https://forums.adobe.com/thread/2138992
After changing the below, it started working
<plugin name="org.apache.cordova.inappbrowser" source="pgb" />

to
<plugin name="cordova-plugin-inappbrowser" />


text:
Q: how to implement the instagram login Oauth using javascript and java I'm new to Oauth and to instagram.I got register for the application and got client id, client secret, redirect url.I don't have any idea how to implement it.Can anyone help me out.

A: Seems like its not possible to authenticate Instagram Login.There are not still providing any API to authenticate an account with username and password credentials.You can authenticate your account by this request
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
You will get ClientID by
Register


text:
Q: Output of Batch file with a number of cmd commands saved in a single text file I am trying to get the output of my batch file into a text file. I know by using '>'
I can get the standard output stream text, however in this case the batch file has multiple cmd commands and I don't know how to get outputs for each of this into a text file.
Any help is greatly appreciated.

A: Hope this helps
@echo off
rem start the file with a single >
echo test1 > file.txt
rem append the file with a double >>
echo test2 >> file.txt
type file.txt


text:
Q: x86/32bit PHP on 64bit Windows Server 2008 This may not be the right place for this question, please point me at the correct SE site if not.
The PHP Documentation for the function ip2long states:

Note
Because PHP's integer type is signed, many IP addresses will result in negative integers on 32-bit architectures

Which is fine, however I am little confused if the version of PHP makes a difference?
I am running 64bit Server 2008 with 32bit PHP installed, and I am getting negative integers with some IP addresses. I am clearly running on a 64bit architecture, so this shouldn't be the case according to the (admittedly very vague) documention.
I can only assume that it's because I am running 32bit PHP?? But I can't confirm this anywhere.

A: You are correct that it is because you are running a 32-bit build of PHP.  Since it is compiled as a 32-bit application, despite running on a 64-bit system you still do not get 64-bit integers.
It should also be noted that at the time of writing 64-bit builds of PHP on Windows do not provide 64-bit integers (or large file support) so even if you go with a 64-bit version you will still experience integer overflow.
You can try using sprintf with the %u format to try to get a string representation of the 64-bit number.  I used this code with older PHP4 applications running on 32-bit where I wanted to print out a 64-bit integer.  Note that it may not be suitable if you need to do anything other than output the 64-bit number.
$string = sprintf('%u', $someBigInteger);


text:
Q: WKWebKit does not refresh webpage I am using Xcode 8.3.3 and Swift 3 to develop an app for the iMac using Cocoa. My goal is to use VCgoToWebPage and display a webpage to the user. My program calls this function many times, but the only webpage I see is the last one called. How do I implement a window refresh inside this function and wait for the webpage to be fully rendered?
func VCgoToWebPage(theWebPage : String) {
    let url = URL(string: theWebPage)!
    let request = URLRequest(url: url)
    webView.load(request)

    /*The modal box allows the web pages to be seen. Without it, after a series of calls to VCgoToWebPage only the last page called is displayed.  The modal box code is just for debugging and will be removed.  */

    let alert = NSAlert()
    alert.messageText="calling EDGAR page"
    alert.informativeText=theWebPage
    alert.addButton(withTitle: "OK")
    alert.runModal()
}

A: You can use navigation delegate to make sure navigation to a page is complete before trying to load another. Have your class conform to WKNavigationDelegate and set webView.navigationDelegate to that class instance.
var allRequests = [URLRequest]()
func VCgoToWebPage(theWebPage : String) {
    guard let url = URL(string: theWebPage) else {
       return
    }
    let request = URLRequest(url: url)
    if webView.isLoading{
       allRequests.append(request)
    } else {
       webView.load(request)
    }
}
func webView(WKWebView, didFinish: WKNavigation!){
    if let nextRequest = allRequests.first{
       webView.load(nextRequest)
       allRequests.removeFirst()
    }
}


text:
Q: How to detect a firewall in Windows? My app needs to make a GET request to a website and I'd like to be able to know if it's being blocked by a firewall, and ask the user to add an exception.
How can I find out that my get request failed because of a firewall, instead of something else?

A: If it's a good firewall, you can't.  Among other options, a firewall can:

*

*reply with one of several different ICMP messages, indicating the destination is not accessible, or

*silently discard the request, resulting in a timeout.

A reasonable option is to explain why the app was unable to access the website, and provide some helpful suggestions:

    No response from www.site.com:
    * Your computer may not be connected to the Internet.
    * The site may be down.
    * The site may be blocked by a firewall.

    The network indicated that www.site.com is not accessible:
    * Helpful messages go here.

The important point is to differentiate, perhaps better than I did above, between the types of failure, and the reasons behind them.  For example, the steps for troubleshooting "no response" will be different from those for troubleshooting "the device told me it's not listening on that port."

A: Try to access the internet with a short timeout...
If the command fails, you can suppose that the machine has a firewall which requires user interaction.
If the firewall is good, you can't detect it.

A: Use Win32 Firewall apis (classic)


text:
Q: Echo certain letters of a string, but only if it hasn't been echoed already I am trying to echo certain letters of a string where if a letter has already been echoed it cannot be echoed again.
Here is my current code:
<?php
$string = 'AABACADA';
    echo $string[1];
    echo $string[3];
    echo $string[4];
    echo $string[5];
    echo $string[6];
    echo $string[7];
?>

The result of this code is 'AACADA'. But I want to change the code so that a letter can only be echoed once, so the code's result should be 'ACD'.
I'm honestly stuck and would really appreciate some help. Thank you.

A: You could use count_chars($string, $mode) and set the $mode to 3.
Check out the doumentation:  http://php.net/count_chars

A: you can try this. I am not sure it is what you are looking for.
$string = 'AABACADA';
$tmp = [];
for ($i = 0; $i < strlen($string); $i++) {
  if ($i === 2) continue;
  $tmp[] = $string[$i];
}

print_r(array_unique($tmp));

Result: Array ( [0] => A [3] => C [5] => D )


text:
Q: "zingchart-angularjs is not available" I'm new to angular and web applications in general and I'm having a hard time trying to using zingchart.
What I'd like to do is create charts on an angular application through zingchart, but I'm getting this error on the browser console when I try to run my application.
I'm sure I've correctly added the 'zingchart-angularjs' dependency in my controller, but I'm not that sure about declaring the zingchart libraries inside my hmtl. I have a few questions, please:
1) I downloaded zingchart, but couldn't find the zingchart.min.js file after the download. How important is it to make the whole thing work? How to download it?
2) I work on eclipse. Should I install zingchart on eclipse as a plugin? If so, can someone help? So far I simply moved the zingchart-angularjs.js file to my project folder and declared its path on my html within the script tags. Will it work on eclipse?
3) How should I exactly declare the zingchart libs inside the html? I mean, should I inform the FULL path for the zingchart-angularjs.js file, like "script type="text/javascript" src="C:/kdi/workspace/cnt-ui-web/src/main/webapp/app/spas/cnt/partials/zingchart.min.js" /script or declaring the relative path is enough? If the latter, how should that be?
Thanks.

A: Question 1) -> Yes you need to add zingchart.min.js or zingchart.js in your html.
You can include the cdn for zingchart.min.js (zingchart cdn version) in html as,
 http://cdn.zingchart.com/zingchart.min.js

Question 2) -> No you need not install zingchart as a plugin. You just need to include the js files(libraries) in your project.
Question 3) -> No need to provide the full path. Relative path to your html file will do. See relative path vs absolute path
The sequence of .js files should be,
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="http://cdn.zingchart.com/zingchart.min.js"></script>
<script type="text/javascript" src="zingchart-angularjs.js"></script>

Take care of the paths in src attribute, that's the path of file.


text:
Q: Difficulty assigning a Discount As the title says, I'm having trouble assigning discounts to my products. When I load the page it says nan and undefined. Any help is appreciated. Thankyou!
This is my JavaScript code:
var ProductType;
var ProductQty;
var ProductPrice;
var DiscountPercent;
var TotalAmount;
function calculate() {
  ProductType = prompt("Please enter the type of product you require!").toUpperCase();
  document.write("
");
  ProductQty = prompt("Please enter the number of products you require!");
  elsestatement();
  ProductQty = parseInt(ProductQty);
  document.write("Type of Products:" + ProductType);
  document.write("
");
  document.write("Number of Products:" + ProductQty);
  document.write("
");
  var GrossAmount =(ProductPrice) * (ProductQty);
  document.write("Gross Amount is:" + GrossAmount);
  GrossAmount = parseInt(GrossAmount);
  discountAmt();
  var DiscountAmount = (GrossAmount) - (GrossAmount) * (DiscountPercent)
  var TotalAmount = (GrossAmount) * (DiscountPercent)
  document.write("
");
  document.write("Discount Amount:" + DiscountAmount)
  document.write("
");
  document.write("Discount Percent:" + DiscountPercent)
  document.write("
");
  document.write("Total Amount:" + TotalAmount)
}

function elsestatement(){
  if (ProductType == 'A') {
    ProductPrice = 100;
  } else if (ProductType == 'B') {
    ProductPrice = 75;
  }  else if (ProductType == 'C'){
    ProductPrice = 50;
  }
  else {
    document.write("
");
    document.write("Invalid Product Type");
    document.write("
");
  }
  if (ProductQty <1|| ProductQty >100) {
    document.write("Invalid Quantity")
  }
}

function discountAmt() {
  if (GrossAmount <200) {
    DiscountPercent = '0';
  }  else if (GrossAmount >= 200 && GrossAmount<=399.99) {
    DiscountPercent = '.05';
  }  else if (GrossAmount>=400 && GrossAmount<=599.99 ) {
    DiscountPercent = '.075';
  }  else if (GrossAmount >=600)
    DiscountPercent = '.1';
}

This is my HTML Code:
<!DOCTYPE html>

<title>Product</title>

Product Calc

A: Sorry for the confusion. I was mistaken about the unclosed function. Instead, the problem is that GrossAmount was defined in the calculate function instead of in the outer scope. Therefor, it was not reachable in the discountAmt function.
Here is your fixed code, except with the document.writes removed so that it can run in the sandbox:

var ProductType;
var ProductQty;
var ProductPrice;
var DiscountPercent;
var TotalAmount;
var GrossAmount;

function calculate() {
  ProductType = prompt("Please enter the type of product you require!").toUpperCase();
  ProductQty = prompt("Please enter the number of products you require!");
  elsestatement();
  ProductQty = parseInt(ProductQty);
  GrossAmount = ProductPrice * ProductQty;
  GrossAmount = parseInt(GrossAmount);
  discountAmt();
  var DiscountAmount = GrossAmount - GrossAmount * DiscountPercent;
  var TotalAmount = GrossAmount * DiscountPercent;
}

function elsestatement(){
  if (ProductType == 'A') {
    ProductPrice = 100;
  } else if (ProductType == 'B') {
    ProductPrice = 75;
  } else if (ProductType == 'C'){
    ProductPrice = 50;
  } else {}
  if (ProductQty < 1|| ProductQty > 100) {}
  console.log('ProductPrice: ', ProductPrice);
}

function discountAmt() {
  if (GrossAmount < 200) {
    DiscountPercent = '0';
  } else if (GrossAmount >= 200 && GrossAmount <= 399.99) {
    DiscountPercent = '.05';
  } else if (GrossAmount >= 400 && GrossAmount <= 599.99) {
    DiscountPercent = '.075';
  } else if (GrossAmount >= 600) {
    DiscountPercent = '.1';
  }
  console.log('DiscountPercent: ', DiscountPercent);
}

calculate();

A: Obviously you are not closing the elsestatement function ie } is missing. and manage the code like this
change
<!DOCTYPE html>

<title>Product</title>

Product Calc

to
<!DOCTYPE html>

<title>Product</title>

Product Calc


text:
Q: How to stop a thread in java and let the same thread to do another thing? I start one thread to download contents from the internet, at one time, the thread is downloading one file, and then i want it stop and begin to download another file, what should i do? should i count on the concurrency mechanism  in java?

A: You can start your thread using a single-thread executor, then when you kill it (gracefully I hope) and start a new one it will ensure that it's using the same thread.
// Suppose you have a DownloadFile class that implements Runnable
DownloadFile task1 = new DownloadFile();

...

ExecutorService exec = Executors.newSingleThreadExecutor();

Future<Boolean> future = exec.submit( task1, Boolean.TRUE );

...

// Cancel the task
future.cancel();

// Give the executor another task
DownloadFile task2 = new DownloadFile();
...
exec.submit( task2, Boolean.TRUE );

Other useful docs:

*

*Future

*ExecutorService

A: Stopping thread using stop() method is not recommended.

I start one thread to download
  contents from the internet, at one
  time, the thread is downloading one
  file, and then i want it stop and
  begin to download another file, what
  should i do?

You need to use the sleep( ) method of Thread class to pause  the same thread for some specified milliseconds before you can continue the work with the same thread.

Note : Once the thread has been stopped, it can't resume its work. It will result in IllegalThreadStateException.
See :

*

* Why are Thread.stop() , Thread.suspend() and Thread.resume()  Deprecated ?

*How to stop a java thread gracefully ?

A: To interrupt a thread from a current processing and redirect it to something else is a classic synchronization problem. This is done as follows:
Have a job queue. The jobs in the job queue [or more specifically the objects in the job queue] should have a method [say process()] that the thread will execute. The thread generally does not know the details of the process() method. It only cares that it has to run the process() method.
The thread must wait on the job queue. This is done as follows:
Job j = null;

synchronized(jobQueueInstance)
{
    if(jobQueueInstance.isEmpty())
    {
        jobQueueInstance.wait();
    }

    j = jobQueueInstance.poll(); //get the job from the head of the queue
}

try
{
    j.process();
}
catch(InterruptedException ex)
{
    //thread is interrupted, means it needs to abandon this job and fetch a new one from the queue
}

I hope this helps. However I have omitted a few things to oversimplify the problem:

*

*I have omitted the Job class declaration, I guess it will either be an interface or an abstract class.

*I have also omitted the part where some other thread will add a new Job() and notify()  on the jobQueueInstance.

*Also omitted the part about the thread that will interrupt() the "busy" job-running thread.
NOTE Threads 3 and 4 can be the same thread.

A: You should place a timeout on your download using the software for downloading.  This usually results in an Exception which you can catch, clean up what you are doing and continue on.
Unless the software you are using supports interrupts or time out settings, there is no safe way to force this to happen externally. You can use stop() safely provided your intention is to shutdown at soon as possible. (In which case System.exit() is a better option)
If you have a library which you have no choice but to kill, you need to run it in a separate process and kill the whole process.  This will ensure any resources used will be cleaned up by the OS. (Assuming it hasn't left temporary files etc. ;)


text:
Q: i have been trying to separate the column of my csv file. actually there are 6 column but some column are 5 and it affecting my result 2018-03-06 12:23:13;read;country_5;2458291108;Australia
2018-03-06 12:23:16;read;country_7;2458291957;Reddit;Australia
2018-03-06 12:23:19;read;country_7;2458203986;Asia
2018-03-06 12:23:25;read;country_6;2458291958;Reddit;Asia
2018-03-06 12:23:25;read;country_7;2458286097;Asia
2018-03-06 12:23:31;read;country_5;2458291846;Australia
2018-03-06 12:23:33;read;country_5;2458291959;Reddit;Asia
2018-03-06 12:23:38;read;country_4;2458291960;AdWords;Asia
2018-03-06 12:23:42;read;country_2;2458199318;Europe

A: If the above is the content of your file then you can use the basic operation of python.
column1 = []
column2 = []
column3 = []
column4 = []
column5 = []
fopen = open("filename.csv","r")
lines  = fopen.readlines()
for line in lines:
   fields = line.split(";")
   field[0].append(column1)
   field[2].append(column2)
   .....#put for other columns as well

Now you got five lists you can convert this into series and you can make dataframe.

A: I'm assuming your input file looks like
2018-03-06 12:23:13;read;country_5;2458291108;Australia
2018-03-06 12:23:16;read;country_7;2458291957;Reddit;Australia
2018-03-06 12:23:19;read;country_7;2458203986;Asia
2018-03-06 12:23:25;read;country_6;2458291958;Reddit;Asia
2018-03-06 12:23:25;read;country_7;2458286097;Asia
2018-03-06 12:23:31;read;country_5;2458291846;Australia
2018-03-06 12:23:33;read;country_5;2458291959;Reddit;Asia
2018-03-06 12:23:38;read;country_4;2458291960;AdWords;Asia
2018-03-06 12:23:42;read;country_2;2458199318;Europe

and the problem is the last two columns.
If you do this (file named input.csv here)
import csv

lines = []
with open('input.csv', 'r') as file:
    csv_file = csv.reader(file, delimiter=';')
    for line in csv_file:
        if len(line) == 5: # If input for column 5 is missing: insert placeholder
            line = line[:4] + ['NO INPUT', line[4]]
        lines.append(line)

or shorter
with open('input.csv', 'r') as file:
    lines = [line[:4] + ['NO INPUT', line[4]] if len(line) == 5 else line
             for line in csv.reader(file, delimiter=';')]

you get the following aligned lines
[
 ['2018-03-06 12:23:13', 'read', 'country_5', '2458291108', 'NO INPUT', 'Australia'],
 ['2018-03-06 12:23:16', 'read', 'country_7', '2458291957', 'Reddit', 'Australia'],
 ['2018-03-06 12:23:19', 'read', 'country_7', '2458203986', 'NO INPUT', 'Asia'],
 ['2018-03-06 12:23:25', 'read', 'country_6', '2458291958', 'Reddit', 'Asia'],
 ['2018-03-06 12:23:25', 'read', 'country_7', '2458286097', 'NO INPUT', 'Asia'],
 ['2018-03-06 12:23:31', 'read', 'country_5', '2458291846', 'NO INPUT', 'Australia'],
 ['2018-03-06 12:23:33', 'read', 'country_5', '2458291959', 'Reddit', 'Asia '],
 ['2018-03-06 12:23:38', 'read', 'country_4', '2458291960', 'AdWords', 'Asia'],
 ['2018-03-06 12:23:42', 'read', 'country_2', '2458199318', 'NO INPUT', 'Europe']
]

I have filled in the missing 5th columns with 'NO INPUT'. You can of course do here whatever seems appropriate (for example None).
If you actually want to separete the columns: This
columns = [[] for _ in range(6)]
with open('input.csv', 'r') as file:
    csv_file = csv.reader(file, delimiter=';')
    for line in csv_file:
        if len(line) == 5: # If input for column 5 is missing: insert placeholder
            line = line[:4] + ['NO INPUT', line[4]]
        for i, item in enumerate(line):
            columns[i].append(item)

or a bit more compact
with open('input.csv', 'r') as file:
    lines = [line[:4] + ['NO INPUT', line[4]] if len(line) == 5 else line
             for line in csv.reader(file, delimiter=';')]
columns = [[lines[i][j] for i in range(len(lines))] for j in range(6)]

gives you
[
 ['2018-03-06 12:23:13', '2018-03-06 12:23:16', '2018-03-06 12:23:19', '2018-03-06 12:23:25', '2018-03-06 12:23:25', '2018-03-06 12:23:31', '2018-03-06 12:23:33', '2018-03-06 12:23:38', '2018-03-06 12:23:42'],
 ['read', 'read', 'read', 'read', 'read', 'read', 'read', 'read', 'read'],
 ['country_5', 'country_7', 'country_7', 'country_6', 'country_7', 'country_5', 'country_5', 'country_4', 'country_2'],
 ['2458291108', '2458291957', '2458203986', '2458291958', '2458286097', '2458291846', '2458291959', '2458291960', '2458199318'],
 ['NO INPUT', 'Reddit', 'NO INPUT', 'Reddit', 'NO INPUT', 'NO INPUT', 'Reddit', 'AdWords', 'NO INPUT'],
 ['Australia', 'Australia', 'Asia', 'Asia', 'Asia', 'Australia', 'Asia ', 'Asia', 'Europe']
]


text:
Q: Looking for a way to use 'Sortable' function with PHP I have a folder of images which I had hoped to load with php into a list of images that could be moved around with the Sortable jQueryUI function. I ran a basic test of php so I know that php isn't failing, but my code might be faulty for other reasons and my experience with jQueryUI is lacking. Below are the important parts of the code I was hoping to use.

<?php
  $imagesDir = '/uploads/gallery1/';
  $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
  $imglist = json_encode($images);
  for ($i = 1; $i <= count($imglist); $i++) {
?>
<?php
echo $array[$i];
?>
<?php
  }

?>

The images fail to display, and no list is created.
Any help or suggestions are greatly appreciated.

A: Try replacing your PHP code block with
<?php
    $imagesDir = dirname(__FILE__) . '/uploads/gallery1/';
    $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
    for ($i = 0; $i < count($images); $i++) {
?>
<?php
    echo $images[$i];
?>
<?php

And please, specify what exactly the problem is - if it's an error - please, attach the message to the question


text:
Q: Unable to run Java project suddenly. Error 404 in tomcat I have attached my project's folder tree view in the screenshot below

Is there any mistake in it ? Yesterday I was still able to run it, today it's giving me enormous amount of errors.
Edited--


text:
Q: Making a void dynamic I create some picture box dynamic, but i dont know how to make a individual action on click.
PictureBox[] app=new PictureBox[file.Length];
int i = 0, prev=20;
foreach(string element in file)
{
    app[i] = new PictureBox();
    app[i].BackgroundImage = Image.FromFile(element.Remove(element.Length - 3) + "png");
    app[i].Location = new Point(prev, 85);
    app[i].Size = new Size(100, 100);
    app[i].Name = "test" + i;
    app[i].Click += new EventHandler(run(element, dir));

    this.Controls.Add(app[i]);

    i++;
    prev += 20;
}

private void run(string element, string dir)
{
      MessageBox.Show(element);
}

So how can I do that. Please help! Thanks!

A: Is this what you want?
app[i].Click += (sender, args) => { MessageBox.Show(element);};

A: try this
app[i].Click += (s, e) => { run(element,dir); };

A: Try to avoid using delegates/functions within a foreach loop,  and if you do, use a copy of the object, not the variable in the loop statement.
var elementCopy = element;
...
app[i].Click += (sender,evt) => run(elementCopy,dir);

If you use the element directly, there is a chance it will always use the last element in the enumerable for the delegate
Edit: Refer to this: Using the iterator variable of foreach loop in a lambda expression - why fails?
It explains why you should do what I said more in-depth.


text:
Q: Is it possible to switch back and forth between Scenekit rendering and normal iOS app rendering? It would be nice to use the regular iOS app buttons during menu'ing, then go into Scenekit rendering for game play.
Thanks


text:
Q: Html: BarbaJS Slider transition I am using this library for the first time, my problem is that the slider works when the page is first loaded. The slider does not work when I switch to another page and return to the scroll page again. please can you help me i'm new here about barba js, i don't know how to do it, i will be very happy if you help her.
As shown in the picture. the first image works when the page loads. Doesn't work on 2 images

A: my research has yielded results. maybe i will help someone
for different pages. Js should be called.
barba.hooks.afterEnter((data) => {
jQuery.getScript("jsname.js");
});