text:
Q: Запуск приложения как службу в Windows. FAILED 1053 Собрал приложение, руководствуясь данным туториалом. Запускается и все хорошо работает.
Перенес приложение на сервер. Поскольку я собирал приложение через Publish в Visual Studio с указанием, что хочу иметь один файл, поэтому я переношу три файла .exe, .pdb, settings.json.
Через sc, как указано в руководстве создаю службу
.\sc.exe create "service1" binpath="C:\path\to\publish\service.exe"

И запускаю на сервере
.\sc.exe start "service1"

Получаю ошибку
[SC] StartService FAILED 1053:

The service did not respond to the start or control request in a timely fashion. windows server

Понятное дело, поискал и вот, что перепробовал:

*

*Манипуляции с ServicesPipeTimeout-ключом в регистре

*Проверены версии .NET и Runtime с ними

*Обновление системы

Дайте подсказку, как отловить то, что мешает запуску?
Приложение для .NET 6.0, C#, Windows Server 2019
Program.cs
using CsvToDdWorker;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Logging.EventLog;

using IHost host = Host.CreateDefaultBuilder(args)
    .UseWindowsService(options =>
    {
        options.ServiceName = "service1";
    })
    .ConfigureServices(services =>
    {
        LoggerProviderOptions.RegisterProviderOptions<
            EventLogSettings, EventLogLoggerProvider>(services);

        services.AddSingleton<SendToDbService>();
        services.AddHostedService<WindowsBackgroundService>();
    })
    .ConfigureLogging((context, logging) =>
    {
        logging.AddConfiguration(
            context.Configuration.GetSection("Logging"));
    })
    .Build();

await host.RunAsync();

WindowsBackgroundService.cs
namespace CsvToDdWorker
{
    public class WindowsBackgroundService : BackgroundService
    {
        private readonly SendToDbService _sendService;
        private readonly ILogger<WindowsBackgroundService> _logger;

        public WindowsBackgroundService(
            SendToDbService sendService,
            ILogger<WindowsBackgroundService> logger) =>
            (_sendService, _logger) = (sendService, logger);

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    _sendService.SendToDb(_logger);
                    await Task.Delay(TimeSpan.FromMinutes(20), stoppingToken);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "{Message}", ex.Message);
                Environment.Exit(1);
            }
        }
    }
}

UPD
Попробовал так же поиграться с периодом запуска приложения. Изменял на секунды, минуту, час. Дело не в этом.
UPD1
Запустил исполнение на сервере без службы функцию SendToDb(_logger). на прямую через dotnet run. Она работает без проблем.

A: На самом деле ошибка, которая указана в вопросе очень широкая. Описание, которое прилагается к исключению совсем не несет никакого смысла, вот это
[SC] StartService FAILED 1053:

The service did not respond to the start or control request in a timely fashion. windows server

Что удалось выяснить:

*

*Моя проблема заключалась в невнимательности при следовании инструкции. В Publish-рутине в окне всех настроек Deployment mode -> Self-contained забыл указать.

*Ошибки, исключения в самой логике приложения никак не влияют на появление данной проблемы. Я инсценировал проблемы, собирал и запускал. Да, приложение крашится, но не в момент запуска службы, а в момент исполнения. И совсем другие коды ошибок.


text:
Q: Defining Multiple Elements of a Multi-Dimensional Array In Ada, when you declare a array, you can do something like
    Work_Day : constant array (Day) of Boolean := (Mon .. Fri => True, Sat | Sun => False);

which utilizes the .. and | symbols to account for multiple elements of the array instead of having to reference each array.
I want to do something similar, but with a array of arrays, and I dont want to do it at the declaration, but instead later in the program, when I might have to redefine the initial value. I am attempting to do something like
   -- Set elements 2 through 5 of row 1 to asdf
   Array_of_Arrays(1)(2..5) := "asdf";

or
   -- Set elements 1 and 3 of row 1 to asdf2
   Array_of_Arrays(1)(1 | 3) := "asdf2"

But neither seem to be the correct syntax. Is there a way of doing this?
Thanks

A: The syntax
Array_of_Arrays(1)(2..5) := "asdf";

is legal, assuming that what you have is really an array of arrays.  However, I'm guessing that you don't.  Unlike some languages (C, Java, etc.), Ada makes a distinction between multi-dimensional arrays and "arrays of arrays".  A two-dimensional array is declared something like
type Array_Type is array (1 .. 10, 1 .. 5) of Character;
Array_2D : Array_Type;

(and similarly for 3- or higher-dimensional arrays).  When you declare your array type like this, you use indexes separated by commas to refer to a single element:
Array_2D (2, 3) := 'x';

and not
Array_2D (2) (3) := 'x';  -- wrong!!  will not compile

You can't use a slice for multi-dimensional arrays:
Array_2D (1, 2..5) := "asdf";

The language designers just didn't allow that.
An array of arrays would be declared like:
type Array_Row is array (1 .. 5) of Character;
type Array_Of_Array_Type is array (1 .. 10) of Array_Row;
Array_Of_Arrays : Array_Of_Array_Type;

Now, since the array row type is separate, you don't use the multi-dimensional array syntax.  To get at one character, you'd use something like
Array_Of_Arrays (2) (3) := 'x';

and it's legal to do something like
Array_Of_Arrays (1) (2..5) := "asdf";

but not
Array_Of_Arrays (1, 2..5) := "asdf";  -- syntax error

The key is to remember that in this case, each "row" of the array is a separate array object with its own array type; while in the multi-dimensional case, rows don't have their own types.
You can use either one; there are some cases where an array of arrays may be more appropriate, and some where a multi-dimensional array is more appropriate.
Since String is an array type, this also is an array of arrays:
type Array_Of_Strings is array (1 .. 10) of String(1..5);

and this is legal:
A : Array_Of_Strings;

A (3) (4) := 'y';

but not
A (3, 4) := 'y';         -- illegal

redpajama_set_name: RedPajamaStackExchange


text:
Q: variable in XML subelement I'm thinking of Python code to create a dynamic xml ETREE subElement.
I have a hierarchical header to describe a peace of book as the following:
<Books>
<Booktype List= "Story > Fiction > Young">
#here the rest of book text
</Booktype>
<Booktype List= "Science > Math > Young">
#here the rest of book text
</Booktype>
</Books>

How to get a hierarchical xml tag like this :
<Books>
<Booktype>
  <Story>
    <Fiction>
         <Young>
#here the rest of book text
         </Young>
    </Fiction>
  </Story>
</Booktype>
</Books>

This is my code:
import re
import xml.etree.ElementTree as ET
from xml.etree import ElementTree

List= "Story>Fiction>Young"
List = List.split('>')
root = ET.Element('Books')
Booktype =ET.SubElement(root,'Booktype')

for l in List:
  ND = ET.SubElement(Booktype,str(l))
  Booktype.append(ND)

tree = ET.ElementTree(root)
ElementTree.tostring(root,'utf-8')

I got this bad result:
'<Books><Booktype><Story /><Story /><Story /><Fiction /><Fiction /><Young /><Young /><Story /><Story /><Fiction /><Fiction /><Young /><Young /></Booktype></Books>'

A: If you want to nest the list elements you have to keep the reference to the previous one so you can add the child element to it, and not to the Booktype element. See the variable currrent in the examples.
from xml.etree import ElementTree as ET

xml_string = '''<Books>
<Booktype List= "Story > Fiction > Young">
#here the rest of book text
</Booktype>
<Booktype List= "Science > Math > Young">
#here the rest of book text 2
</Booktype>
</Books>
'''

xml = ET.fromstring(xml_string)
for booktype in xml.findall('Booktype'):
    types = map(lambda x: x.strip(), booktype.get('List').split('>'))
    current = booktype
    for t in types:
        current = ET.SubElement(current, t)
    current.text = booktype.text
    booktype.text = ''
    del booktype.attrib['List']
print ET.tostring(xml,'utf-8')

Gives me the result:
<Books>
<Booktype><Story><Fiction><Young>
#here the rest of book text
</Young></Fiction></Story></Booktype>
<Booktype><Science><Math><Young>
#here the rest of book text 2
</Young></Math></Science></Booktype>
</Books>

And if you want to create a completely new structure you can do:
xml = ET.fromstring(xml_string)
root = ET.Element('Books')
for booktype in xml.findall('Booktype'):
    current = ET.SubElement(root, 'Booktype')
    for t in map(lambda x: x.strip(), booktype.get('List').split('>')):
        current = ET.SubElement(current, t)
    current.text = booktype.text
print ET.tostring(root, 'utf-8')


text:
Q: c# Windows Form Application is crashed on client machine my app is crushing on client PC . i installed another SQL server 2014 in my second laptop after changing the SQL connection string and setting file it's work for me normal . and in my developer machine " the first one" is working simple. but when i change the connection setting as i did for my laptop and take the App to client machine it crushing .
i am using the same SQL Server 2014 on all of computers.
and show this message :

i tried to reinstall new .Net Framework but not work too .
what should i do her ?

A: In Program.cs, App.cs or App.xaml.cs you can register an exception handler which catches all exceptions that are unhandled, even those leading to a crash. Register a function to AppDomain.CurrentDomain.UnhandledException as soon as the program launches and in that handler you can dump the ExceptionObject in the second argument to a text file. That will at least give you further information to work with.
Other than that there is no way for us to pinpoint even a remote cause for that crash, as we have not enough information.

A: I entirely agree with the need for a Error handling in your code!  Nevertheless, the following might help.

*

*I strongly recommend not having a fixed connection string within your application.  That makes it very hard to port to client machines.  Instead include the connection string in your Settings.

*On the client machine open Notepad and save a new empty file with a .udl extension (you will need to select All Files on the Save Dialog dropdown), eg testconn.udl.  Now from Explorer double click the new .udl file.  A Data Link Properties Window should open.  On the provider tab, select SQL Server Native Client. On the Connection Tab, select the name of the client's SQL Server and fill in the other options as appropriate.  Now click Test Connection.  Hopefully, it will say Test succeeded. Now click OK, and re-open the .udl file in Notepad.  It will have created an oledb string.  For SQLClient, you will not need the "Provider=" part, and you can also ignore Initial File Name and ServerSPN; the rest however, will give you the values that the client needs as a connection string.

*Assuming you have done 1. and 2. you can now edit your app's config file to contain the correct connection string.
The only thing that can go wrong, is if Test Connection in 2. does not work.  There could be so many reasons for this, that I will not try to second guess here.  Please try it, and report back any problems. If Test Connection does not succeed, at least you can be sure that the problem is not your code!


text:
Q: Execute loop function for specific files from a directory I have a folder contains 10 files (in 5 categories depending on time of measurements is Sec) sorted by name as follow:
   measured_data_2Sec_1_.txt
   measured_data_2Sec_2_.txt

   measured_data_4Sec_1_.txt
   measured_data_4Sec_2_.txt
   .
   .
   .
   measured_data_10Sec_1_.txt
   measured_data_10Sec_2_.txt

I need to run a loop function as follow:
First import only files with 2Sec:
measured_data_2Sec_1_.txt
measured_data_2Sec_2_.txt

and analysis data and save them, then return back to import only files with 4Sec:
measured_data_4Sec_1_.txt
measured_data_4Sec_2_.txt

