text:
Q: What could be wrong with my function for finding a solution for circle-line collision? So I am working on a simple function in which you provide a single point and an angle along with the radius of the circle, the line intersects, and you get back one of the points of intersection. For some very unknown reason I am not getting the expected x position?
My calculation for the x position is based on: http://mathworld.wolfram.com/Circle-LineIntersection.html
I would be very satisfied if any of you guys could do the same, but for your function to spit out the x position expected in this very case to be -27.386 for one solution and 27.386 for the other, according to the Desmos Graphing Calculator.
The point is (-70, -40.415), going at an an angle of PI/6 and the circle radius is sqrt(1000). Using this info, you should be able to get the two x solutions.
My code:
function sgn(x) {
    return x < 0 ? -1 : 1;
}

function findPointOfCollision(p, t, r) { // p -> point, t -> theta, r -> radius
    p2 = [p[0] + 200*Math.cos(t), p[1] + 200*Math.sin(t)]; // Another point in the line given by point and angle

    let x1 = p[0];
    let y1 = p[1];

    let x2 = p2[0];
    let y2 = p2[1];

    let dx = x2 - x1;
    let dy = y2 - y1;

    let dr = Math.sqrt(dx*dx + dy*dy);
    let D = x1*y2 - x2*y1;

    let x = (D*dy + sgn(dy)*dx*Math.sqrt(r*r*dr*dr - D*D))/dr*dr;

    return [x]; // Only need the x position for the collision point atm
}

function start () {
    console.log(findPointOfCollision([-70, -40.415], Math.PI/6, 31.6227766017));
}

A: Your algorithm is correct, but you have an error in the last formula when you divide by dr²: A/dr*dr means (A/dr)*dr, which effectively cancels out the division. You must place parentheses around the denominator here: A/(dr*dr).
When I change the formula for x to:
    let x = (D*dy + sgn(dy)*dx*Math.sqrt(r*r*dr*dr - D*D)) / (dr*dr);

I get the expected value of about 27.386.


text:
Q: Pass an object property key, not its value, as a parameter in Javascript I am trying to write a simple, portable function where I can pass in an object.property and set its value from the result. Simple example:
var myFunction = function (result){
  var data;
  //get some data
  return result = data;
};

myObject.someData;
myFunction(pass reference to key of myObject.someData here)

I want to pass reference to key of myObject.someData here. Brownie points for also declaring it here instead of line above.
Now for my actual code:
var configurations;
var oldServer;
//make a call to get details of old server here

//helper function to stream json into a variable
var streamToString = function(stream, result) {
  var data = '';
  var chunk;

  stream.on('readable', function() {
      while ((chunk=this.read()) != null) {
          data += chunk;
      }
  });
  stream.on('end', function() {
    data = JSON.parse(data);
    return result = data;
  });
}

//declare shadowsocks as a property, so it can be passed as a param
configurations.shadowsocks;

//
streamToString(sequest.get('root@'+ oldServer[0].networks.v4[0].ip_address, '/etc/shadowsocks-libev/config.json', {
  privateKey: sshKey,
  readyTimeout: 20000
 }, function (error, stdout) {
   if (error) {
     throw error;
   }
 }), configurations.shadowsocks
);

I know I can do this the "wrong way" by doing:
 stream.on('end', function() {
        data = JSON.parse(data);
        return configurations.shadowsocks = data;
      });
    }

but then it's not portable. I would like to make this portable.

A: What you're asking for is not possible in JavaScript. The best you could probably do is to pass both the object and the property name to be set. For example:
function streamToString(stream, result, resultKey) {
  var data = '';
  var chunk;

  stream.on('readable', function() {
      while ((chunk=this.read()) != null) {
          data += chunk;
      }
  });
  stream.on('end', function() {
    data = JSON.parse(data);
    result[resultKey] = data;
  });
}

Then use it like:
streamToString(/*...*/, configurations, 'shadowsocks');

I should also point out that unless you're doing this as a one-off task and don't care when it completes, you should instead use a callback that gets called with the value, and then set the property to that value in the callback. That way you will know when the property has been set and is ready for use.

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS game performance increases during profiling I have been developing a SpriteKit game in Xcode targeting the iPhone4 as my weakest device. The FPS has been terrible, and I am working to improve it. When I ran instruments to time profile my game, the FPS was a perfect 60. So this has me thinking that I have been building my game with some configuration that hurts the performance, perhaps a debug mode of some kind. I have not changed very many of the project settings from the default SpriteKit project.
I do not know enough about iOS to figure out what changed to increase the performance of my game. Which setting is causing the slowdown?


text:
Q: После transform элемент размытый Почему буква C размытая? Я пытаюсь это адаптировать под разные размеры текста, при --spanNum: 2rem можно заметить, что буква  C становится размытым

let openSpan = document.querySelectorAll('.openSpan');

for (let i = 0; i < openSpan.length; i++) {
    openSpan[i].addEventListener('click', () => {
        openSpan[i].classList.toggle('active');
    });
}
.service-block__card {
 background-color: white;
 display: -moz-flex;
 display: -ms-flex;
 display: -o-flex;
 display: -webkit-box;
 display: -ms-flexbox;
 display: -webkit-flex;
 display: -moz-box;
 display: flex;
 -webkit-box-orient: vertical;
 -webkit-box-direction: normal;
     -ms-flex-direction: column;
         -webkit-flex-direction: column;
            -moz-box-orient: vertical;
            -moz-box-direction: normal;
         flex-direction: column;
 max-width: 500px;
 margin: 10px auto 0;
 padding: 10px;
 -webkit-box-align: center;
     -ms-flex-align: center;
         -webkit-align-items: center;
            -moz-box-align: center;
         align-items: center;
 -webkit-transition: all .2s linear;
 -o-transition: all .2s linear;
 -moz-transition: all .2s linear;
 transition: all .2s linear;
}

.service-block__card-text {
 display: -moz-flex;
 display: -ms-flex;
 display: -o-flex;
 display: -webkit-box;
 display: -ms-flexbox;
 display: -webkit-flex;
 display: -moz-box;
 display: flex;
 -webkit-box-orient: vertical;
 -webkit-box-direction: normal;
     -ms-flex-direction: column;
         -webkit-flex-direction: column;
            -moz-box-orient: vertical;
            -moz-box-direction: normal;
         flex-direction: column;
 overflow: hidden;
}

.hide__text {
 overflow: hidden;
 -webkit-transition: all .4s linear;
 -o-transition: all .4s linear;
 -moz-transition: all .4s linear;
 transition: all .4s linear;
}

.service-block__card-open {
 color: black;
 font-weight: bold;
 margin: 10px auto;
 font-size: 20px;
 cursor: pointer;
 -moz-user-select: none;
 -webkit-user-select: none;
     -ms-user-select: none;
         user-select: none;
 display: block;
}

:root {
 --atf: cubic-bezier(.58,-0.71,.41,1.55);
 --spanNum: 2rem;
 --spanNumTopB: -webkit-calc(-1 * ( var(--spanNum)*1.2 ) );
 --spanNumTopB: -moz-calc(-1 * ( var(--spanNum)*1.2 ) );
 --spanNumTopB: calc(-1 * ( var(--spanNum)*1.2 ) );
 --spanNumLeftB: -webkit-calc( -1 * ( (var(--spanNum)*11)/160 ) );
 --spanNumLeftB: -moz-calc( -1 * ( (var(--spanNum)*11)/160 ) );
 --spanNumLeftB: calc( -1 * ( (var(--spanNum)*11)/160 ) );
 --spanNumSec: 1s;
}

.openSpan {
 display: -webkit-box;
 display: -ms-flexbox;
 display: -webkit-flex;
 display: -moz-box;
 display: flex;
 font-size: var(--spanNum);
 font-family: sans-serif;
 font-weight: bold;
 text-transform: uppercase;
 -webkit-perspective: 1000px;
         -moz-perspective: 1000px;
      perspective: 1000px;
 -moz-user-select: none;
 -webkit-user-select: none;
     -ms-user-select: none;
         user-select: none;
 cursor: pointer;
 max-height: var(--spanNum);
}

.openSpan .ab {
 position: relative;
 -webkit-transform-style: preserve-3d;
         -moz-transform-style: preserve-3d;
      transform-style: preserve-3d;
 -webkit-transition: var(--spanNumSec) var(--atf) transform;
 -o-transition: var(--spanNumSec) var(--atf) transform;
 -moz-transition: var(--spanNumSec) var(--atf) transform;
 transition: var(--spanNumSec) var(--atf) transform;
}

.openSpan .ab > div {
 width: 100%;
 -webkit-backface-visibility: hidden;
         -moz-backface-visibility: hidden;
      backface-visibility: hidden;
 text-align: end;
}

.openSpan .b {
 margin-top: var(--spanNumTopB);
 margin-left: var(--spanNumLeftB);
 -webkit-transform: rotateX(180deg) rotateZ(90deg);
         -moz-transform: rotateX(180deg) rotateZ(90deg);
      transform: rotateX(180deg) rotateZ(90deg);
}

.openSpan .c {
 -webkit-transition: var(--spanNumSec) var(--atf) transform;
 -o-transition: var(--spanNumSec) var(--atf) transform;
 -moz-transition: var(--spanNumSec) var(--atf) transform;
 transition: var(--spanNumSec) var(--atf) transform;
}

.openSpan.active .ab{
 -webkit-transform: rotateX(180deg) rotateZ(90deg);
         -moz-transform: rotateX(180deg) rotateZ(90deg);
      transform: rotateX(180deg) rotateZ(90deg);
}

.openSpan.active .c {
 -webkit-transform: rotateX(-360deg);
         -moz-transform: rotateX(-360deg);
      transform: rotateX(-360deg);
}

Раз

С

вернуть

A: Как вариант, можно использовать zoom
PS При зуме видно, что размер шрифта буквы становится чуть меньше. Поэтому можно добавить font-size, немного увеличив размер шрифта. Таким образом подогнать его под нужный нам размер и устранить эту неприятность. :)

let openSpan = document.querySelectorAll('.openSpan');

for (let i = 0; i < openSpan.length; i++) {
    openSpan[i].addEventListener('click', () => {
        openSpan[i].classList.toggle('active');
    });
}
:root {
 --atf: cubic-bezier(.58,-0.71,.41,1.55);
 --spanNum: 2rem;
 --spanNumTopB: calc(-1 * ( var(--spanNum)*1.2 ) );
 --spanNumLeftB: calc( -1 * ( (var(--spanNum)*11)/160 ) );
 --spanNumSec: 1s;
}

.openSpan {
 display: flex;
 font-size: var(--spanNum);
 font-family: sans-serif;
 font-weight: bold;
 text-transform: uppercase;
 perspective: 1000px;
 -moz-user-select: none;
 user-select: none;
 cursor: pointer;
 max-height: var(--spanNum);
}

.openSpan .ab {
 position: relative;
 transform-style: preserve-3d;
 transition: var(--spanNumSec) var(--atf) transform;
}

.openSpan .ab > div {
 width: 100%;
 backface-visibility: hidden;
 text-align: end;
}

.openSpan .b {
 margin-top: var(--spanNumTopB);
 margin-left: var(--spanNumLeftB);
 transform: rotateX(180deg) rotateZ(90deg);

  zoom: 98%;
  font-size: 2.08rem;
}

.openSpan .c {
 transition: var(--spanNumSec) var(--atf) transform;
}

.openSpan.active .ab{
 transform: rotateX(180deg) rotateZ(90deg);
}

.openSpan.active .c {
 transform: rotateX(-360deg);
}

Раз

С

вернуть


text:
Q: Rails 3 assets add ?body=1 If I view the source there is a ?body=1 added to all assets (css and js)
like this
<script src="/assets/jquery.livequery.js?body=1" type="text/javascript"></script>

what is it? and why?

A: The body param is required by Sprockets and is used internally to determine whether to send back the asset directly (an image or other binary file) or the contents of the file (js and css). While these are technically the same thing, Sprockets treats bundles of files and static files in different ways.


