text:
Q: NLog custom Target LogCat I am really struggling to get a basic custom target working with NLog on a Xamarin Android app.
I'd like to create a simple target to LogCat, in order to be able to use a tag so my debug will be easier and more 'human'
LogCatTarget.cs :
using NLog;
using NLog.Config;
using NLog.Targets;
using Android.Util;

namespace NLog.CustomTarget
{
    [Target("LogCat")]
    public sealed class LogCatTarget : TargetWithLayout
    {
        public LogCatTarget()
        {
            this.Tag = "XamTag";
        }

        //[RequiredParameter]
        public string Tag { get; set; }

        protected override void Write(LogEventInfo logEvent)
        {
            string logMessage = this.Layout.Render(logEvent);

            SendTheMessageToLogCat(this.Tag, logMessage, logEvent.Level);
        }

        private void SendTheMessageToLogCat(string tag, string message, LogLevel level)
        {
            switch (level.Name.ToLower())
            {
                case ("trace"):
                    Log.Verbose(tag, message);
                    break;
                case ("debug"):
                    Log.Debug(tag, message);
                    break;
                case ("info"):
                    Log.Info(tag, message);
                    break;
                case ("warn"):
                    Log.Warn(tag, message);
                    break;
                case ("error"):
                    Log.Error(tag, message);
                    break;
                case ("fatal"):
                    Log.Wtf(tag, message);
                    break;
            }

        }
    }
}

in my MainApplication.cs
 void RegisterNlog()
        {

#if DEBUG
            NLog.Common.InternalLogger.LogToConsole = true;
            NLog.Common.InternalLogger.LogFile = "c:\\log.txt";
            NLog.Common.InternalLogger.LogLevel = NLog.LogLevel.Trace;

            //Reference custom Nlog extension for logcat
            Target.Register<NLog.CustomTarget.LogCatTarget>("LogCat");

            var logCatTarget = new NLog.CustomTarget.LogCatTarget();
            logCatTarget.Layout = @"${message}";
            logCatTarget.Tag = "coucou";
            LogManager.Configuration.AddTarget("logcatname", logCatTarget);

            var rule1 = new LoggingRule("*", NLog.LogLevel.Debug, logCatTarget);
            LogManager.Configuration.LoggingRules.Add(rule1);
#endif

        }

I also have a NLog.config with a console and a file target which are working fine. (This is why I am adding target and rule and not making a new config)
I launch my app and use a button which call all level of Android.Util.Log and those of Nlog logger
_butClear.Click += delegate
            {
                _txtDebug.Text = "";

                _logger.Trace("logger test");
                _logger.Debug("logger test");
                _logger.Info("logger test");
                _logger.Warn("logger test");
                _logger.Error("logger test");
                _logger.Fatal("logger test");

                Android.Util.Log.Verbose("XXaaMMM", "logger test");
                Android.Util.Log.Debug("XXaaMMM", "logger test");
                Android.Util.Log.Info("XXaaMMM", "logger test");
                Android.Util.Log.Warn("XXaaMMM", "logger test");
                Android.Util.Log.Error("XXaaMMM", "logger test");
                Android.Util.Log.Wtf("XXaaMMM", "logger test");
            };

I put a break point in LogCatTarget.cs on write method, which is ovverided. But I never reach it...
Why ?!!!?  cruel worlddddd ! :)
Thanks for your help.

A: Rolf Kristensen gave me the answer in comments :
Simply add NLog.LogManager.ReconfigExistingLoggers(); at the end of my RegisterNlog() did the trick !
This is not mentionned in the docs (https://github.com/NLog/NLog/wiki/Configuration-API), or I missed it.
Thanks Rolf !

A: NLog.Targets.MauiLog has been released, and supports writing to:

*

*Android.Util.Log / LogCat

*Apple iOS / MacOS - Unified Logging OSLog (replacement of print and NSLog)


text:
Q: the meaning of "developed" I have learned something about adjective phrases and participle phrases.
We can't say:

The window open in the fourth floor is broken.

Because "open in the fourth floor" is not an adjective phrase.
But if we say:

The country developed in 1990s is my hometown

Here it means the country became a developed country or just made some progress?
Because if the participle is the predicative, I'm not sure if it should follow the same rule as the adjective does. "Be developed in 1990s" is not an adjective phrase, right?

A: You're sort of correct.  "in the fourth floor" is not an adjectival phrase.
"In the fourth floor", however, is an adverbial phrase.  It modifies the adjective "open."  You absolutely can say that correctly, and "open on the fourth floor" is absolutely a valid adjectival phrase.  It consists of an adjective and an adverbial phrase.
However, the preposition more commonly used with "on the X floor" is "on."
"The country developed in (the) 1990's" again has an adverbial phrase that begins with "in."
"The" is correct before 1990's because 1990's is a proper, count noun.  Ask yourself "how many 90's are there?"
If the answer is one, use "the".
If the answer is many, use "a".
If the answer is "that makes no sense, you can't count this thing," use no article before the word.
Edit: Transcription error, and then I wrote it in a confusing way.  Corrected with the help of the below.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ionic 6 websocket client cordova plugin I'm using ionic 6 (with Angular). Is there a websocket client plugin?
I want to communicate with a websocket server written in c# but I can't find any plugins to use ionic as websocket client.

A: You don't need a dedicated ionic plugin if you just want to subscribe to a websocket. Existing angular websocket libraries should work.
I personally prefer using socket-io, which works perfectly fine: https://socket.io/

A: I suggest you to use the same websocket pattern on backend as the frontend. The socket.io doesn't communicate with others websockets, so it means you need to check first which WS actually you are using on backend to keep using the same on the mobile App.


text:
Q: Difference between return statements in SQL Stored Procedure I would like to know the difference between
    IF X= 0
    BEGIN
         RETURN
    END

and
    IF X= 0
    BEGIN
         RETURN 1
    END

Which is a better practice when used in a Stored Procedure.
Thanks in anticipation

A: Both are equally valid depending on your requirements. If you simply want to exit your procedure then RETURN will suffice.  On the other hand if you want to tell the calling procedure the result of the call then you can do RETURN 1 or any other integer.
More on http://msdn.microsoft.com/en-us/library/ms174998.aspx


text:
Q: Dynamic relocation of code section Just out of curiosity I wonder if it is possible to relocate a piece of code during
the execution of a program. For instance, I have a function and this function should
be replaced in memory each time after it has been executed. One idea that came up our mind
is to use self-modifying code to do that. According to some online resources, self-modifying
code can be executed on Linux, but still I am not sure if such a dynamic relocation is possible. Has anyone experience with that?

A: Yes dynamic relocation is definitely possible.  However, you have to make sure that the code is completely self-contained, or that it accesses globals/external functions by absolute references.  If your code can be completely position independent, meaning the only references it makes are relative to itself, you're set.  Otherwise you will need to do the fixups yourself at loading time.
With GCC, you can use -fpic to generate position independent code.  Passing -q or --emit-relocs to the linker will make it emit relocation information.  The ELF specification (PDF link) has information about how to use that relocation information; if you're not using ELF, you'll have to find the appropriate documentation for your format.

A: As Carl says, it can be done, but you're opening a can of worms.  In practice, the only people who take the trouble to do this are academics or malware authors (now donning my flame proof cloak).
You can copy some code into a malloc'd heap region, then call it via function pointers, but depending on the OS you may have to enable execution in the segment. You can try to copy some code into the code segment (taking care not to overwrite the following function), but the OS likely has made this segment read-only. You might want to look at the Linux kernel and see how it loads its modules.

A: If all these different functions exist at compile time then you could simply use a function pointer to keep track of the next one that is to be called. If you absolutely have to modify the function at runtime and that modification can't be done in place then you could also use a function pointer that is updated with address of the new function when it is created/loaded. The rest of your system would then call the self-modifying function through the function pointer and therefore doesn't have to know or care about the self-modifying code and you only have to do the fixup in one place.


text:
Q: Editing a TreeView node doesn't change the TreeNode Key I have a TreeView with user-editable nodes. I like to use the node caption as key to my tree node :
+ Root
|+ Node1
||- SubNode1
||- SubNode2
|+ Node2
||- SubNode3
||- SubNode4

So I can reach a node like this:
MyTreeView.Nodes["Root"].Nodes["Node2"].Nodes["SubNode3"]

The problem is that, as I allow the user to rename any node, I would need also to change the key of my node in its parent in the AfterLabelEdit handler... which seems (logically) not to be done automatically.
Unfortunately, Nodes["blabla"] is readonly, Nodes.Add(string Key, TreeNode Node) doesn't exist, and I can't find a way to do this without throwing (sooner or later) a bad exception.
Any idea ?

A: Well, changing the Node.Name property seems to work...


text:
Q: How do AWS Lambda instances scale? I understand that AWS Lambda is supposed to abstract the developer from the infrastructure. However I don't quite understand how scaling would work.
Does it automatically start new containers during high traffic?

A: AWS Lambda functions can be triggered by many different event sources.
AWS Lambda runs each Lambda function runs as a standalone process in its own environment. There is a default limit of 1000 concurrent Lambda functions.
There is no need to think of Lambda "scaling". Rather, whenever an event source (or your own application) runs a Lambda function, the environment is created, the function is run, and the environment is torn down. When there is nothing that is invoking a Lambda function, it is not running. When 1000 invocations happen, then 1000 Lambda functions run.
It "scales" automatically by running in parallel on AWS infrastructure. You only pay while a function is running, per 100ms. It is the job of AWS to ensure that their back-end infrastructure scales to support the number of Lambda functions being run by all customers in aggregate.

A: If you whant to change the nubmer of desired instanzes in Auto Scaling Group, you chan use botocore.session
import botocore.session

client = session.create_client('autoscaling')

   client.set_desired_capacity(
        AutoScalingGroupName='NAME',
        DesiredCapacity=X,
        HonorCooldown=True|False
    )

https://docs.aws.amazon.com/cli/latest/reference/autoscaling/set-desired-capacity.html


text:
Q: Error 403 when trying to read emails using EWS I'm receiving error 403 when trying to read e-mails using code below
 IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId)
                .WithClientSecret(clientSecret)
                .WithTenantId(tenant)
                .WithAuthority(new Uri(String.Format(CultureInfo.InvariantCulture, instance, tenant)))
                .WithRedirectUri(redirectUri)
                .Build();

            string[] scopes = new string[] { "https://outlook.office365.com/.default" };

            result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
            if (result != null)
            {
                string token = result.AccessToken;

                service = new ExchangeService
                {
                    Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"),
                    Credentials = new OAuthCredentials(token),
                    ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, email)
                };

                service.HttpHeaders.Add("X-AnchorMailbox", email);
            }
            var emails = service.FindItems(WellKnownFolderName.Inbox, new FolderView(10));