and so on....
I tried my code:
 import numpy as np
 import glob
 import matplotlib.pyplot as plt

 files = glob.glob("input/*.txt")
 for f in files:
     intial_data = np.loadtxt(f)
 # Select Y-axis
     amp = intial_data[:,0]
 # Select X-axis
     volt = intial_data[:,1]

 # modify X-axis
     amp_corr = amp*2
 # modify Y-axis
     volt_corr = volt/0.2
     plt.plot(amp_corr ,volt_corr )

But this code run the loop for all of them.
My target is to run the loop for each category separately.


text:
Q: Adaptive User Interface based on user experience I need to modify a web application's interface based on user behavior. For example, new users will see the interface in a simplified way and expert users will see all the features of the application. How can I distinguish between the two types of users? The web application is built on Flask. How should I approach and is there any constructive tutorial that I can follow?

A: You could use Cookies/Local Storage to count and save how many times they have visited, or if they have visited before. This can be done through Flask, see here for how it's done: link.
Alternatively, give the user the option to toggle between the views, and use a cookie to save their option.


text:
Q: entering the last created directory via sftp connection i have opened an SFTP connection to a remote server via Linux shell script, now i need to enter to the last created directory in directory /distribution and download the files from it, the code looks like:
lftp -u ${sourceEnv},${sourcePass} sftp://${sourceHost}<<EOF
cd $sourceBuildDir/distribution
variable=$(ls -t -r | tail -n 1)
cd $variable
mget *
bye
EOF

but it doesn't work via SFTP connection neither the command ls -t -r | tail -n 1 by itself nor the variable creation.
Any ideas ?
Thanks in advance

A: in the same spirit of Marc B's answer, I don't think you can do it all inside of lftp.
In particular I don't think it supports user variables... (I should check...)
So, for some purposes you can call the shell from which you start lftp inside of a lftp script. For example:
# This is a lftp script (like yours)
ls -tr| ! "tail -1|awk '{print $NF}'"

Everything after the '!' is passed to the unix shell. The 'tail' that is called is the system tail and not some lftp command. The same goes for awk, which I use to get only the name of the dir (ls of lftp gives all file permissions etc...)
For more complex things (as your requested) I believe you're better off with a shell script that uses lftp just as any other shell command. Your example would become something like:
    # Call lftp to log in and do 'ls', capture the ouput and process it.
    sourceBuildDir=$(lftp -c "open ${sourceEnv}:${sourcePass}@${sourceHost}; ls" \
                     |tail -1|awk '{print $NF}');
    echo "I am about to download $sourceBuildDir";
    # Call lftp with the processed dir name and do the rest
    # (btw. did you consider using the 'mirror' command?)
    lftp -c "open ${sourceEnv}:${sourcePass}@${sourceHost}; \
             cd $sourceBuildDir/distribution; mget *";

P.S.
Sometimes lftp commands produce extra stuff like "[FEAT negotiation...]" that may break the script. You can probably solve by repeating lftp commands twice, so that the second time they succeed without further negotiation by lftp.
Hope this helps getting on the right track! Cheers.


text:
Q: Can I control the font size in the margins of a StyledTextCtrl? I've slightly reduced the font size of my StyledTextCtrl, but it didn't affect the font size in the margins of the text control, namely the line number font:

Is there any way to control the font size in the margins?

For those interested, here is my subclass:
class CustomTextCtrl(StyledTextCtrl):
    """A `StyledTextCtrl` subclass with custom settings."""
    def __init__(self, *args, **kwargs):
        StyledTextCtrl.__init__(self, *args, **kwargs)

        # Set the highlight color to the system highlight color.
        highlight_color = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self.SetSelBackground(True, highlight_color)

        # Set the font to a fixed width font.
        font = wx.Font(12, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL,
                       wx.FONTWEIGHT_NORMAL, False, 'Consolas',
                       wx.FONTENCODING_UTF8)
        self.StyleSetFont(0, font)

        # Enable line numbers.
        self.SetMarginType(1, wx.stc.STC_MARGIN_NUMBER)
        self.SetMarginMask(1, 0)
        self.SetMarginWidth(1, 25)

    def SetText(self, text):
        """Override of the `SetText` function to circumvent readonly."""

        readonly = self.GetReadOnly()
        self.SetReadOnly(False)
        StyledTextCtrl.SetText(self, text)
        self.SetReadOnly(readonly)

    def ClearAll(self):
        """Override of the `ClearAll` function to circumvent readonly."""

        readonly = self.GetReadOnly()
        self.SetReadOnly(False)
        StyledTextCtrl.ClearAll(self)
        self.SetReadOnly(readonly)

A: You're using the wrong style number for StyleSetFont. You probably meant to use:
self.StyleSetFont(wx.stc.STC_STYLE_DEFAULT,font)

which has a value of 32 not 0. If you want to set the font for the line numbers separately, use:
self.StyleSetFont(wx.stc.STC_STYLE_LINENUMBER,font)

See wxStyledTextCtrl - Styling & Style Definition for more details.


text:
Q: Dependency Injection design question What are the advantages/disadvantages of the following approaches for injecting configuration information into a newly constructed instance? Which would you use?
interface IApplicationConfiguration {
    string SourcePath { get; }
    string DestinationPath { get; }
}

Option one:
class DailyFilePathProvider {
    private readonly string sourcePath;
    private readonly string destinationPath;
    public DailyFilePathProvider(string sourcePath, string destinationPath) {
        this.sourcePath = sourcePath;
        this.destinationPath = destinationPath;
    }
}

var configuration = container.Resolve<IApplicationConfiguration>();
var provider = new DailyFilePathProvider(configuration.SourcePath, configuration.DestinationPath);

Option two:
class DailyFilePathProvider {
    private readonly string sourcePath;
    private readonly string destinationPath;
    public DailyFilePathProvider(IApplicationConfiguration configuration) {
        this.sourcePath = configuration.SourcePath;
        this.destinationPath = configuration.DestinationPath;
    }
}

var configuration = container.Resolve<IApplicationConfiguration>();
var provider = new DailyFilePathProvider(configuration);

Thanks for all thoughts.

A: It depends,
I would go for option two if IApplicationConfiguration only contains configuration related to the DailyFilePathProvider. If it contains configurations for other parts of your application you might consider this 'bad separation of concerns'. In that case a better option would be to add a property IDailyFilePathProviderCfg to the IApplicationConfiguration that contains configuration specifically for the DailyFilePathProvider. That way you get best of both worlds, you only inject relevant data like in option one but the code is also easy to maintain like in option two.
Personally I think application wide configuration is best abstracted away in a static class So all parts of the code can easily access settings.
The answer to this question depends a lot on personal programming style I guess. It also depends on the type and size of application you are building. Personally I don't like to inject more in a constructor than needed for the object you are building.

A: This answer of mine to a similar question may provide some insight:
Dependency Injection and AppSettings
The gist is that the Confguration interface is plumbing which adds no semantic value in the class that consumes it. There is also an example of how to structure an application so these values can easily be disseminated. The answer was marked as the question's accepted answer.