text:
Q: Using strptime %z with special timezone format I am working with .csv data that was exported from Teradata.  Several columns were originally timestamps with timezones, so after loading the .csv in R I'd like to convert these columns (which are loaded as strings) to POSIXlt or POSIXct.  I am using strptime, but the format of the timezone from the .csv file does not match what strptime is expecting.  For example, it expects -0400 but the .csv has the format -04:00 where a colon separates the hours and minutes.
I can remove the colon, but this is an extra step and complication I'd like to avoid if possible.  Is there a way to tell strptime to use a different format for the timezone (%z)?
Here is an example:
## Example data:
x <- c("2011-10-12 22:17:13.860746-04:00", "2011-10-12 22:17:13.860746+00:00")
format <- "%Y-%m-%d %H:%M:%OS%z"

## Doesn't work:
strptime(x,format)
## [1] NA NA

## Ignores the timezone:
as.POSIXct(x)
## [1] "2011-10-12 22:17:13 EDT" "2011-10-12 22:17:13 EDT"

## Remove the last colon:
x2 <- gsub("(.*):", "\\1", x)
x2
## [1] "2011-10-12 22:17:13.860746-0400" "2011-10-12 22:17:13.860746+0000"

## This works, but requires extra processing (removing the colon)
strptime(x2,format)
## [1] "2011-10-12 22:17:13" "2011-10-12 18:17:13"

So I'm looking to achieve this last result using something like strptime(x,"%Y-%m-%d %H:%M:%OS%zz"), where %zz is a custom expression for the timezone that recognizes the -04:00 format.  Or %zH:%zM might be even better.
If this isn't possible, does anyone have a slick/flexible function for converting strings (of various formats) to dates for multiple columns of a data.frame/data.table?

A: It turns out lubridate can handle this format:
library(lubridate)
ymd_hms(x)
## [1] "2011-10-13 02:17:13 UTC" "2011-10-12 22:17:13 UTC"

Or, to display in the local timezone:
with_tz(ymd_hms(x))
## [1] "2011-10-12 22:17:13 EDT" "2011-10-12 18:17:13 EDT"

For more flexibility (still using lubridate):
parse_date_time(x, "%Y-%m-%d %H:%M:%OS%z")

For faster speed (amongst lubridate options):
lubridate:::.strptime(x, "%Y-%m-%d %H:%M:%OS%OO")

Timings:
microbenchmark(
  ymd_hms(x),
  parse_date_time(x, "%Y-%m-%d %H:%M:%OS%z"),
  lubridate:::.strptime(x, "%Y-%m-%d %H:%M:%OS%OO"),
  strptime(gsub("(.*):", "\\1", x), format)
)

## Unit: microseconds
##                                               expr      min       lq       mean    median        uq      max neval
##                                         ymd_hms(x) 1523.819 1578.495 1715.14577 1629.5385 1744.3695 2850.393   100
##         parse_date_time(x, "%Y-%m-%d %H:%M:%OS%z") 1108.676 1150.633 1273.77301 1190.3315 1264.8050 5947.204   100
##  lubridate:::.strptime(x, "%Y-%m-%d %H:%M:%OS%OO")   89.838  103.390  112.45338  107.8425  115.2265  216.512   100
##        strptime(gsub("(.*):", "\\\\1", x), format)   46.716   58.294   71.90934   69.9415   86.5860  105.044   100

A: I've just come across this question trying to achieve the same thing.
The only thing I've found to fix it is to use regex to remove the colon, as you have mentioned. You can tighten the regex a little to avoid making mistakes in the replacement.
x2 <- gsub('^([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]+[+-][0-9]{2}):([0-9]{2})$',
           '\\1\\2',
           x)
# [1] "2011-10-12 22:17:13.860746-0400" "2011-10-12 22:17:13.860746+0000"


text:
Q: Entity Framework 6 ошибка DTO - "has no key" Сделал модель:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Server.DB
{
    [Serializable]
    [Table("users")]
    public class UserDTO : AbstractDto {
        [Key]
        public UInt32 ID { get; set; }
        public string Login { get; set; }
        public string Password { get; set; }
        public string Nick { get; set; }
    }
}

далее, код коннектора:
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using MySql.Data.Entity;

namespace Server.DB {

    [DbConfigurationType(typeof(MySqlEFConfiguration))]
    public class EntityContext : DbContext, IEntityContext {

        public EntityContext() : base("name=DBConnector") { }

        public DbSet<UserDTO> Users { get; set; }

    }

}

При попытке простого Select-а:
var query = UnitOfWorkFactory.Instance.Get.EntityContext.Set<UserDTO>().AsQueryable();
UserDTO user = query.Where(q => q.Login == "test@test.ru" && q.Password == "1234").ToList()[0];

Получаю исключение:

Необработанное исключение типа "System.Data.Entity.ModelConfiguration.ModelValidationException" в EntityFramework.dll
Дополнительные сведения: One or more validation errors were detected during model generation:
Server.DB.DataAccess.UserDTO: : EntityType 'UserDTO' has no key defined. Define the key for this EntityType.
Users: EntityType: EntitySet 'Users' is based on type 'UserDTO' that has no keys defined.

Подскажите, в чём ошибка, и как можно заставить EF6 посмотреть на схему?
С EF6 до этого не работал.

Добавлено
Делаю миграцию, получаю следующее исключение:

PM> Enable-Migrations -ProjectName SqlDbAPI -StartUpProjectName OGameServer -ContextTypeName Server.DB.EntityContext -Verbose -Force
Using StartUp project 'OGameServer'.
  Checking if the context targets an existing database...
  System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
     в System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName)
     в System.Data.Entity.Internal.AppConfig.<.ctor>b__2(ProviderElement e)
     в System.Linq.Enumerable.WhereSelectEnumerableIterator 2.MoveNext()
     в System.Collections.Generic.List 1..ctor(IEnumerable 1 collection)
     в System.Linq.Enumerable.ToList[TSource](IEnumerable 1 source)
     в System.Data.Entity.Internal.AppConfig.<.ctor>b__1()
     в System.Lazy 1.CreateValue()
     в System.Lazy 1.LazyInitValue()
     в System.Lazy 1.get_Value()
     в System.Data.Entity.Internal.AppConfig.get_DbProviderServices()
     в System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.RegisterDbProviderServices()
     в System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetServiceFactory(Type type, String name)
     в System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.<>c__DisplayClass1.b__0(Tuple 2 t)
     в System.Collections.Concurrent.ConcurrentDictionary 2.GetOrAdd(TKey key, Func 2 valueFactory)
     в System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetService(Type type, Object key)
     в System.Data.Entity.Infrastructure.DependencyResolution.ResolverChain.<>c__DisplayClass3.b__0(IDbDependencyResolver r)
     в System.Linq.Enumerable.WhereSelectArrayIterator 2.MoveNext()
     в System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable 1 source, Func 2 predicate)
     в System.Data.Entity.Infrastructure.DependencyResolution.ResolverChain.GetService(Type type, Object key)
     в System.Data.Entity.Infrastructure.DependencyResolution.CompositeResolver 2.GetService(Type type, Object key)
     в System.Data.Entity.Infrastructure.DependencyResolution.DbDependencyResolverExtensions.GetService[T](IDbDependencyResolver resolver)
     в System.Data.Entity.DbContext.InitializeLazyInternalContext(IInternalConnection internalConnection, DbCompiledModel model)
     в System.Data.Entity.DbContext..ctor(String nameOrConnectionString)
     в Server.DB.EntityContext..ctor() в G:\Sources\MinGW\QuickStart\OGame\Server\SqlDbAPI\DBMySql\EntityContext.cs:строка 11
  --- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
     в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     в System.Data.Entity.Infrastructure.DbContextInfo.CreateInstance()
     в System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo, Func 1 resolver)
     в System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
     в System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
     в System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration migrationsConfiguration)
     в System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
     в System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
     в System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
     в System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
     в System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldInitialCreate(String language, String rootNamespace)
     в System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
     в System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.

A: Ответ был найден совершенно СЛУЧАЙНО. Никакая миграция не помогла, более того, процесс миграции так же валился с той же злощастной ошибкой об отсутствии первичного ключа. Ошибка была в том, что EF вообще не воспринемает в упор типы UIntXX/uint! Изменение типа ключа на int - исправило все ошибки, и проект запустился без миграции...
Если кто нибудь ответит почему это происходит, буду очень признателен!


text:
Q: Problem with affiliations - Magnetic Resonance in Medicine manuscript I am preparing a manuscript to submit to MRM. They provided the Latex template but there is something odd. The author affiliations don't appear below the names in full line but they broke down in small lines. Every affiliation should be in single long line.
Here is the code
\author[1\authfn{1}]{Author One PhD}
\author[2\authfn{1}]{Author A.~Two MD}
\author[2\authfn{2}]{Author Three PhD}
\author[2]{Author B.~Four}

\contrib[\authfn{1}]{Equally contributing authors.}

% Include full affiliation details for all authors
\affil[1]{Department, Institution, City, State or Province, Postal Code, Country}
\affil[2]{Department, Institution, City, State or Province, Postal Code, Country}

I attached a photo how it looks like. Any help would be highly appreciated.

A: The whole aim of a journal template is to hold blocks of information to be completely reset by the journal type setters. The way a template compiles is not always the way it will be published. In order to ensure fields are filled in in a uniform fashion they may be presented to the author in a variety of ways, then can be compiled in a different sequence (or suppressed). Possibly  typeset in yet another. As long as you are following the template exactly and don't change its structure you cant go wrong
From the WOL (Wiley Online Library) instructions
Reviewers receive manuscripts with no authors' names listed to ensure unbiased, double-blinded review.
Instead of providing the authors' names and affiliations in the main manuscript file, please do so on a separate title page file. Do not give names of authors or their affiliations in the main manuscript tex.


text:
Q: How to get Windows text resource from current display language If Windows is set to a non-English display language, certain UI elements in Windows also change (e.g. MessageBoxButtons appear in the selected display language). Is there any way to get those text resources and integrate into my .Net application?

A: In theory, yes you could. The Windows common controls retrieve localized strings for the relevant language using MUI files in %WINDIR%\System32{LocaleIdentifier}. There is an example on MSDN that shows how you can do the same in win32. So you could in load localized strings from comctl32.dll.mui and comdlg32.dll.mui using the same IDs as the Windows controls though P/Invoke. But this wouldn't be pretty, could cause breaks in future updates of Windows (it's private data, with no promise that it won't change) and would frankly seem overkill.  It's much easier and safer to maintain your own set of localized strings!


text:
Q: how to concatenate two items in array of string using java? I have a text file i already read it and return an array of string "lines" in this structure
{(1),text,(2),text,(3),text........}

I want to restructure it as
{(1)text,(2)text,(3)text........}

which mean concatenate every number like (1) with the next text and so on
public String[] openFile() throws IOException {

        FileInputStream inStream = new FileInputStream(path);
        InputStreamReader inReader = new InputStreamReader(inStream,"UTF-8");
        BufferedReader textReader = new BufferedReader(inReader);

        int numberOfLine = countLines();
        String[] textData = new String[numberOfLine];

        for (int i = 0; i < numberOfLine; i++) {
            // if (textReader.readLine()!= null) {
            textData[i] = textReader.readLine();
            //}

        }

        textReader.close();
        return textData;

    }

how can i do it please using Java language ?
Thanks for your helps and your opinions

A: String[] newArray = new String[textData.length / 2];

for (int i = 0; i < textData.length - 1; i+=2) {
  newArray[i / 2] = textData[i] + textData[i + 1];
}

But be sure that your textData has an even length
Put this snippet before the return statement and return newArray instead;

A: It seems that the comma you want to omit is always preceded by a closing bracket. Assuming that that is the only time it happens in your string you could just do a simple replacement in your for-loop:
textData[i] = textData[i].replace("),", ")");

If that isn't the case, then another thing you could do is work on the basis that the comma you want to remove is the first in the string:
    //Locate index of position of first comma in string
     int firstComma = x.indexOf(',');

     //Edit string by concatenating the bit of the string before the comma
and the bit after it, stepping over the comma in the process
     textData[i] = (textData[i].substring(0, firstComma)).concat(textData[i].substring(firstComma + 1));