On Azure portal I did:

*

*Register new application and copied tenant id, client id, client secret

*Added EWS.AccessAsUser.All in API auth.

But still receiving 403 - Forbidden when trying to get email from inbox
What am I missing?


text:
Q: Unit testing "authorize" Spring Security JSP taglib Is there a way to unit test the use of the authorize tag provided by Spring Security? The MockMvc integration does not go far enough to do that, as I can only seem to check for the forwarded/redirected URL but not the content of the URL.
The work I am doing involves writing custom SpEL expressions and it would be great to check that they work on real sec:authorize usages! Right now I am confined to testing that the basic call to these expressions are working outside the scope of the JSP pages (specifically using the access attribute in the intercept-url element)

A: Unfortunately, JSPs don't work in unit testing since they need to be compiled by the servlet container. I would recommend using something that works without the container (i.e. Thymeleaf) since you can easily render your response in these instances.
If you use a technology that can render outside of the container, then you can leverage the HtmlUnit MockMvc integration found in Spring Framework 4.2+. If you are on an older version of Spring Framework and cannot upgrade, you can use Spring Test HtmlUnit.
NOTE Spring Test HtmlUnit is now only maintained as part of Spring Framework 4.2+ and not as a distinct project.
If you really must use JSPs, it will likely be somewhat painful. However, there is a pretty decent github project that lists some mechanisms for unit testing JSPs. Out of the options JspTest seems the most promising (but still quite dated).
If you are feeling ambitious it would be quite interesting to see if you could provide a hook with Jasper (Tomcat's JSP compiler) to work with MockMvc.


text:
Q: Matching values between two lists in Python? I'm a bit stumped with what logic to use to be able to match a list to a CSV-file/list containing values. I've had an idea to use a for loop to simple iterate through the CSV and match it:
for j in range(len(data)):
    if STR_list[j] in data[j]:
        print(data[j])

But this doesn't actually print out matches as I want it. Here is what the the data and STR_list values look like when printed (before the for loop above):
print(STR_list):
['AGATC', '4', 'AATG', '1', 'TATC', '5']

print(data)
[OrderedDict([('name', 'Alice'), ('AGATC', '2'), ('AATG', '8'), ('TATC', '3')]), OrderedDict([('name', 'Bob'), ('AGATC', '4'), ('AATG', '1'), ('TATC', '5')]), OrderedDict([('name', 'Charlie'), ('AGATC', '3'), ('AATG', '2'), ('TATC', '5')])]

So in this case, the row with 'Bob' would have been a match as the values line up. Should I be using regex for this or am I right in thinking a for loop could be used?
Edit: Here is how I open the CSV (so it seems like it's a list after all?)
with open('file.csv') as csvfile:
reader = csv.DictReader(csvfile)
data = list(reader)

A: if STR_list[j] in data[j]:

This line should be tabbed over to be within the for loop.   Assuming that was a copy/paste error:
STR_list[j] isn't looking at the entire STR_list, only the j-th item in it (So when you look at data[0], you're looking at 'AGATC', when you look at data[1] you're looking at '4' etc).
What you want is to look for all of STR_list and see if it is in the 2nd, 3rd, and 4th position of each check for data.
Additionally, STR_list needs to be formatted the same way that data is, so you would want a list of tuples there (or an OrderedDict, I'm not familiar with that data type so I don't know if that's entirely what makes up data).
Really, what you want to look for is the equivalent of:
if [('AGATC', '2'), ('AATG', '8'), ('TATC', '3')] in a subset of OrderedDict([('name', 'Alice'), ('AGATC', '2'), ('AATG', '8'), ('TATC', '3')])
I realize I'm not giving you exactly the code you need, but I hope I'm explaining it so that you can understand and figure it out for yourself.

A: for j in range(len(data)):
    #we flatten the OrderedDict into a list
    flattened_data = [x for item in data[j].items() for x in item]
    #Now we verify that the list STR_list and the list flattened_data (minus the 2 first element, aka "name" and the actual name) are equal
    if sum([1 for x1, x2 in zip(STR_list, flattened_data[2:]) if x1 == x2])==len(STR_list):
       #Now we print the name of the person which is at index 1 inside the new list
       print(flattened_data[1])

Basically you need learn how to compare two lists and how to select a specific element from a list


text:
Q: html tag to resize size of html element Is there a tag I can wrap around a html table or body to re-size it without affecting the functionality of the content being re sized. Is the best way to do this to wrap the content in a html table and then re size the table itself ?

A: Simplistic case using CSS:
<body class="resize">
    Lorem ipsum..
</body>

Corresponding CSS
<style>
    .resize {
        font-size: NEW FONT SIZE;
        height: NEW HEIGHT;
        width: NEW WIDTH;
    }
</style>

Or dynamically with jQuery:
$('body').addClass('resize');

A: You can use jquery.wrap()
$("#content").wrap("<table>")

    or with attribute

$("#content").wrap("<table id='wrapper'>")


text:
Q: MongoDB unknown top level operator: $expr nodejs I tried finding solution for this online, but no success.
This is the code:
Invoice.count( { $expr: {$gt: [ "$totalAmount", "$remainingDebt" ]} } ).exec(callback);

where totalAmount and remainingDebt are fields in schema Invoice.
The result I get is: "unknown top level operator $expr".
I am using mongoose 5.0.11 and mongo lab.
Any ideas?

A: which version you are Using for the MongoDB since MLab is Providing the Maximum 3.6 version of the Mongo so you need to either modify the Query or upgrade the Mongo DB version.

A: I'm use this query.
InvoiceModel.aggregate([
    {
      $expr:{'$gt': [ "$totalAmount", "$remainingDebt" ]}
    },
    {
      $count:'COUNT'
    }
 ],(error, result)=>{
   console.log(result)
})


text:
Q: Looping on objects // Error: Objects are not valid as a React child I have a problem looping on object. I couldn't solve it. Please help me.
I am on a React project to improve my skill and gonna work with React Hooks.
There is a file like below which contains an object. I'm gonna fetch from an api.
I wanna to display the object details which i need on the page.
I've tried a lot of way to solve but they didn't work.
I am not adding all the codes what i tried but there is the simple one below which tells my goal. What is the correct solution to iterate on objects in React, JS ..
Thanks in advance.
import React from 'react';

export default function ValueRef() {

    const myList = {
        "location_suggestions": [
          {
            "id": 61,
            "name": "London",
            "country_id": 215,
            "country_name": "United Kingdom",
            "country_flag_url": "https://b.zmtcdn.com/images/countries/flags/country_215.png",
            "should_experiment_with": 0,
            "has_go_out_tab": 0,
            "discovery_enabled": 0,
            "has_new_ad_format": 0,
            "is_state": 0,
            "state_id": 142,
            "state_name": "England and Wales",
            "state_code": "England and Wales"
          },
          {
            "id": 3454,
            "name": "London, ON",
            "country_id": 37,
            "country_name": "Canada",
            "country_flag_url": "https://b.zmtcdn.com/images/countries/flags/country_37.png",
            "should_experiment_with": 0,
            "has_go_out_tab": 0,
            "discovery_enabled": 0,
            "has_new_ad_format": 0,
            "is_state": 0,
            "state_id": 124,
            "state_name": "Ontario",
            "state_code": "ON"
          },
          {
            "id": 5836,
            "name": "London, KY",
            "country_id": 216,
            "country_name": "United States",
            "country_flag_url": "https://b.zmtcdn.com/images/countries/flags/country_216.png",
            "should_experiment_with": 0,
            "has_go_out_tab": 0,
            "discovery_enabled": 0,
            "has_new_ad_format": 0,
            "is_state": 0,
            "state_id": 85,
            "state_name": "Kentucky",
            "state_code": "KY"
          },
        ],
        "status": "success",
        "has_more": 0,
        "has_total": 0,
        "user_has_addresses": true
      }

    console.log(myList)

    return (

{
            Object.values(myList).map((detail)=>(
{detail}
))

        }

    )
}

Error: Objects are not valid as a React child (found: object with keys {id, name, country_id,
country_name, country_flag_url, should_experiment_with, has_go_out_tab, discovery_enabled,
has_new_ad_format, is_state, state_id, state_name, state_code}). If you meant to render a collection
of children, use an array instead.

A: This is because you are iterating over nested objects, that needs to be treated differently.
Oversimplifying your object, it is something like this :
const myList = {
        "location_suggestions": [ ...objects ],
        "status": "success",
        "has_more": 0,
        "has_total": 0,
        "user_has_addresses": true
      }

Now, when you do :
Object.values(myList).map((detail)=>(
{detail}
))

As you can see in your first iteration itself, the detail object contains an array, which is a type of object, that cannot be kept in a React render return.
There are 2 solutions to your problem,

*

*Remove / skip the location_suggestions key to avoid the error.

*Create a seperate iteration logic for location_suggestions


text:
Q: How to profile HP QuickTest Pro tests Is there any method to profile (measure execution time of code)  tests for QuickTest Professional?
Or VBScript profiler, that can be applied for that purpose?
Or at least approach and beacons how it can be done?
Thank you!

A: QTP has built in transactions for measuring time (see screen shot)

If that doesn't fit your needs you can use MercuryTimers as described here.


text:
Q: Get user input from form and update it by id - mongodb and node.js How to update a record by hard coding the MLAB ID in the server using  app.post.
Any help would be great.
Thanks
Answered

A: Try updating your record instead of inserting a new one. To update your record your record must contain an immutable field.
Refer this question to see how to find and update with mongoose

A: Try this:
app.post('/form1', function (req, res, next) {
  record.findOneAndUpdate({"_id": ObjectId("THE ID IN MLAB")}, req.body, {new: true}, function (err, doc) {
    if (err) {
      res.status(500).end()
    } else {
      res.status(200).end()
    }
  })
});

Documentation: https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate


text:
Q: Separar string por quantidade de caracteres Estou desenvolvendo um componente para ler o arquivo enviado pela DataPrev com a relação de obituários mensais. Esse arquivo é um TXT e a cada 210 caracteres é uma pessoa diferente.
A documentação pode ser vista neste link: SISOBI.
Eu estou acostumado a separar dados assim através de um delimitador, usando o Split(), porém esse em especial não possui nenhum, e é separado por quantidade de caracteres.
Eu fiz a Action para enviar o arquivo TXT para a aplicação, e ler os dados contidos no mesmo.
Ex:
string exemplo = "13032015joao";

Dessa string, necessito retirar os dados e colocar em variáveis, como:
int dia = 13;
int mes = 03;
int ano = 2015;
string nome = joao;

A quantidade de caracter é fixo, exemplo:
Dia sempre será 2 caracteres, e após ele sempre virá o mês com 2 caracteres, e após o ano... E assim até terminar os 210 caracteres.
Utilizando o Split() caso tivesse um delimitador, ficaria mais ou menos assim:
var exemplo = "13|03|2015|joao";
 string[] stringSeparators = new string[] { "|" };
            var result = nomeDescrypt.Split(stringSeparators, StringSplitOptions.None);

var dia = Convert.ToInt32(result[0]);
var Mes= Convert.ToInt32(result[1]);
var Ano= Convert.ToInt32(result[2]);
var Nome= Convert.ToInt32(result[3]);

Minha dúvida é: Como separar uma string, delimitando por quantidade de caracteres?
Meu controller para ler o arquivo está assim:
[HttpPost]
        public ActionResult Index(HttpPostedFileBase file)
        {
            //verifica se o arquivo está nulo
            if (file == null)
            {
                TempData["MensagemError"] = "Erro ao realizar o upload do arquivo!";
                return View("Index");
            }

            //Salvar o arquivo txt
            string path = Path.Combine(Server.MapPath("~/App_Data/Uploads/" + file.FileName));
            file.SaveAs(path);

            //Realiza a leitura do arquivo txt
            var fileContents = System.IO.File.ReadAllText(path);

            //testar se está lendo o arquivo
        TempData["Mensagem"] = fileContents;

            return RedirectToAction("Index");
        }

Exemplo de layot:
000028000280000016427201412310000000000MARCIO SEARA RIBEIRO                                                        MARIA PETANIA DE OLIVEIRA SEARA 19780306201412319442067052500000000000000000000007657
000028000290000016428201412310000000000MAIRE VALENTIM DA SILVA                                                     MAIRE VALENTIM DA SILVA         19281105201412310387867350700000000000000000000007657

A: O método que você está procurando é o Substring():
using static System.Convert;
using static System.Console;

public class Program {
    public static void Main() {
        var exemplo = "13032015joao";
        var dia = ToInt32(exemplo.Substring(0, 2));
        var mes = ToInt32(exemplo.Substring(2, 2));
        var ano = ToInt32(exemplo.Substring(4, 4));
        var nome = exemplo.Substring(8);
        WriteLine(dia);
        WriteLine(mes);
        WriteLine(ano);
        WriteLine(nome);
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
É possível fazer algumas coisas para automatizar a execução do código. Ele pode ficar mais curto e generalizado, mas a lógica é uma pouco mais complexa. Só para referência a forma mais genérica:
using System;
using static System.Console;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        var exemplo = "13032015joao";
        //o último elemento poderia ser 200, por exemplo
        //o que se for garantido que ele tenha o tamanho, evitaria o if no método
        var partes = SplitFixed(exemplo, new List<int>() {2, 2, 4, 0});
        foreach(var parte in partes) {
            WriteLine(parte);
        }
        //poderia fazer as conversões aqui e jogar nas variáveis individuais

        //alternativa com tipos, não sei se compensa o esforço
        //para fazer certo daria o mesmo trabalho que fazer manualmente
        //poucos casos esta forma seria realmente mais vantajosa e o ideal é que a conversão
        //fosse feita através de lambdas contendo o código de conversão e não com tipos
        var partes2 = SplitFixedTyped(exemplo, new List<Tuple<int, Type>>() {
            new Tuple<int, Type>(2, typeof(int)),
            new Tuple<int, Type>(2, typeof(int)),
            new Tuple<int, Type>(4, typeof(int)),
            new Tuple<int, Type>(0, typeof(string))});
        foreach(var parte in partes2) {
            WriteLine("Dado: {0} - Tipo {1}", parte, parte.GetType());
        }

    }
    public static List<String> SplitFixed(string texto, List<int> tamanhos) {
        var partes = new List<String>();
        var posicao = 0;
        foreach(var tamanho in tamanhos) {
            if (tamanho > 0) { //padronizei que 0 significa que deve ir até o fim
                partes.Add(texto.Substring(posicao, tamanho));
            } else {
                // o ideal é que não tenha essa parte e todos os tamanhos sejam definidos
                //o 0 só pode ser usado como último parâmetro.
                partes.Add(texto.Substring(posicao));
            }
            posicao += tamanho;
        }
        return partes;
    }
    //esta implementação é um pouco ingênua, não funciona em todas as situações mas funciona com o básico
    public static List<object> SplitFixedTyped(string texto, List<Tuple<int, Type>> tamanhos) {
        var partes = new List<object>();
        var posicao = 0;
        foreach(var tamanho in tamanhos) {
            if (tamanho.Item1 > 0) { //padronizei que 0 significa que deve ir até o fim
                partes.Add(Convert.ChangeType(texto.Substring(posicao, tamanho.Item1), tamanho.Item2));
            } else {
                // o ideal é que não tenha essa parte e todos os tamanhos sejam definidos
                //o 0 só pode ser usado como último parâmetro.
                partes.Add(texto.Substring(posicao));
            }
            posicao += tamanho.Item1;
        }
        return partes;
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Uma solução genérica pode ser útil se você tiver que lidar com vários arquivos de colunas de tamanho fixo com layout diferentes. Mas quando vai fazer algo genérico tem que pensar bem em todas as possibilidades, é bom garantir que os parâmetros estão em ordem. Eu fiz rapidinho sem considerar tudo o que pode acontecer.
Na época que eu fiz não existia Span e tuplas por valor como existem hoje, então este código pode ser otimizado.


text:
Q: Is codeignitor2 work with xampp 1.2 version My codeignitor2 application is built with xampp 1.7. When we deploy the same in the production server which is having a xampp version of 1.1.
Actually, after login with one user and logout again by logging with another user id and navigating to the menus. We have seen the earlier (first logged in username instead of second logged in username) logged in user details in the header page.
We will be able to see the session username randomly with both the users some times.
Can u please help me on this to fix.

A: It depends on php version used in xampp and codeigniter.

A: Code Igniter should work with XAMPP. See the Code Igniter installation details for detailed instructions.

A: Below are the requirements for Codeigniter
PHP version 5.4 or newer is recommended.
MySQL (5.1+) via the mysql (deprecated), mysqli and pdo drivers
Oracle via the oci8 and pdo drivers
PostgreSQL via the postgre and pdo drivers
MS SQL via the mssql, sqlsrv (version 2005 and above only) and pdo drivers
SQLite via the sqlite (version 2), sqlite3 (version 3) and pdo drivers
CUBRID via the cubrid and pdo drivers
Interbase/Firebird via the ibase and pdo drivers
ODBC via the odbc and pdo drivers (you should know that ODBC is actually an abstraction layer)
So you just need to check your xammp support these


text:
Q: Some clarification about how ant copy some files into a folder? I am pretty new to ant (I came from Maven and Ant is a nightmare for me !!!)
I have this target:
<target name="linuxdriver"
    description="Linux Driver">
    <copy file="${deps.linuxdriver.dir}/${deps.linuxdriver.name}" tofile="${project.datadir}/${deps.linuxdriver.name}"/>
    <copy file="${deps.linuxdriver.dir}/${deps.linuxdriver.name}" tofile="${project.deploy}/data/${deps.linuxdriver.name}"/>
    <chmod perm="+x" file="${project.datadir}/${deps.linuxdriver.name}"/>
    <chmod perm="+x" file="${project.deploy}/data/${deps.linuxdriver.name}"/>
</target>

and I have also a property file in which there is definied the "variable" (are named variable?) used in the previous ant code, specifically I have:

project.datadir         = ${basedir}/data
project.deploy.dir      = Release
project.deploy          = ${basedir}/../${project.deploy.dir}

And now I have some doubts:
1) What represents ${basedir}? A specific directory? What?
2) Using the previous information what exactly are the two destination folder in which the files are copied (using the "copy file...to file" tag)?

A: That concept of basedir is described in the ANT manual:

*

*Built-in properties

*Writing a simple Buildfile
It's normally set to be the directory from where you run the build (can be overridden).
If you need to see how properties are resolved, consider running your build in debug mode


text:
Q: Is it bad practice to have a single photo loaded over and over again from the db for every time it's used on the same page in ruby on rails? As a feature on my website I have micro-posting with the ability for other users to reply with comments. When a user enters their account area they can view their posts and see comments too. I'm currently cleaning up after completion of this project and notice that when a user enters their account area my logs show the following: full log: here
I'm concerned about:
1) The part of logs where it shows a users photo being loaded several times. I'm guessing this is where the same user has left several comments on a few posts on another users or their own profile. It's loading the same photo over and over again. Shouldn't this just be done once then some how used again to load the photo each time it comes up again? or is it ok to have that same photo loaded again and again?
2) I noticed some places in the logs that show this:
CACHE (0.0ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` =  LIMIT 1
        [9e77936f78cd46e332128ec31ccc5964] [127.0.0.1]   CACHE (0.0ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` =  LIMIT 1
        [9e77936f78cd46e332128ec31ccc5964] [127.0.0.1]   CACHE (0.0ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` =  LIMIT 1

IT looks like it's searching for nothing. Is this normal? If not then any idea why it could be happening? I would like to track down the issue and stop it. Other than this my site seems to be working flawlessly but I'm not sure if that's the same story behind the scenes.
3) Is there anything in my logs that I should be looking out for? Any bad things to spot?
All advice appreciated
Kind regards

A: Are you loading the image using JavaScript? In that case, you may be making calls to the backend repeatedly for the same photo.
If you are loading it using a URL, is it the same URL for the photos? For example, are you doing this:
http://example.com/getPhoto?userid=2&comment=10

when you should be doing:
http://example.com/getPhoto?userid=2

In the second case, your browser will cache the image and you don't really have to worry about it. The browser will take care that the image is fetched only once.
Also, if you are doing this the right way, check for the HTTP headers in your response, specifically the Cache-control field. Does it by any chance say this:
Cache-Control: No-Cache

If that is the case, the browser is asked not to keep a cache and hence request the server again and again for the same resources. Just omitting it will work or you may set it to max-age <something>.

A: 1) I'm thinking it's OK to load the same photo more than once on a single page - the issue only comes up when a single user has posted multiple comments that load in a given area. If your pagination is 20 comments per page then it will always load 20 pictures if each post is by a different user; even in the most extreme case of 2 posters putting up 10 comments each, caching would only prevent 18 database queries - which I strongly doubt represents a noticeable performance improvement.
2) My guess is that there's a query that's looking for a user with the ID of nil. To track that down, I'd narrow the misfiring query down to a specific method, then sprinkle in a few puts commands around the queries to see what's actually being looked up.  Maybe even a raise 'searching for nil id' unless id here or there.
3) If your app seems to be running OK, then there's nothing specific in the logs to hunt for. Make sure you've got good unit test coverage and good feature test coverage (I like Cucumber for this kind of testing) and that should help ensure your app stability. The only time you should need to refer to your logs is if your tests are all passing but you still see something in the app behaving contrary to expectations - then you sift through the log to see if you can figure out why the app is misbehaving. Once you've got it, fix the bug and write a new test to make sure that you don't accidentally regress the fix later.


text:
Q: Java Generic For Parameterized Class : Unbounded Wildcards vs Raw Type I have a parameterized interface RestHandler.
public interface RestHandler<T> {
   blah blah blah...
}

And I need to create a class from config using Class.forName. Now I come up with three version , which ALL compiles successfully.
Version 1:
@SuppressWarnings("unchecked")
public static <T> RestHandler<T> create(final String handlerImplFqcn) throws ClassNotFoundException,
                                                                    IllegalAccessException,
                                                                    InstantiationException {
    Class<?> handlerClass = Class.forName(handlerImplFqcn);
    return (RestHandler<T>) handlerClass.newInstance();
}

Version 2:
public static RestHandler<?> create(final String handlerImplFqcn) throws ClassNotFoundException,
                                                                    IllegalAccessException,
                                                                    InstantiationException {
    @SuppressWarnings("rawtypes")
    Class handlerClass = Class.forName(handlerImplFqcn);
    return (RestHandler<?>) handlerClass.newInstance();
}

Version 3:
public static RestHandler<?> create(final String handlerImplFqcn) throws ClassNotFoundException,
                                                                    IllegalAccessException,
                                                                    InstantiationException {
    Class<?> handlerClass = Class.forName(handlerImplFqcn);
    return (RestHandler<?>) handlerClass.newInstance();
}

My question is , why they ALL work and which one would be best practice ?

A: Version 1, re-written to this:
public static <T extends RestHandler<?>> RestHandler<T> create(final String handlerImplFqcn) throws ClassNotFoundException, IllegalAccessException, InstantiationException, ClassCastException {
    Class<T> handlerClass = (Class<T>) Class.forName(handlerImplFqcn);
    return (RestHandler<T>) handlerClass.newInstance();
}

A: Use version 1.
Version 2 uses raw types - avoid these if at all possible.
Version 3 uses <?> which is also often an anti pattern as it rarely achieves what you mean to achieve.


text:
Q: TypeError: object of type 'NoneType' has no len() Python on application deployment I'm just learning python and I'm trying to run my application but get the following:
Traceback (most recent call last):
  File "/Users/plugins/bluegreen.py", line 433, in <module>
    cnames = [bluegreen.get_cname(green), bluegreen.get_cname(blue)]
  File "/Users/plugins/bluegreen.py", line 66, in get_cname
    if len(data.get("cname")) == 0:
TypeError: object of type 'NoneType' has no len()

Here are the contents of line 66 and 433:
66:
def get_cname(self, app):
    response = self.get("/apps/{}".format(app))
    data = json.loads(response.read())
    if len(data.get("cname")) == 0:
      return None
    return data.get("cname")

433:
cnames = [bluegreen.get_cname(green), bluegreen.get_cname(blue)]

Edit 1:
If I place a print(data), I get the following:
{u'entrypoints': [], u'routeropts': {}, u'description': u'', u'repository': u'git@10.10.1.1.nip.io:hello-green.git', u'tags': [], u'lock': {u'Owner': u'', u'Reason': u'', u'AcquireDate': u'0001-01-01T00:00:00Z', u'Locked': False}, u'routers': [{u'type': u'traefik', u'name': u'traefik', u'opts': {}, u'address': u'hello-green.10.10.1.1.nip.io'}], u'deploys': 0, u'routingsettings': None, u'teams': [u'admin'], u'platform': u'go', u'teamowner': u'admin', u'plan': {u'router': u'traefik', u'swap': 0, u'cpushare': 100, u'name': u'autogenerated', u'memory': 0}, u'ip': u'hello-green.10.10.1.1.nip.io', u'owner': u'admin@shipa.io', u'router': u'traefik', u'units': [], u'pool': u'gce', u'name': u'hello-green'}
Traceback (most recent call last):
  File "/Users/brunoandrade/.shipa/plugins/bluegreen.py", line 434, in <module>
    cnames = [bluegreen.get_cname(green), bluegreen.get_cname(blue)]
  File "/Users/brunoandrade/.shipa/plugins/bluegreen.py", line 67, in get_cname
    if len(data.get("cname")) == 0:
TypeError: object of type 'NoneType' has no len()

Edit 2:
Not sure why I get no cname key, since I'm getting it here:
  config = Config.load('shipa-bluegreen.ini')

  app_name = config['name']
  blue = "%s-blue" % app_name
  green = "%s-green" % app_name

  bluegreen = BlueGreen(token, target, config)

  apps = [blue, green]
  cnames = [bluegreen.get_cname(green), bluegreen.get_cname(blue)]

Which is reading from the shipa-bluegreen.ini, which I have in the file:
[Application]
name: hello

Any help would be really appreciated
Thanks!

A: You printed out data, and got
{u'entrypoints': [], u'routeropts': {}, u'description': u'', u'repository': u'git@10.10.1.1.nip.io:hello-green.git', u'tags': [], u'lock': {u'Owner': u'', u'Reason': u'', u'AcquireDate': u'0001-01-01T00:00:00Z', u'Locked': False}, u'routers': [{u'type': u'traefik', u'name': u'traefik', u'opts': {}, u'address': u'hello-green.10.10.1.1.nip.io'}], u'deploys': 0, u'routingsettings': None, u'teams': [u'admin'], u'platform': u'go', u'teamowner': u'admin', u'plan': {u'router': u'traefik', u'swap': 0, u'cpushare': 100, u'name': u'autogenerated', u'memory': 0}, u'ip': u'hello-green.10.10.1.1.nip.io', u'owner': u'admin@shipa.io', u'router': u'traefik', u'units': [], u'pool': u'gce', u'name': u'hello-green'}

You can clearly see that there is no key called "cname" in here.

A: There's no cname key in data. data.get("cname") returns None if the key isn't found but you can specify an explicit default. Use an empty string as the default instead.
def get_cname(self, app):
    response = self.get("/apps/{}".format(app))
    data = json.loads(response.read())
    if len(data.get("cname", "")) == 0:
      return None
    return data.get("cname")


text:
Q: Is this an if else statement
Possible Duplicate:
What do two question marks together mean in C#?

I just came across the code below and not really sure what it means and can't google it because google omits the ??
int? x = 32;
int  y = x ?? 5;

Is the second line some sort of if else statement, what does the ?? mean

A: if(x == null)
     y = 5
else
     y = x

A: It's called the null-coalescing operator.
If the value to the left of the ?? is null, then use the value to the right of the  ?? otherwise use the left hand value.
Expanded out:
y = x == null ? 5 : x

or
if(x == null)
     y = 5
else
     y = x

A: The ?? operator is used with a collection of variables and evaluates to the value of the first non-null variable. For example, consider the following code:
int? x = null;
int? y = null;
int? z = null;

y = 12;
int? a = x ?? y ?? z;

The value of a will be 12, because y is the first variable in the statement with a non-null value.

A: Yes This is if else statement.
Have a look of this URL http://www.webofideas.co.uk/Blog/c-sharp-double-question-mark-syntax.aspx


text:
Q: Cant figure out how to get bootstrap table to work with electron renderer I am trying to integrate bootstrap data table with an electron app. I got the table itself up and running on the HTML side but I can't seem to figure out the way to get the renderer (js) to communicate with the DataTable element.
I've tried accessing the functions directly with:
var toolTable = document.getElementById('toolTable');
toolTable.bootstrapTable({});

but that just result with:

Uncaught TypeError: toolTable.bootstrapTable is not a function

any pointer? Thanks!

A: Not sure exactly what 'bootstrapTable' function is supposed to be doing?  But if it is supposed to be a function added by some external library on top of jQuery - first make sure you import jQuery before the library that may utilize it.
If this is not the case, you can populate a table dynamically by using jquery .innerHTML() to your table.  Or, you can use DataTables as per: https://datatables.net/examples/styling/bootstrap


text:
Q: Vue app - Firebase deploy database issues I successfully deployed my Vue app using Firebase hosting except for one small thing - the database that I was running from localhost isn't appearing / being referenced when I navigate to the hosting URL (https://.firebaseapp.com.
Instead, any changes I make in attempt to recreate the data on the hosted site only effects my instance running on localhost!
Basically:

*

*Why am I not seeing any db data once i deploy using the standard firebase commands firebase init and firebase deploy?

*When I deploy how can I use the same database from localhost but have it running as a copy so that the deployed database and localhost database are kept separate?

A: *

*I answered the first part via changing how I was deploying. Screenshot is attached.

*I answered the second part through this post


text:
Q: Sobrepor a seta para voltar ao topo sobre videos, imagens, etc Não estou conseguindo sobrepor a seta para voltar ao top que é fixa em minha página.
Sempre quando passa por imagens, videos e algumas aplicações que usam JavaScript ela some.
Gostaria de saber se há alguma solução especifica.
Uso os seguintes código para uso da seta

E o CSS da classe o outro é :
.botaotopo {
  display:scroll;
  position:fixed;
  bottom:2px;
  right:2px;
}

E o JS:
(function($){$.fn.UItoTop=function(options){var defaults={text:'To Top',min:200,inDelay:600,outDelay:400,containerID:'toTop',containerHoverID:'toTopHover',scrollSpeed:1200,easingType:'linear'},settings=$.extend(defaults,options),containerIDhash='#'+settings.containerID,containerHoverIDHash='#'+settings.containerHoverID;$('body').append(''+settings.text+'');$(containerIDhash).hide().on('click.UItoTop',function(){$('html, body').animate({scrollTop:0},settings.scrollSpeed,settings.easingType);$('#'+settings.containerHoverID,this).stop().animate({'opacity':0},settings.inDelay,settings.easingType);return false;}).prepend('').hover(function(){$(containerHoverIDHash,this).stop().animate({'opacity':1},600,'linear');},function(){$(containerHoverIDHash,this).stop().animate({'opacity':0},700,'linear');});$(window).scroll(function(){var sd=$(window).scrollTop();if(typeof document.body.style.maxHeight==="undefined"){$(containerIDhash).css({'position':'absolute','top':sd+$(window).height()-50});}
if(sd>settings.min)
$(containerIDhash).fadeIn(settings.inDelay);else
$(containerIDhash).fadeOut(settings.Outdelay);});};})(jQuery);

A: Elementos com um z-index maior são empilhados diante dos elementos com um menor z-index
 .botaotopo {
   z-index: 1;
   ..........
   ..........

No seu caso isso vai funcionar, só vai parecer que não lá no rodapé que é da mesma cor :)


text:
Q: How to have a request scoped variable in remix JS? I'm new to remix Js and wanted to understand what the best way is to get this done.
I have an app that calls a function which in turn calls an API to load user details. This user information is used to paint multiple things like header, footer and load the appropriate view for the user.
The thing I notice is that currently for a single page load request from the browser, the function (and in turn the API) is called independently multiple times by the module that renders the header, footer, page etc. What I wanted to know is if it is possible to have the user details saved in a variable so that for a single request all the modules can use this variable and it needs to be only fetched once per browser request.
I tried the following but it did not work
let userDetails;

export function getUserDetails(userId){

  if(!userDetails){
     console.log("Calling API to fetch user details);
     //call the API
     userDetails = async getUserById(userId);
  }
  return userDetails;
}

One option we have is to save the user details in the browser/session but that is not allowed due to some policies. What would be the best way to achieve this so that we only need to call the API once per request from the browser and save subsequent calls for a single page load to fetch the same info ?
TLDR : what would be the best way to initialize an object in an remix server module so that its value could be accessible by other modules and it has to be set only once per a request from a browser.

A: Dataloader can be used to solve this issue.
It offers request-level caching (and batching) which means parallel loaders on the initial HTML request can cooperate while remaining independent.
Example usage with remix can be found here.
// Root.tsx
export const loader = async ({ context }) => {
  const user = await context.loaders.userById.get("user_1");
  return json({ user });
}

// ...

// Child.tsx
export const loader = async ({ context }) => {
  // This will await the same promise created in the Root.tsx loader
  const user = await context.loaders.userById.get("user_1");
  return json({ user });
}

// ...

Having said that, I would warn that the abstraction cost of dataloader is quite high and to only use it if you really can't afford to call into your API multiple times (loaders run in parallel so it's more an issue of upstream load over performance).
It's also worth noting that SPA navigations won't see the benefit because each loader is called as a separate request from the browser so a request-level cache will be ineffective.


text:
Q: What does it mean whenever a function ends with })(jQuery);? I tried googleing, but Google doesn't seem to care about parentheses...

A: If you see this:
(function($) {
    // ...code using $...
})(jQuery);

It's doing two things:

*

*Defining an anonymous function that uses $ as its reference to jQuery.

*Calling it, passing in jQuery.

You could do it like this:
function foo($) {
    // ...code using $...
}
foo(jQuery);

...but that creates an unnecessary symbol.
All of this is because jQuery has the symbol jQuery and the symbol $, but it's not uncommon for people to use jQuery.noConflict() to tell jQuery to return $ back to whatever it was when jQuery loaded, because a couple of other popular libraries (Prototype and MooTools, to name two) use $ and this lets someone use those libraries and jQuery together. But you can still use $ within your function, because the argument shadows whatever that symbol means outside the function.

A: It basically automatically invokes the anonymous/lambda function defined and supplies the jQuery reference to it.
Pretty much the same as functionCall(jQuery) except you define it and invoke it in the same line/expression.

A: Usually these are of the form...
(function($) {
    // do something with $
})(jQuery);

Which means that the function is actually doing something with jQuery (it defines function(a) {...} and then passes jQuery in as a), but it wants to be able to use $ instead jQuery inside the function.
This allows things like $(this) and so on even if jQuery is invoked in No-Conflict mode (and thus $ wouldn't refer to jQuery normally).


text:
Q: How to send an object with out class from one api to another api? I am writing two api's, Api 1 and Api 2. I have an object of type "dynamic" in my api 1. I am trying to send this object to api 2.
Here is my code
public IActionResult processPensionInput([FromBody]dynamic inputFromPensionerBody)
{

    using(var askPensionDisbursement = new HttpClient())
    {
        var jsonstring = JsonConvert.SerializeObject(inputFromPensionerBody);
        askPensionDisbursement.BaseAddress = new Uri("http://localhost:51549/api/PensionDisbursements/");
        var responseTalk = askPensionDisbursement.GetAsync("calculate?inputFromPensioner="+ jsonstring);
        responseTalk.Wait();

        return Ok(responseTalk.Result);
        int code = (int)responseTalk.Result.StatusCode;
        if(code==10)
        {
            var readTask = responseTalk.Result.Content.ReadAsStringAsync();

            return Ok("Okay");
        }

        return Ok("Not okay");
    }
}

The other api's code is
public IActionResult calculatefromdetails(dynamic inputFromPensioner/*,dynamic serviceCharge*/)
{
    StatusCodeResult flag = new StatusCodeResult(21);
    using (var response = new HttpClient())
    {
        //some loooong code here...
    }
    return new StatusCodeResult(10);
}

But the problem arises in the first api itself, where in the postman ,the output is 415 media type not found.
How to send the object from one api to another.

A: You can't implement a json string in .GetAsync in the api 1.


text:
Q: JSP page import does not work on JBoss I am using the following in one of my jsp's. In eclipse it shows the error:

The import com.nucleus.core.loanproduct.ContractType cannot be
  resolved

But on starting jetty up, the class is resolved and any usages of the var contractTypeLoan do not give any error. But the same project when deployed on a
JBoss server, gives the said error.
<%@ page import="com.nucleus.core.loanproduct.ContractType"%>
 <script type="text/javascript">
 // static final String LOAN = "Loan"; in Contract Type
 var contractTypeLoan = "<%=ContractType.LOAN%>";
  </script>
 ..............
 ..............
 function applyContractTypeChanges(){
    contractTypeSelected = $("#contractType option:selected").text();
     if(contractTypeSelected == contractTypeLoan){
         // Check always fails.
     }

Is this some issue with JBoss?


text:
Q: How to do a custom redirection on AllAuth Social Account Signup I have tried to do the following, but neither redirect nor render works:
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter, get_account_adapter
from allauth.account.adapter import DefaultAccountAdapter

from django.shortcuts import render

class SocialAccountAdapter(DefaultSocialAccountAdapter):
    def __init__(self, request=None):
        DefaultSocialAccountAdapter.__init__(self, request)

    def save_user(self, request, sociallogin, form=None):
        """
        Saves a newly signed up social login. In case of auto-signup,
        the signup form is not available.
        """
        print('saving user')
        u = sociallogin.user
        u.set_unusable_password()
        if form:
            get_account_adapter().save_user(request, u, form)
        else:
            get_account_adapter().populate_username(request, u)
        sociallogin.save(request)
        print('right before redirect')
        return render(request, 'accounts/signup.html',
                      context={'title': 'Edit Profile', 'register_update': 'Update'})

Only an ImmediateHttpResponse(redirect('url')) works, but then it redirects to the login page.
Signals does not work either.

A: Oops...I've found a solution to my own problem...
Just create a sign in processor view in your views.py, like so:
def sign_in_processor(request):
    user = request.user
    required = [#User Fields that were not filled up by the social provider on creation]
    for f in required:
        if not f:
            return redirect('profile_edit')
    return redirect('home')

'profile_edit' is a view based off a UserChangeForm from django.contrib.auth.forms or its derivatives.


text:
Q: object of class wp_error could not be converted to string in my site Error:

Catchable fatal error: Object of class WP_Error could not be converted to string in thanks.php on line 86

The code is below where problem is:
 $wpdb->get_results('SELECT phone, user_nicename, user_email FROM ol_users WHERE ID = "'.$pidl.'"');


text:
Q: calling `file.show` on a directory causing crash I called file.show on a variable that contained a path instead of a file and R crashed.
When I brought it back up, I tested
 file.show("~")

And I get a consistent crash.
Can anyone confirm?  I'm getting an issue on both R 3.0 and R 2.15.3

R 3.0 - hangs indefinitely
> sessionInfo()
R version 3.0.0 (2013-04-03)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] data.table_1.8.8

R 2.15.3 - crashes and cannot gracefully abort
R version 2.15.3 (2013-03-01)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base


text:
Q: How to best understand the relationship between cheroot vs cherrypy I've read the official documentation but didn't find a definite answer. What is the relationship between cheroot and Cherrypy? I see Cherrypy imports a lot of codes from cheroot. Is it another project?

A: In the beginning, there was only CherryPy, which combined an HTTP server, an HTTP application-development framework, and some process and environment controls. At some point, I noticed other people were using the CherryPy HTTP server with other frameworks, like Django and Flask, but constantly complained about polluting their beautiful frameworks with (gasp) threadlocals and method dispatch. So I split out the HTTP server and the process controls into cheroot so such users could feel better about using it, and made a version of CherryPy which no longer included those modules but instead imported cheroot.


text:
Q: VS 2010 output regenerated automatically I am using VS 2010 in windows 7 64-bit. It keeps giving me error when I build my project, saying the output is being locked.
I manually delete the output exe and it keeps coming back even though I haven't recompiled the code. What's going on?

A: This has been the most frustrating problem I've seen and it seems to be related to the ** Windows Search service**. I have to disable it and the problem went away 99% of the time. Occasionally it still came back. I just waited 30 seconds.

A: Another source of the problem: Application Experience Service. I enabled it and the issue completely disappeared.
Now happy coding again.


text:
Q: How can I aggregate online count for per hour if I only have online and offline event record of device in clickhouse If I have online and offline event record of device.
CREATE TABLE IF NOT EXISTS connect_log (
 `deviceId` Int64,
 `eventTime` Datetime() ,
 online Int8
 )  ENGINE = MergeTree
 ORDER BY (`deviceId`,`eventTime`);

How can I write a MATERIALIZED VIEW that aggregate online device count for per hour.
The online count is not only the count of online event , it must include all device that is ever online in this hour(the last event is not offline even the last online event is recorded in many days ago or the last offline event is in the this hour).
test case
insert1
INSERT into connect_log values
(1,'2020-07-30 10:01:00',1),
(2,'2020-07-30 10:01:0',1),
(3,'2020-07-30 11:01:00',1);

result1:
............................
2020-07-30 10:00:00| 2
............................
2020-07-30 11:00:00| 3
............................

then insert2
INSERT into connect_log values
(1,'2020-07-30 11:51:00',0),
(2,'2020-07-30 12:01:0',0),
(3,'2020-07-30 13:51:00',0);

result1:
............................
2020-07-30 10:00:00|  2
............................
2020-07-30 11:00:00| 3
............................
2020-07-30 12:00:00| 2
............................
2020-07-30 13:00:00| 1
............................

A: Try this way:
CREATE MATERIALIZED VIEW connect_log_hourly_mv
ENGINE = AggregatingMergeTree()
PARTITION BY tuple()
ORDER BY (hourlyEventTime)
AS
SELECT
  toStartOfHour(eventTime) AS hourlyEventTime,
  uniqExactIfState(deviceId, online = 1) AS onlineDeviceUniqCountState
  /*
  .. other aggregates ..
  */
FROM connect_log
GROUP BY hourlyEventTime;

Query to get aggregated result:
SELECT
    hourlyEventTime,
    uniqExactIfMerge(onlineDeviceUniqCountState) onlineDeviceUniqCount
FROM connect_log_hourly_mv
GROUP BY hourlyEventTime
HAVING onlineDeviceUniqCount > 0
ORDER BY hourlyEventTime;

UPDATE
Materialized view calculates the preliminary aggregates (the status of the earliest event in an hour) that used to calculate final result:
CREATE MATERIALIZED VIEW connect_log_hourly_mv
ENGINE = AggregatingMergeTree()
PARTITION BY tuple()
ORDER BY (hourlyEventTime)
AS
SELECT
  toStartOfHour(eventTime) AS hourlyEventTime,
  deviceId,
  argMinState(online, eventTime) AS firstEventStatusState
FROM connect_log
GROUP BY hourlyEventTime, deviceId;

Query:
SELECT
  hourlyEventTime,
  countIf(deviceId, firstEventStatus = 1) AS uniq_count
FROM (
  SELECT
    hourlyEventTime,
    deviceId,
    argMinMerge(firstEventStatusState) firstEventStatus
  FROM connect_log_hourly_mv
  GROUP BY hourlyEventTime, deviceId)
GROUP BY hourlyEventTime
ORDER BY hourlyEventTime


text:
Q: Powershell runspaces clipboard interaction I've recently gotten around to using runspaces, but I've a wall of sorts.
I had this little script where one of the functions sets clipboard to a predefined text.
When run in default runspace it works perfectly. As soon as I placed the script in a runspace, it fails to execute the way I want. I assume that each runspace has its own clipboard. Is there a way to interact with default runspace clipboard from within another one or call a function outside runspace from within it?

A: In PowerShell 7+ something like this would work out of the box:
$ps = [powershell]::Create().AddScript{
    Set-Clipboard 'foo bar baz'
    Start-Sleep 5
}
$async = $ps.BeginInvoke()
$ps.EndInvoke($async)
$ps.Dispose()

(Get-Clipboard) -eq 'foo bar baz' # True

In Windows PowerShell its a bit more trickier, you must use a Runspace setting the Runspace.ApartmentState Property to STA:
$rs = [runspacefactory]::CreateRunspace()
$rs.ApartmentState = [System.Threading.ApartmentState]::STA
$rs.Open()
$ps = [powershell]::Create().AddScript{
    Set-Clipboard 'foo bar baz'
    Start-Sleep 5
}
$ps.Runspace = $rs
$async = $ps.BeginInvoke()
$ps.EndInvoke($async)
$ps, $rs | ForEach-Object Dispose

(Get-Clipboard) -eq 'foo bar baz' # True

Inspecting the Error stream before disposing can always give you a good hint of what could've gone wrong, i.e. using Clipboard.SetText method if not using STA we would get this error:

Exception calling "SetText" with "1" argument(s): "Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it."

Same goes for Set-Clipboard which uses the same API, different method, behind the scenes:
Message        : Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure
                 that your Main function has STAThreadAttribute marked on it.
Data           : {}
InnerException :
TargetSite     : Void SetDataObject(System.Object, Boolean, Int32, Int32)
StackTrace     :    at System.Windows.Forms.Clipboard.SetDataObject(Object data, Boolean copy, Int32 retryTimes, Int32
                 retryDelay)
                    at Microsoft.PowerShell.Commands.SetClipboardCommand.SetClipboardContent(List`1 contentList,
                 Boolean append, Boolean asHtml)
                    at Microsoft.PowerShell.Commands.SetClipboardCommand.EndProcessing()
                    at System.Management.Automation.CommandProcessorBase.Complete()
HelpLink       :
Source         : System.Windows.Forms
HResult        : -2146233056


text:
Q: How exactly do I interrupt a thread? I'm trying to figure out exactly how to interrupt a thread. I know this has been asked before but I'm not sure I've understood correctly.
I currently have:
public class Test implements Runnable {
    public void run() {
        int i = 0;
        while(!Thread.currentThread().isInterrupted() && i < 100) {
            System.out.println(i++);
        }
    }
    public static void main(String args[]) {
        Thread x = new Thread(new Test());
        x.start();
        for (int i = 0; i < 100; i++) {
            System.out.println(i+100);
            if (i == 75) {
                x.interrupt();
            }
        }
    }
}

Which has both threads count to 100. It's a simple example, I know but it occurs to me that if I was doing something more complicated in the run method then a while loop on the outside might not be good enough. So what I'm asking is:
If I have for example 50 lines of code in the run method and I want to interrupt the thread wherever in those 50 lines of code it is then would I have to have loads of ifs to check it hasn't been interrupted between each line? As far as my understanding of the whole thing at the moment goes, that would be the case...which makes me think I've missed something.
Thanks for the help :)

A: Your understanding is correct - interrupt is intended for co-operative rather than pre-emptive interruption.  It is up to the target thread to decide when it is safe to be interrupted, and to make the appropriate checks at that time.  Certain blocking operations will throw InterruptedException if the thread is interrupted while blocked, but other than that it's up to you to check Thread.interrupted() as appropriate.  In most algorithms you don't want to allow interruption at arbitrary points, but only at well defined places where you know the state will be consistent.
Note that you should make the checks using Thread.interrupted() rather than Thread.currentThread().isInterrupted(), as the former resets the interruption flag after checking it.  Once isInterrupted returns true it will continue to return true on every call until the flag is reset, which is probably not what you want.

A: Adding to what Ian Roberts already said,
If you are not writing the top-level application (i.e., if the code that you are writing is going to be called by anybody else), then there is only one reasonable way to handle an InterruptedException;

*

*Safely abort whatever operation your caller asked you to do,

*Make sure to leave things in a state where your caller can start a new operation if that's what your caller wants to do, and

*re-throw InterruptedException.

Code that behaves any other way is likely to surprise whoever calls it, and surprising the caller is never a good idea.
If you are writing the top-level application, then go ahead and handle InterruptedException any way that suits you.  (Just hope that the libraries that you call won't do anything that surprises you.)


text:
Q: how to use java agent to handle applet events I'm trying to handle events in Java forms I don't have the source for.
until now I used the endorsed folder to replace java.applet.Applet with my own inherited implemention.
but endorsed is disabled in Java 9.
now I'm looking for a new solution, and I'm trying to use Java Agent with instrumentation to achieve the same thing.
but when I add a class and use it I also need to provide all of the Applet classes I import in a ClassLoader.
and the jars i need to import are on a web server i don't know the URL to, and I don't want to add them manually (in the endorsed solution i didn't need to do it)
is there another way to do it? or am I missing something?


text:
Q: Accessing the table fields with relation yii2 Model users has onetomany relation with category
 public function getCategory()
    {
         return $this->hasMany(Category::className(), ['user_id' => 'user_id']);
    }

I am not being able to access the fields of category using this relation.
   public function actionGetResults()
            {
                $results = users::find()->where(['user_id' =>8])
                                        ->with('category')
                                        ->all();

                echo "<pre>"; print_r($results);
            }

$results here shows an array with fields of category. i.e category_name, category_id etc. but if i do this:
 echo "<pre>"; print_r($results->category_name);

it fails.

A: First of all, since relation type is has many, category name is misleading and it's better to use categories.
Second, you are accessing related field wrong. $results is an array of User models and categories property of each model contains an array of related Category models to that user.
Use nested foreach loop:
foreach ($results as $user) {
    foreach ($user->categories as $category) {
        var_dump($category->name);
    }
}

Or to get the name of the first user's first category:
$results[0]->categories[0]->name

Note that the second approach is only for demonstration purposes and can fail with Undefined index error if user or / and category does not exist.
Read Working with Relational Data for more info.


text:
Q: SPARQL query. OPTIONAL subquery and HAVING MIN MAX values I have some trouble in making SPARQL query for my DB.
There are individuals (materials) in classes (material groups).
Every material have some properties like density, tensile strength etc.,
but not all materials have all of them.
I need to make a query where I will enter range values for each property, and if material have that property,
compare my range of values with material's range of values.
I did that with subqueries, and HAVING becouse each property can have more values linked by blank node, but it doesn't work.
I would like to have results like:
material | propertyLabel    | minValue | maxValue
mat01   | tensile strength | 250       | 250
mat02   | tensile strength | 255       | 280
mat01   | density          | 4800       | 4900
mat02   | density          | 5000      | 5010

and my query looks like this:
 SELECT DISTINCT ?material ?propertyLabel ?minValue ?maxValue WHERE {

?material rdf:type/rdfs:subClassOf* res:Material . #Get all materials

{ OPTIONAL {
 SELECT ?material ?propertyLabel (MIN(?value) AS ?minValue) (MAX(?value) AS ?maxValue) WHERE {
 ?material pro:hasDensity [ unit:hasValue ?value ; unit:hasUnit ?unit ] .
  pro:hasDensity rdfs:label ?propertyLabel .
 } GROUP BY ?material ?propertyLabel
   HAVING ((MAX(?value) > 4500) && (MIN(?value) < 10000))
} }

{ OPTIONAL {
 SELECT ?material ?propertyLabel (MIN(?value) AS ?minValue) (MAX(?value) AS ?maxValue) WHERE {
 ?material pro:hasUltimateTensileStrength [ unit:hasValue ?value ; unit:hasUnit ?unit ] .
  pro:hasUltimateTensileStrength rdfs:label ?propertyLabel .
 } GROUP BY ?material ?propertyLabel
   HAVING ((MAX(?value) > 50) && (MIN(?value) < 300))
} }

# Other properties...

}

ADDITIONAL INFO
Ok, here comes cleaner code and clarification...
Yes, this answer with VALUES now works, but...
It outputs materials that have value for even one property and that property,
but what i need is materials that satisfy all properties that they have IF they have it.
So let's say we have materials:
res:m1
res:m2
res:m3

and material properties:
pro:hasYieldStrenght
pro:hasMeltingPoint
Pro:hasDensity

that properties are linked trough blank node to their values and units (for a range).
material 1 has some property 1 and that property can have multiple values (1, 2, 3.. Thats why I was using MIN and MAX) like this:
res:m1 pro:hasYieldStrength
[ unit:hasValue "100"^^xsd:double ; unit:hasUnit unit:MegaPascal ] ,
[ unit:hasValue "133"^^xsd:double ; unit:hasUnit unit:MegaPascal ] ;

Some materials don't have some properties (they are unknown in real world or they are not in db).
Now, how I want to search materials is let's say I want all materials with:
pro:hasDensity 2000 - 3000
pro:hasMeltingPoint 250 - 400
So i need range intersection of mine search values and min and max in db for particular property.
That's why i have:
HAVING ((MAX(?value) > ?low) && (MIN(?value) < ?high))

And all of that is working if I set only one property on input.
But when I want to search for multiple intersections (properties), result contains property per material,
So let's say that material only satisfy one of the properties, then that property and material would be in results.
What I need as result is materials that satisfy ALL properties IF they have it .
If material don't have value for some property (nobody measure it let's say) and satisfy all other, it should be considered in results with or without empty values on that property, but if material fail to satisfy even one property then it should not be considered in results, not only for that property, but in general, that material.
That's why i was thinking about OPTIONAL but i'm loosing it allready because of that bug with values that i spent two days :p
here is new code:
SELECT ?m ?p (MAX(?value) AS ?maxValue) (MIN(?value) AS ?minValue) WHERE {
VALUES (?p ?low ?high)
{
  ( pro:hasDensity 1 300 )
  ( pro:hasYieldStrength 30 300 )
  ( pro:hasMeltingPoint 100 350 )
}
?m ?p [ unit:hasValue ?value ; unit:hasUnit ?unit ]
} GROUP BY ?m ?p ?low ?high
  HAVING ((MAX(?value) > ?low) && (MIN(?value) < ?high))

It's like it doesn't even consider density as none of them have density that low,
and this is result:
m   p   maxValue    minValue
#m74653522  #hasYieldStrength   110.0   100.0
#m36767231  #hasYieldStrength   262.0   220.0
#Phosphorus #hasMeltingPoint    317.0   317.0

On the other hand, there are materials with that low density but it doesn't consider them couse other properties are not satisfied. (like it's the problem in first row of properties I don't know..)

A: Some data, please…
Without seeing your data, it's hard to say exactly what the problem is, but it sounds like you have data something like the following, where each material has several values for a couple of properties.  In this case, two materials, m1 and m2, have several properties each for properties p1 and p2 (which also have labels):
@prefix : <urn:ex:>
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>

:p1 rdfs:label "P one" .
:p2 rdfs:label "P two" .

:m1 :p1 10, 12, 14, 16 ;
    :p2 90, 100, 110, 120 .
:m2 :p1 11, 13, 15, 17 ;
    :p2 95, 105, 115, 125 .

A query
It sounds like you want to specify lower and upper bounds for each property, and then for each property and pair of bounds, retrieve all values of the property within the bounds for each instance, and record the maximum and minimum value for the property for each material. The following query does that by specifying the properties and bounds in a values block. (See the appendix if you're not familiar with values blocks.)  The results follow.
prefix : <urn:ex:>
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>

select ?material
       ?pLabel
       (min(?value) as ?min)
       (max(?value) as ?max)
where {
  values (?p ?lowerBound ?upperBound) {
    (:p1 12 15)
    (:p2 97 116)
  }
  ?material ?p ?value .
  ?p rdfs:label ?pLabel .
  filter ( ?lowerBound <= ?value && ?value <= ?upperBound )
}
group by ?material ?pLabel
order by ?pLabel ?material

----------------------------------
| material | pLabel  | min | max |
==================================
| :m1      | "P one" | 12  | 14  |
| :m2      | "P one" | 13  | 15  |
| :m1      | "P two" | 100 | 110 |
| :m2      | "P two" | 105 | 115 |
----------------------------------

Appendix A: using values to simply unions
In SPARQL 1.1, the values block lets you replace, e.g.,
{ ?s :p1 :o1 }
union
{ ?s :p2 :o2 }

with
values (?p ?o) {
  (:p1 :o1)
  (:p2 :o2)
}
?s ?p ?o

Appendix B: If you can't use values
Here's the equivalent query using union rather than values:
prefix : <urn:ex:>
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>

select ?material
       ?pLabel
       (min(?value) as ?min)
       (max(?value) as ?max)
where {
  {
    ?material :p1 ?value .
    :p1 rdfs:label ?pLabel .
    filter ( 12 <= ?value && ?value <= 15 )
  }
  union
  {
    ?material :p2 ?value .
    :p2 rdfs:label ?pLabel .
    filter ( 97 <= ?value && ?value <= 116 )
  }
}
group by ?material ?pLabel
order by ?pLabel ?material


text:
Q: Rasa Agent does not support more than 23 req/sec As we were doing a stress testing of a Rasa Agen before deploying on the production, we encountered that it only supports 23 requests per second with a response time of 1 second.
If we try to increase the requests by more than 23, then the response time increases gradually; it becomes more than 5 seconds, regardless of its hardware.
Is there any way to eliminate this limit?
I am on Rasa version 2.1.2

A: We have done a similar kind of exercise for kAIron, which internally uses rasa 2.1.2 and not able to have more than 23 req/seq; even with our chat server implementation using tornado, which still under development, we can reach 32 req/seq max with response time up to 1 sec.
In our experience, to achieve more concurrency, one option is to deploy the rasa chat server on Kubernetes with horizontal scaling


text:
Q: R Bass Diffusion Using nls() with predictors How do researchers include additional predictors/independent variables when estimating the bass curve? I've read that Bass diffusion does not accept additional predictors, but yet I see papers claiming that they do. With that said, is this possible with the nls() function in R? I have created some toy data and an example without the extra predictor, advert.
TIA
library(data.table)

options(scipen=999)
rm(list=ls())

df <- data.table(
  year  = seq(1979, 1988, by=1),
  T     = 1:10,
  sales = c(840, 1470, 2110, 4000, 7590, 10950, 10530, 9470, 7790, 5890),
  advert = c(100,100,100,100,100,75,75,50,50,25))
df[, sales_cumulative := cumsum(sales)]

est_bass <- nls(sales ~ M*(((P+Q)^2/P)*exp(-(P+Q)*T))/(1+(Q/P)*exp(-(P+Q)*T))^2,
                # add P and Q below
                start=c(list(M = 60630, P = 0.03, Q = 0.38)),
                data = df)
coef(est_bass)

# P, Q, M parameters
m  = coef(est_bass)[1]
p  = coef(est_bass)[2]
q  = coef(est_bass)[3]

Tdelt <- (1:100)/10
ngete <- exp(-(p+q)*Tdelt)

# plot pdf
par(mfrow=c(1,2))

Bpdf <- m*((p+q)^2/p)*ngete/(1+(q/p)*ngete)^2
plot(Tdelt, Bpdf, xlab = "Year from 1979", ylab = "Sales per year", type = "l")
points(df$T, df$sales) # compare to original

# plot cdf
Bcdf <- m*(1-ngete)/(1+(q/p)*ngete)
plot(Tdelt, Bcdf, xlab = "Year from 1979", ylab = "Cumulative sales", type = "l")
points(df$T, df$sales_cumulative)


text:
Q: Node.js readline line event callback guaranteed to finish before next call? I just fixed a bug where I was reading and rewriting files with readline and the lines were being written out of order (it ended up being due to an asynchronous fs.write() call).
But one thing I thought was happening was that the readline line event was coming in in the correct order, but perhaps my callback function for some of the lines was finishing after another line event had been handled.
To demonstrate:
line1 event comes in
line1 event finishes handling
line2 event comes in //Takes a long time to process
line3 event comes in
line3 event finishes handling
line2 event finished handling //And because it was after line3, gets written back after too

The final file output from above would be like:
line1
line3
line2

I didn't see any such guarantee in the docs and my testing seems to point that the above is not possible but I'm not sure. Is the above scenario possible with readline?

A: NodeJS runs your JavaScript code on a single event loop, what the JavaScript specification calls a job queue. That means that when your code is running responding to line2, it is guaranteed not to be called to respond to line3 while it's still running — if that event occurs while your code is running, the job to call your callback is queued but waits in the job queue until you finish and the event loop can pick up the next job in the queue.
Obviously, this is only true for synchronous code, because asynchronous things (like fs.write) only start a process, they don't wait for it to finish; completions are jobs that are added to the queue. So callbacks from asynchronous calls may well happen after the next event came in.
E.g., consider this code:
stream.on("line", function() {
    // do a lot of synchronous work that may tie up the thread for a while
});

you can be certain that your callback will not be called for line 3 while it's still processing the callback for line 2.
But while processing the callback for line 2:
stream.on("line", function() {
    // Code here IS guaranteed to run before we get called for line 3
    callAnAsyncFunction(function(err, data) {
        // Code here is NOT guaranteed to run before we get called for line 3
    });
    // Code here IS guaranteed to run before we get called for line 3
});


text:
Q: Unicorn does not use default ruby version I have an rails app using unicorn, nginx on aws.
I have just updated ruby version from 2.0 to 2.2.1.
ruby -v returns

ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-linux]

I was tried to restart unicorn service
sudo service unicorn_game-mercenaries_production stop
sudo service unicorn_game-mercenaries_production start

and the result was

/home/gamemercs/.rvm/gems/ruby-2.2.1@game-mercenaries/gems/bundler-1.10.6/lib/bundler/definition.rb:412:in
  validate_ruby!': Your Ruby version is 2.0.0, but your Gemfile
  specified 2.2.1 (Bundler::RubyVersionMismatch)    from
  /home/gamemercs/.rvm/gems/ruby-2.2.1@game-mercenaries/gems/bundler-1.10.6/lib/bundler.rb:123:in
  setup'   from
  /home/gamemercs/.rvm/gems/ruby-2.2.1@game-mercenaries/gems/bundler-1.10.6/lib/bundler/setup.rb:18:in <top (required)>'   from
  /usr/share/ruby/vendor_ruby/2.0/rubygems/core_ext/kernel_require.rb:55:in
  require'     from
  /usr/share/ruby/vendor_ruby/2.0/rubygems/core_ext/kernel_require.rb:55:in
  `require'

Here is my unicorn.rb:
working_directory "/home/gamemercs/rails_apps/game-mercenaries/current"
pid "/home/gamemercs/rails_apps/game-mercenaries/shared/tmp/pids/unicorn.pid"
stdout_path "/home/gamemercs/rails_apps/game-mercenaries/shared/log/unicorn.stdout.log"
stderr_path "/home/gamemercs/rails_apps/game-mercenaries/shared/log/unicorn.stderr.log"

listen "/tmp/unicorn.game-mercenaries_production.sock"

worker_processes 2
timeout 30

preload_app true

before_exec do |server|
  ENV["BUNDLE_GEMFILE"] = "/home/gamemercs/rails_apps/game-mercenaries/current/Gemfile"
end

before_fork do |server, worker|
  # Disconnect since the database connection will not carry over
  if defined? ActiveRecord::Base
    ActiveRecord::Base.connection.disconnect!
  end

  # Quit the old unicorn process
  old_pid = "#{server.config[:pid]}.oldbin"
  if File.exists?(old_pid) && server.pid != old_pid
    begin
      Process.kill("QUIT", File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH
      # someone else did our job for us
    end
  end

  if defined?(Resque)
    Resque.redis.quit
  end
  p 'stop'

  sleep 1
end

after_fork do |server, worker|
  # Start up the database connection again in the worker
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.establish_connection
  end

  p 'start'
  if defined?(Resque)
    Resque.redis = 'localhost:6379'
  end
end

/etc/init.d/unicorn_game-mercenaries_production
#!/bin/bash
### BEGIN INIT INFO
# Provides: unicorn
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Manage unicorn server
# Description: Start, stop, restart unicorn server for a specific application.
### END INIT INFO
set -e

# Feel free to change any of the following variables for your app:
TIMEOUT=${TIMEOUT-60}
APP_ROOT=/home/gamemercs/rails_apps/game-mercenaries/current
PID=/home/gamemercs/rails_apps/game-mercenaries/shared/tmp/pids/unicorn.pid

AS_USER=gamemercs
CMD="export HOME; true "${HOME:=$(getent passwd "$AS_USER" | cut -d: -f6;)}" ; cd $APP_ROOT && ~/.rvm/bin/rvm 2.2.1@game-mercenaries do bundle exec unicorn -D -c /home/gamemercs/rails_apps/game-mercenaries/shared/config/unicorn.rb -E production"

set -u

OLD_PIN="$PID.oldbin"

sig () {
  test -s "$PID" && kill -$1 `cat $PID`
}

oldsig () {
  test -s $OLD_PIN && kill -$1 `cat $OLD_PIN`
}

run () {
  if [ "$(id -un)" = "$AS_USER" ]; then
    eval $1
  else
    su -c "$1" - $AS_USER
  fi
}

case "$1" in
start)
  sig 0 && echo >&2 "Already running" && exit 0
  run "$CMD"
  ;;
stop)
  sig QUIT && exit 0
  echo >&2 "Not running"
  ;;
force-stop)
  sig TERM && exit 0
  echo >&2 "Not running"
  ;;
restart|reload)
  sig USR2 && echo reloaded OK && exit 0
  echo >&2 "Couldn't reload, starting '$CMD' instead"
  run "$CMD"
  ;;
upgrade)
  if sig USR2 && sleep 2 && sig 0 && oldsig QUIT
  then
    n=$TIMEOUT
    while test -s $OLD_PIN && test $n -ge 0
    do
      printf '.' && sleep 1 && n=$(( $n - 1 ))
    done
    echo

    if test $n -lt 0 && test -s $OLD_PIN
    then
      echo >&2 "$OLD_PIN still exists after $TIMEOUT seconds"
      exit 1
    fi
    exit 0
  fi
  echo >&2 "Couldn't upgrade, starting '$CMD' instead"
  run "$CMD"
  ;;
reopen-logs)
  sig USR1
  ;;
*)
  echo >&2 "Usage: $0 <start|stop|restart|upgrade|force-stop|reopen-logs>"
  exit 1
  ;;
esac

I'd appreciate any help.
how can I make unicorn to use default ruby(v2.2.1)?

A: Can you please edit the GEM_HOME and GEM_PATH in /etc/init.d/unicorn, to reflect your new ruby version path/number?


text:
Q: How can I prove the following statement and calculate the whole part of it? I am currently trying to exercise for a competition and have the following problem for it:
$A_n = \log_{n}(n+1)+\log_{n+1}(n)$
where $n$ is natural number. I must prove that $A_n$ can never be a whole number and I must calculate the whole part of $A_n$ .
I also must study the monotonicity of the $A_n$ sequence.
I tried by converting the logarithms to the natural base but failed with it.
I would gladly appreciate your help in solving this problem, I am pretty stuck with it.
Thanks in advance!

A: $\begin{array}\\
A_n
&= \log_{n}(n+1)+\log_{n+1}(n)\\
&= \dfrac{\log(n+1)}{\log(n)}+\dfrac{\log(n)}{\log(n+1)}\\
&=x+\dfrac1{x}
\qquad x=\dfrac{\log(n+1)}{\log(n)}
\gt 1\\
&=(\sqrt{x}-\dfrac1{\sqrt{x}})^2+2\\
&\gt 2\\
\end{array}
$
If
$A_n \ge 3$
then
$\sqrt{x}-\dfrac1{\sqrt{x}}
\ge 1$.
Let
$y=\sqrt{x}
\gt 1$.
If
$y-\dfrac1{y} \ge 1$
then
$y^2-y \ge 1$
or
$(y-\frac12)^2
\ge \frac54
$
or
$y
\ge \frac{1+\sqrt{5}}{2}
$
so
$x
=y^2
\ge \frac{1+2\sqrt{5}+5}{4}
= \frac{3+\sqrt{5}}{2}
\gt 2.618
$.
But,
using natural logs,
$\begin{array}\\
x
&=\dfrac{\log(n+1)}{\log(n)}\\
&=\dfrac{\log(n)+\log(1+1/n)}{\log(n)}\\
&=1+\dfrac{\log(1+1/n)}{\log(n)}\\
&\lt 1+\dfrac1{n\log(n)}
\qquad \log(1+z)<z\\
&\lt 1+\dfrac1{2\log(2)}
\qquad (z\log(z))'=1+\log(z)>1
\text{ for } z>1\\
&\lt 1.8\\
\end{array}
$
which contradicts
$x > 2.618$.
Therefore
$2 < A_n < 3$.


text:
Q: Bootstrap.css "font-family" on  tag crashed page on all IE versions! (windows7 64 bit machine) I was using the updating version of bootstrap which is Bootstrap v2.3.1., and it crashed on IE, my machine is Windows 7 64 bit, and i've tried all my IE version browser, it all crashed, said "Internet Explorere restricted this webpage from running scripts or ActiveX Controls" then i close this message, then the page just goes blank, which whatever default background color you have.
then i tried to take off the bootstrap.css, the website displays text etc on IE.
then i tried to go to http://twitter.github.com/bootstrap/index.html which is the offical site, it display the same error message on IE. other browsers all fine!
then i go back to the bootstrap.css, and try to debug it, i found that if i delete the line font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; from the  tag the site's showing on the IE screen! but of course the styling a bit messy, cause missing the font, but the page displays on IE finally!
Does anyone facing this issue before? and do you know how to fix this? it displays very ugly on IE, if i put back any font-family style, the page crashed again...

A: I had the same problem, it appears to be the first two fonts that are causing the issue, I changed the attribute to....
font-family: Arial, sans-serif;
and it looks OK, provided you like Arial! if not try another font.

A: I had been unable to use my IE on Windows 7 64 bit for almost a year.  It would switch to compatibility mode and then crash on almost 70% of websites that I visited.  After lots of troubleshooting and research I found that the Helvetica fonts installed on my machine were not completely compatible with Windows 7 or IE.  Since uninstalling the Helvetica fonts from my machine, IE has been working great.