A: I prefer option 2 so I can easily add more settings without changing the ctor. I would also switch it to...
class DailyFilePathProvider {
    private readonly IApplicationConfiguration configuration;

A: The first code only uses some kind of dependency injection to resolve which configuration to use, but it doesn't use dependency injection when constructing the DailyFilePathProvider.
So I would go for option number two where you actually are injecting the configuration into DailyFilePathProvider.
Here are some more about patterns with NInject as an example: Injection patterns


text:
Q: Write To TextFile Using StreamWriter My contents are displayed in the console, but my text file is never generated.  What is keeping my text file from being generated?
        public static void GetDirInfo()
    {
        string filename = "C:\\Test.txt";
        string sourcePath = @"C:\";
        var dir = new DirectoryInfo(sourcePath);
        Console.WriteLine(dir);
        var children = dir.EnumerateFileSystemInfos();
        Console.WriteLine(children);
        var files = children.OfType<FileInfo>().Count();
        Console.WriteLine(files);
        var directories = children.OfType<DirectoryInfo>().Count();
        Console.WriteLine(directories);

        using (var sw = new StreamWriter(filename, true))
        {
            sw.WriteLine(dir);
            sw.WriteLine(children);
            sw.WriteLine(files);
            sw.WriteLine(directories);
        }
     }

A: I tried running your code and got UnauthorizedAccessException. I ran the same code as an admin and the file was created.


text:
Q: How to make code to manipulate string on specific condition in javascript using loops? here I'm having a JSON data after JSON parsing we can take data property as string
data:"BUSINESS.id,BUSINESS.stokens[],BUSINESS.plist(BUSINESS.inventory),BUSINESS.bslist(BUSINESS.srvinventory),BUSINESS.sur(USER.store.roles.role)[{scdate,sudate,rid,urname,sid,suid}]"

and I need to split it by specific requirement
text = BUSINESS.id,BUSINESS.stokens[]
list = BUSINESS.plist(BUSINESS.inventory),BUSINESS.bslist(BUSINESS.srvinventory)
object = BUSINESS.sur(USER.store.roles.role)[{scdate,sudate,rid,urname,sid,suid}]

make sure that while programming don't consider BUSINESS as string could be also
data:"id,stokens[],plist(inventory),bslist(srvinventory),sur(USER.store.roles.role)[{scdate,sudate,rid,urname,sid,suid}]"

text = id,stokens[]
list = plist(inventory), bslist(srvinventory)
object = sur(USER.store.roles.role)[{scdate,sudate,rid,urname,sid,suid}]

make code for this string in javascript
I tried to split code based on (",") but it does not satisfy the requirement as we need to make code separately for text, list, and object
please divide string on given requirement
the text has only . or []
list have only ()
an object is a combination of ()[{}]

A: You can use the regex with String.prototype.match

let data = "BUSINESS.id,BUSINESS.stokens[],BUSINESS.plist(BUSINESS.inventory),BUSINESS.bslist(BUSINESS.srvinventory),BUSINESS.sur(USER.store.roles.role)[{scdate,sudate,rid,urname,sid,suid}]";
let out = data.match(/(.*\[\]),?(.*\(.*\)),?(.*\(.*\).*\[\{.*\}\]),?/);
console.log(out.slice(1,4))

let data = "id,stokens[],plist(inventory),bslist(srvinventory),sur(USER.store.roles.role)[{scdate,sudate,rid,urname,sid,suid}]";
let {1: text, 2: list, 3: object} = data.match(/(.*\[\]),?(.*\(.*\)),?(.*\(.*\).*\[\{.*\}\]),?/);
console.log(text);
console.log(list);
console.log(object);


text:
Q: How to display in the Title the numer of marks on a scatter-plot How can I capture the number of Marks in a scatter-plot?   I want to display it in the worksheet Title.

A: I think you might be able to use the SIZE() function to count the number of marks. https://help.tableau.com/current/pro/desktop/en-us/functions_functions_tablecalculation.htm
Edit:
If you apply your SIZE() table calculation along the specific dimensions that define your marks you should get the total number of marks accessible at each point.

A: You can do this with the WINDOW_COUNT function.
WINDOW_COUNT(COUNTD([Number of Records]))
or
WINDOW_COUNT(SUM([Number of Records]))

I get the same result in either case and both return the number of marks in my view as indicated in the lower left of the sheet tab.

Then update your Compute Using to the level of detail of your marks.


text:
Q: Passing parameters from Flutter to Google Cloud Functions I'm trying to figure out how to communicate between Flutter and Google Cloud Functions.
I wrote a simple Google Cloud Function that returns a list and a parameter but I keep receiving null when I call the function with a parameter. Why is this happening?
The Flutter Function
Future<void> getFruit() async {
   HttpsCallable callable = FirebaseFunctions.instance.httpsCallable('listFruit');
   final results = await callable.call(['hello']);
   List fruit = results.data;
   print(fruit);// ["Apple", "Banana", "Cherry", "Date", "Fig", "Grapes"]
 }

The Google Cloud Function
const functions = require("firebase-functions");

exports.listFruit = functions.https.onCall((data, context) => {
  return ["Apple", "Banana", "Cherry", "Date", "Fig", "Grapes", data.text];
});

The Output
flutter: [Apple, Banana, Cherry, Date, Fig, Grapes, null]

Expected Output
flutter: [Apple, Banana, Cherry, Date, Fig, Grapes, hello]

Can someone please help me figure out why my expected output is not coming out?

A: replace
final results = await callable.call(['hello']);

with
final results = await callable.call({text: 'hello'});


text:
Q: Rewriting $p(A\cup B)$ We can write $p(A\cup B) = p((A\cup B)\cap S) = p((A\cup B)\cap (B\cup B^{c})) = p((A\cap B^{c})\cup B)$, how has the final step occurred?

A: By the distributive law: $$(A\cap B^c) \cup B = (A\cup B)\cap (B^c\cup B) = (A\cup B)\cap(B \cup B^c)$$
In your problem, we started from above, on the right to obtain the equivalent expression, given above on the left.
(In case you're confused about $S = B\cup B^c$, recall that $B \cup B^c$ is the entire probability space).


text:
Q: conflicts in Git feature branches, how to detect them early With developing Java with Git, we have the frequent problem that different people change the same classes in different feature branches, which results in merge conflicts.  While these problems are inevitable to some point, we would like to detect these problems early, so people can talk and align.
I see two possible solutions here: best practices (like looking at other peoples branches) and tool support.  If I miss some best practices, so please point me to some document.  If there are tools (you add branches to a list and get an email in case of possible conflicts), please tell me.

A: That's similar to continuous integration.
You could have whatever build-system you use for continuous integration (teamcity, jenkins) try to merge branches every day/hour and send an e-mail when it failed to do it automatically.

A: One solution could be to rebase your branches frequently.
Once another developer has merged his branch in master (or another common dev branch), you can rebase your current branch with master and thus deal with the conflicts at this moment.
Another good practice is to have short-lived branches that will allow to see conflicts rapidly.
You can also have the developers open a merge request as soon as they start to work on their branches, that way, other developers can see if they are working on the same files and anticipate conflicts.


text:
Q: NetworkingError: getaddrinfo EMFILE dynamodb.eu-west-1.amazonaws.com:443 There is a table say company. If we try to get the company by it primary key we get the following error.
PLEASE NOTE: This error is not for all instances. It is not repeatedly getting failed. It occurs sometimes but often. 20% of requests are failing
{ Error: getaddrinfo EMFILE dynamodb.eu-west-1.amazonaws.com:443
at Object._errnoException (util.js:1022:11)
at errnoException (dns.js:55:15)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)
message: 'getaddrinfo EMFILE dynamodb.eu-west-1.amazonaws.com:443',
code: 'NetworkingError',
errno: 'EMFILE',
syscall: 'getaddrinfo',
hostname: 'dynamodb.eu-west-1.amazonaws.com',
host: 'dynamodb.eu-west-1.amazonaws.com',
port: 443,
region: 'eu-west-1',
retryable: true,
time: 2019-07-18T05:30:09.145Z }

A: There was a discussion on aws/aws-sdk-js-v3 with issue #3019 where it was recommended to lower the socket timeouts.
This happened to me too when I used the agent as below
new https.Agent({
  keepAlive: true,
  maxSockets: Infinity,
}

Then I looked more into the documentation here at Reusing Connections with Keep-Alive in Node.js and what I found was an interesting thing

The easiest way to configure SDK for JavaScript to reuse TCP connections is to set the AWS_NODEJS_CONNECTION_REUSE_ENABLED environment variable to 1. This feature was added in the 2.463.0 release.

So, I removed the httpsAgent from the AWS DynamoDBClient connection and added the required environment variable -
AWS_NODEJS_CONNECTION_REUSE_ENABLED: 1

The error was resolved and things were working as expected.
I hope somebody might find this answer helpful.


text:
Q: What features of C++ or other OOPL's are difficult to implement using YACC, or alternatively a recursive descent parser? It has been said that C++ can be done with a recursive descent parser, or with an LL parser, or even with some difficulty and LALR parser, but that these tasks require hacking and kludging. OK, so what is the most OOP-like grammar that can be done each of these parser types without any major difficulty that requires kludges? What OOP features are prohibited by each of these types of parser?

A: The biggest problem with C++ is that often you cannot tell if something is a declaration or statement/expression until you've reached the semicolon. It requires "infinite lookahead", which you can do with some LL approaches (usually recursive-descent). You would definitely need a hacked LALR approach. (I used to work for Frank DeRemer, the inventor of LALR; they hired me as a guy who preferred LL to help them with a hybrid approach, but I ended up switching to a Java training company with Terence Parr, the creator of PCCTS/ANTLR before we really got into it)
Most other languages really aren't that difficult to create a LALR grammar; LL can take a little more thought because it normally cannot handle left-recursive rules (ANTLR 3 now can, but there are some limitations to how you can use it if you need a precedence grammar)

A: LL, SLR, LALR, LR, define successively larger classes of grammars, i.e. syntaxes.
A feature doesn't have to be OO to be non-LL, non-SLR, non-LALR, non-LR, ...
Conversely there are no OO features I am aware of that aren't capable of being expressed in LL, LALR, or LR grammars respectively. [Whether that has actually been done in the dozens of languages concerned is another issue.]
In short your question doesn't make sense.


text:
Q: Can't run 2 different scripts on the same yiigridview in yii So I have this gridview:
<?php $this->widget('zii.widgets.grid.CGridView', array(
            'id'=>'symptoms-grid',
            'selectableRows'=>1, //ability to select one symptom at a time
            'dataProvider'=>$model->search(),
            'htmlOptions'=>array('id'=>'symptomsSearchgrid'),
            'columns'=>array(
                'symptomCode',
                'title',
                'inclusions',
                'exclusions',
                'symptomCategory',

            ),
    )); ?>

And this javascript....script:
Yii::app()->clientScript->registerScript('search', "
        $( document ).ready(function() {

        $('#symptomSelectDiv').hide();

        $('#categorySelectDropDown').change(function(){
            $('#symptomSelectDiv').show();
            $('#symptoms-grid').yiiGridView('update', {
                data: $(this).serialize()
            });
            return false;
        });

        $('#symptomsSearchgrid table tbody tr').on('click', function() {

            var firstColVal = $(this).find('td:first-child').html();
            $('#symptomToBeSearched').val(firstColVal);
        });
        });
 ");

My problem is that I can only either get the
    $('#symptoms-grid').yiiGridView('update', {
            data: $(this).serialize()
        });

function to work or the:
 $('#symptomsSearchgrid table tbody tr').on('click', function() {

        var firstColVal = $(this).find('td:first-child').html();
        $('#symptomToBeSearched').val(firstColVal);
    });

one, and it seems quite random too. Basically in order to get the other function to "start working" I have to change the id (either the grid id or the DOM id) of one function to something different for the other function to work (while the other doesn't).
So let's say at first the update function works and the click function doesn't. Then I change the ID of update to something wrong and click works. Then I change the id of update back to the correct one, but it still doesn't work, yet click works. THen I change click to a wrong id and update starts working correctly. But again, if I change click to the correct id it doesn't work.....
Any ideas what I'm doing wrong?

A: I think your issue is that your are giving your grid two id's one when creating it and one in htmloption.


text:
Q: iframe has eaten my JavaScript codes. What's going wrong? <!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
    <iframe id="frame" allowfullscreen="allowfullscreen" frameborder="0" style="height: 300px; width: 100%">
</div>

<script type="text/javascript">
    console.log("test");
</script>
<body>
</html>

Here, I have placed the JS codes at the bottom of the page. And the result is it's eaten. If I remove the iframe element, the codes work fine. Evidently, the iframe I place here is an empty one without linking to any source. Hence, no other inline JS codes are brought in. BTW, if I put scripts in the head block, they work fine too.
I really don't know WHY? Could anybody give me some comments?

A: Use a validator (such as http://html5.validator.nu/ or http://validator.w3c.org). The biggest problem you have is that you're not closing the iframe with a </iframe> tag. Anything between iframe tags will only show for clients who have iframes disabled.
Final code should look like:
<iframe id="frame" allowfullscreen="allowfullscreen" frameborder="0" style="height: 300px; width: 100%">
    This page requires iframes... blah blah.
</iframe>

In the future, always validate when you're not 110% sure.


text:
Q: Is there a USB alternative to Mass Storage which works at the filesystem layer? Is there a USB alternative to Mass Storage which works at the filesystem layer?
The goal is to be make a USB device which is mountable as a filesystem, not a block device.
The difference is that working at the filesystem layer would allow the device to coordinate writes to it's backing storage that happen both from the host OS and from the device itself.
Interfacing at the block device layer, means that the device would have to stop writing as soon as it was mounted on the host OS (as SD cards in phones used to).
I'm interested in support in the big three OSs (Linux, OSX and Windows 7+), but not Andriod, iOS or other Unix variants.

A: The Media Transfer Protocol device class is pretty close to what you're looking for. It's not always exposed as a "normal" filesystem in all operating systems, but it does implement operations at the file level, rather than at the block level, like you're asking for.

A: The most direct way to do what you're suggesting is to implement your USB device so that it looks like a network interface to the host system. Internally, your device would "pretend" to be a USB-to-Ethernet adapter talking to a remote filsystem using, say, NFS or CIFS protocol.
The major operating systems already have drivers to support this type of operation, and if you're using some sort of Linux in your device, most of the the code for that side already exists, too.


text:
Q: Embeddable Common Lisp (ECL): load shared library with extension functions Is it possible to load a shared library in ECL, import some C functions which receive and return cl_object (as if they were defined with ecl_def_c_function()) and invoke them in REPL (without compiling a *.lisp file)?
For example:
// file 'extensions.c' compiled to 'extensions.so'

cl_object
    do_something
        (cl_object arg)
{
    cl_object
        result = ...;

    return result;
}

; in ECL REPL
(uffi:load-foreign-library #p".../extensions.so")
... ; importing stuff
(format t "got: ~a~%" (do-something "text"))

As I found there's no way of telling ECL (via UFFI) that C functions deal with cl_object, not a regular pointer (void*).

A: Looks like you can't do it as easy as in Python.
The only solution I found so far:
extlib.c
#include <stdio.h>
#include <ecl/ecl.h>

static
cl_object
    make_pair
        (cl_object arg)
{
    return cl_cons(arg, arg);
}

void
    init_extlib
        (void)
{
    ecl_def_c_function(
        ecl_read_from_cstring("make-pair"),
        make_pair,
        1
    );
}

Compile it:
clang `ecl-config --cflags` extlib.c -shared -fPIC -o extlib.so `ecl-config --libs`

load-extlib.lisp
(uffi:load-foreign-library "~/extlib.so")
(uffi:def-function ("init_extlib" init-extlib)
                   ()
                   :returning :void)
(init-extlib)

Compile it:
ecl -compile load-extlib.lisp -o load-extlib.fas

Load & test it:
ecl -load load-extlib.fas
> (make-pair "blah")

("blah" . "blah")


text:
Q: Minimum Euclidean Distance I have two dataframes (attached image). For each of the given row in Table-1 -
Part1 - I need to find the row in Table-2 which gives the minimum Euclidian distance. Output-1 is the expected answer.
Part2 - I need to find the row in Table-2 which gives the minimum Euclidian distance. Output-2 is the expected answer. Here the only difference is that a row from Table-2 cannot be selected two times.
I tried this code to get the distance but not sure on how to add other fields -
import numpy as np
from scipy.spatial import distance

s1 = np.array([(2,2), (3,0), (4,1)])
s2 = np.array([(1,3), (2,2),(3,0),(0,1)])
print(distance.cdist(s1,s2).min(axis=1))

Two dataframes and the expected output:

A: The code now gives the desired output, and there's a commented out print statement for extra output.
It's also flexible to different list lengths.
Credit also to: How can the Euclidean distance be calculated with NumPy?
Hope it helps:
from numpy import linalg as LA

list1 = [(2,2), (3,0), (4,1)]
list2 = [(1,3), (2,2),(3,0),(0,1)]

names = range(0, len(list1) + len(list2))
names = [chr(ord('`') + number + 1) for number in names]

i = -1
j = len(list1) #Start Table2 names
for tup1 in list1:
    collector = {} #Let's collect values for each minimum check
    j = len(list1)
    i += 1
    name1 = names[i]
    for tup2 in list2:
        name2 = names[j]
        a = numpy.array(tup1)
        b = numpy.array(tup2)
#        print ("{} | {} -->".format(name1, name2), tup1, tup2, "   ", numpy.around(LA.norm(a - b), 2))
        j += 1
        collector["{} | {}".format(name1, name2)] = numpy.around(LA.norm(a - b), 2)
        if j == len(names):
            min_key = min(collector, key=collector.get)
            print (min_key, "-->" , collector[min_key])

Output:
a | e --> 0.0
b | f --> 0.0
c | f --> 1.41


text:
Q: White space between actionbar and statusbar as you can see in the picture below, the white space lays between status bar and actionbar. I normally include android.support.v7.widget.Toolbar with TextView and then I set supportActionbar in MainActivity.
This bug happens only on Sony phone with android 6.0

A: Try this code
ActionBar actionBar = getActionBar();
    if(actionBar !=null)
    {
        actionBar.hide();
    }


text:
Q: How do I set up a very simple deployment using a Gitlab CI runner? I'd like to automatically deploy new work from my Gitlab repository to a live website running on a production server. The live website is a GIT repo clone of the live branch.
My questions:

*

*each time a 'build' happens, the runner seems to clone my repo afresh, into ~/builds/.... Is this mandatory behaviour? All I think I really want is a git pull inside my production website directory.

*if it really has to clone the repo each time, why doesn't it git reset it? At least that would save a ton of bandwidth over time, wouldn't it?

*how do I run my deploy.sh which is in the repository root? I currently get this error in my gitlab.com builds info: bash: line 23: deploy.sh: command not found
My .gitlab-ci.yml file:
deploy_to_production:
  script:
    - deploy.sh
  only:
    - live
  tags:
    - prod

Details
To do this, I want to run a simple shell script that I wrote (deploy.sh) on the production server, whenever I push to a specific branch of my repo (the live branch, in my case). This shell script is in my GIT repository, alongside my .gitlab-ci.yml.
The script basically just does a git reset, fetch and pull, bringing the production version up to date with what's in the repository.
I have installed a "shell" multi-runner on my server, and connected that to gitlab.com, where I can see it active.
Overall, I am barking up the wrong tree? Should I change my deploy.sh so that it doesn't do a git checkout of the new work, but rather uses cp or perhaps rsync to move the new code from ~/builds/... into the production website?

A: Q: Is the cloning a mandatory behavior?
As far as I know it is because the assumption is that during the build process you work with the code.
If that's not your case and you only want to "tell the production server" to pull the code from your repo, then maybe you can take a different approach and use a webhook instead. GitLab would make a HTTP request to your server and pass the information about the event (push, merge, etc.) in the JSON format. The receiving script would then parse it and make a decision whether to do the git pull.
If you do have other tasks to perform on the code during the build process before deployment, then yes, alter the strategy and use the code that the runner has already checked out for you. I'd probably attempt to have the change atomic in some way (rsyncing into the live directory would leave your application in some uncertain state when it runs and in a mess if it fails for some reason), e.g. by having the live code in a directory that is symlinked. The deployment script would then copy the new code directory to its final destination, make any necessary adjustments and change the symlink's target from the old live directory to the new one.
Q: If it really has to clone the repo each time, why doesn't it git reset it?
That's more of a question for the developers. Anybody else's answer would be just speculation.
Q: How do I run my deploy.sh which is in the repository root?
If the deploy.sh script has the executable bit set, then use ./deploy.sh, otherwise bash deploy.sh.


text:
Q: spring  with wildcards I'd like to load key-value pairs from multiple locations. My first guess was:
<util:properties id="requestProcessorRepository"
  location="classpath*:*requestProcessors.properties"/>

but it is not valid
Invocation of init method failed; nested exception is java.io.FileNotFoundException: class path resource [classpath*:*requestProcessors.properties] cannot be opened because it does not exist
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1412)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:546)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:872)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
    at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
    ... 24 more

Without wildcards, it starst to work.
So any other possibilities to create a properties object / map from wildcarded files?

A: First of all, your resource path classpath*:*requestProcessors.properties is not reliable (from Spring Reference):

Please note that "classpath*:" when
  combined with Ant-style patterns will
  only work reliably with at least one
  root directory before the pattern
  starts, unless the actual target files
  reside in the file system. This means
  that a pattern like "classpath*:*.xml"
  will not retrieve files from the root
  of jar files but rather only from the
  root of expanded directories.

If you solve this problem, you can load properties as follows:
<bean id = "requestProcessorRepository"
    class = "org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name = "locations"
        value = "classpath*:somefolder/*requestProcessors.properties" />
</bean>

(Original version of the code was more complex, but there is no need in it, since Spring converts path with wildcards to Resource[] automatically).


text:
Q: Teradata SQL Assistant: Alternatives {on Windows} Are there alternatives to Teradata SQL Assistant {on windows}, possibly freeware?
Heidi is great but it does not support Teradata.
What are the pros and cons of the alternatives?

A: Teradata Studio and Studio Express are the long term replacements for SQL Assistant from Teradata. They are developed around an Eclipse based IDE and are available to download from Teradata Developer Exchange.

A: Database .NET is a Free universal database manager for Windows All,
It supports most popular databases, including Teradata database.

A: Not sure if the reason is price,  but the latest version of SQL Assistant is downloadable free from Teradata's website:
http://downloads.teradata.com/download/tools/teradata-studio
You don't have to install everything, just pick and choose what you want.


text:
Q: Dart Http Package request timeout While using http package in my flutter app, I encountered a slight issue. I am testing on localhost and when I post something in database using http.post, it doesn't return response for default time (i.e. 60s I think) when server is not running. And when I start the apache and mysql services within the timeout, it posts the data in the server . Is there any way to reduce the timeout of the http requests in dart http package? Or is there any alternative solution?

A: You have two options availabe.
Reduce the timeout on the HttpClient

final client = new HttpClient();
client.connectionTimeout = const Duration(seconds: 10);

This will apply to all request made by the same client. If the request exceeds this timeout, a SocketException is thrown.
Set a per request timeout
You can set a timeout on any Future using the Future.timeout method.
try {
  ..
  final request = await client.get(...);
  final response = await request.close().timeout(const Duration(seconds: 10));
  // more code
} on TimeoutException catch (e) {
  // handle timeout
}

A: This is for http package
final response = await http.post(Url).timeout(Duration(seconds: 5));

And this is for Dio package (recommend to test this package)
BaseOptions options = new BaseOptions(
    baseUrl: baseUrl,
    connectTimeout: 10000, //10 seconds
    receiveTimeout: 10000,
   );

Dio dio = new Dio(options);

Response<dynamic> response = await dio.post(url, data: mapData);


text:
Q: Processing algorithm as expression in QGIS I would like to be able to set an expression as the default value of an attribute (in layer properties-->attributes form) which uses an algorithm from the QGIS toolbox.
In this case, the algorithm I want to use is 'Zonal statistics' to calculate the average altitude of polygons (vector layer), based on a DEM (raster layer). I have copied the algorithm from the toolbox function after running it, and attempted to use it in the field calculator in various ways to see if it would work as an expression and it does not.
In other cases, I would also like to know how to use the expression editor to run other processing algorithms or plugins.
I am aware of layer actions and the graphical modeler, but I'd like to use the expression editor if possible (in order to input default values).

A: Basically this is possible using a custom function. You just have to rebuild the Python syntax. For my testing purposes this worked fine:
from qgis.core import *
from qgis.gui import *
import processing

@qgsfunction(args='auto', group='Custom')
def run_processing_algorithm(algorithmName, algorithmParams, feature, parent):
    algorithm_result = processing.run(algorithmName, algorithmParams)
    result_layer = algorithm_result['OUTPUT']
    result_feature = result_layer.getFeature(feature.id())
    return result_feature

While e.g. using this as expression to return a feature:
run_processing_algorithm(
    'native:zonalstatisticsfb', -- name of the algorithm to run
    map( -- dictionary of parameters
        'COLUMN_PREFIX','_',
        'INPUT','nameofyourinputlayer',
        'INPUT_RASTER','nameofyourinputraster',
        'OUTPUT','memory:',
        'RASTER_BAND',1,
        'STATISTICS',array(0,1,2)
    )
)

With this feature you can do whatever you want. E.g. return an attribute, its geometry or whatever. To return a specific attribute, combine it with attribute() expression or attributes() to get all fields and values as dictionary/map. For example:
attribute(
    run_processing_algorithm(
        'native:zonalstatisticsfb',
        map(
            'COLUMN_PREFIX','_',
            'INPUT','zonalstatisticpolygons',
            'INPUT_RASTER','DGM20',
            'OUTPUT','memory:',
            'RASTER_BAND',1,
            'STATISTICS',array(0,1,2)
       )
    ),
    '_sum'
)

Tested this with the native processing algorithms zonalstatisticsfb and buffer in QGIS 3.22. Both work fine, so I guess most algorithms should be usable this way. Note that you can not input a layer by using e.g. @layer as this will return an error; You have to write the layernames as strings.
Also you can of course adjust the custom function to your personal needs or tweak it a little. For example use default settings or add an optional expression as input to pick the feature you want instead of getting the result feature by its id. The latter would e.g. make sense when running qgis:voronoipolygons as here the resulting feature id does not match with the input feature id.

A: That's a great solution, but I think it could fail when there is a fid field with non consecutive numbers.
I made this slight modification, and it works fine for me:
from qgis.core import *
from qgis.gui import *
import processing

@qgsfunction(args='auto', group='Custom')
def run_processing_algorithm(meuFeatureId, algorithmName, algorithmParams, feature, parent):
    algorithm_result = processing.run(algorithmName, algorithmParams)
    result_layer = algorithm_result['OUTPUT']
    result_feature = result_layer.getFeature(meuFeatureId)
    return result_feature

And then the expression:
attribute(
    run_processing_algorithm(  @row_number  ,
        'native:zonalstatisticsfb',
        map(
            'COLUMN_PREFIX','_',
            'INPUT','zonalstatisticpolygons',
            'INPUT_RASTER', 'DGM20',
            'OUTPUT','memory:',
            'RASTER_BAND',1,
            'STATISTICS',array(0,1,2)
       )
    ),
    '_mean'
)

Do you think it is correct?


text:
Q: How to change DASH-ICON color with CSS? It is possible to change colors of DashIcons with CSS? I couldnt get it to work.

A: Yes, this is possible. Make sure your CSS selector is correct. You can target the specific HTML element or its ::before pseudo element and change colour with CSS. Can you post your HTML snippet of the element you want to change and the CSS selector you are using? Maybe you mean to change the colour inside WP admin area for all dash-icons? In that case:
.dashicons { color: red; }

A: The correct way:
#adminmenu div.wp-menu-image:before {
    color: #000; <-- here
}

#adminmenu .wp-has-current-submenu div.wp-menu-image:before {
    color: #000; <-- here
}

And to make sure you get the hover state of the selected submenu
#adminmenu li.wp-has-current-submenu:hover div.wp-menu-image:before,
#adminmenu .wp-has-current-submenu div.wp-menu-image:before,
#adminmenu .current div.wp-menu-image:before,
#adminmenu a.wp-has-current-submenu:hover div.wp-menu-image:before,
#adminmenu a.current:hover div.wp-menu-image:before,
#adminmenu li.wp-has-current-submenu a:focus div.wp-menu-image:before,
#adminmenu li.wp-has-current-submenu.opensub div.wp-menu-image:before {
    color: #000; <-- here
}