text:
Q: How to derive Bernoulli's theorem for an elastic fluid from Lamb's equation Here I state Lamb's version of the Euler's equation for an elastic fluid:
$$ \partial_t \vec v + \vec \Omega \times \vec v + \vec \nabla \left( \frac{\|\vec v\|^2}{2} + \frac{p}{\rho} + \psi + \phi_b\right) = 0$$
where $\vec\Omega$ is the vorticity of the fluid, $p$ the pressure, $\rho$ the density, $\vec b$ is a potential body force such that $\vec b = \vec \nabla \phi_b$ and $\psi$ is Helmholt's density of energy that in our course has been defined as the fuction $\psi = \psi(\rho)$ such that $$p(\rho) = \rho^2 \frac{\partial \psi}{\partial \rho}$$
Using Lamb's equation we stated this version of Bernoulli's theorem:
Theorem: Consider an elastic eulerian fluid, then in steady flow the quantity $\frac{\|\vec v\|^2}{2} + \frac{p}{\rho} + \psi + \phi_b$ is constant along the flow lines. (Usually I've been told that the quantity $w :=\frac{p}{\rho} + \psi$ is called Gibbs' free energy)
Proof: It sufficies to show that $\vec v \cdot \vec \nabla \left( \frac{\|\vec v\|^2}{2} + w + \phi_b\right) = 0$ but this is obvious from Lamb's equation.
My questions are:

*

*Why It sufficies to show that $\vec v \cdot \vec \nabla \left( \frac{\|\vec v\|}{2} + w + \phi_b\right) = 0$ to prove that theorem? (The obviousness of the next passage is clear to me)

*How this theorem can be linked to the "classical" Bernoulli statement: $p = -\rho \frac{\|\vec v \|^2}{2} + k$ where $k$ is a constant?

A: A Streamline (flow line) is a  curve with parametric representation $\mathbf{x}_S(s)$ at some fixed time $t$ such that
$$\mathbf{x}_S(s) \times \mathbf{v}(\mathbf{x}_S(s),t) = 0$$
The velocity field is, therefore, tangential to the streamline at any point, and
$$\frac{d \mathbf{x}_S}{ds}(s) = \alpha(s) \mathbf{v}(\mathbf{x}_S(s),t) $$
Defining the quantity $H (\mathbf{x},t) = \frac{\| \mathbf{v}\|^2}{2} + w + \phi_b$, we have
$$\mathbf{v}(\mathbf{x}_S(s),t) \cdot \nabla H(\mathbf{x}_S(s),t) = 0,$$
and, by the chain rule,
$$\frac{\partial}{\partial s} H(\mathbf{x}_S(s),t) = \nabla H(\mathbf{x}_S(s),t)\cdot \frac{d \mathbf{x}_S}{ds}(s) =  \alpha(s) \mathbf{v}(\mathbf{x}_S(s),t)\cdot \nabla H(\mathbf{x}_S(s),t) = 0 $$
Therefore, $H$ is constant along a streamline, where value of this constant can be different for each streamline.

What you refer to as the "classical" Bernoulli statement,
$$\tag{1} p + \frac{1}{2} \rho \|\mathbf{v}\|^2 = k,$$
where $k$ is constant at all points in the domain is valid for steady inviscid, incompressible and irrotational flow.
For a proof, begin with the Euler equations governing steady, inviscid flow,
$$\tag{2}\rho (\mathbf{v} \cdot \nabla) \mathbf{v} = - \nabla p,$$
along with the incompressibility condition $\nabla \cdot \mathbf{v} = 0$.
By the general vector identity
$$\nabla (\mathbf{a} \cdot  \mathbf{b}) = (\mathbf{a} \cdot \nabla) \mathbf{b} +  (\mathbf{b} \cdot \nabla) \mathbf{a} +   \mathbf{a} \times (\nabla \times \mathbf{b}) + \mathbf{b} \times (\nabla \times \mathbf{a}),$$
we get with $\mathbf{a} = \mathbf{b} = \mathbf{v}$,
$$\nabla (\|\mathbf{v}\|^2) = \nabla (\mathbf{v} \cdot  \mathbf{v}) = 2(\mathbf{v} \cdot \nabla) \mathbf{v}  + 2\mathbf{v} \times (\nabla \times \mathbf{v})$$
For irrotational flow, where $\nabla \times \mathbf{v} = 0$, this reduces to
$$\tag{3}(\mathbf{v} \cdot \nabla) \mathbf{v} = \nabla (\frac{1}{2}\|\mathbf{v}\|^2)$$
Since $\rho$ is constant we obtain after substituting (3) into (2),
$$\nabla (\frac{1}{2}\rho\|\mathbf{v}\|^2) = -\nabla p, $$
whence $\nabla (p + \frac{1}{2}\rho\|\mathbf{v}\|^2) = 0$ and (1) must hold where $k$ is a global constant.

A: I show an intuitive argument. The velocity field defines some integral curves. These are referred to as flow lines and have the property of having the velocity field as tangents. Clearly any quantity F with a gradient always orthogonal to the velocity field will have the gradient orthogonal to the integral curves as well. In such a situation F must be constant along the integral curves.


text:
Q: Changing DocumentRoot in Apache2 on Mac Sierra I want to change the DocumentRoot for my Apache Server as I keep my files for Web Development in another location. The default Document Root is
DocumentRoot "/Library/WebServer/Documents"

I changed that to :
DocumentRoot "/Users/blah/Documents/project"

I also changed :
<Directory "/Library/WebServer/Documents">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
#   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important.  Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options FollowSymLinks Multiviews
MultiviewsMatch Any

#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   AllowOverride FileInfo AuthConfig Limit
#
AllowOverride None

#
# Controls who can get stuff from this server.
#
Require all granted
</Directory>

to this:
<Directory "/Users/blah/Documents/project">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
#   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important.  Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options +ExecCGI
AddHandler cgi-script .cgi .py
MultiviewsMatch Any
Options Indexes FollowSymLinks MultiViews
Order allow,deny
Allow from all
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   AllowOverride FileInfo AuthConfig Limit
#
AllowOverride None

#
# Controls who can get stuff from this server.
#
Require all granted
</Directory>

However when i run localhost on my terminal I get the error:
Forbidden
You don't have permission to access / on this server.
I read through many previous posts regarding similar errors and saw that it was necessary to change permission of the folder. So I did that too. I can't seem to find out what is wrong. This is what comes up when I run ls -la in my project folder:
  total 24
drwxrwxrwx  5 raveen  staff  170 Oct 16 13:37 .
drwxr-xr-x  6 raveen  staff  204 Oct 15 20:09 ..
-rwxrwxrwx@ 1 raveen  staff  438 Oct 16 15:17 index.cgi
-rwxrwxrwx  1 raveen  staff   90 Oct 15 22:56 mongo1.php
-rwxrwxrwx@ 1 raveen  staff  372 Oct 16 13:37 mongo1.py


text:
Q: dplyr & gracefully dealing with SQL NULL values I'm trying to use dplyr to work with SQL databases using R and I'd like to gracefully handle SQL's NULL values--either by simply filtering them out or treating them as zeros when the come up, depending on the scenario--without making any changes to the underlying database itself. (In other words, I'm not asking about converting all NULL values to zero from within SQL.)
Basically, I'm trying to use dplyr to work with SQL databases but I keep getting unexpected results.
# Using Lahman's Database, available here:
# https://www.kaggle.com/seanlahman/the-history-of-baseball

library(dplyr)

db.path <- '~/data/SQLite Databases/the-history-of-baseball/database.sqlite'
con <- DBI::dbConnect(RSQLite::SQLite(), db.path)

batting_db <- tbl(con, 'batting')

# the result of this code is at least (seemingly) correct--the columns appear
# to be the correct type and the entries shown are all accurate:
batting_db %>%
    filter(hr >= 50)

# however, when the additional constraint is added, columns get coerced to
# characters and rows where hr == '' start showing up
batting_db %>%
    filter(hr >= 50, year >= 1985)

First, why is this even an issue? Why wouldn't empty strings get filtered out since '' >= 50 evaluates to FALSE? (Note: Adding the additional constraint that hr != '' appears to have fixed this behavior, though I still don't understand why...)
Also, as far as converting these empty strings to zero now I'm not even sure if that's necessary since apparently dplyr treats them as zero in calculations(?!).
# mutate appears to treat these empty strings as '0' in calculations
batting_db %>%
    filter(hr >= 30, year >= 1985) %>%
    select(player_id:g, h, hr) %>%
    mutate(hr2 = hr + 5, hr3 = g * hr)

Basically, I'm just not getting a hold of dplyr's behavior when using it to access databases and I'd appreciate any insight.

A: I suspect, but don't know, that dplyr will turn any NULLs in a SQL database to NA. I can't create a data frame with NULLs to test since that is not a valid R construct. I would need to see an example.  If we assume that NULLs get changed to NA, this example will turn the NA's to zero AND work on a copy of the table, not modifying the database.
library(RSQLite)
library(dplyr)

#create dummy SQL database
set.seed(123)
tax<-tibble(taxpayer_id=1:10,income=runif(10,50,60),income_misc=runif(10,0,5)) %>%
  mutate(income_misc=ifelse(income_misc<2,NA,income_misc))
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con,"tax_tbl",tax,overwrite=TRUE)

# now extract
tax_db <- tbl(con, 'tax_tbl')
tax_db
#> # Source:   table<tax_tbl> [?? x 3]
#> # Database: sqlite 3.22.0 [:memory:]
#>    taxpayer_id income income_misc
#>          <int>  <dbl>       <dbl>
#>  1           1   52.9        4.78
#>  2           2   57.9        2.27
#>  3           3   54.1        3.39
#>  4           4   58.8        2.86
#>  5           5   59.4       NA
#>  6           6   50.5        4.50
#>  7           7   55.3       NA
#>  8           8   58.9       NA
#>  9           9   55.5       NA
#> 10          10   54.6        4.77

tax <- tax_db %>%
  as_tibble() %>% #have to create a data frame, not database, to modify NAs
  mutate_all(funs(replace(., is.na(.), 0)))

dbDisconnect(con)

tax
#> # A tibble: 10 x 3
#>    taxpayer_id income income_misc
#>          <dbl>  <dbl>       <dbl>
#>  1           1   52.9        4.78
#>  2           2   57.9        2.27
#>  3           3   54.1        3.39
#>  4           4   58.8        2.86
#>  5           5   59.4        0
#>  6           6   50.5        4.50
#>  7           7   55.3        0
#>  8           8   58.9        0
#>  9           9   55.5        0
#> 10          10   54.6        4.77
Created on 2019-02-20 by the reprex package (v0.2.1)

A: This solves the problem of a poorly constructed SQL table presented in the example above by converting all columns to type character, replacing empty strings with NA and converting back to integer where appropriate.  If you are trying to compute stats on the stats you certainly don't want missing values to be treated as zero, but you know that already.
library(dplyr)
library(DBI)

db.path <- "database.sqlite"
con <- DBI::dbConnect(RSQLite::SQLite(), db.path)
batting_db <- tbl(con, 'batting')

batting <- batting_db %>%
  mutate_all(as.character) %>%
  as_tibble %>% # must be a data frame for na_if to work
  na_if("") %>%  #replace empty strings with NA
  #convert numerics back to numerics
  mutate_at(vars(-one_of(c("player_id","team_id","league_id"))),as.integer)

# add a new table to the database with our clean data
dbWriteTable(con,"batting_mod",batting,overwrite=TRUE)
# back to where we started from but with a clean table
batting_db <- tbl(con, 'batting_mod')
batting_db

# Source:   table<batting_mod> [?? x 22]
# Database: sqlite 3.22.0 [C:\Users\nsteinm\Documents\R\temp\database.sqlite]
   player_id  year stint team_id league_id     g    ab     r     h double triple    hr   rbi    sb
   <chr>     <int> <int> <chr>   <chr>     <int> <int> <int> <int>  <int>  <int> <int> <int> <int>
 1 abercda01  1871     1 TRO     NA            1     4     0     0      0      0     0     0     0
 2 addybo01   1871     1 RC1     NA           25   118    30    32      6      0     0    13     8
 3 allisar01  1871     1 CL1     NA           29   137    28    40      4      5     0    19     3
 4 allisdo01  1871     1 WS3     NA           27   133    28    44     10      2     2    27     1
 5 ansonca01  1871     1 RC1     NA           25   120    29    39     11      3     0    16     6
 6 armstbo01  1871     1 FW1     NA           12    49     9    11      2      1     0     5     0
 7 barkeal01  1871     1 RC1     NA            1     4     0     1      0      0     0     2     0
 8 barnero01  1871     1 BS1     NA           31   157    66    63     10      9     0    34    11
 9 barrebi01  1871     1 FW1     NA            1     5     1     1      1      0     0     1     0