All of the dashicon css and the related wp-menu-image css is in the admin-menu.css sheet.


text:
Q: unresolved socket address This is more of a novice question, but I am unable to get the type of answer I am looking for on Google.
I was reading the InetSocketAddress class in java.net package and I came across this method named createUnresolved(String host, int port). This method creates an unresolved Socket.
Basically what do we mean by unresolved ? I have come across this term often in errors while compiling a program but never have understood it completely. Can anyone please explain the general meaning in java, and meaning with context to the said method.
Thanks.

A: I found this in a sun-blog:

But decided to keep it as is but use createUnresolved() to create an
  InetSocketAddress, so that we know what was used to instantiate it. If
  the user slapped in an IP address to begin with, we won't handle it.
  (I think it was indistinguishable before) The token will have whatever
  the user used (IP or name) in the beginning and in case of using name,
  the key to the token cache won't change even with addr changes. So the
  delegation token should continue to work.

Basically, it's a half-baked InetSocketAddress - so it's not the final iteration. It's an intermediary step..
And From API:

It can also be a pair (hostname + port number), in which case an
  attempt will be made to resolve the hostname.
If resolution fails then the address is said to be unresolved but can
  still be used on some circumstances like connecting through a proxy

So we didn't find the hostname, or the user-friendly "www.abc.com" method.
But if we are connecting via a proxy it's OK because that the proxy server handles the hostname  .

A: I had the same exception: java.net.UnknownHostException: Host is unresolved: https://www.google.com
The problem was because I added the protocol https://, the problem is resolved after I removed https://
try {
    Socket socket = new Socket();
    socket.connect(new InetSocketAddress("www.google.com", 443), 100);
    socket.close();
    return true;
} catch (IOException e) {
    e.printStackTrace();
    return false;
}


text:
Q: How many 6-digit numbers can be formed using the digits 1,2,3,4,5,6 and 7, so that the digits do not repeat and the terminal digits should be even? We know that the last digit should be even --> 2,4 or 6
Also, a digit should only be used only once --> 7.6.5.4.3.2 (let us call it 'var1')
So, shouldn't the answer be (var1)x3 ? ( 3  for each number ending with 2, 4 and 6 respectively)
Can someone point out any mistake(s) I may have made ?
Thank you.

A: The $7\cdot 6\cdot 5\cdot 4\cdot 3\cdot 2$ would be the correct answer if we didn't have the final digit being even constraint. But as we do, it makes sense to think of the number in two separate parts: the last digit, and then the first five.
As you say, there are three choices for the terminal digit. But then, for the first five digits, we don't have a choice of seven digits any more - we have the choice of six ($\{1,3,5,7 \}$ or one of the unused two even digits). So the number of options for the first five is $6\cdot 5\cdot 4\cdot 3\cdot 2 = 720$.
The final answer is therefore $3 \cdot 720 = 2160$ possible numbers.
EDIT: Just for fun, I confirmed the answer in Python, so the question can also be answered programmatically, though the above method is much preferable.
count = 0
for i in range(100000, 999999 + 1):
    temp = list(int(x) for x in str(i))
    if len(temp) == len(set(temp)) and temp[-1] % 2 == 0:
        if "0" not in str(i) and "8" not in str(i) and "9" not in str(i):
            count += 1
print("count =", count)

Output: count = 2160

A: Thanks to the help from the comment, if you still fancy reading the answer below, you will get the same answer.
If they used $2$ even numbers from $3$ even numbers in the first $5$ digits and order them, after then they pick up $3$ numbers from the $4$ odd numbers and put them into the remain $3$ positions and need to order them.
$T_1 = (3C2 * 5C2 * 2P1) *(4C3 * 3P3$): 1440
If they choose $1$ even numbers from $3$ even numbers and put them into the first $5$ digits, and they pick up $4$  numbers from $4$ odd numbers and put them into remaining $4$ positions. And they pick up $1$ even number from the $2$ even numbers.
$T_2$ =  ($3C1 * 5C1) * (4C4 * 4P4) * 2C1$ ):720
$T = T_1 + T_2$.


text:
Q: A delete button is hiding behind another element. How can I make that element to be at the top so it's visible? I'm trying to draw a delete button right at the right top corner of the collapsible box. I already did it but for some reason I can't make it show at the top of the collapsible element so it's visible. I tried to set it to visibility: visible but I still can't make it visible. Any ideas or suggestions will be appreciated.
Here's my HTML code:

            Close

 1 new

January 6th 2016

         first

        <button href='#' id='bt01' data-icon='check' data-iconpos='right' style='width:100px;' onclick='alert(1);event.stopPropagation();' >Reply</button>

 first

January 6th 2016

Audi

BMW

Cadillac

Ferrari

And my jsfiddle example

A: To get the effect yore looking for you would need to add overflow: visible; to the containing element:
a.ui-collapsible-heading-toggle.ui-btn.ui-icon-expand.ui-btn-icon-right.ui-btn-b { overflow:visible;}
Here is the JS Fiddle


text:
Q: Android flash xml gallery I try to develop a simple xml flash gallery in android. it dose not work when i try to preview the image. can someone help me?
This is my xml file
<?xml version="1.0" encoding="utf-8"?>
<galleryPackage>

        <image>

            <imgURL>/mnt/sdcard/SketchCraft/MyDrawing 1.png</imgURL>
    </image>

</galleryPackage>

i'm not sure how to refer file in the phone memory in xml. and im expecting many errors with my actionscript and xml file here.
this is my actionscript
import flash.net.URLLoader;
import flash.events.Event;
import flash.display.Loader;
import flash.net.URLRequest;

var xmlRequest:URLRequest = new URLRequest("XMLcth.xml");
var xmlLoader:URLLoader = new URLLoader(xmlRequest);
var imgData:XML;
var imageLoader:Loader;
var rawImage:String;

var imgNum:Number = 0;

xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);

function xmlLoaded(event:Event):void{
    imgData= new XML(event.target.data);
    rawImage = imgData.image[imgNum].imgURL;
    imageLoader =new Loader();
    imageLoader.load(new URLRequest(rawImage));
    mc_image.addChild(imageLoader);
    }

A: Based on the comments above, your XML is malformed & cannot be read by ActionScript.
Format your XML as follow:
<?xml version="1.0" encoding="utf-8"?>
<galleryPackage>
    <image>
        <imgURL><![CDATA[/mnt/sdcard/SketchCraft/MyDrawing 1.png]]></imgURL>
    </image>
</galleryPackage>

You missed a ? in XML declaration:
<?xml version="1.0" encoding="utf-8">


text:
Q: The Golden Ratio shows up in the cosine function. Do other related numbers do so as well? I just learned that

*

*$\cos\left(\frac{π}{5}\right)$ = $\frac{φ}{2}$,

*$\cos\left(\frac{2π}{5}\right)$ = $\frac{1}{2φ}$ = $-\frac{ψ}{2}$,

*$\cos\left(\frac{3π}{5}\right)$ = $-\frac{1}{2φ}$ = $\frac{ψ}{2}$, and

*$\cos\left(\frac{4π}{5}\right)$ = $-\frac{φ}{2}$,

where $φ = \frac{1 + \sqrt{5}}{2}$ is the Golden Ratio and $ψ = \frac{1 - \sqrt{5}}{2}$ is the Golden Ratio Conjugate.
It seems suggestive to me that the Golden Ratio involves the square root of five and also appears in the output of the cosine function for inputs proportional to the inverse of five. So I did some digging.
The Golden Ratio is a member of the group of numbers which are solutions to the cubic equation $x^3 - a x - 1 = 0$, with $a = 1$ giving the Plastic Ratio $ρ = \sqrt[3]{\frac{9 + \sqrt{69}}{18}} + \sqrt[3]{\frac{9 - \sqrt{69}}{18}}$ and two complex roots, and $a = 2$ giving the Golden Ratio $φ$ plus the Golden Ratio Conjugate $ψ$ and $-1$. The value for $a = 3$ does not seem to have a name that I can find, but it does also show up in the cosine function.
If we denote the real-valued roots as $R_n(a)$, going from most positive at $n = 1$ to most negative at $n = 3$, then

*

*$\cos\left(\frac{π}{9}\right) = \frac{R_1(3)}{2} ≈ \frac{1.879385}{2}$,

*$\cos\left(\frac{2π}{9}\right) = -\frac{R_3(3)}{2} ≈ -\frac{-1.532089}{2}$,

*$\cos\left(\frac{4π}{9}\right) = -\frac{R_2(3)}{2} ≈ -\frac{-0.347296}{2}$,

*$\cos\left(\frac{5π}{9}\right) = \frac{R_2(3)}{2} ≈ \frac{-0.347296}{2}$,

*$\cos\left(\frac{7π}{9}\right) = \frac{R_3(3)}{2} ≈ \frac{-1.532089}{2}$, and

*$\cos\left(\frac{8π}{9}\right) = \frac{-R_1(3)}{2} ≈ -\frac{1.879385}{2}$.

Given that these two sets of roots for $a = 2$ and $a = 3$ show up, it makes me wonder if more do so as well. However, I haven't been able to find an way to fit the Plastic Ratio into the cosine function for $a = 1$, or the unnamed roots for $a = 4$.
Do the roots for other values of $a$ appear in the output of the cosine function? Is the appearance of these two sets of roots purely a coincidence, or is there some deeper mathematical connection?