10 barrofr01  1871     1 BS1     NA           18    86    13    13      2      1     0    11     1
# ... with more rows, and 8 more variables: cs <int>, bb <int>, so <int>, ibb <int>, hbp <int>,
#   sh <int>, sf <int>, g_idp <int>


text:
Q: Subtype SwingWorker: where would I place my statements that would not run in the GUI thread I have created a subtype of SwingWorker and I wanted to know where would I place my statements that would not run in the GUI thread.
Note: this is a simple SwingWoker subtype and it consists of done() dolnBackground(), run(), process(), publish()
(Don't know if I should have the run method in there)
Cheers
UPDATE
I just found out that I cannot call dolnBackground, process and done methods directly. I have a feeling the answer is the publish method. Can anyone please confirm.

A: You could place the code in doInBackground() method.
And instead of directly invoking the method, you'd have to do something like

mySwingWorker.execute();

from the event-dispatch thread. That initiates the call.


text:
Q: GMail, IMap and Outlook: Speeding it up? I  finally set up Outlook to use GMail and IMAP, but unfortunately, it's extremely slow. The reason, I think for this is because I have 14300 emails in my inbox. And I have no intention to delete them. So, my questions are:

*

*Is there a way to archive old messages, in order to speed things up?

*Any other suggestions on how I can speed it up?

Note: It's only really slow when I click on "Send and Receive". The actual synchronization is what takes forever.

A: Here are some suggestions, probably the one regarding downloading headers only will make a big difference:
http://www.labnol.org/software/tutorials/solutions-for-slow-gmail-imap-with-microsoft-outlook/1761/

A: As well as setting it to 'headers only', if you have a lot of folders, that will also slow it down. Try only subscribing to the folders you actually need regularly, the others will still be there but it won't be syncing them every single time you do a send/receive.

A: To archive old email in Gmail:

*

*In the search box type "in:inbox -is:starred before:2008/06/01" where the date is in yyyy/mm/dd format.

*Press the Select All link. When you press this link, but you have more than a page of results a new link will appear that says "Select all conversations that match this search" - press that

*In the Action drop down, select Archive.

Note: you could also create a label "Old" and have all mails older than a set date be named old. Update the date query will keep your Inbox trimmed. By archiving all mail with the "Old" label, you don't have to manually do these steps every time and it's easier to restore/find them.

Read this article to speed up your Outlook, it explains how to speed up Gmail's IMAP integration with Outlook by:

*

*only downloading headers from the Spam and Trash folders.

*adjusting the time that Outlook should wait before checking for new mail

Removed content that violated copyright

A: There might be a better way of achieving a truly faster gmail experience with Outlook (2007):
When you use IMAP Folders the client and the server have to go back and forth to distinguish any changes that might exist and synchronize them.  This happens very often, and as a result with many sub folders and many messages this can take a considerable amount of time.  For instance when moving messages out of your inbox and into a sub folder.  Or determining the number of unread messages.
The best way I accomplished a faster Outlook w/ GMAIL was to adjust which folders are being synchronized on send/receive by right clicking the imap root folder and selecting IMAP Folders.  You will have a new screen that will query ALL ONLINE folders or Subscribed folders.  Click Subscribed folders and perform the query.  I only need my inbox synchronized for changes, so I remove all other NON DEFAULT folders (I think I have 200 or so).  Also I selected to show all folders not just subscribed folders. If you remove a default folder you will be yacked at and it will return to the list.  Once that is completed you can also adjust your send and receive groups (google it). I like to receive all headers and download full content for subscribed folders (now you get why you adjust the subscribed folders!!).  That seems right for my purposes, but you can choose just headers.  Once you click on a message from your inbox, it will connect to IMAP and download the rest.  Understand that this requires an active connection, hence why I like to download the entire content of the message all the time.
After I adjusted my subscribed folders and send / receive groups, my Outlook is performing like a champ.  Where is used to crash, I can only attribute that to having too many subscribed folders ALL being synchronized when performing a send and receive.
My next challenge:  Implement a warning msg in Outlook when you try and send an email that is larger than 25MB...


text:
Q: Postgres : create function in a particular database Code :
CREATE FUNCTION square_num(num integer)
 RETURNS INTEGER AS $$

BEGIN

 IF (num<0) THEN
 RETURN 0;
 END IF;

 RETURN num*num;

END; $$
LANGUAGE PLPGSQL;

The above code created a function in the database postgres and schema public. How can I create a function in a particular database and it's schema? Thanks.

A:
The above code created a function in the database postgres and schema
  public.

No. It creates function in the database you are connected to in a first existing schema from search_path.
Example:
-bash-4.2$ psql t
psql (10.1)
Type "help" for help.

t=# create table tt();
CREATE TABLE
t=# select table_catalog,table_schema from information_schema.tables where table_name = 'tt';
 table_catalog | table_schema
---------------+--------------
 t             | public
(1 row)

I defined database name t on connection, so relation is created in database t. I don't have schema postgres,so $user was skipped, next "default" schema is public:
t=# show search_path;
   search_path
-----------------
 "$user", public
(1 row)

so now:
t=# create schema postgres;
CREATE SCHEMA
t=# create table tt();
CREATE TABLE

see - no error that relation already exists, because:
t=# select table_catalog,table_schema from information_schema.tables where table_name = 'tt';
 table_catalog | table_schema
---------------+--------------
 t             | public
 t             | postgres
(2 rows)

function creation follows same rules, I used table as shorter syntax...
reading: https://www.postgresql.org/docs/current/static/ddl-schemas.html#DDL-SCHEMAS-PATH

The first schema in the search path that exists is the default
  location for creating new objects.

finally answering

How can I create a function in a particular database and it's schema?

connect to needed database and either explicitely specify schema name:
CREATE FUNCTION my_schema.square_num(...and so on

or adjust search_path to meet your needs
update for sake of clarity I used schema name postgres to comply with original post. both using postgres database and creating postgres schema can be confusing for new users. There is nothing special (or system) about the default postgres database (that can be recreated any time from template), neither the name postgres gives any special attributes to schema. I only used it for OP to easier reproduce the example (as clearly from the fact that he connect to postgres database, user probably did not specify database name, connecting as OS user postgres). Thus to demonstrate how search_path first value $user was picked up, I used same name as username ...


text: Q: Catalogue Price Rules not working properly for different customer groups I am trying to apply catalogue price rule for a different customer group, It's working fine for "general" customer group but when I changed it to different customer group then the discount is not applied to products.


text:
Q: Can not count how many number of unique date are available in every part of string I divided my string in three part using newline ('\n'). The output that i want to achieve: count how many number of unique date are available in every part of string.
According to below code, first part contains two unique date, second part contains two and third part contains three unique date. So the output should be like this: 2,2,3,
But after run this below code i get this Output: 5,5,5,5,1,3,1,
How do i get Output: 2,2,3,
Thanks in advance.
        String strH;
        String strT = null;
        StringBuilder sbE = new StringBuilder();
        String strA = "2021-03-02,2021-03-02,2021-03-02,2021-03-02,2021-03-02,2021-03-11,2021-03-11,2021-03-11,2021-03-11,2021-03-11," + '\n' +
                "2021-03-07,2021-03-07,2021-03-07,2021-03-07,2021-03-07,2021-03-15,2021-03-15,2021-03-15,2021-03-15,2021-03-15," + '\n' +
                "2021-03-02,2021-03-09,2021-03-07,2021-03-09,2021-03-09,";

        String[] strG = strA.split("\n");
        for(int h=0; h<strG.length; h++){
            strH = strG[h];
            String[] words=strH.split(",");
            int wrc=1;
            for(int i=0;i<words.length;i++) {
                for(int j=i+1;j<words.length;j++) {
                    if(words[i].equals(words[j])) {
                        wrc=wrc+1;
                        words[j]="0";
                    }
                }
                if(words[i]!="0"){
                    sbE.append(wrc).append(",");
                    strT = String.valueOf(sbE);
                }
                wrc=1;
            }
        }
        Log.d("TAG", "Output: "+strT);

A: I would use a set here to count the duplicates:
String strA = "2021-03-02,2021-03-02,2021-03-02,2021-03-02,2021-03-02,2021-03-11,2021-03-11,2021-03-11,2021-03-11,2021-03-11" + "\n" +
              "2021-03-07,2021-03-07,2021-03-07,2021-03-07,2021-03-07,2021-03-15,2021-03-15,2021-03-15,2021-03-15,2021-03-15" + "\n" +
              "2021-03-02,2021-03-09,2021-03-07,2021-03-09,2021-03-09";
String[] lines = strA.split("\n");
List<Integer> counts = new ArrayList<>();
for (String line : lines) {
    counts.add(new HashSet<String>(Arrays.asList(line.split(","))).size());
}
System.out.println(counts);  // [2, 2, 3]

Note that I have done a minor cleanup of the strA input by removing the trailing comma from each line.

A: With Java 8 Streams, this can be done in a single statement:
String strA = "2021-03-02,2021-03-02,2021-03-02,2021-03-02,2021-03-02,2021-03-11,2021-03-11,2021-03-11,2021-03-11,2021-03-11," + '\n' +
              "2021-03-07,2021-03-07,2021-03-07,2021-03-07,2021-03-07,2021-03-15,2021-03-15,2021-03-15,2021-03-15,2021-03-15," + '\n' +
              "2021-03-02,2021-03-09,2021-03-07,2021-03-09,2021-03-09,";

String strT = Pattern.compile("\n").splitAsStream(strA)
        .map(strG -> String.valueOf(Pattern.compile(",").splitAsStream(strG).distinct().count()))
        .collect(Collectors.joining(","));

System.out.println(strT); // 2,2,3

Note that Pattern.compile("\n").splitAsStream(strA) can also be written as Arrays.stream(strA.split("\n")), which is shorter to write, but creates an unnecessary intermediate array. Matter of personal preference which is better.
String strT = Arrays.stream(strA.split("\n"))
        .map(strG -> String.valueOf(Arrays.stream(strG.split(",")).distinct().count()))
        .collect(Collectors.joining(","));

The first version can be further micro-optimized by only compiling the regex once:
Pattern patternComma = Pattern.compile(",");
String strT = Pattern.compile("\n").splitAsStream(strA)
        .map(strG -> String.valueOf(patternComma.splitAsStream(strG).distinct().count()))
        .collect(Collectors.joining(","));


text:
Q: UWP (Windows 10) application submission failed I am trying to publish an application to the windows store and it keeps failing. The error I receive is the following.

Could someone tell me what am I missing. There are no input fields in the first three pages to have placeholders. Placeholders in the other pages aren't long.

A: They mean a different definition of the word placeholder. In this case placeholder is not meant as specifically an TextBox placeholder, but rather a non-interactive UI or incomplete UI.
To give you an example of such placeholder - suppose you are building a restaurant recommendation app and you want to have a navigation feature there which will display a map that will show the user's current location and target location. You want to release a beta version of your app to testers but don't have this map implemented yet. So a placeholder would be if you placed a static image (screenshot) of a map in place where the active map control will be so that the tester sees what the UI will look like when finished, but otherwise the feature is missing.
In your case you should check if the first three pages actually work the way user expects or if they are not looking "as if they should do something" while they don't. If you are unsure what to do, post more details about what the app does and what is in these three pages.


text:
Q: App always crashes when editing video I'm trying to create a new app for editing video on iPhone, and using AVFoundation framework. When using AVMutableComposition and AVMutableVideoComposition to generate a video, the app crashed because of memory, is there any better way to edit video? or how to optimize it?
following is the code, I think it's mainly because the animatedTitleLayer I created, I add about 5 photos, to perform core animation.

    // Set up Core Animation layers to contribute a title animation overlay if we have a title set.
    if (self.titleText) {
        animatedTitleLayer = [self buildAnimatedTitleLayerForSize:videoSize];

        if (! forPlayback) {
            // For export: build a Core Animation tree that contains both the animated title and the video.
            CALayer *parentLayer = [CALayer layer];
            CALayer *videoLayer = [CALayer layer];
            parentLayer.frame = CGRectMake(0, 0, videoSize.width, videoSize.height);
            videoLayer.frame = CGRectMake(0, 0, videoSize.width, videoSize.height);
            [parentLayer addSublayer:videoLayer];
            [parentLayer addSublayer:animatedTitleLayer];

            if (! videoComposition) {
                // No transition set -- make a "pass through video track" video composition so we can include the Core Animation tree as a post-processing stage.
                videoComposition = [AVMutableVideoComposition videoComposition];

                [self buildPassThroughVideoComposition:videoComposition forComposition:composition];
            }

            videoComposition.animationTool = [AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];
        }
    }

    if (videoComposition) {
        // Every videoComposition needs these properties to be set:
        videoComposition.frameDuration = CMTimeMake(1, 30); // 30 fps
        videoComposition.renderSize = videoSize;
    }

Is there any other to convert core animation to video? in the above code, I have to add all photos at the same time.
There is an app, Splice video editor, did very good, fast and stable. What I'm going to do is almost the same as it, convert core animation to video, but slow and unstable.


text:
Q: How to write global event handler procedure that makes controls visible/enabled I store controls 'visible' and 'enabled' property in DB table. Depending on user's role I make some controls  not visible/enabled.
fields of db Table "Controls": id, role_id, form (varchar), comp_name(varchar), visible (boolean), enable (boolean)
query qControls: select * from controls where form=:form
calling of this procedure from OnShow of main form:
 application.CreateForm(TForm1, Form1);
 FORM := 'Form1';
 Form1.showModal;

Called procedure:
procedure RightsOnControls();
    var i:integer;

    begin
      fMain.qControls.Close;
      fMain.qControls.Params[0].AsString:= FORM; //FORM is global variable:  FORM:='Form1'
      fMain.qControls.Open;
      if fMain.qControls.RecordCount>0 then begin
        while not fMain.Controls.Eof do begin
          for I := 0 to form1.ControlCount - 1 do
            if uppercase(form1.Controls[i].Name)= uppercase(fMain.qControlsComp_name.AsString) then
               begin
                form1.Controls[i].Visible:=fmain.qControlsVisible.AsBoolean;
                form1.Controls[i].Enabled:=fmain.qControlsEnable.AsBoolean;
               end;
        fMain.qControls.next;
        end;
      end;
    end;

My questions are:

*

*how make procedure as general event handler,not for only Form1?

*It finds only controls located on form, not controls located on the panel/Page control (tabsheet). How change it?

A: Call this procedure with the form to handle (f.i. form1) and the query (fMain.qControls):
procedure RightsOnControls(AForm: TForm; AQuery: TFDQuery);

  function FindChildControl(Parent: TWinControl; const ControlName: string): TControl;
  var
    I: Integer;
  begin
    for I := 0 to Parent.ControlCount - 1 do begin
      Result := Parent.Controls[I];
      if SameText(Result.Name, ControlName) then Exit;

      if Result is TWinControl then begin
        Result := FindChildControl(TWinControl(Result), ControlName);
        if Result <> nil then Exit;
      end;
    end;
    Result := nil;
  end;

var
  ctl: TControl;
begin
  AQuery.Close;
  AQuery.Params[0].AsString := AForm.Name;
  AQuery.Open;
  while not AQuery.Eof do begin
    ctl := FindChildControl(AForm, AQuery.FieldByName('Comp_name').AsString);
    if ctl <> nil then begin
      ctl.Visible := AQuery.FieldByName('Visible').AsBoolean;
      ctl.Enabled := AQuery.FieldByName('Enable').AsBoolean;
    end;
    AQuery.next;
  end;
end;

In case you don't use FireDAC, change the query type to whatever is appropriate.


text:
Q: Exporting BIRT report into CSV I am Using BIRT for reporting in my project.
The report shows correct value for amount(String) as 123456789123, but when i try to export the same report into csv, the csv file shows same amount as 1.234E11.
I want to value as 123456789123 in csv too.
Please help
Thanks

A: I imagine this is probably an issue with viewing it in Excel.  Exporting data does not export format codes.  Open the csv in notepad and you will see the correct data.  If you export the report to excel you can set a custom format code like #####0 in the Format Number property in the properties editor for the data item.

A: If the number is too large excel will display the value like that. If you expand the column and set the column to number under format cells it will display correctly. You will need to save it as an excel workbook.

A: We just had this problem with the our BiRT reporting tool.  When we opened the exported file in a text editor the number was formatted in scientific notation.  This was a bug with one of Birt's custom formatters.
We had to look at org.eclipse.birt.report.engine.dataextraction.impl.CommonDataExtractionImpl and change the line
valueFormatters[i] = new NumberFormatter( patterns[i], this.locale );

to
String pattern = patterns[i] == null ? "Unformatted" : patterns[i];
valueFormatters[i] = new NumberFormatter( pattern, this.locale );

Setting the pattern to "Unformatted" made default format stay as a normal integer rather than scientific notation (via a decimal formatter).


text:
Q: "Way" vs "Ways" in a specific sentence I'm not sure if "way" or "ways" is correct in this sentence:

The ways power is used in factories varies by X, Y, and Z.

With X, Y, and Z describing different features of factories.
The context is a technical document about energy efficiency. This is in an intro, leading to more specifics on the different ways factories use energy and can be more efficient. That's why it says "The ways power is used". But it sounds a little odd - should it be "The way power is used"?

A: Both are correct. You  find sometimes  an accompanying adjective (several, various, different, many, etc.), as in "the * ways you have". (ngram)


text:
Q: Why am I getting 'Subquery returns more than 1row' error in my UNION ALL query? My query is like this:
SELECT 0 AS CNT1
      , COUNT(*) AS CNT2
FROM (
    SELECT (SELECT CANCEL_DTM FROM TR_LST_TABLE TLT2
            WHERE TLT1.CANCEL_NO = TLT2.PURCHASE_NO) CANCEL_DTM
           , TLT1.PURCHASE_DTM
    FROM TR_LST_TABLE TLT1
    WHERE TLT1.CLSS = 'CANCEL'
) A
WHERE DATE_FORMAT(A.CANCEL_DTM,'%m') != DATE_FORMAT(A.PURCHASE_DTM,'%m')
UNION ALL
SELECT COUNT(*) AS CNT1
      , 0 AS CNT2
FROM FROM TR_LST_TABLE TLT1
WHERE TLT1.CLSS = 'PURCHASE'

By separating UNION ALL, both queries normally come out in the form I want as follows.
CNT1              CNT2
----------------------
some number    some number

Then, if you do UNION ALL, I think it should come out in the form below,
CNT1              CNT2
----------------------
some number    some number
some number    some number

However, I do not understand why the error 'Subquery returns more than 1row' is emitted when UNION ALL is performed.
When I looked at my query, 'WHERE DATE_FORMAT(A.CANCEL_DTM,'%m') != DATE_FORMAT(A.PURCHASE_DTM,'%m')' If I don't have this part, I get the result I wanted, but I need a WHERE clause.
Is there any usage of UNION ALL query that I am not aware of?


text:
Q: What is a good way to prove that the function $\Bbb Z_n \rightarrow \Bbb Z_u \times\Bbb Z_v$ is well defined? Given a function of the type $\Bbb Z_n \rightarrow \Bbb Z_u \times\Bbb Z_v$ ($[x]_n\rightarrow([x]_u, [x]_v)$) where of course $n=u*v$ how can I prove that is a well defined function?

A: For $f:\mathbb{Z}_n\to\mathbb{Z}_u\times\mathbb{Z}_v$, $[x]_n\mapsto ([x]_u, [x]_v)$
It might go like this:
To prove that this function is well-defined, we have to check if it really does not matter which representative of the equivalence class we choose.
So let $[x]_n=[y]_n$. Then $x=nk+r$ and $y=nl+r$ with $0\leq r<n$.
Now $f([x]_n-[y]_n)=f([x-y]_n)=([x-y]_u, [x-y]_v)\stackrel{x-y=n(k-l)}{=}([n(k-l)]_u, [n(k-l)]_v)\stackrel{n=uv}{=}([0]_u,[0]_v)$


text:
Q: CSS variables - How to use multiple variables on the same property? Using CSS variables, we can use the following:
style="
  opacity:var(--SOMETHING, 1)
  ">

But, how to use multiple such variables, for the same property (e.g. opacity), as in the not-working:
style="
  opacity:var(--SOMETHING, 1);
  opacity:var(--ANOTHERTHING, 1)
  ">

In fact, because I am using SVGs, in my particular use-case, I can solve this by using the working:
style="
  opacity:var(--SOMETHING, 1);
  fill-opacity:var(--ANOTHERTHING, 1)
  ">

But this will ONLY solve it because we used two variables only. For three variables, this hack stops being possible. How to make the following work?
style="
  opacity:var(--SOMETHING, 1);
  opacity:var(--ANOTHERTHING, 1);
  opacity:var(--YETSOMETHINGELSE, 1)
  ">

Here's a MWE code snippet:

.HIDDEN_LAYER{
  visibility:hidden;
  opacity:0;
}
.CLICKME_TICKBOX{
  fill:white;
  stroke:black;
}
.CLICKED_TICKBOX{
  fill:white;
  stroke:black;
}
.CLICKME_TEXTS{
  font-family:sans-serif;
  font-size:16px;
}
.CLICKED_TEXTS{
  font-family:sans-serif;
  font-size:16px;
  stroke:black;
  stroke-width:0.5;
}
.BOTTOM-LAYER_RECTANGLES{
  fill:white;
  stroke:black;
}
.ZZZ_RECTANGLES{
  visibility:hidden;
  cursor:help;
  fill:yellow;
  stroke:black;
  --QQQ_SOMETHING_AAA: 0.7;
  --QQQ_SOMETHING_BBB: 0.2;
}
.FFF_RECTANGLES{
  visibility:hidden;
  cursor:help;
  fill:red;
  stroke:black;
  --PPP_SOMETHING_AAA: 0.2;
  --PPP_SOMETHING_BBB: 0.7;
}
.LEGENDBOX_ZZZ{
  fill:yellow;
  stroke:black;
}
.LEGENDBOX_FFF{
  fill:red;
  stroke:black;
}
.LEGENDS{
  cursor:pointer;
}
<svg id="SVG"
  version="1.1"
  xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  width="1320"
  height="1125"
  viewBox="-15 -45 1350 1155">

<symbol id="SOMETHING_AAA">
<use
  xlink:href="#RECTANGLE"
  transform="translate(637.5, 25)"
  style="
  opacity:var(--QQQ_SOMETHING_AAA, 1);
  fill-opacity:var(--PPP_SOMETHING_AAA, 1)
  ">
</use>
</symbol>
<symbol id="SOMETHING_BBB">
<use
  xlink:href="#RECTANGLE"
  transform="translate(15, 215)"
  style="
  opacity:var(--QQQ_SOMETHING_BBB, 1);
  fill-opacity:var(--PPP_SOMETHING_BBB, 1)
  ">
</use>
</symbol>

<g class="BOTTOM-LAYER_RECTANGLES">
<use xlink:href="#SOMETHING_AAA" />
<use xlink:href="#SOMETHING_BBB" />
</g>

<g class="ZZZ_RECTANGLES">
<use xlink:href="#SOMETHING_AAA">
<title>Something here 111.</title>
</use>
<use xlink:href="#SOMETHING_BBB">
<title>Something here 222.</title>
</use>
<set
  to="visible"
  attributeType="CSS"
  attributeName="visibility"
  end="CLICKED_ZZZ.click;bg.click"
  begin="CLICKME_ZZZ.click" />
<set
  to="1"
  attributeType="CSS"
  attributeName="opacity"
  end="CLICKED_ZZZ.click;bg.click"
  begin="CLICKME_ZZZ.click" />
</g>

<g class="FFF_RECTANGLES">
<use xlink:href="#SOMETHING_AAA">
<title>Something here 333.</title>
</use>
<use xlink:href="#SOMETHING_BBB">
<title>Something here 444.</title>
</use>
<set
  to="visible"
  attributeType="CSS"
  attributeName="visibility"
  end="CLICKED_DDD.click;bg.click"
  begin="CLICKME_DDD.click" />
<set
  to="1"
  attributeType="CSS"
  attributeName="opacity"
  end="CLICKED_DDD.click;bg.click"
  begin="CLICKME_DDD.click" />
</g>

<g id="LEGENDS"
  class="LEGENDS"
  transform="translate(15, -15)">

<g id="ZZZ">
<g id="CLICKME_ZZZ">
<rect id="CLICKME_TICKBOX_ZZZ"
  class="CLICKME_TICKBOX"
  x="0"
  y="0"
  width="15"
  height="15">
</rect>
<use id="CLICKME_LEGENDBOX_ZZZ"
  class="LEGENDBOX_ZZZ"
  x="30"
  y="-5"
  xlink:href="#LEGENDBOX">
</use>
<text id="CLICKME_TEXT_ZZZ"
  class="CLICKME_TEXTS"
  x="65"
  y="12.5">
Click me
</text>
</g>
<g id="CLICKED_ZZZ"
  class="HIDDEN_LAYER">
<use id="CLICKED_TICKBOX_ZZZ"
  x="0"
  y="0"
  xlink:href="#CLICKED_TICKBOX">
</use>
<use id="CLICKED_LEGENDBOX_ZZZ"
  class="LEGENDBOX_ZZZ"
  x="30"
  y="-5"
  xlink:href="#LEGENDBOX">
</use>
<text id="CLICKED_TEXT_ZZZ"
  class="CLICKED_TEXTS"
  x="65"
  y="12.5">
Click me
</text>
<set
  to="visible"
  attributeType="CSS"
  attributeName="visibility"
  end="CLICKED_ZZZ.click;bg.click"
  begin="CLICKME_ZZZ.click" />
<set
  to="1"
  attributeType="CSS"
  attributeName="opacity"
  end="CLICKED_ZZZ.click;bg.click"
  begin="CLICKME_ZZZ.click" />
</g>
<animate id="ZZZ_ANIMATE"
  fill="freeze"
  dur="3s"
  keyTimes="0;1"
  values="0;1"
  attributeType="CSS"
  attributeName="opacity" />
</g>

<g id="DDD"
   transform="translate(0,40)">
<g id="CLICKME_DDD">
<rect id="CLICKME_TICKBOX_FFF"
  class="CLICKME_TICKBOX"
  x="0"
  y="0"
  width="15"
  height="15">
</rect>
<use id="CLICKME_LEGENDBOX_FFF"
  class="LEGENDBOX_FFF"
  x="30"
  y="-5"
  xlink:href="#LEGENDBOX">
</use>
<text id="CLICKME_TEXT_FFF"
  class="CLICKME_TEXTS"
  x="65"
  y="12.5">
Click me
</text>
</g>
<g id="CLICKED_DDD"
  class="HIDDEN_LAYER">
<use id="CLICKED_TICKBOX_FFF"
  x="0"
  y="0"
  xlink:href="#CLICKED_TICKBOX">
</use>
<use id="CLICKED_LEGENDBOX_FFF"
  class="LEGENDBOX_FFF"
  x="30"
  y="-5"
  xlink:href="#LEGENDBOX">
</use>
<text id="CLICKED_TEXT_FFF"
  class="CLICKED_TEXTS"
  x="65"
  y="12.5">
Click me
</text>
<set
  to="visible"
  attributeType="CSS"
  attributeName="visibility"
  end="CLICKED_DDD.click;bg.click"
  begin="CLICKME_DDD.click" />
<set
  to="1"
  attributeType="CSS"
  attributeName="opacity"
  end="CLICKED_DDD.click;bg.click"
  begin="CLICKME_DDD.click" />
</g>
<animate id="DDD_ANIMATE"
  fill="freeze"
  dur="3s"
  keyTimes="0;1"
  values="0;1"
  attributeType="CSS"
  attributeName="opacity" />
</g>

</g>

<defs id="DEFINITIONS">
<rect id="RECTANGLE"
  width="85"
  height="95">
</rect>
<rect id="RECTANGLE_YELLOW"
  width="42.5"
  height="95">
</rect>
<rect id="LEGENDBOX"
  x="0"
  y="0"
  width="25"
  height="25">
</rect>
<path id="CLICKED_TICKBOX"
  class="CLICKED_TICKBOX"
  d="M 0,0 15,15 M 0,15 15,0 M 0,0 15,0 15,15 0,15 Z"/>
</defs>

Note that it is working because, in the MWE, I alternate between "opacity:var" and "fill-opacity:var". I DO NOT WANT TO DO THAT, I want to use fill-opacity ONLY, because there might need to be further instances of the "click me" added.


text:
Q: JQuery aplicar a mesma função em uma div duplicada Bom dia, estou aprendendo a programar em JS e JQuery e me deparei com um problema que ainda não consegui resolver. Usando PHP estou colocando dentro de um laço While uma tag DIV e uma tag SPAN, e dentro da span um valor trazido do banco de dados, desse jeito:
 while ($row_ano = $ne->fetch(PDO::FETCH_ASSOC)){

    ?>

            <?php echo  $row_ano['nota'] ?>

<?php
}
?>

Nesse laço, ele repete essa div duas vezes, e com dois valores diferentes, somente dois valores. Eu planejava fazer com que o JQuery pegasse o valor dentro do Span e caso fosse menor que 6 a div ficasse vermelha, caso maior azul (essa div, no caso, é um circulo). Com isso, eu fiz isso:

    var color = $.each($("#text"), function() {  //o text é o id do span
    var nota = $("#nota").text(color);           //o nota é o id da div
    console.log(color);

    for (color=0;color < 6;color++){
        $("#nota").removeClass("badge bg-primary text-wrap");
        $("#nota").addClass("badge bg-danger text-wrap");
    }
        color++;
    });

O meu problema é: Que se eu colocar dois valores menores que 6, somente uma das div fica vermelha, enquanto a outra continua azul, ou seja, esse trecho de código só está modificando somente uma div, enquanto ele deveria modificar as duas caso o valor fosse um número inferior a 6. Se alguém puder me ajudar a melhorar meu código ou a encontrar uma solução vou ficar muito grato.
espero que alguém consiga entender o codigo, deve tá todo errado, tentei várias vezes resolver isso :(

A: Primeiro erro que está acontecendo, você não pode ter mais de um ID com o mesmo nome, quando precisamos ter mais de um seletor com o mesmo nome, usamos as classes.
Para acessar a tag pai, utilizamos a função parent e nela, adicionamos a classes necessária.
Eu acabei removendo o atributo style, pois não devemos adicionar estilização direto na tag, é recomendado criar uma classe para essa estilização.

        <?php echo  $row_ano['nota'] ?>

$.each($(".valor-nota"), function() {
    var valorNota = $(this).html()

    if(valorNota < 6){
        $(this).parent().removeClass('bg-primary').addClass('bg-danger')
    } else {
        $(this).parent().removeClass('bg-danger').addClass('bg-primary')
    }
});


text:
Q: Close Dropzone on button 'Save' click
I'm using Dropzone plugin for uploading images, and I have a little problem with it. After clicked 'Save' button, files POST to the server, but popup still shows in the browser. So, I'm wondering, if this is normal plugin behaviour, and if it's not, could I listen to the click event on 'Save' button, and close a popup after it?
EDITED
My html

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Edit Resource

                <button form="resource-creator" type="reset" class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
                <button form="resource-creator" type="submit" class="btn btn-success" data-loading-text="Proceed...">Save</button>

Initialization of the Dropzone
initFileUpload: function() {
    if (this.dropzone) return;

    this.dropzone = new Dropzone(this.$('.dropzone-box').get(0), {
        url: this.options.url.fileUpload,

addRemoveLinks : true,
            maxFiles: 1,
            acceptedFiles: '.jpg, .mp4',
            dictResponseError: "Can't upload file!",
            thumbnailWidth: 138,
            thumbnailHeight: 120,

            previewTemplate: $('#drop-item-preview').html()
        });

        this.dropzone.on('complete', this._onUploadFileComplete.bind(this));
    }

A: As you wasn't able to post complete codes related to the uploader, not able to give you solution based on your uploader. But, if you understand the below code, you'll be able to achieve what you are trying to.
this.on("complete", function (file) {
    if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
        // Some options to hide the Container or Modal
        $('#file-uploader-container').hide(); // If the uploader is in a Container hide it
        $('#file-uploader-modal').hide(); //If your uploader is in a Bootstrap modal, hide it by applying Display none on the Modal.
        $('#file-uploader-modal').modal('hide'); //By closing modal programmatically.
        $('#file-uploader-modal #btn-close').trigger('click');  // By triggering Modal's close button (give an ID to call it)
    }
});

Depending on your need, apply script on the container or modal. Wish it will solve your issue.


text:
Q: Rechart xAxis label overflow bug I am having an issue with recharts library, in this case BarChart component
What i want to achieve is to customize the label text in xAxis, i already created a custom component for tick, to make text too long having ellipsis or something like this, but seems i can't do anything for text overflow or decide any size.
Here's my code so far:
function renderTicks(props) {
  console.log(props)
  const space = props.width / props.visibleTicksCount
  console.log(space)
  const stringLength = props.payload.value.length * 7
  console.log(stringLength)
  return (
    <text
    style={{ fontSize: 10 }}
    width={70} verticalAnchor="start" textAnchor="middle" x={props.x} y={props.y}>{props.payload.value}</text>
  )
}

function BarChart({ config = {}, data = {} }) {
  console.log(data)
  return (
    <StyledChart width={450} height={450} data={data} >
      <XAxis
        tick={renderTicks}
        height={100}
        interval={0} dataKey="name" >
        <Label value="" content={<LabelCustom />} />
      </XAxis>
      <YAxis />
      <Tooltip />
      <Bar dataKey="value" fill={colorsChart[0]} />
    </StyledChart>
  );
}

Here is the current behaviour:

I found lot of problem like this browsering the problem but not valid solution,
any tip is appreciated


text:
Q: Calculate proportions within groups in a data frame in R I have the following data frame in R. For this experiment I was testing the survival of cells at several times with 2 treatments, and 2 replicates for each treatment. I want to calculate the percentage of cells alive at each time for each treatment/replicate.
For example, for Treat 1 Rep 1 it would be 500/500, 470/500, 100/500, 20/500, for Treat 2 Rep 1 it would be 430/430, 420/430, 300/430, 100/430
Thanks!
x <- data.frame("treatment"= c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2),
                "rep"=c(1,1,1,1,2,2,2,2,1,1,1,1,2,2,2,2),
                "Time" = c(0, 30, 60, 180, 0, 30, 60, 180, 0, 30, 60, 180,0, 30, 60, 180 ),
                "cells_alive" = c(500, 470, 100, 20, 476, 310, 99, 2, 430, 420, 300, 100, 489, 451, 289, 4))

A: We can group by 'treatment', 'rep', calculate the 'prop'ortion by dividing the 'cells_alive' with the value of 'cells_alive' that correspond to 'Time' as 0
library(dplyr)
x1 <- x %>%
   group_by(treatment, rep) %>%
   mutate(prop = cells_alive/cells_alive[Time == 0])

-output
x1
# A tibble: 16 x 5
# Groups:   treatment, rep [4]
#   treatment   rep  Time cells_alive    prop
#       <dbl> <dbl> <dbl>       <dbl>   <dbl>
# 1         1     1     0         500 1
# 2         1     1    30         470 0.94
# 3         1     1    60         100 0.2
# 4         1     1   180          20 0.04
# 5         1     2     0         476 1
# 6         1     2    30         310 0.651
# 7         1     2    60          99 0.208
# 8         1     2   180           2 0.00420
# 9         2     1     0         430 1
#10         2     1    30         420 0.977
#11         2     1    60         300 0.698
#12         2     1   180         100 0.233
#13         2     2     0         489 1
#14         2     2    30         451 0.922
#15         2     2    60         289 0.591
#16         2     2   180           4 0.00818

Or with match
x %>%
     group_by(treatment, rep) %>%
     mutate(prop = cells_alive/cells_alive[match(0, Time)])

if the 'Time' is already ordered
x %>%
     group_by(treatment, rep) %>%
     mutate(prop = cells_alive/first(cells_alive))


text:
Q: What book is set on a giant space ship with the captain infested by a parasite? The novel has several story lines going on at the same time.
The one I remember the most is inside a giant spaceship, we are talking many km long. The captain of the ship is kept frozen due to a parasite that spreads when he is unfrozen. The main character seeks his advice from time to time by thawing him a little so his brain is active enough to talk on the machine.
He acquired the parasite when he and another crew member went into a sea of aliens/information. Later on, it was revealed that the captain actually replaced the crew member's mind with his own when they were in the sea. In the end he was thawed and the parasite took over the ship.
Another story line had something to do with ancient alien ruins and advanced aliens hiding behind black holes that would kill off life in the galaxy every once in a while.

A: That's definitely Revelation Space by Alastair Reynolds, which is the first of a series. A couple of names that may ring a bell and confirm it: the captain's infection is called the Melding Plague and the Inhibitors kill off life in the galaxy.


text:
Q: Javascript activeElement doesen't work for dynamically created text-fields I'm trying to create dynamically text fields when some text is entered to the text field. At first it created new textfield after every keystroke, but i tried to narrow it down so it would create one text-field per text-field.
To explain with a brief example, what i want to get is that in the beginning i have textfield A. If something is typed in textfield A then textfield B is created under textfield A. If something is typed in textfield B then textfield C is created under textfield B, and so on until the user leaves the last one empty.
What's wrong is the activeElement does not get chosen for dynamically created element. My idea was that when another textfield gets selected it will become (should've become) an activeElement with a length of a zero thus changing createNew to true and allowing it to create new textfield.
I hope i explained clearly what i'm trying to achieve, but English is not my mother-tongue so it's a bit difficult. I may be approaching this problem with a bad perspective so if someone has a better idea how to create text fields dynamically i'm open to different options. I did some googling before and didn't find much about that particular idea.
Anyways, here's my js.
//This is the javascript for the namepage.html
var createNew = true;