A: Substitute $x=m \cos t$ to get $$m^3 \cos^3 t - a m \cos t -1=0$$
Let $$m=\sqrt{\frac{4a}{3}}$$ then it rearranges (assuming $a,m\ne 0$) to
$$4 \cos^3 t - 3 \cos t = \sqrt{\frac{27}{4a^3}}$$
Using trigonometric identity
$$\cos (3t) = \sqrt{\frac{27}{4a^3}}$$
So
$$x = \sqrt{\frac{4a}{3}} \cos\left(\frac{1}{3} \cos^{-1}\left(\sqrt{\frac{27}{4a^3}}\right)\right)$$
When $a=1$ the R.H.S. of the penultimate equation is bigger than $1$ so $\cos^{-1}$ is problematic. Note that $\cos^{-1}/3$ is multi-valued.


text:
Q: How did people get the inspiration for the sums of cubes formula? I stumbled upon this neat formula for sums of cubes with arbitrary $x,y\in\mathbb{Z}$$$(x^2+9xy-y^2)^3+(12x^2-4xy+2y^2)^3=(9x^2-7xy-y^2)^3+(10x^2+2y^2)^3\tag1$$
With $1729=1^3+12^3=9^3+10^3$ as its first instance. And I believe that this formula was used by Ramanujan to find a formula for$$a^3+b^3=c^3\pm1$$
So my question?

Questions:

*

*What would be someone's thinking process when finding other formulas such as $(1)$?

*Are there any other formulas similar to $(1)$?

I'm thinking along the lines of starting with $$(x^2+axy+by^2)^3+(cx^2+dxy+ey^2)^3=(fx^2+gxy+hy^2)^3+(ix^2+jxy+ky^2)^3$$
But even Mathematica can't solve the ensuing system that follows. So for the moment, I'm stuck.

A: The formula that Ramanujan actually recorded, as well as Euler's solution, are discussed by Ono in  https://arxiv.org/abs/1510.00735
The original formula was
$$ \left( 6 a^2 - 4ab + 4 b^2 \right)^3 =  \left( 3 a^2 +5ab - 5 b^2 \right)^3 +  \left( 4 a^2 - 4ab + 6 b^2 \right)^3 +  \left( 5 a^2 - 5ab -3 b^2 \right)^3  $$
The formula can be made more symmetric still. The two classes of forms of discriminant $85$ are represented by
$$  x^2 + 9 xy - y^2, $$
$$  3 x^2 + 7 xy - 3 y^2.  $$ The latter is equivalent to $3 x^2 - 5 xy - 5 y^2, $ off by a single minus sign.
The two classes of (primitive) forms of discriminant $-20$ are represented by
$$  x^2 + 5 y^2, $$
$$  2 x^2 + 2 xy + 3 y^2.  $$
That is, one may pass between Ramanujan's version and yours by using Gauss composition in order to multiply by $3,$ which passes between the principal genus and the other genus, both for discriminant $85$ and $-20.$
On page 2 they give Ramanujan's modern version of Euler's complete solution.
When
$$ \alpha^2 + \alpha \beta + \beta^2 = 3 \lambda \gamma^2, $$
$$  \left( \alpha + \lambda^2 \gamma  \right)^3 +  \left( \lambda \beta + \gamma \right)^3 =  \left(\lambda \alpha + \gamma \right)^3 +  \left( \beta + \lambda^2 \gamma \right)^3   $$
http://esciencecommons.blogspot.com/2015/10/mathematicians-find-magic-key-to-drive.html

A: Actually, Mathematica can solve,
$$\small (x^2+axy+by^2)^3+(cx^2+dxy+ey^2)^3+(fx^2+gxy+hy^2)^3+(ix^2+jxy+ky^2)^3 =0\tag2$$
One may be guided by the principle of fait accompli (accomplished fact). Ramanujan and others already found solutions therefore $(2)$, approached the right way, must be solvable.
What you do is expand $(2)$ and collect powers of $x,y$. The Mathematica command is Collect[P(x,y),{x,y}] to get,
$$P_1x^6+P_2x^5y+P_3x^4y^2+P_4x^3y^3+P_5x^2y^4+P_6xy^5+P_7y^6 = 0$$
where the $P_i$ are polynomials in the other variables. The hard part is then solving the system,
$$P_1 = P_2 = \dots =P_7 = 0$$
After much algebraic manipulation (which I don't have the strength to type all down), one ends up with the simple identity (which I gave to Mathworld back in 2005),

$$(ax^2-v_1xy+bwy^2)^3 + (bx^2+v_1xy+awy^2)^3 + (cx^2+v_2xy+dwy^2)^3 + (dx^2-v_2xy+cwy^2)^3 = \color{blue}{(a^3+b^3+c^3+d^3)}(x^2+wy^2)^3\tag3$$
  where,
  $$v_1= c^2-d^2\\ v_2= a^2-b^2\\ w= (a+b)(c+d)$$

Thus, if the $RHS$ is zero, or you find a single instance of $\color{blue}{a^3+b^3+c^3+d^3 = 0}$, then the $LHS$ yields a quadratic parameterization that guarantees an infinite more. So to answer your question, $(3)$ can be used to generate infinitely many Ramanujan-type formulas like $(1)$.
Example: The two smallest taxicab numbers are,
$$1^3+12^3=9^3+10^3\\
\color{blue}{2^3+16^3=9^3+15^3}$$
Using the second one and formula $(3)$, and after scaling the variable $y' \to y/12$ to reduce coefficient size, one gets,
$$(\color{blue}2 x^2 + 12 x y - 48 y^2)^3 + (\color{blue}{16} x^2 - 12 x y - 6 y^2)^3 +  (\color{blue}{-9} x^2 - 21 x y + 45 y^2)^3 + (\color{blue}{-15} x^2 + 21 x y + 27 y^2)^3  = 0$$
and you can see its "parents" in blue.


text:
Q: Error while migrating from eclipse to android studio Hello I am new to android studio. I have a existing eclipse project, which runs on (2.3.3 android api 10) only.
When I migrate my existing eclipse project to android studio. I face below error.
Error:Unable to load class 'org.codehaus.groovy.runtime.typehandling.ShortTypeHandling'.
Possible causes for this unexpected error include:
You are using JDK version 'java version "1.7.0_75"'. Some versions of JDK 1.7 (e.g. 1.7.0_10) may cause class loading errors in Gradle.
Please update to a newer version (e.g. 1.7.0_67).
Open JDK Settings
Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)
The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)
In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.

Here is my build.gradle file.
apply plugin: 'android'
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0+'
    }
}

allprojects {
    repositories {
        mavenCentral()
    }
}
dependencies {
    compile fileTree(include: '*.jar', dir: 'libs')
    }
android {
    compileSdkVersion 10
    buildToolsVersion "10"

     compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the tests to tests/java, tests/res, etc...
        instrumentTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 10
    }
}

Can anyone help me. Thanks in advance.

A: I solved the problem.
I just have to change my buildToolsVersion.
From
buildToolsVersion "10"

to
 buildToolsVersion "19.1.0"

Now its works perfectly.
Thanks,

A: please ensure your sdk is newer than jdk1.7.0_67.
 open your android studio preferences page for check.


text:
Q: CUDA Sorting Many Vectors / Arrays I have many (200 000) vectors of integers (around 2000 elements in each vector) in GPU memory.
I am trying to parallelize algorithm which needs to sort, calculate average, standard deviation and skewness for each vector.
In the next step, the algorithm has to delete the maximal element and repeated calculation of statistical moments until some criteria is not fulfilled for each vector independently.
I would like to ask someone more experienced what is the best approach to parallelize this algorithm.
Is it possible to sort more that one vector at once?
Maybe is it better to not parallelize sorting but the whole algorithm as one thread?

A:
200 000 vectors of integers ... 2000 elements in each vector ... in GPU memory.

2,000 integers sounds like something a single GPU block could tackle handily. They would fit in its shared memory (or into its register file, but that would be less useful for various reasons), so you wouldn't need to sort them in global memory. 200,000 vector = 200,000 blocks; but you can't have 2000 block threads - that excessive
You might be able to use cub's block radix sort, as @talonmies suggests, but I'm not too sure that's the right thing to do. You might be able to do it with thrust, but there's also a good chance you'll have a lot of overhead and complex code (I may be wrong though). Give serious consideration to adapting an existing (bitonic) sort kernel, or even writing your own - although that's more challenging to get right.
Anyway, if you write your own kernel, you can code your "next step" after sorting the data.

Maybe is it better to not parallelize sorting but the whole algorithm as one thread?

This depends on how much time your application spends on these sorting efforts at the moment, relative to its entire running time. See also Amdahl's Law for a more formal statement of the above. Having said that - typically it should be worthwhile to parallelize the sorting when you already have data in GPU memory.


text:
Q: PDF attachment using sendgrid- JAVA Code to add content:
for (Attachment attachment:message.getSendGridAttachments()) {
   nvps.add(new BasicNameValuePair(String.format(PARAM_FILES, attachment.getName()),attachment.getData()));
}

In Attachment Class:
public class Attachment implements Serializable{

    public  String name;
    public  InputStream contents;
    public  String data;
    public  String type;
    public String getType() {
        return type;
    }
    public String getData() {
        return data;
    }

    public String getName() {
        return name;
    }

    public InputStream getContents() {
        return contents;
    }

    public Attachment(File file) throws FileNotFoundException {
        byte[] fileData = null;
        try {
            fileData = org.apache.commons.io.IOUtils.toByteArray(new FileInputStream(file));
        } catch (IOException ex) {

        }
        try {
            this.data = new String(fileData, 0, (int) file.length(), "UTF-8");
            LOG.info("data is :{}",new String(fileData, 0, (int) file.length(), "UTF-8") );
        } catch (UnsupportedEncodingException e) {
        }
        this.name = file.getName();
        this.contents = new FileInputStream(file);
        this.type = "application/pdf";
    }

    public Attachment(String name, InputStream contents, String data) {
      this.name = name;
      this.contents = contents;
      this.data = data;
    }

}

Problem here is I am getting 10kb pdf file in attachment but while opening its showing nothing.
When I open same file using text editor it shows me some garbage data(seems like byte stream)

A: You're reading the file contents twice; couldn't you do something like this:
public class Attachment implements Serializable{

    public  String name;
    public  byte[] data;
    public  String type;
    public String getType() {
        return type;
    }
    public String getData() {
        try {
            return new String(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // very unlikely
        }
    }

    public String getName() {
        return name;
    }

    public InputStream getContents() {
        return new ByteArrayInputStream(data);
    }

    public Attachment(File file) throws FileNotFoundException {
        try {
            data = org.apache.commons.io.IOUtils.toByteArray(new FileInputStream(file));
        } catch (IOException ex) {

        }
        this.name = file.getName();
        this.type = "application/pdf";
    }

    public Attachment(String name, byte[] data, String type) {
      this.name = name;
      this.data = data;
      this.type = type;
    }

}


text:
Q: Cannot write to MMF using pointer I would like to write char* buf[] to shared memory.
I got several pointer to several maps - char* m_pP[MAX], maps are opened
m_oMMF[channel] = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, wstring);
m_pP[channel] = (char*) MapViewOfFile(m_oMMF[channel], FILE_MAP_ALL_ACCESS, 0, 0, size);

size of map is big enough, I got int offset where I wanna to write in shared memory using this m_P[] pointer but I am struggling at the syntax of this.
Im not so experienced in C++.
Can anyone help me with this?
Thanks

A: Not sure If I understood clearly.
But I assume, you have character pointer pointing to mapped memory and you are trying to write data after certain offset.
char * ptr_to_memory = m_pP[channel];

//buf is array of character pointer, so you need to know the "index" as well as "size" of the data you need to write.

char * data_to_write = buf[index];

memcpy( ptr_to_memory + offset, data_to_write, size );

Remember to do some sanity check, whether ( ptr + offset ) is within the mapped region.


text:
Q: C.VIM not working I have a simple question (that I don't seem to be able to answer),
I am a new VIM/Linux user, and since I do c++ development I decided to install the C.VIM plugin to speed up my development time. The problem is, it says in the plug-in (c++) menu that to do a switch statement I have to write \ss (for me the leader is ",", so it's ",ss") but when I do this it just puts me in insert mode and nothing happens. I know the plugin is well set up because when I open a new c++ file it generates a comment box where I can give the description of the program.
I would love it if I would be able to use the shortcuts, because using the menu just losses the point of using vim.
Oh and please, just keep in mind that I am new to vim, I still have hard time figuring out what means <c-r> + TAB (which is, if i'm not mistaking "ctrl-r <tab>"), so if you could just try to explain the solution clearly without to much jargon I would appreciate it. (while i'm here, does anyone know of a good vim tutorial where I could understands all of the vim jargon, thanks!)
I appreciate all the help.

A: I use this cheat sheet:
http://www.worldtimzone.com/res/vi.html

A: Please add the below line to .vimrc and
helptags ~/.vim/bundle/c.vim/doc

Note: I have pointed to my c.vim doc and I use bundle, it may differ for you :)


text:
Q: overvoltage and transient protection for ADC pin I'm building an industrial circuit, and want to use 0-10V and 4-20mA sensors in this circuit.
I want to protect my ESP32 MCU(NodeMcu board) from transients and high voltages.
I design this circuit and have questions:

*

*Is this circuit works good for my purpose?

*which component is necessary and Which one is optional(schottky diodes,100nf capacitor,polyfuse)?

*NodeMcu does not have any Analog ground ,does it matter?

*whats your opinion on this circuit?
It's not a precision system, but I want to protect it in a good way.

A: assuming that you modified the D3

-Is this circuit works good for my purpose?

it should be working. However you should not that in the ADC analog front end there is an internal holding capacitor. You potential divider has an output resistor of R2 approx. This may delay the charging of the hold capacitor if you have high sampling rate or high frequency signal. Attached is the ADC front end inside a microchip. It should be the same.

-which component is necessary and Which one is optional(schottky diodes,100nf capacitor,polyfuse)?

schottky diodes important. 100nF don't know, you should take care they attenuate your signal and add a delay(phase shift) in to your signal so you may get the wrong value of the sensor in that time. The corner frequency of this circuit is about 400 Hz. If your signal frequency is more than that the capacitor will filter out the high frequency and you will get small readings.

-NodeMcu does not have any Analog ground ,does it matter?

It may be directly connected to the Digital one. check datasheet and technical
references.

-whats your opinion on this circuit

You will have negative voting by this kind of questions.

-its not a precision system ,but i want to protect it in a good way.

I will add another resistor (1k) before connecting this circuit to the ADC. so the schottky diode will conduct most of the currents if a surge occurred in the analog side. This resistor should be as close as possible to the ADC pin in the board.


text:
Q: Scheduling events with changing Time zone I need help with this scenario:
1) Currently it is summer time. I need to create a time interval for June 9 Monday 6 PM - 7 PM EDT and every week after that until end of  2018. This interval will be for students to schedule appointments with a tutor. The client right now sends that as a request for creating start time at June 9 Mondays 2 PM UTC. (EDT is -4 hours offset) The server creates a start time in db for June 9 2 PM UTC and adds 7 days worth of milliseconds to create recurring
^ this causes an issue because of DST. Let's say it is right now November 5th (which is after daylights saving change). The DB still has Nov 5, 2 PM UTC saved as value. But because my timezone changed, instead of offsetting by 4 hours like I did on June, I offset by 5 hours. So the correct start time is "6 PM session in my timezone" becomes "7 PM my timezone". this is the error
the solution is either of one of two (or combination of both):
1)  instead of adding 7 days worth of milisecond, you add 1 week worth of miliseconds depending on the user's timezone  Currently, there's no way to extract a person's timezone based on utc offset (-400, which is right now in east coast USA, is also applicable to Canada, Carribeans, South America etc. We need to save a user's timezone as a string, rather than UTC offset count. There is an international standard for timezones)
2) ?? something else


text:
Q: How to set superscript for expandable parentheses? The following code compiled with error:
\documentclass{report}
\usepackage{chemfig}
\begin{document}
    \schemestart
    \chemfig{R-C(=[:60]O)-[:-60]O-H}
    \arrow{<=>}
    \chemleft[\chemfig{R-C(=[:60]O)-[:-60]O}\chemright]^{-}
    \+
    \chemfig{H^+}
    \schemestop
\end{document}

I'd like to place that minus sign on the upper right corner of the right parenthesis.

A: This seems to work:
\documentclass{report}
\usepackage{chemfig}

\begin{document}

\schemestart
\chemfig{R-C(=[:60]O)-[:-60]O-H}
\arrow{<=>}
\chemleft[\chemfig{R-C(=[:60]O)-[:-60]O}\chemright{]^{-}}
\+
\chemfig{H^+}
\schemestop

\end{document}

ChemFig provides the \chemleft and \chemright command pair. These allow to set expandable delimiters on either side of a material. The commands must be followed by delimiters, just like in the case of TeX primitive commands \left and \right:
\chemleft<car1><material>\chemright<car2>

where <car1> and <car2> can be "(" et ")" or "[" and "]", or any other expandable delimiter consistent with the
\left et \right commands.

I just tried: miracles happen. ;-)

A: If you put the corresponding formula inside a \subscheme it will get a node name that you can refer to from another tikzpicture with remember picture,overlay for which chemfig has the shortcut \chemmove. Then you can add anything anywhere:
\documentclass{article}
\usepackage{chemfig}
\begin{document}

% \schemedebug{true} % look up and visualize the nodes and node names

\schemestart
  \chemfig{R-C(=[:60]O)-[:-60]O-H}
  \arrow{<=>}
  \subscheme{\chemleft[\chemfig{R-C(=[:60]O)-[:-60]O}\chemright]}
  \+
  \chemfig{H^+}
\schemestop
\chemmove[red]{
  \node[right] at (c3.north east) {top right} ;
  \node[right] at (c3.south east) {bottom right} ;
  \node[left] at (c3.north west) {top left} ;
  \node[left] at (c3.south west) {bottom left} ;
}

\end{document}


text:
Q: Understanding C++ String Concatenation In C++, I'm trying to understand why you don't get an error when you construct a string like this:
const string hello = "Hello";
const string message = hello + ", world" + "!";

But you do get a compile time error with this:
const string exclam = "!";
const string msg =  "Hello" + ", world" + exclam

Compile time error is:
main.cpp:10:33: error: invalid operands of types 'const char [6]' and
'const char [8]' to binary 'operator+'

Why is the first run fine but the second produce a compile time Error?

A: It will make more sense if you write it out:
hello + ", world" + "!"; looks like this:
operator+(operator+(hello, ", world"), "!");

While
"Hello" + ", world" + exclam looks like this
operator+(operator+("Hello" , ", world"), exclam);

Since there is no operator+ that takes two const char arrays, the code fails.
However, there is no need for one, as you could concatenate them like the following (note I just removed the + sign):
const string msg =  "Hello" ", world" + exclam


text:
Q: Retrieve data from multiple table in sql using some condition I have created three tables namely
studentdetails (sid,sname,slname),
books (bid,bname,bprice),
bookingdetails (sid,bid)
sql query
I want to display the student name who has booked dbms book.

A: JOINS should do the work, like the query below:
SELECT studentdetails.name from books
inner join bookingdetails on bookingdetails.bid = books.bid
inner join studentdetails on studentdetails.id = bookingdetails.sid
where books.name = 'dbms'

A: Join help us to fetch data from multiple table,so below query can work :
 SELECT Slname
   FROM studentdetails sd
   JOIN BookingDetails bd
     ON sd.sid = bd.sid
   JOIN books bk
     ON bk.bid = bd.bid
    AND bk.bname = 'DBMS'


text:
Q: Woocommerce add order notes to failed order admin email I need to add a specific order note in woocommerce to a failed order email to the admin.
I am using the following code in functions.php which works - except it places all comments in the email.
I only want notes with the text "Error processing payment blah blah blah" in them to be added to the email such as this example:
Error processing payment. Reason: Processor Declined – Possible Stolen Card
Below is the code I am using - how do I make it filter and add only those notes which contain the text "Error processing payment" in them and not send all comments?
// Add comments to Failed order emails

add_action( 'woocommerce_email_order_meta', 'woo_add_order_notes_to_email', 10, 3 );
function woo_add_order_notes_to_email( $order, $sent_to_admin = true, $plain_text =
false ) {

// You want to send those only to the Admin
if ( ! $sent_to_admin ) {
    return;
}

// You can also check which email you are sending, by checking the order status
// Optional, comment it out, if not needed
if ( 'failed' != $order->get_status() ) {
    // Will end execution, with everything other than the completed order email.
    return;
}

$notes = array();

$args = array(
    'post_id' => $order->id,
    'approve' => 'approve',
    'type' => '' // You don't need type as orders get only order notes as comments.
);

// Remove the filter excluding the comments from queries
remove_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ) );

// You get all notes for the order /public and private/
$notes = get_comments( $args );

// Add the filter again.
add_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ) );

echo '
IMPORTANT Order Notes
';
echo '
';
if ( $notes ) {
    foreach( $notes as $note ) {
        $note_classes = get_comment_meta( $note->comment_ID, 'is_customer_note', true ) ? array( 'customer-note', 'note' ) : array( 'note' );
        ?>
        <li rel="<?php echo absint($note->comment_ID); ?>" class="<?php echo implode(' ', $note_classes); ?>">

                <?php echo wpautop( wptexturize( wp_kses_post( $note->comment_content ) ) ); ?>

    <?php
    }
} else {
    echo '
There are no order notes
';
}
echo '
';
}

Can you please help?

A: You can use the wc_get_order_notes function to get all notes based on a specific order id.
You will need to create an array to use as a function parameter with the following keys:

*

*limit as an empty field (no limit)

*order_id the order id of which to get notes