function getNewInsertion() {
    var container = document.getElementById("inputcontainer");

    if (document.activeElement.value.length == 0 && createNew == false){
        createNew = true;
    }
    else if (createNew == true){
        createNew = false;
        var input = document.createElement("input");
        input.type = "text";
        input.className = "form-control text-controller"; // set the CSS class
        input.placeholder = "Sisesta siia nimi";
        container.appendChild(input);
    }

    return createNew;
}

$(function() {
    $(".text-controller").bind("paste cut keydown",function(e) {
        getNewInsertion();

    })

});

A: You should delegate the event on the container:
$(function() {
    $("#inputcontainer").on( "paste cut keydown", "input", function(e) {
        getNewInsertion();
    })
});

Here I leave you a snippet:

var createNew = true;

function getNewInsertion() {
    var container = document.getElementById("inputcontainer");

  if (document.activeElement.value.length == 0 && createNew == false){
        createNew = true;
    }
    else if (createNew == true){
        createNew = false;
        var input = document.createElement("input");
        input.type = "text";
        input.className = "form-control text-controller"; // set the CSS class
        input.placeholder = "Sisesta siia nimi";
        container.appendChild(input);
    }

    return createNew;
}

$(function() {
    $("#inputcontainer").on( "paste cut keydown", "input", function(e) {
        getNewInsertion();
    })

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inputcontainer">
  <input type="text" class="text-controller" />
</div>


text:
Q: How to Unlock image files and delete it from specific folder? cannot delete image files in folder. i know it locked and used by another process but i dont know which process holding it and how to unlock the image files so i can delete it. tried to guess by putting .Dispose() method in every loop ending but no luck. >_<
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

using System.Net;
using System.Drawing;
using System.IO;

using AForge.Video;
using AForge.Video.VFW; //video recording

namespace example
{
    public partial class LiveRecording2 : System.Web.UI.Page
    {
        AVIWriter writer = new AVIWriter("MSVC");

        protected void Page_Load(object sender, EventArgs e)
        {

        }

         private void Get1Image()
        {
             for (int i = 0; i < 11; i++)
             {
                string ImagePath = Server.MapPath("~\\Videos\\liveRecording2\\") + string.Format("{0}", i + 1) + ".jpg";
                string ip = "http://example.ip.com:portNo/jpeg.cgi";
                string sourceURL = ip;
                WebRequest req = (WebRequest)WebRequest.Create(sourceURL);
                req.Credentials = new NetworkCredential("userName", "password");
                WebResponse resp = req.GetResponse();
                Stream stream = resp.GetResponseStream();
                Bitmap bmp = (Bitmap)Bitmap.FromStream(stream);
                bmp.Save(ImagePath);
            }
        }

        private void doRecording()
        {
            string ImagePath = Server.MapPath("~\\Videos\\liveRecording2\\");
            string SavingPath = Server.MapPath("~\\Videos\\liveRecording2\\"); //recorded video path
            string VideoName = "ICS-" + String.Format("{0:yyyyMMdd_hhmmss}", DateTime.Now) + ".avi";
            writer.Open(SavingPath + VideoName, 640, 480); //create an AVI file and open it for images adding

            // create frame image
            Bitmap image = new Bitmap(320, 240);
            //var cubit = new AForge.Imaging.Filters.ResizeBilinear(320, 240);
            string[] files = Directory.GetFiles(ImagePath);
            writer.FrameRate = 25;
            int index = 0;
            int failed = 0;
            foreach (var item in files)
            {
                index++;
                try
                {
                    image = Image.FromFile(item) as Bitmap;
                    //image = cubit.Apply(image);

                    for (int i = 0; i < 5; i++)
                    {
                        writer.AddFrame(image);
                    }
                }
                catch
                {
                    failed++;
                }
                //this.Text = index + " of " + files.Length + ". Failed: " + failed;
             }
            writer.Close();
            writer.Dispose();
            this.Label1.Text = "status: Video was successfully created";
            this.Label2.Text = "Video Path: ~/Videos/liveRecording2/" + VideoName;
            DeleteImage();
        }

       protected void Button1_Click(object sender, EventArgs e)
        {
            Get1Image();
            doRecording();
        }

        public void DeleteImage()
        {
            DirectoryInfo di = new DirectoryInfo(Server.MapPath("~\\Videos\\liveRecording2\\"));
            FileInfo[] files = di.GetFiles("*.jpg");
                             //.Where(p => p.Extension == ".jpg").ToArray();
            foreach (FileInfo file in files)
            {
                file.Delete(); // **error here**
            }

            this.Label3.Text = "Image deleted";
        }
    }
}

A: Your problem is probably here:
image = Image.FromFile(item) as Bitmap;

Try wrapping that bit of code in a using:
using(image = Image.FromFile(item) as Bitmap)
{
   //  rest here
}


text:
Q: Converting Array[(Double,Double)] to Seq[Seq[Double]] I am fairly new to Scala and I have to use a function which takes as argument of type Seq[Seq[Double]]. However, my data has the type Array[(Double,Double)].
I tried using .toSeq to convert the data, but that doesn't work.
Any fixes in this regard would be highly appreciated. Thanks!

A: val input: Array[(Double, Double)] = ...
val output: Seq[Seq[Double]] = input.map { case (x, y) => Seq(x, y) }

Unfortunately, there is no generic way to type-safely convert a tuple to a list in the standard library. shapeless, however, does provide this functionality:
import shapeless.syntax.std.tuple._

val input: Array[(Double, Double)] = ...
val output: Seq[Seq[Double]] = input.map(_.toList)

Shapeless is smart enough to compute a lowest upper bound in case your tuple contains components of different types:
val input: Array[(Double, Int)] = ...
// AnyVal is the closest type which both Double and Int are subtypes of
val output: Seq[Seq[AnyVal]] = input.map(_.toList)

Finally, there is a non-type-safe way to do this using only the standard library tools. You can rely on the fact that all tuples in Scala implement the Product trait and therefore are iterable as collections of Any:
val input: Array[(Double, Double)] = ...
val output: Seq[Seq[Double]] = input.map(_.productIterator.toSeq.asInstanceOf[Seq[Double]])

This is safe as long as you're careful, but it does require an explicit cast and it is more verbose.
If you have fixed-length tuples of relatively small size, then I'd say it is better to use the partial function-based approach. Otherwise, it is up to you, but I'd use shapeless because it is type safe, and I also use shapeless in many of my projects for other things as well, so it is kind of free for me :)


text:
Q: Python: Overflow encountered in double-scalars I have a system of 5 differential equations that I am solving using odeint and I am running into divide by zero error in one of my differential equations. To by pass it, I tried two methods-
(a) one creating a function and returning 0.1 if denominator ever hit 0
(b) adding a small positive number to the denominator.
However both are not giving me desired results.
When I am not using either of these two solution, my code is running properly and I am getting desired graphs till the denominator goes 0. I have also attached the graphs. As we can see, the graphs are getting drawn correctly till just after 3 seconds after which the value becomes "nan" due to divide by zerror. Kindly help me get rid of this problem! Thanks in advance
PFA
My code is
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

t=np.linspace(0,250,10000)
c=5
k=50
eta=2.5
gamma,gamma1,gamma2=10,9,10
b,a1,a2=2,3,4
def check(x1,u,a1,x2,a2,b):
    return (.1 if np.sin(x1)==0 else b*(1/(np.sin(x1)))*u-a1*x2-a2*x1**2)

def f(Y,t):
    x1,x2,h,h1,h2=Y[0],Y[1],Y[2],Y[3],Y[4]
    #x"+a1x'+a2x^2=bcosec(x)u
    e=x1-np.sin(t)
    de=x2-np.cos(t)
    s=c*e+de
    u=-k*s-eta*np.tanh(s)+s*h1*x2+np.sin(x1)*h2*x1**2-np.sin(x1)*h*np.sin(t)-h*np.sin(t)*c*de-h*np.cos(x1)*s/2
    x1dot=x2
    #x2dot=b*(1.0/(np.sin(x1)+1e-8))*u-a1*x2-a2*x1**2
    x2dot=check(x1,u,a1,x2,a2,b)
    hdot=gamma*(s*np.tanh(10*np.sin(x1))*(s*np.cos(x1)/2+np.sin(x1)*np.sin(t)-np.sin(x1)*c*de))
    h1dot=gamma1*(s*np.tanh(10*np.sin(x1))*np.sin(x1)*x2)
    h2dot=gamma2*(s*np.tanh(10*np.sin(x1))*np.sin(x1)*x1**2)
    return[x1dot,x2dot,hdot,h1dot,h2dot]

y0=[0.1,0.2,0,0,0]
sol=odeint(f,y0,t,mxstep=500000,atol=1e-6)
x=sol[:,0]
xd=sol[:,1]
h=sol[:,2]
h1=sol[:,3]
h2=sol[:,4]
e,de=x-np.sin(t),xd-np.cos(t)
s=c*e+de
u=-k*s-eta*np.tanh(s)+s*h1*xd+np.sin(x)*h2*x**2-np.sin(x)*h*np.sin(t)-h*np.sin(t)*c*de-h*np.cos(x)*s/2
plt.subplot(2,3,1)
plt.plot(t,x,t,e,'r--')
plt.subplot(2,3,2)
plt.plot(x,xd)
plt.subplot(2,3,3)
plt.plot(t,u)
plt.subplot(2,3,4)
plt.plot(t,h)
plt.subplot(2,3,5)
plt.plot(t,h1)
plt.subplot(2,3,6)
plt.plot(t,h2)
print(x)
plt.show()

A: in check you have
    if np.sin(x1)==0

which compares a numpy floating point family value to an integer for an exact match.  While mathematically you only get an undefined value for the inverse of 0, in computer floating point taking the inverse of a very small number can drive you into something that is larger than can be represented.  Try checking if your sine is less than math.exp(math.log(2.0) * -32.0). This value is something small that can be represented exactly as a float in binary, which would not be true of a decimal like 0.000000001 converted to a binary floating point number.


text:
Q: ReadFile code using Win32 API to read from serial port very slow I'm trying to read 2048 samples from an nRF52832 chip via COM port on my PC. I have connected the UART pins from the nRF-chip to the computer using a UART-to-USB cable. I have been able to printf and NRF_LOG_INFO from it previously at a baud rate of 921600. Now that I want to do something with the data, in real time, I need to read it myself. But when I run the attached code (see below), it takes over 15 seconds to read these samples, that should have been read in about 1 second.
Any ideas on how to make this code run faster?
(the real-time aspect will be added later, for now my goal is to get the program to read fast enough)
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdint.h>
#include <time.h>

#define SUCCESS 0
#define BUF_SIZE 2048

char* hComm_init_error_modes[7] = {"",             //NOT INTENDED FOR USE
                                   "",             //NOT INTENDED FOR USE
                                  "ERROR OPENING SERIAL PORT\n",
                                  "ERROR RETRIEVING COMM STATE\n",
                                  "ERROR CONFIGURING COMM STATE\n",
                                  "ERROR RETRIEVING COMM TIMEOUTS\n",
                                  "ERROR CONFIGURING COMM TIMEOUTS\n",};

HANDLE hComm;

uint8_t m_buf[BUF_SIZE];
uint8_t single_val_buf[1];
//int m_buf_full = 0;

int hComm_init(char* port){

    hComm = CreateFileA(port,                           //PORT NAME
                        GENERIC_READ | GENERIC_WRITE,   //READ/WRITE
                        0,                              //NO SHARING
                        NULL,                           //NO SECURITY
                        OPEN_EXISTING,                  //OPEN EXISTING PORT ONLY
                        0,                              //NON OVERLAPPED I/O
                        NULL);                          //NULL FOR COMM DEVICES

    if (hComm == INVALID_HANDLE_VALUE){
        return 2;
    }

    DCB commStateConfig;

    if (!GetCommState(hComm, &commStateConfig)){
        return 3;
    }

    commStateConfig.BaudRate = 921600;
    commStateConfig.ByteSize = 8;

    if (!SetCommState(hComm, &commStateConfig)){
        return 4;
    }

    COMMTIMEOUTS comm_timeouts;

    if (!GetCommTimeouts(hComm, &comm_timeouts)){
        return 5;
    }

    comm_timeouts.ReadIntervalTimeout = 0;
    comm_timeouts.ReadTotalTimeoutMultiplier = 0;
    comm_timeouts.ReadTotalTimeoutConstant = 1;
    comm_timeouts.WriteTotalTimeoutMultiplier = 0;
    comm_timeouts.WriteTotalTimeoutConstant = 0;

    if (!SetCommTimeouts(hComm, &comm_timeouts)){
        return 6;
    }

    return 0;
}

int main(int argc, char* argv[]){
    if (argc != 2){
        printf("\nWrong number of inputs! Please provide the com port number and nothing else.\n");
        return 1;
    }
    char portname[11+strlen(argv[1])];
    strcpy(portname, "\\\\.\\COM");
    strcat(portname, argv[1]);

    int err = hComm_init(portname);

    if (err != SUCCESS){
        printf("%s", hComm_init_error_modes[err]);
        goto RUNTIME_ERROR;
    }

    printf("OPENED AND CONFIGURED SERIAL PORT SUCCESSFULLY\n");

    if (!SetCommMask(hComm, EV_RXCHAR | EV_ERR)){
        printf("SetCommMask failed with error code: %ld\n", GetLastError());
        goto RUNTIME_ERROR;
    }

    DWORD dwEvtMask;
    DWORD read;
    int readcount = 0;

    while (1){
        read = 0;
        dwEvtMask = 0;

        if(kbhit()) //Check for key press
        {
            if(27 == getch()) // ESC pressed
            {
                printf("Key ESC pressed, exiting...\n");
                goto CLEAN_EXIT;
            }
        }

        if (WaitCommEvent(hComm, &dwEvtMask, NULL))
        {

            if (dwEvtMask & EV_ERR)
            {
                printf("Wait failed with error %ld.\n", GetLastError());
                goto RUNTIME_ERROR;
            }

            if (dwEvtMask & EV_RXCHAR)
            {
                if(!ReadFile(hComm, single_val_buf, 1, &read, NULL)){
                    printf("\n\nERROR when reading\n\n");
                }
                m_buf[readcount] = *single_val_buf;
                readcount++;
            }

            if (readcount == BUF_SIZE){
                double diff_ms = (clock()-start) * 1000. / CLOCKS_PER_SEC;
                print_m_buf(); //for testing only, remove later
                printf("Time spent reading: %f ms\n", diff_ms);
                goto CLEAN_EXIT;
            }
        } else {
            DWORD dwRet = GetLastError();
            if( ERROR_IO_PENDING == dwRet)
            {
                printf("I/O is pending...\n");

                // To do.
            }
            else
                printf("Wait failed with error %ld.\n", GetLastError());
        }
    }

CLEAN_EXIT:
    CloseHandle(hComm);
    return 0;

RUNTIME_ERROR:
    printf("Runtime error, program exited.\n");
    CloseHandle(hComm);
    return -1;
}

A: The code only reads a single byte on each iteration. This is very slow.
You're using an extra intermediate buffer (e.g. single_val_buf). Better/easier to read directly into the m_buf target buffer (i.e. no need to copy the bytes).
The code also polls the keyboard on every iteration. The important part is to keep up with the data and excessive keyboard polling can slow things down. Better to poll the keyboard periodically (e.g. every so many iterations).
Side note: goto is ugly/bad style and is easily refactored.

Here's some refactored code. It is annotated
I've used cpp conditionals to denote old vs new code:
#if 0
// old code
#else
// new code
#endif

Anyway, here is the code:
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdint.h>
#include <time.h>

#define SUCCESS 0
#define BUF_SIZE 2048

char *hComm_init_error_modes[7] = {
    "", // NOT INTENDED FOR USE
    "", // NOT INTENDED FOR USE
    "ERROR OPENING SERIAL PORT\n",
    "ERROR RETRIEVING COMM STATE\n",
    "ERROR CONFIGURING COMM STATE\n",
    "ERROR RETRIEVING COMM TIMEOUTS\n",
    "ERROR CONFIGURING COMM TIMEOUTS\n",
};

HANDLE hComm;

uint8_t m_buf[BUF_SIZE];
// NOTE/BUG: not needed -- we can read directly into m_buf
#if 0
uint8_t single_val_buf[1];
#endif

//int m_buf_full = 0;

int
hComm_init(char *port)
{

    hComm = CreateFileA(port,           // PORT NAME
        GENERIC_READ | GENERIC_WRITE,   // READ/WRITE
        0,                              // NO SHARING
        NULL,                           // NO SECURITY
        OPEN_EXISTING,                  // OPEN EXISTING PORT ONLY
        0,                              // NON OVERLAPPED I/O
        NULL);                          // NULL FOR COMM DEVICES

    if (hComm == INVALID_HANDLE_VALUE) {
        return 2;
    }

    DCB commStateConfig;

    if (!GetCommState(hComm, &commStateConfig)) {
        return 3;
    }

    commStateConfig.BaudRate = 921600;
    commStateConfig.ByteSize = 8;

    if (!SetCommState(hComm, &commStateConfig)) {
        return 4;
    }

    COMMTIMEOUTS comm_timeouts;

    if (!GetCommTimeouts(hComm, &comm_timeouts)) {
        return 5;
    }

    comm_timeouts.ReadIntervalTimeout = 0;
    comm_timeouts.ReadTotalTimeoutMultiplier = 0;
    comm_timeouts.ReadTotalTimeoutConstant = 1;
    comm_timeouts.WriteTotalTimeoutMultiplier = 0;
    comm_timeouts.WriteTotalTimeoutConstant = 0;

    if (!SetCommTimeouts(hComm, &comm_timeouts)) {
        return 6;
    }

    return 0;
}

int
main(int argc, char *argv[])
{
    if (argc != 2) {
        printf("\nWrong number of inputs!"
            " Please provide the com port number and nothing else.\n");
        return 1;
    }
    char portname[11 + strlen(argv[1])];

    strcpy(portname, "\\\\.\\COM");
    strcat(portname, argv[1]);

    int err = hComm_init(portname);

    if (err != SUCCESS) {
        printf("%s", hComm_init_error_modes[err]);
        goto RUNTIME_ERROR;
    }

    printf("OPENED AND CONFIGURED SERIAL PORT SUCCESSFULLY\n");

    if (!SetCommMask(hComm, EV_RXCHAR | EV_ERR)) {
        printf("SetCommMask failed with error code: %ld\n", GetLastError());
        goto RUNTIME_ERROR;
    }

    DWORD dwEvtMask;
    DWORD read;
    int readcount = 0;

#if 1
    int ret = 0;
    unsigned int iter = 0;
#endif

    while (1) {
        ++iter;
        read = 0;
        dwEvtMask = 0;

        // Check for key press
        if (((iter % 1024) == 1) && kbhit()) {
            // ESC pressed
            if (27 == getch()) {
                printf("Key ESC pressed, exiting...\n");
                break;
            }
        }

        if (WaitCommEvent(hComm, &dwEvtMask, NULL)) {
            if (dwEvtMask & EV_ERR) {
                printf("Wait failed with error %ld.\n", GetLastError());
                ret = -1;
                break;
            }

// NOTE/BUG: this only reads _one_ char at a time and uses an extra buffer
#if 0
            if (dwEvtMask & EV_RXCHAR) {
                if (!ReadFile(hComm, single_val_buf, 1, &read, NULL)) {
                    printf("\n\nERROR when reading\n\n");
                }
                m_buf[readcount] = *single_val_buf;
                readcount++;
            }
#else
// NOTE/FIX: read many bytes at once -- put them directly into the final buffer
            if (dwEvtMask & EV_RXCHAR) {
                if (! ReadFile(hComm,
                    &m_buf[readcount], sizeof(m_buf) - readcount,
                    &read, NULL)) {
                    printf("\n\nERROR when reading\n\n");
                    ret = -2;
                    break;
                }

                // increase total accumulated count
                readcount += read;

                // a nicety: force immediate repoll of keyboard
                iter = 0;
            }
#endif

// NOTE/BUG: better to use ">=" rather than "=="
#if 0
            if (readcount == BUF_SIZE) {
#else
            if (readcount >= BUF_SIZE) {
#endif
                double diff_ms = (clock() - start) * 1000. / CLOCKS_PER_SEC;

                print_m_buf();          // for testing only, remove later
                printf("Time spent reading: %f ms\n", diff_ms);
                break;
            }
        }

        // handle WaitCommEvent error?
        else {
            DWORD dwRet = GetLastError();
            if (ERROR_IO_PENDING == dwRet) {
                printf("I/O is pending...\n");
                // To do.
            }
            else {
// NOTE: no need to call GetLastError twice
#if 0
                printf("Wait failed with error %ld.\n", GetLastError());
#else
                printf("Wait failed with error %ld.\n", dwRet);
#endif
            }
        }
    }

    if (ret < 0)
        printf("Runtime error, program exited.\n");
    CloseHandle(hComm);

    return ret;
}


text:
Q: SEO для доменов в разных зонах Есть сайт, его адрес example.com. Теперь я зарегистрировал домен example.ru.
Любой пользователь, заходя на эти домены, обращается к одному и тому же серверу. Но тогда возникает проблема: в поисковых системах контент сайта будет дублироваться (один для зоны com, другой - для ru) - это, видимо, не очень хорошо.
Хотел бы получить совет: как вообще ПРАВИЛЬНО используют два таких домена? С какой целью?
A: Ну наверное правильно делать редирект на основной и в сети продвигать его. Продвигать два одинаковых сайта под разными доменами - точно плохо.
A: Пример - Гугл, у них тоже много доменов. Вообще, поисковые системы видят адреса с www и без www как разные, а тут еще разные домены. Поэтому нужен и редирект, и дополнительно в файле robots.txt и в панелях для веб-мастеров ПС надо указывать основной хост, чтобы ПС видели сайт так, как Вы хотите. Да в помощи ПС для веб-мастеров это все описано.