Finally you can use the PHP strpos function to check that the count contains the string "Error processing payment".
// Add comments to Failed order emails
add_action( 'woocommerce_email_order_meta', 'woo_add_order_notes_to_email', 10, 4 );
function woo_add_order_notes_to_email( $order, $sent_to_admin, $plain_text, $email ) {

    // You want to send those only to the Admin
    if ( ! $sent_to_admin ) {
        return;
    }

    // You can also check which email you are sending, by checking the order status
    // Optional, comment it out, if not needed
    if ( 'failed' != $order->get_status() ) {
        // Will end execution, with everything other than the completed order email.
        return;
    }

    // Get the admin order notes
    $args = array(
        'limit'    => '',
        'order_id' => $order->get_id(),
    );
    $notes = wc_get_order_notes( $args );

    // If there are no notes
    if ( empty($notes) ) {
        echo '
There are no order notes
';
        return;
    }

    echo '
IMPORTANT Order Notes
';
    echo '
';
    foreach( $notes as $note ) {
        // Print only the note containing the string "Error processing payment"
        if ( strpos( $note->content, 'Error processing payment' ) !== false ) {
            $note_classes = $note->customer_note ? array( 'customer-note', 'note' ) : array( 'note' );
            ?>
            <li rel="<?php echo absint($note->id); ?>" class="<?php echo implode(' ', $note_classes); ?>">

                    <?php echo wpautop( wptexturize( wp_kses_post( $note->content ) ) ); ?>

            <?php
        }
    }
    echo '
';
}

The code has been tested and works. Add it to your active theme's functions.php.


text:
Q: How can I get the list of all device admins (active as well as inactive ) in android? The Google API allows us to get the list of all active admins in the device from the method: getActiveAdmins(). However, my requirement is that I want the list of all possible admins in the device , whether active or not. Is there some method to do so ?
Thanks

A: You can find list of applications by below code
final Intent deviceAdminIntent = new Intent("android.app.action.DEVICE_ADMIN_ENABLED", null);
final List<ResolveInfo> pkgAppsList = getPackageManager().queryBroadcastReceivers(deviceAdminIntent, 0);
for (ResolveInfo aResolveInfo : pkgAppsList) {
    String pkg = aResolveInfo.activityInfo.applicationInfo.packageName;
        String name = aResolveInfo.activityInfo.applicationInfo.loadLabel(getPackageManager()).toString();

    System.out.println("Package :: " + pkg);
    System.out.println("Name :: " + name);
}

You can get all the necessary data in the ResolveInfo of an application. You can check ResolveInfo javadoc here.

I wrote a method which returns the ComponentName as same as getActiveAdmins
private List<ComponentName> getAllAdmins(Context mContext) {
        List<ComponentName> result = new ArrayList<ComponentName>();

        // Read all receivers who can listen android.app.action.DEVICE_ADMIN_ENABLED
        // You can add all other action which can be used for DeviceAdminReceiver
        final Intent deviceAdminIntent = new Intent("android.app.action.DEVICE_ADMIN_ENABLED", null);
        final List<ResolveInfo> pkgAppsList = mContext.getPackageManager().queryBroadcastReceivers(deviceAdminIntent, 0);
        for (ResolveInfo aResolveInfo : pkgAppsList) {
            // Prepare component and add to list

            result.add(new ComponentName(aResolveInfo.activityInfo.applicationInfo.packageName,
                    aResolveInfo.activityInfo.name));

            //String pkg = aResolveInfo.activityInfo.applicationInfo.packageName;
            //String name = aResolveInfo.activityInfo.applicationInfo.loadLabel(getPackageManager()).toString();
            //System.out.println("Package :: " + pkg);
            //System.out.println("Name :: " + name);
        }
        return result;
    }

A: You can find the necessary code in the following Android source for DeviceAdminSettings: https://android.googlesource.com/platform/packages/apps/Settings/+/kitkat-release/src/com/android/settings/DeviceAdminSettings.java
DevicePolicyManager mDPM; // = (DevicePolicyManager) getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE);
final HashSet<ComponentName> mActiveAdmins = new HashSet<ComponentName>();
final ArrayList<DeviceAdminInfo> mAvailableAdmins = new ArrayList<DeviceAdminInfo>();

...

    mActiveAdmins.clear();
    List<ComponentName> cur = mDPM.getActiveAdmins();
    if (cur != null) {
        for (int i=0; i<cur.size(); i++) {
            mActiveAdmins.add(cur.get(i));
        }
    }
    mAvailableAdmins.clear();
    List<ResolveInfo> avail = getActivity().getPackageManager().queryBroadcastReceivers(
            new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
            PackageManager.GET_META_DATA | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS);
    if (avail == null) {
        avail = Collections.emptyList();
    }
    // Some admins listed in mActiveAdmins may not have been found by the above query.
    // We thus add them separately.
    Set<ComponentName> activeAdminsNotInAvail = new HashSet<ComponentName>(mActiveAdmins);
    for (ResolveInfo ri : avail) {
        ComponentName riComponentName =
                new ComponentName(ri.activityInfo.packageName, ri.activityInfo.name);
        activeAdminsNotInAvail.remove(riComponentName);
    }
    if (!activeAdminsNotInAvail.isEmpty()) {
        avail = new ArrayList<ResolveInfo>(avail);
        PackageManager packageManager = getActivity().getPackageManager();
        for (ComponentName unlistedActiveAdmin : activeAdminsNotInAvail) {
            List<ResolveInfo> resolved = packageManager.queryBroadcastReceivers(
                    new Intent().setComponent(unlistedActiveAdmin),
                    PackageManager.GET_META_DATA
                            | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS);
            if (resolved != null) {
                avail.addAll(resolved);
            }
        }
    }
    for (int i = 0, count = avail.size(); i < count; i++) {
        ResolveInfo ri = avail.get(i);
        try {
            DeviceAdminInfo dpi = new DeviceAdminInfo(getActivity(), ri);
            if (dpi.isVisible() || mActiveAdmins.contains(dpi.getComponent())) {
                mAvailableAdmins.add(dpi);
            }
        } catch (XmlPullParserException e) {
            Log.w(TAG, "Skipping " + ri.activityInfo, e);
        } catch (IOException e) {
            Log.w(TAG, "Skipping " + ri.activityInfo, e);
        }
    }

    getListView().setAdapter(new PolicyListAdapter());

This is how Android lists them for you in the Device Admins tab.


text:
Q: Find the roots of the polynomial $ 3X^3 -32X^2+73X +28$ using Vieta's relations They are asking me to find the roots of the polynomial $ 3X^3 -32X^2+73X +28$ using Vieta's relations. They also tell me that $x_1 - x_2 = 3$.
I have tried to use first Vieta's relation($x_1 + x_2 + x_3 = \frac{32}{3}$), but I don't get anything meaningful.

A: Using your first relation, $x_1+x_2+x_3=\frac{32}{3}$, and given that $x_1-x_2=3$, so that $x_1=3+x_2$ we can obtain
$$x_3=\frac{23}{3}-2x_2$$
A second Vieta's relation can then be used
$$x_1x_2+x_1x_3+x_2x_3=\frac{73}{3}$$
Substituting $x_1=3+x_2$ and $x_3=\frac{32}{3}-2x_2$ into this results in a quadratic in $x_2$, which can be simplified to
$$(x_2-4)(9x_2-1)=0$$
resulting in two possible values, $x_2=4$ or $x_2=\frac{1}{9}$. Substituting these two values into the cubic leads to only one of them, $x_2=4$, satisfying the equation.
Thus, we have $x_1=7$  and $x_3=-\frac{1}{3}$ as the other roots.
Summarising, the roots of the polynomial are $x_1=7$, $x_2=4$ and $x_3=-\frac{1}{3}$.


text:
Q: implementing a stack of commands for obtaining a transactional behaviour- Delphi I need to create a tool for performing complex scripts against a database.
For several resasons I cannot rely on DB transactional behaviour, but I need to implement my own transactional system.
The approach I am trying is with the help of the command pattern (my case is more complex, here I put a simplified version for discussion):
type
  IMyCommand = interface(IInterface)
    procedure Execute();
    procedure Undo();
  end;

type
  TSQLCommand = class (TInterfacedObject, IMyCommand)
  private
    FDBConnection: TDBConnection;
    FDBQuery: TDBQuery;
    FExecuteSQL: string;
    FUndoSQL: string;
    FExecuted: boolean; // set to True as the command has been executed
  public
    procedure Execute;
    procedure Undo;
    procedure Prepare(aExecuteSQL, aUndoSQL: string);
    constructor Create(aDBConnection: TDBConnection);
    destructor Destroy; override;
  end;

I create a set of actions, for every action I will pass a "Execute" and "Undo" sql statement, examples:
A call to Prepare could be:
Prepare('INSERT INTO TESTTABLE (ID, DATA) VALUES (15, 'Hello')',// aExecuteSQL
'DELETE FROM TESTTABLE WHERE ID = 15'); //aUndoSQL

so somehow I am making very small changes (like inserting a single simple row, updating a single row, ...), for every change the "undo" is very obvious.
I will prepare a stack of command objects (using probably the TObjectStack collection), and call the Execute method one command at a time and as one is executed I will set FExecuted to True, and save the component to disk.
So what I whant to do is to run all the scripts, but I want to manage the cases in which something goes wrong.
If something goes wrong I would like to execute all the commands from last to first calling the Undo method. Of course before doing this I need to be able to restore from disk the components (in case the failure is an hardware failure, in case the failure is another reason I already have the stack in memory and I can easily call undo one command at a time).
Note: The main reason why I cannot rely on the DB transactional behaviour is that I need to insert also big blobs, and every blob is downloaded from internet and then inserted, so I cannot leave a transaction open for ever because I want to commit every small change to the db. What I do with blobs is download one, insert it, download next, insert it, ...
So my question is: could you suggest a way to persist to disk my objects? I have Delphi 2009, so one option is to make a TInterdacedPersistent and save the component to stream and then to file, anyway in this way I would have many files, with extra complicatinos, while I would prefer a single file. Could you suggest?
Edit: I realized TObjectStack is buggy in Delphi 2009 (Pop doesn't return a correct type), so the same can be done with TObjectStack.

A: I can't see a better approach than using a transaction, as Andrei K. mentioned your implementation is NOT safe, therefore using StartTransaction, Commit and Rollback is a MUST!


text:
Q: Are there any model checkers or proof systems for the Pi Calculus I have become mildly obsessed with Milner's Pi Calculus, and while I can have lots of fun drawing out little diagrams on my whiteboard, I was curious if there are any good (or bad even) modeling systems for it to do checking against your logic, in a similar fashion to something like TLA+.
If such a system does not exist or is not necessary due to reason x, I would love an explanation to why if possible.


text:
Q: Reduce the number of Django database calls for a ForeignKey? I have a query on some Django models with a ForeignKey, and I've noticed that it means there are multiple database calls, that perhaps should not be necessary.
This are my models:
class Store(models.Model):
    name = models.CharField(max_length=100)
class Computer(models.Model):
  model = models.CharField(max_length=500)
  store = models.ForeignKey(Store)

My view:
results = Computer.objects.filter(model=model)

And this is my template:
{% for result in results %}
<li class="result">
{{ result.name }} from {{ result.store.name }}
</li>
{% endfor %}

Using django-debug-toolbar I can see that there is one database call to get the results: SELECT ••• FROM "mydb_computer"/, as I'd expect.
But then there are many more database calls (one for each result) to get the store name: SELECT ••• FROM "mydb_store" WHERE "computer_store"."id" = 27 etc.
Is there some way I can make the store name a property of the item, to avoid these multiple database calls?

A: select_related should do what you want it to:
results = Computer.objects.filter(model=model).select_related('store')