text:
Q: Código na camada de negócio do depois de gravar dos funcionários (V10) Pretendo colocar código no evento depois de gravar da camada de negócio dos motores do ERP primavera V10, para efetuar algumas ações nos funcionários independentemente da origem da alteração dos dados.
No entanto, o código abaixo não está a ser executado. É preciso configurar mais alguma coisa?
Tenho outro código no evento depois de gravar dos funcionários nos editores que está a funcionar normalmente.
public class ApiRhpBSFuncionarios : RhpBSFuncionarios
{
    public override void DepoisDeGravar(RhpBEFuncionario ObjBEFuncionario, ExtensibilityEventArgs e)
    {
        base.DepoisDeGravar(ObjBEFuncionario, e);

        /*
        código diverso
        */
    }
}

A: Olá
Essse tipo de eventos não estão ainda disponiveis para esse modulo, pelo menos para já. Pelo que consegui saber junto o produtor trata-se de uma limitação sem uma data de resolução.

A: Boa tarde,
É necessário colocar este código depois do AbreEmpresaTrabalho:
// Use this service to trigger the API events.
ExtensibilityService service = new ExtensibilityService();

service.Initialize(_BSO);

// Check if service is operational
if (service.IsOperational)
{
    // Inshore that all extensions are loaded.
    service.LoadExtensions();
}

Para isto é necessário também fazer os seguinte using:
using Primavera.Extensibility.Engine;

Referenciando as seguintes dlls:
Primavera.Extensibility.Engine.dll
Primavera.Extensibility.Patterns.dll


text:
Q: Merging two ADs - one on Office 365, the other from G-Suite to 365 - what to do? We have a company merger scenario that involves two unrelated forests, one of which is using Office 365 and the other G-Suite.  The plan is to migrate the two domains and shift all of the users to Office 365.  I was curious if anyone has run into this scenario before and if so, did you migrate domains first or did you migrate mail first?  Is there a benefit to doing one before the other?
On one hand it would seem beneficial to migrate the mail first as there are more direct business needs to getting mail/calendaring working company-wide and then migrate resources into one single domain.  Are there any problems with this or is it better to take care of the domain migration first and then migrate the mail?
Are there any major caveats to either route?  It seems like Office 365 can be a single tenant for two separate forests - is a domain trust required or can they exist separately?  I'm also worried that merging the two domains after doing the Office 365 migration could pose some problems as far as securities go, but that's just a guess...
Thanks!

A: Are you using AD Office365 integration or the Azure Active Directory? I would guess GSuite is an integration.
Sounds like you are on the right track to split the migration process into two or more stages.Fortunately, Active Directory, Office365 and GSuite can be configured to be independent of each other. I would definitely only migrate one system of users at a time. For example if Office365 is the end goal maybe get all the GSuite users using Office365 Mail first. Than proceed to getting the mail domains dns records  merged and straightened out. I would do the Active Directory on the computers last if it can keep running as is.

redpajama_set_name: RedPajamaStackExchange


text: Q: Need to be able to navigate the soft keyboard with a remote So I am developing an application that will be used on devices without a touchscreen and will instead be using a remote to navigate the application. I have focus working on the app such that navigation is pretty intuitive. But I have an edit text that lets the user change the name of the device. Problem is that I can't navigate the soft keyboard to enter a name into the edit text. I can't see any way to get the keyboard to have focus so I can then use the remote to enter the new name. Is this possible or will I have to write my own soft keyboard?


text:
Q: How to highlight today's date in calendar using python
highlight current date in python using Calendar library.
  Below is my program.

import calendar
c = calendar.TextCalendar(calendar.MONDAY)
str = c.formatmonth(2018,1)
print (str)

Output

A: I switched to HTMLCalendar from regular calendar ; added extra html tags around today's date ; displayed new calendar.
It is written for jupyter notebook. it can be done for ipython interactive, but formatting is more cumbersome.
    import calendar
    import datetime as dt
    from IPython.display import display,HTML

    # find out today's date
    t = dt.datetime.today()

    # create HTML Calendar month
    cal = calendar.HTMLCalendar()
    s= cal.formatmonth (t.year,t.month)

    # display calendar without highlighting today
    display(HTML(s))

    # add cell's backgroundcolor, bold and underling html tags
    # around today's date
    ss = s.replace('>%i<'%t.day, ' bgcolor="#66ff66">%i<'%t.day)
    display(HTML(ss))

A: A clean and simple solution without workarounds:
from datetime import datetime
import calendar

curr_year = datetime.now().year
curr_month = datetime.now().month
curr_day = datetime.now().day

#ANSI escape sequences for colors
colored_day = '\033[92m' + str(curr_day) + '\033[0m'

calendar_output = (calendar.month(curr_year, curr_month))

#finds the first occurrence of today's date and changes its color
highlighted_day = calendar_output.replace(str(curr_day), colored_day, 1)

print(highlighted_day)

Result (note the current day 7):


text:
Q: sql server conditional select into temp table I'm working in SQL Server 2008, and I'm trying to select into a temp table based on a certain condition...for a report, I need up to 18% of the records to be of a certain product type.
if ((@totalRecords * .18) > @productTypeCount)
    select * into #tmpLP_REIT
    from myTable where productType = @productType
else
    select top 18 percent * into #tmpLP_REIT
    from myTable where productType = @productType

I keep getting error "there is already an object named '#tmpLP_REIT' in the database" even though I know it isn't there because when I try to drop such table, it points out it doesn't exist. I also get this error on the else clause.
It seems it's ignoring my if statement and going right through creating the first table, then trying to create it again. any suggestions?

A: Is this code in a loop?..  that would explain the error if it were happening the second time though.  If not, the syntax checker must just be choking because it sees 2 queries creating the same table, not realizing it is a conditional.
One solution would be to create the table first, and then change the syntax of those 2 queries to insert into queries.
Another solution would be to use dynamic SQL... build the right query in the conditional, and then execute it afterwards.  This should get passed the validation you're currently triggering.


text:
Q: Dancing .gif in slideshow "smears" the image in OpenOffice Impress I'm creating slides which includes a dancing .gif

Unfortunately when I play the slideshow, it leaves an impression of the image in the background, like this

How to fix this???
This .gif render properly in SlideShow mode


text:
Q: copy directory to remote computer using powershell I'm a beginner and i tried to make a simple script to save our current scripts on other admin computer.
So:
$SAVE = Get-ADComputer -filter " name -notlike '* *mycomputer*' " -SearchBase 'OU=Supervision,OU=...'

Foreach ($S in $SAVE)

{

Copy-Item 'd:\doc\*' -destination '\\$S\d$\test'

}

I tried selecting the Name (adding a pipe after the get-adcomputer) but it fail and trying the line copy item without the for each work so i don't know where i went wrong.
If someone could point me the problem?
I tried Test-Path \\$A\D$ and it returned a true
Thank

A: i found a way to make it work: I deleted the " . I did not replace them and to make sure it would work created a new variable in the loop $tst = $S.IPv4Address and replaced the $S in the path name by $tst so now it's like that : Copy-Item 'd:\doc\*' -destination \\$tst\d$\test it seems to work.


text:
Q: Compare two lists and give 1 and 0 using if command There are two lists{2,5,9,...} and {natural numbers}. I need to compare it with natural numbers and get a list with 0 and 1 if the number is present in the list, to get {0,1,0,0,1,0,0,0,1,..}

A: list = {2,5,9,20};
res = ConstantArray[0, Last[list]] (* replace Last by Max if list is not ordered *)
res[[list]] = 1;
res

{0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}

A: How about this? A little verbose...
list = {2, 5, 9, 10, 119};
checklist[list_List] := Boole /@ (MemberQ[list, #] & /@ Range[Max[list]])
checklist@list

{0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 1}

Edit:
Another one, just for fun:
CoefficientList[Plus @@ ((x^#) & /@ list), x]

A: list = {2, 5, 9};
checklist = RandomInteger[{0, 10}, 10]
(*{9, 0, 2, 2, 0, 0, 8, 7, 0, 4}*)

Map[(If[MemberQ[list, #], 1, 0]) &, checklist]
(*{1, 0, 1, 1, 0, 0, 0, 0, 0, 0}*)

A: Use SparseArray.
SparseArray[List /@ {2, 5, 9} -> 1] // Normal
(* {0, 1, 0, 0, 1, 0, 0, 0, 1} *)


text:
Q: empty PATH returned when entering new Docker image I have written a Dockerfile for building a docker image:
#author russell jarvis rjjarvis@asu.edu

#start from the serial version of ubuntu NEURON+Python as if its a module
# add mpi support

#NEURON Dockerfile
#Docker comments must be of this form.
# This is the syntax for a directive. Don't get confused
#Set the base image to pyneuron-toolbox

FROM russelljarvis/pyneuron-toolbox
RUN echo $PATH

WORKDIR $HOME
RUN sudo /opt/conda/bin/conda install -y mpi4py ipython
RUN echo $PATH

WORKDIR /home/docker

RUN \
   sudo wget https://www.open-mpi.org/software/ompi/v2.0/downloads/openmpi-2.0.0.tar.gz && \
   sudo tar -xzf openmpi-2.0.0.tar.gz && \
   sudo rm openmpi-2.0.0.tar.gz
RUN echo $PATH

WORKDIR /home/docker/openmpi-2.0.0

RUN \
  sudo ./configure && \
  sudo make all && \
  sudo make install

RUN echo $PATH

#Download  maven, and its java dependencies

WORKDIR $HOME/git
RUN sudo apt-get -y install default-jre default-jdk maven

RUN echo $PATH

WORKDIR /home/docker/neuron/nrn-7.4

RUN sudo ./configure --prefix=`pwd` --without-iv --with-nrnpython=/opt/conda/bin/python --with-paranrn=/usr/bin/mpiexec
RUN sudo make all && \
   sudo make install

RUN echo $PATH

WORKDIR src/nrnpython
RUN sudo /opt/conda/bin/python3.4 setup.py install

RUN echo $PATH
RUN echo "its chowning the USER directory that seems to break path"
#RUN sudo chown -R docker $HOME
RUN echo $PATH
WORKDIR /home/docker/git
#RUN git clone https://github.com/NeuroML/jNeuroML
RUN git clone https://github.com/russelljjarvis/jNeuroML.git
WORKDIR jNeuroML
RUN sudo /opt/conda/bin/python getNeuroML.py
ENV ADDITIONAL_PATH="/neuron/nrn-7.4/x86_64/bin"
CMD export PATH=$PATH:$ADDITIONAL_PATH; /bin/echo -e "ADDITIONAL_PATH is $ADDITIONAL_PATH\nPATH is $PATH"
RUN echo $PATH
RUN echo $ADDITIONAL_PATH

#WORKDIR /home/docker/git
#RUN git clone

I build the image specified by the Dockerfile with
$docker build .

I find the IMAGE ID for the latest build and enter it using:
$docker run -it d10bd1b2c2bb /bin/bash

However when I enter the docker image I find that the content of environmental variable PATH is empty.
The final commands are:
ENV ADDITIONAL_PATH="/neuron/nrn-7.4/x86_64/bin"
CMD export PATH=$PATH:$ADDITIONAL_PATH; /bin/echo -e "ADDITIONAL_PATH is $ADDITIONAL_PATH\nPATH is $PATH"
RUN echo $PATH
RUN echo $ADDITIONAL_PATH

The outputs of the RUN echo statements are appropriate. The docker environmental variables seem fine when in the process of building the image, however, the problem only seems to arise when I enter the docker image.
If those final Docker commands are omitted, the PATH variable is still an empty string when I enter into the freshly minted image.
I wonder if anyone knows what is going wrong?
Thanks for any suggestions.

A: Only statements similar in form to the following:
ENV PATH /opt/conda/bin/conda:/opt/conda/bin/python:$PATH
should be used to set an environmental variable.
The path variable can then be checked with:
RUN echo $PATH
during the build, however commands like
conda and python may not work as expected during the build process, however the PATH variable will be updated properly when you enter the docker image.


text:
Q: How to determine with JavaScript, if the user is in internal or external Network? I have a button with a JavaScript that 'calls' a php-file.
The site is accessible from the internal network and from the world wide web.
If I click the button from www the php is not working because the address in the JavaScript is an internal 192.168.x.x adress.
function doSomething(id)
{
            var url ="http://192.168.1.1/phpfile.php?id" +id;

            var win = window.open(url, '_blank');
                if(win){
                    //Browser has allowed it to be opened
                    win.focus();
                }
                else
                {
                    //Broswer has blocked it
                    alert('Please allow popups for this site');
                }
}

Is it possible to differentiate if the call is from the internal or another network?
In another case (php) I use an if-else to solve the problem
((substr($_SERVER['REMOTE_ADDR'],0,8) == "192.168.") ||($_SERVER['REMOTE_ADDR'] == "127.0.0.1"))
? 'http://internal/address/' : 'http://my.external.de/''

A: If the button and the JavaScript-code reside in a HTML page delivered from the same server, it can test and set the correct value, before delivering this page.
$PREFIX = ((substr($_SERVER['REMOTE_ADDR'],0,8) == "192.168.") ||($_SERVER['REMOTE_ADDR'] == "127.0.0.1")) ? 'http://internal/address/' : 'http://my.external.de/''
function doSomething(id) {
    var url ="<?=PREFIX?>phpfile.php?id" +id;
....

A: As far I understand, you want your web site to work locally with localhost/192.168.x.x/127.0.0.1 or on the remote web server and distinguish which configuration you have so your javascript switch properly from one to the other.
First, you cannot get your IP address from javascript directly, you need to use a relay web site for this: see this thread for the answer.
But, in your case I believe there is a much more simpler way to proceed, and without any 'if'. Javascript (or the browser) is smart enough to route calls for you. Change your code to this:
function doSomething(id)
{
        var url ="/phpfile.php?id" +id;

        var win = window.open(url, '_blank');
            if(win){
                //Browser has allowed it to be opened
                win.focus();
            }
            else
            {
                //Broswer has blocked it
                alert('Please allow popups for this site');
            }
}

Your client browser will route the call to localhost automatically, if you loaded the page running the script, from localhost. And route to my.external.de, if you loaded the page running the script, from my.external.de.


text:
Q: Play 2 - Include another routes file in conf/routes I've got 50+ legacy Spring w/JPA domain models I'm bringing into a new Java Play app to build a CRUD interface around. After examining several options I decided I wanted to write some code to generate the 50+ controllers and ~50*5 view files whenever a make a change to a set of templates. Basically I want to scaffold the code kind of how I used to do it in RoR. I've written this is as an executable Java class (ie with a main()).
As there will be 250+ routes required for this project is there a way to put all of the generated routes in a separate routes file that would then be included in 'conf/routes'? That way I can separate the generated routes for these legacy domain models from the ones I add to 'conf/routes' manually.
A related question would be: Is there anything similar to RoR's "resources :cities" declaration in routes.rb in Play? (FYI in RoR this creates all of the CRUD routes for the model declared as a resource)
The app is currently running Play 2.3.0 but we have plans to move it to 2.4.2 once we can make Guice and Spring play nice together.


text:
Q: Validating a Salesforce Id Is there a way to validate a Salesforce ID, maybe using RegEx? They are normally 15 chars or 18 chars but do they follow a pattern that we can use to check that it's a valid id.

A: This regex has given me the optimal results so far.
\b[a-z0-9]\w{4}0\w{12}|[a-z0-9]\w{4}0\w{9}\b

A: There are two levels of validating salesforce id:

*

*check format using regular expression [a-zA-Z0-9]{15}|[a-zA-Z0-9]{18}

*for 18-characted ids you can check the the 3-character checksum:

Code examples provided in comments:

*

*C#

*Go

*Javascript

*Ruby

A: You can also check for 15 chars, and then add an extra 3 chars optional, with an expression similar to:
^[a-z0-9]{15}(?:[a-z0-9]{3})?$

on i mode, or not:
^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$

Demo

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.

RegEx Circuit
jex.im visualizes regular expressions:

A: Javascript:   /^(?=.*?\d)(?=.*?[a-z])[a-z\d]{18}$/i
These were the Salesforce Id validation requirements for me.

*

*18 characters only

*At least one digit

*At least one alphabet

*Case insensitive

Test cases
Should fail
1
a
1234
abgcde
1234aDcde
12345678901234567*
123456789012345678
abcDefghijabcdefgh

Should pass
1234567890abcDeFgh
1234abcd1234abcd12
abcd1234abcd1234ab
1abcDefhijabcdefgf
abcDefghijabcdefg1
12345678901234567a
a12345678901234567

For understanding the regex, please refer this thread

A: Something like this should work:
[a-zA-Z0-9]{15,18}

It was suggested that this may be more correct because it prevents Ids with lengths of 16 and 17 characters to be rejected, also we try to match against 18 char length first with 15 length as a fallback:
[a-zA-Z0-9]{18}|[a-zA-Z0-9]{15}

A: Just use instanceOf to check if the string is an instance of Id.
String s = '1234';
if (s instanceOf Id) System.debug('valid id');
else System.debug('invalid id');

A: The regex provided by Daniel Sokolowski works perfectly to verify if the id is in the correct format.
If you want to verify if an id corresponds to an actual record in the database, you'll need to first find the object type from the first three characters (commonly known as prefix) and then query the object type:
boolean isValidAndExists(String key) {
    Map<String, Schema.SObjectType> objTypes = Schema.getGlobalDescribe();

    for (Schema.SObjectType objType : objTypes.values()) {
        Schema.DescribeSObjectResult objDesc = objType.getDescribe();
        if (objDesc.getKeyPrefix() == key.substring(0,3)) {
            String objName = objDesc.getName();
            String query = 'SELECT Id FROM ' + objName + ' WHERE Id = \'' + key + '\'';
            SObject[] objs = Database.query(query);
            return !objs.isEmpty();
        }
    }
    return false;
}

Be aware that Schema.getGlobalDescribe can be an expensive operation and degrade the performance of your application if you use that often.
If you need to check that often, I recommend creating a Custom Setting or Custom Metadata to store the relation between prefixes and object types.

A: The easiest way I've come across, is to create a new ID variable and assign a String to it.
ID MyTestID = null;
try {
    MyTestID = MyTestString; }
catch(Exception ex) { }

If MyTestID is null after trying to assign it, the ID was invalid.

A: Assuming you want to validate Ids in Apex, there are a few approaches discussed in the other answers.  Here is an alternative, with notes on the various approaches.
The try-catch method (credit to @matt_k) certainly works, but some folks worry about overhead, especially if testing many Ids.
I used instanceof Id for a long time (credit to @melani_s), until I discovered that it sometimes gives the wrong answer (e.g., '481D0B74-41CF-47E9').
Multiple answers suggest regexen.  As the accepted answer correctly points out (credit to @zacheusz), 18 character Ids are only valid if their checksums are correct, which means the regex solutions can be wrong. That answer also helpfully provides code in several languages to test Id checksums.  But not in Apex.
I was going to implement the checksum code in Apex, but then I realized the Salesforce had already done the work, so instead I just convert 18 digit Ids to 15 digit Ids (via .to15() which uses the checksum to fix capitalization, as opposed to truncating the string) and then back to 18 digits to let SF do the checksum calc, then I compare the original checksum and the new one.  This is my method:
    static Pattern ID_REGEX = Pattern.compile('[a-zA-Z0-9]{15}(?:[A-Z0-5]{3})?');
    /**
     * @description Determines if a string is a valid SalesforceId.  Confirms checksum of 18 digit Ids.
     *              Works for cases where `x instanceof id` returns the wrong answer, like '481D0B74-41CF-47E9'.
     *              Does NOT check for the existence of a record with the given Id.
     * @param s     a string to validate
     *
     * @return      true if the string `s` is a valid Salesforce Id.
     */
    public static Boolean isValidId(String s) {
        Matcher m = ID_REGEX.matcher(s);
        if (m.matches() == false) return false;     // if it doesn't match the regex it cannot be valid
        if (s.length() == 15) return true;          // if 15 char string matches the regex, assume it must be valid
        String check = (Id)((Id)s).to15();          // Convert to 15 char Id, then to Id and back to string, giving correct 18-char Id
        return s.right(3) == check.right(3);        // if 18 char string matches the regex, valid if checksum correct
    }

A: Additionally checking getSObjectType() != null would be perfect if we are dealing with Salesforce records
public static boolean isRecordId(string recordId){
        try{
            return string.isNotBlank(recordId) && ((Id)recordId.trim()).getSObjectType() != null;
        }catch(Exception ex){
            return false;
        }
}


text:
Q: Do adjectives ending in "-ed" derive from words that were once used as verbs? Talented derives from talent, which is not a verb in Modern English.
Has talent ever been used as verb? Are there any words ending in -ed that derive from words once used as verb that is not used nowadays?

A:
Has talent ever been used as verb?

There are no signs of this in any dictionary, etymology dictionary, or online resource I have checked.

Do adjectives ending in "-ed" derive from words that were once used as verbs?

No, not necessarily. Someone is talented because he has talent, not because he was talented by someone or has talented something. As Daniel points out in his answer, there are lots of such constructions: five-fingered, long-legged, lighthearted, etc. These words are not derived from verbs, they are derived from nouns, as Kosmonaut explains in full detail in his answer.

Are there any words ending in -ed that derive from words once used as verb?

Yes. One example is "sacred":

sacredc.1300, from pp. of obsolete verb sacren "to make holy" (early 13c.)

A: The OED makes a clear distinction between the -ed that forms adjectives and the -ed that forms the past participle (and, naturally, any past participle can be used as an adjective).  The adjective-forming -ed (which gives the meaning "possessing, provided with, characterized by") definitely does not have any inherent verb-related qualities, or require that there ever was some verb counterpart at any point in time.  You can go straight from noun to adjective, like in your example with talent.  Even in cases where there is a verb form, e.g. feathered, there is nothing about "feathered bird" that suggests that this feathered came from the verb (i.e. nobody ever feathered the bird).  Compare that to "fallen soldier", where adjective fallen clearly did come from the past participle fallen (i.e. the soldier did fall).
The reason the adjective suffix looks like the past suffix is because they originally came from the same etymological root.  The OED says (modified to have less abbreviations):

-ed is appended to nouns in order to form adjs. connoting the possession or the presence of the attribute or thing expressed by the noun. The function of the suffix is thus identical with that of the Latin participle suffix -tus as used in caudtus (tailed), aurtus (eared), etc.; and it is possible that the Teutonic -ôjo- may originally have been from -ôo- (see past ppl. -ed), the suffix of past participles of verbs in -ôjan formed upon nouns.

The OED also says that there are many cases where it is impossible to tell 100% for certain which -ed adjectives were originally from past participles of verbs that later disappeared, and which were just formed straight from nouns, but surely there are some of the former.

A: Similar to talented are gifted, or winged as in a bird is a winged creature.
Nouns can be turned into adjectives by adding "-ed", but it seems they need a modifier, for example:

*

*kind hearted

*ten toed

*five fingered

*long necked

*evil eyed

*heavenly minded

*long legged


text:
Q: Flutter app not compiling: CocoaPods could not find compatible versions for pod "flutter_facebook_auth" firebase_auth: Using Firebase SDK version '8.15.0' defined in 'firebase_core'
firebase_core: Using Firebase SDK version '8.15.0' defined in 'firebase_core'
[!] CocoaPods could not find compatible versions for pod "flutter_facebook_auth":
In Podfile:
flutter_facebook_auth (from .symlinks/plugins/flutter_facebook_auth/ios)

A: Facebook app events needs to update their ios sdk version. Or you can use :
flutter_facebook_auth: 3.5.0+1

*

*don't use ^ in the version because this will install the lastest
version 3.5.2
source:
https://github.com/darwin-morocho/flutter-facebook-auth/issues/157

A: You can use, in the meantime, the below dependencies in your Pubspec.yaml (these are compatible)
flutter_facebook_auth: 4.3.1
facebook_app_events: ^0.16.0

Hopefully facebook_app_events will be updated soon. You can follow the issue in their GitHub page.


text:
Q: How do I fix booting process in Ubuntu 12.04 after the windows7 removed? The windows7 OS successfully removed, but can't boot in Ubuntu, said the bootmgr is missing. Also the hdd password is frozen.

A: The boot manager for Ubuntu, GRUB2, was probably broken when you removed windows. Try using Boot Repair to fix it. First boot to the Ubuntu live CD. Open a terminal window and run the following code to install and run boot repair:
sudo add-apt-repository ppa:yannubuntu/boot-repair
sudo apt-get update
sudo apt-get install -y boot-repair
boot-repair

Then follow the instructions and options in the program to repair your boot.
You can visit http://www.howtogeek.com/114884/how-to-repair-grub2-when-ubuntu-wont-boot/ for more information.

A: Try Boot-Repair.
Boot-Repair is a simple tool to repair frequent boot issues you may encounter in Ubuntu like when you can't boot Ubuntu after installing Windows or another Linux distribution, or when you can't boot Windows after installing Ubuntu, or when GRUB is not displayed anymore, some upgrade breaks GRUB, etc.
You can either install Boot-Repair, or download it, and boot from the CD.
To install it, just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command(s) below:
sudo add-apt-repository ppa:yannubuntu/boot-repair && sudo apt-get update
sudo apt-get install -y boot-repair && (boot-repair &)

Source:Boot-Repair


text:
Q: Working with convolution-like sums Let $a_k =0 \  \forall k \le 0$ be an integer sequence, and define
$$f(n,s):=\sum_{k=0}^n k^s a_k a_{n-k}$$
We can clearly express $f(n,1)$ in terms of $f(n,0)$ as:
$$f(n,1)=\frac{n}{2} f(n,0)$$
My question is whether there is a way to express $f(n,2)$ in terms of $f(n,1)$ and, if there is not any, how to disprove it.
More generally, when I was working with this type of discrete convolutions, I noticed that it is possible to express $f(n,2l+1)$ in terms of combinations of $f(n,2l), \dots ,f(n,0)$ just by making equal:
$$\sum_{k=0}^n k^s a_k a_{n-k} = \sum_{k=0}^n (n-k)^s a_k a_{n-k}$$
And developing Newton's Binomial. An alternative proof can be found by taking its Fourier transform and working with its properties.
However, this method does not work for even values of $s$, hence my question of wether there exists an alternative method for finding such an expression (while my question if focused on the case $f(n,2)$, there may exist a generalization for $n=2l$). If it were not possible, it would be great to have a proof of it.
Thank you in advance.

A: If I understand correctly, you want a formula of the form $f(n,2) = g\big( n, f(n,1) \big)$ for some function $g$ (which, in particular, does not take the invididual $a_j$ into account).
Such a function cannot exist, as we can see just by taking $n=2$:
\begin{align*}
f(2,2) &= a_1^2 + 4a_0a_2 \\
f(2,1) &= a_1^2 + 2a_0a_2.
\end{align*}
There are certainly triples $(a_0,a_1,a_2)$ for which $a_1^2 + 2a_0a_2$ gives the same value but for which $a_1^2 + 4a_0a_2$ does not; for example, $(a_0,a_1,a_2)=(1,1,5)$ and $(a_0,a_1,a_2)=(3,1,1)$ have this property.


text:
Q: Speed-up calculation of Area of Polygons I have a complicated polygon in the 2d plane, that is an RegionIntersection of RegionUnion of triangles.
Finally, I want to calculate it's Area. Unfortunatly, the Area is really slow. I am not sure why, but presumably because it calculates the result analytically.
I have an example that represents the shapes I am dealing with:
TotalTime = 0;
For[cc = 1, cc <= 50, cc++,
  (* Reconstructing roughly the shapes I am using *)
  BoundIntersect = RegionIntersection[
    RegionDifference[Triangle[RandomReal[{-0.2, 0.2}, {3, 2}]],
     Polygon[RandomReal[{-0.2, 0.2}, {3, 2}]]],
    RegionUnion[Triangle[RandomReal[{-0.2, 0.2}, {3, 2}]],
     Triangle[RandomReal[{-0.2, 0.2}, {3, 2}]],
     Triangle[RandomReal[{-0.2, 0.2}, {3, 2}]],
     Triangle[RandomReal[{-0.2, 0.2}, {3, 2}]],
     Triangle[RandomReal[{-0.2, 0.2}, {3, 2}]]]];

  CurrentTime = AbsoluteTime[];
  BoundaryIntersectRatio = Area[BoundIntersect];
  TotalTime += (AbsoluteTime[] - CurrentTime);
  ];
Print["Total Time: " <> ToString[TotalTime] <> " sec."];

Can you speed it up? In particular, error-ratios in the order of $10^{-4}$ are tolerable.

Update (25.12.2019):
A fair comparison (100 iterations with same polygons for each method):

*

*Henrik Schumacher's method using undocumented Graphics`PolygonUtils function: 0.75005 sec.

*Alx's suggestion using BoundaryDiscretizeRegion: 5.03149 sec.

*My original method: 24.50163 sec.
Result: Speedup of >factor 30! And learned about undocumented function that i can use all over my code. Fantastic, thank you!

A: These undocumented functions do the job almost two orders of magnitude faster:
BoundIntersect = Graphics`PolygonUtils`PolygonIntersection[
    Graphics`PolygonUtils`PolygonComplement @@ (Polygon /@
       RandomReal[{-0.2, 0.2}, {2, 3, 2}]),
    Graphics`PolygonUtils`PolygonCombine[
     Polygon /@ RandomReal[{-0.2, 0.2}, {5, 3, 2}]]
    ];
Graphics`PolygonUtils`PolygonArea[BoundIntersect]


text:
Q: How to select a column in SQL Server with a special character in the column name? I have a table contain the '%' in the column title, and this cause problem when I do the select statement on that column (Find below for more details). Does anyone know how can I select that column by not keeping the original column title?
Example:
Table1
name  ref_no  tot_sales  %Phone
-------------------------------
Alan  1       1          100%
amy   2       1          50%
ken   3       4          30%

Script:
Select %Phone From Table1

Error Message :

Incorrect syntax near phone

A: You may want to wrap your column name in square brackets to have your identifier delimited:
SELECT [%Phone] FROM Table1

If the QUOTED_IDENTIFIER option is set to ON, you can also use ANSI-SQL compliant double quotation marks to delimit identifiers:
SELECT "%Phone" FROM Table1


text:
Q: What does it mean to be "mailing it in" What does it mean to be mailing it in? Can you guys give me example phrases so I can get what it means?
Ex: He's just mailing it in at work today.

A: "Phoning it in" is an expression; I haven't heard "mailing it in" but I assume it means the same thing. Basically, it means "slacking off" or "putting in the minimum effort he can get away with". Some more examples are listed here (see definition 3): https://en.wiktionary.org/wiki/phone_in

A: Considering that the definition of mailing it in is:

To deliver a performance without commitment or effort, with lackluster results.

Here are some exemples:

"Even though I still have an exam in two weeks, I am going to mail it in and get ready for summer!"
"The manager is going to mail it in".


text:
Q: ORA-001722 Invalid Number when insert in Oracle SQL CREATE TABLE the_user( Name VARCHAR(40) not null,
    Address VARCHAR(255) not null,
    Delivery_address VARCHAR(255),
    Email VARCHAR(25) not null,
    Phone INTEGER not null,
    Status INTEGER not null,
    Password VARCHAR(25) not null,
    DOB DATE not null,
    PRIMARY KEY (Email),
    FOREIGN KEY (Status) REFERENCES User_Status (Status_Id),
    CONSTRAINT check_Password CHECK (Password > 4)
);

INSERT  INTO  the_user VALUES  (
    'Pergrin Took',
    '12 Bag end, hobbiton, The Shire, Eriador',
    'The address, Dublin',
    'ptook@lotr.com',
    '8679046',
    '001',
    'treebeard',
    TO_DATE('2013/11/04 14:11:34', 'yyyy/mm/dd hh24:mi:ss')
);

I have the above database in Oracle but when I try to run the insert command I get an ORA-1722 error, Invalid Number. There is a entry in the user_status table which corresponds to the 1 in the insert.
I have been stuck on this for days.

A: Quotes are not a problem - it will be converted implicitly to numbers as far as they are valid.
Check your constraints:
CONSTRAINT check_Password CHECK (Password > 4)

Here you try to compare string and number -> in this comparison Oracle always tries to cast both as numbers -> password fails and you see an error.
Try to use instead of password e.g. '55' and you will see the row is inserted.
Perhaps you wanted to do this?
CONSTRAINT check_Password CHECK (length(Password) > 4)


text:
Q: Autochange values of a variable outside a while loop in Python I do not really know how to correctly ask this question so please bear with me. So,
b=1

a=b

while (a<10):
    b+=1
    #a=b
    print a, b

This returns an infinite loop UNLESS I remove the #. What I am asking is this: is there a way to UPDATE the value of var a without having to put "a=b" inside the loop? On my real script the value of a is a very big formula and I do not want to carry it inside every nested loop because it looks ugly. I tried using "global a" but still it does not work. Any ideas?
EDIT
As suggested here is the real code:
def generator(tar_cal):
    meal_1=["oats", "egg whites", "green apple"]
    meal_1_cal=tar_cal*0.27

    oats_min=50
    egg_whites_min=4
    green_apple_min=1
    sum1=(8*9+11*4+60*4)*oats_min/100 + (0.1*9+3.6*4+0.2*4)*egg_whites_min + (0.3*9+0.5+4+20.6*4)*green_apple_min
    while not (meal_1_cal <= sum1):
        if oats_min<100:
            oats_min+=10
            sum1=(8*9+11*4+60*4)*oats_min/100 + (0.1*9+3.6*4+0.2*4)*egg_whites_min + (0.3*9+0.5+4+20.6*4)*green_apple_min
        elif egg_whites_min<8:
            egg_whites_min+=1
            sum1=(8*9+11*4+60*4)*oats_min/100 + (0.1*9+3.6*4+0.2*4)*egg_whites_min + (0.3*9+0.5+4+20.6*4)*green_apple_min
        else:
            green_apple_min+=1
            sum1=(8*9+11*4+60*4)*oats_min/100 + (0.1*9+3.6*4+0.2*4)*egg_whites_min + (0.3*9+0.5+4+20.6*4)*green_apple_min
    print "meal 1: %d grams kouaker, %d egg whites, %d green apple(s) " %(oats_min, egg_whites_min, green_apple_min)

generator(2000)

A: You need to create separate function, and parameterize the formula. Try something like this:
def calculate_value(oats=50, egg_whites=4, green_apple=1):
   oats_value = (8*9+11*4+60*4)*oats_min/100
   egg_whites_value = (0.1*9+3.6*4+0.2*4)*egg_whites
   green_apple = (0.3*9+0.5+4+20.6*4)*green_apple
   return (oats_value, egg_whites_value, green_apple)

Now, in your actual method, simply call it with the values:
def generator(tar_cal):
    meal_1=["oats", "egg whites", "green apple"]
    meal_1_cal=tar_cal*0.27
    oats_min=50
    egg_whites_min=4
    green_apple_min=1
    sum1 = sum(calculate_value(oats_min, egg_whites_min, green_apple_min))
    while not (meal_1_cal <= sum1):
        if oats_min<100:
            oats_value = oats_min += 10
            sum1=sum(calculate_value(oats=oats_value))
        elif egg_whites_min<8:
            egg_whites = egg_whites_min+=1
            sum1=sum(calculate_value(egg_whites=egg_whites))
        else:
            green_apple = green_apple_min+=1
            sum1 = sum(calculate_value(green_apple=green_apple))
    print "meal 1: %d grams kouaker, %d egg whites, %d green apple(s) " %(oats_min, egg_whites_min, green_apple_min)

generator(2000)

A: In python Integers are copied by value, instead of reference. So if you want to copy by reference you have to define those in a python list.try this code
#python 3.4
b=[1]

a=b

while (a[0]<10):
    b[0]=b[0]+1
    #a=b
    print(a[0], b[0])


text:
Q: Migrate Legacy Application to Symfony2 I have an application with a custom framework, it's very old 7 years ago using old techniques and design patterns.
We are facing problems.
We are using DAO Layer to access the Data objects and by the business need things getting so complicated and DAO is no longer being able to serve the business needs, we are thinking to use Symmfony2 and Doctrine2.
But the problem is :
THE APPLICATION IS REALLY BIG.
More than 7 years development and adding features.
About 11.500 Files and File Avg 1500 Line.
I know it's not an easy job, but i'm sure there's a way to migrate or at least use Doctrine for now without hurting the legacy code.
Please Advice.
Thank you.

A: There is no easy answer to your problems. Dealing with legacy code is always hard.
You should wrap Symfony around your application if possible. Implement a Command or Facade pattern around your app, and make the Symfony controllers call those classes.
Try to separate your DAO access layers by using the repository pattern. Not the Doctrine repositories, but custom ones, specific to your app. When you have repositories separated with interfaces from your app, you can do doctrine implementations of them one by one.
It would be worth thinking about decoupling your application from Symfony so you don't face these kind of problems in the future.
Also, if you can, try to write as many tests as possible, this will make it much easier for you to refactor in the future.
I wrote a blog post with some tips on how to separate from the framework here. The same pattern applies for repositories.


text:
Q: Python Redmine Connection I try to connect myself to a Redmine server with a script running on a  windows 7 virtual machine with these few lines, but it fails.
I did run the script on another computer without problems, has someone some ideas about what could block the connection process on a virtual machine?
redmine_url = 'https://url'
myapi_key = 'myAPIkey'
ticket_author = 'myMail@server.com'
redmine = Redmine(redmine_url, key=myapi_key, impersonate=ticket_author)
project = redmine.project.get('MyProject')
print('im in project number : ',project.id)

Here is the message error

Requests.exceptions.ConnectionError:HTTPSConnectionPool<host='myserver',port=443>:Max
retries exceeded with url:
/URLpath.json?key=myAPIkey&limit=100&offset=0 (Caused by
NewConnectionError('<urllib3.connection.VerirfiedHTTPSConnection
object at 003EA0670>:Failed to established a new connection: [WinError
10061] No connection could be made because the target machine actively
refused it',))


text:
Q: MongoDB Get data when date is between startdate and enddate of table row I want to get only that data between start date and end date.
For.ex I have passed the date: 2020-10-08 12:15:10
Table
-------
Id    Startdate                      EndDate
1     2020-10-10 12:15:10            2020-10-15 12:15:10
2     2020-08-12 12:15:10            2020-08-15 12:15:10

using a MySQL query:
select * from table where '2020-10-08 12:15:10' between startDate and endDate
it's working but I need it in MongoDB so how can do it.
Please help me.


text:
Q: Ubuntu 12.10 wont boot with the windows installer
Possible Duplicate:
Installing Ubuntu on a Pre-Installed UEFI Supported Windows 8 system

I just installed 12.10 on my pc alongside windows 8. I followed all the direction with the windows installer but when i try to boot Ubuntu it says that it cant run it because a file is missing.

A: I had the same problem. I think it's a windows 8 issue. For me it gave a corrupt bootloader. I think the best option is to install with vmware or virtualbox in Windows.
Or you can choose to install Windows 7 and then install it with the Windows installer.


text:
Q: Send CSRF token with laravel header() method Is it possible to protect post method with CSRF token with laravel header() method ?
just like
$obj->header('Content-Type', 'text/xml');

A: Every routes register within your app in the web.php file by default is already protect by the VerifyCsrfToken. In the App\Providers\RouteServiceProvider the method mapWebRoutes attach on every routes in the web.php file the web middleware which is a wrapper of many middleware like you can see in the App\Http\Kernel class
 protected $middlewareGroups = [
    'web' => [
        // others middlewares goes here

        \App\Http\Middleware\VerifyCsrfToken::class,

        // others middlewares goes here
    ],


text:
Q: Sox and pitch change of multiple audio files I want to change pitch, using sox, of every mp3 in every music folder I have. I wrote this in bash:
function pitch_mp3 {
for mp3 in /home/mp3s/*/*.mp3
do
  cd "$(dirname "$mp3")"
  output=$(basename "$mp3" .mp3)PITCHED.mp3
  sox -S "$mp3" -C 192 "$output" pitch 50
done
}

It adds the pitch to for example 01song.mp3 and the output file is 01songPITCHED.mp3.
But what happens is that sox do the job first time, but then goes again cycling through the folders and add pitch to already pitched mp3-s, so they file name turned out to be 01songPITCHEDPITCHED.mp3. I stopped it when I noticed, so I don't know if it is going to add pitch for the third time etc..
Why and how to fix this?

A: If you just want to skip any file ending with PITCHED.mp3 I would use a case statement
case "$mp3" in
  *PITCHED.mp3)
    echo skipping "$mp3"
    ;;
  *)
    #repitch as before
    ;;
esac

A: function pitch_mp3 {
for mp3 in /home/mp3s/*/*.mp3
do
  [[ "$mp3" = *PITCHED.mp3 ]] && continue
  cd "$(dirname "$mp3")"
  output=$(basename "$mp3" .mp3)PITCHED.mp3
  sox -S "$mp3" -C 192 "$output" pitch 50
done
}

I'd also make the extension a variable so I didn't have to retype it, but that's just me.


text:
Q: Concatenating strings from C# in C++ then passing back to C# I'm currently messing around with C++. I want to pass data in from C# into C++ and output back to C#, specifically for use within Unity.
Currently I'm using:
char* testingTwoStrings(char* str1, char* str2)
{
    int str1length = strlen(str1);
    int str2length = strlen(str2);
    int totalLength = str1length + str2length;

    char* convertedString = new char[totalLength];

    strcpy_s(convertedString, totalLength, str1);
    strcat_s(convertedString, totalLength, str2);

    return convertedString;

}

I've done a bit of digging around already, but as this is my first real time dabbling in C++ rather than C# there's a lot of terminology that I don't quite understand.
Currently, building this and calling it from a C# script in Unity is causing Unity to crash.
My current feeling is that it's due to the fact I need to initialize the memory first but I'm not sure where I'm going wrong.
Any answers appreciated!
I've currently done a few bits messing around with strcpy and strcpy_s. if I use strcpy twice, then the script outputs the second one only (presumably it's overwriting the first cpy) but if I use strcat then unity Crashes.


text:
Q: Invertibility of laplacian operator Let $\Omega\in\mathbb{R}^n$ be a bounded open set with smooth boundary. How to prove the invertibility of $$- \triangle:H^2_0(\Omega) \to L²(\Omega) $$
The injectivity is easy. But how to prove surjectivity without the use of weak notion of solution (when the domain becomes $H^1_0(\Omega)$ and this can be easily found in books)?

A: The operator $$- \triangle:H^1_0(\Omega) \to L²(\Omega) $$
is "surjective" in the weak sense (as a direct use of Riesz representation theorem).
Then you can use regularity theorems to prove that, in fact, this weak solution is in $H^2(\Omega)$. A good reference to a  result like this is the Brezis book  "functional analysis, Sobolev spaces and PDE". See theorem 9.25 and note that a $C^2$ domain $\Omega$ is required. So your result is valid from $H^1_0(\Omega)\cap H^2(\Omega) $ to $L²(\Omega) $.


text:
Q: Browser url getting changed showing actual URL location Hi Bellow is my Rewrite rule,Its working perfectly,
  RewriteRule ^forms/result/([A-Za-z0-9-\s]+)/([0-9]+)/?$    http://www.xyz.com/forms/search_box.php?query=$1&page=$2 [R=301,NC,L]

when am requesting bellow link in brouser URL
 http://www.xyz.com/forms/result/700011/1

its opening specific search_box.php file with proper data,but brouser URL changed to actual url just like bellow.I don't want to change the requesting url(http://www.xyz.com/forms/result/700011/1) on browser.
http://www.xyz.com/forms/search_box.php?query=700019&page=3


text:
Q: Вопрос по протоколу ARP Одно из применений ARP это определение MAC-адреса по известному IP-адресу.
Пакет ARP содержит поля Source IP и Source MAC, и поля Destination IP и Destination MAC (ну и другие, конечно).
Когда идет ARP пакет типа ARP-запрос, то в поле Destination MAC - нули.
Когда идет ARP пакет типа ARP-ответ, заполняется поле Destination MAC и в пакете меняются местами получатель и отправитель.
Но, если в пакете-запроса есть поля SrcIP и SrcMAC, то одна ARP-транзакция (ARP-запрос, ARP-ответ) позволяют двум узлам сразу установить соответствие между IP-адресом и MAC-адресом другого. Т.е. в обеих узлах появится запись в ARP-таблице.
Это всегда так, что при одной ARP-транзакции в обеих узлах появляется запись в ARP-таблице или бывает, что нужно делать еще два ARP-запроса, что бы другой узел создал запись в своей ARP-таблице?
И еще такой вопрос: устройство, к которому подключаются компьютеры локальной сети  (например, маршрутизатор) может делать Broadcast-ARP запрос — он принимается всеми компьютерами в одном сегменте локалки.
Но у меня выходит так,что один из компьютеров локальной сети тоже посылает Broadcast-ARP запрос. Какой тут смысл в Broadcast если этот запрос кроме маршрутизатора никто "не услышит"? Не проще послать Glorious запрос, или просто запрос с Destination MAC = 0.

A: Все очень просто, если MAC-адрес конкретного IP не известен, то шлется широковещательный запрос, потому что мы еще не знаем куда слать. Владелец IP ответит. Абсолютно не важно кто посылает запрос маршрутизатор или любой другой компьютер. Все устройства работают одинаково, понадобился IP такой то (и неважно кто он, наш маршрутизатор или другой хост), этого IP еще нет в кеше - шлем широковещательный запрос.
Большинство современных операционных систем добавляют запись в arp-таблицу только когда получают ответ на свой arp-запрос. Во первых броадкаст запросы шлют все устройства в сети, т.е. запрос увидят все. Если кешировать ip-mac со всех пролетающих мимо запросов то таблица будет заполнятся массой не нужной нам информации. Кроме того, существует атака arp-poison (отравление arp кеша). Для нее шлют широковещательные (или unicast) запросы с поддельных MAC-адресов отправителя со случайными IP. Если устройство будет писать к себе все приходящие запросы, то таблица переполнится. По этому чужим запросам верить не принято и будет послан встречный запрос и поверят только ответу.
Если запись IP в таблице уже есть, но достаточно старая и при этом она все еще нужна (с ней идет обмен трафиком) то периодически посылаются проверочные запросы, вот они шлются unicast т.к. MAC назначения известен.
Есть еще особый вид ARP-запросов. Когда машина получила IP (из своих настроек или по DHCP) и включает его на интерфейсе она шлет 3 широковещательных ARP-запроса со своим IP и в Dest и в Src. Это делается для проверки на конфликты IP-адресов в сети. Если такой же IP у кого то в сети уже есть - то он ответит как на обычный запрос и машина или откажется от адреса, полученного по DHCP, или сообщит пользователю о конфликте в случае заданного в ручную (по крайней мере часть ОС так делают)


text:
Q: CSS fit n elements tight horizontally This question is a bit of a css riddle that may or may not have a simple answer:
I have one div (call it #parentDiv) that is of absolute positioning with width 100%.
Within #parentDiv I want to fit n divs, evenly spaced out within the parent div.
In other words, with one div (call it #childDiv1) within #parentDiv, it should fill the screen with the color of #childDiv1.
With two divs, #childDiv1 and #childDiv2, it should fill the screen with the left side being the color of the first, and the right side being the color of the second div.
The key here is that the css properties for all child divs must be equivalent. The reason for this is that I want to add more child divs with jquery later, and have them automatically cram into the parent div.
Any help is greatly appreciated!

A: I think you can accomplish what you want with a display:table on the parent and display:table-cell on the children. Also setting table-layout:fixed will make the cell widths independent of their content.
Markup:

1

2

3

CSS:
.parent {
  display:table;
  table-layout:fixed;
  width:100%;
}
.child {
  display:table-cell;
}


text:
Q: Why do I get "input does not match format" when I use fmt.Fscanf? I'm trying to use fmt.Fscanf but I'm having hard time figuring out how. Having the following code:
package main

import (
    "fmt"
    "strings"
)

func main() {
    var host, user, date, httpStr string
    var code, size int

    r := strings.NewReader(`127.0.0.1 - james [09/May/2018:16:00:39 +0000] "GET /report HTTP/1.0" 200 123`)

    _, err := fmt.Fscanf(r, `%s - %s [%s], "%s" %d %d`,
        &host, &user, &date, &httpStr, &code, &size)
    if err != nil {
        fmt.Printf("Failed to parse log line, error: %+v\n", err)
        panic(err)
    }

    fmt.Println(host, user, date, httpStr, code, size)

}

Go playground: https://play.golang.org/p/zGxc6MXOF3a
I get:
Failed to parse log line, error: input does not match format
panic: input does not match format

goroutine 1 [running]:
main.main()
        .../fscanf/main.go:19 +0x57b
exit status 2

Why?

A: The error comes from how Fscanf parses space-separated strings. This becomes an issue when reading the date and HTTP string:
When it reads the date, instead of reading 09/May/2018:16:00:39 +0000 it will read until the first space: 09/May/2018:16:00:39 then expect ].
To fix this, it would make sense to parse the string as [%s %s], but this would fail more subtly. It would parse the timezone as +0000] because it stops at the first space, not according to the format string. The same issue occurs with the HTTP string: it stops parsing after the verb GET, then after the route /report, but when reading the protocol it reads HTTP/1.0" not HTTP/1.0.
A working solution is as follows:
package main

import (
    "fmt"
    "log"
    "strings"
)

func main() {
    var host, user, date, tzOffset, verb, route, proto string
    var code, size int

    r := strings.NewReader(`127.0.0.1 - james [09/May/2018:16:00:39 +0000] "GET /report HTTP/1.0" 200 123`)

    _, err := fmt.Fscanf(r, `%s - %s %s %s %s %s %s %d %d`,
        &host, &user, &date, &tzOffset, &verb, &route, &proto, &code,
        &size)

    if err != nil {
        log.Fatal(err)
    }

    date = date[1:] + " " + tzOffset[:len(tzOffset)-1]
    httpString := verb[1:] + " " + route + " " + proto[:len(proto)-1]

    fmt.Println(host, user, date, httpString, code, size)
}

Here we ignore the brackets and quotes around the date and HTTP string when parsing, then remove them afterwards.
Output:
127.0.0.1 james 09/May/2018:16:00:39 +0000 GET /report HTTP/1.0 200 123


text:
Q: Can you perform a ternary expression in a javascript string interpolation? I have this variable :
var foobar = "Hi, my name is #{name}";

But if name is not defined at load of the page.. I'd like it to save "unknown" instead.
But writing something like this :
var foobar = "Hi, my name is #{typeof name === 'undefined' ? 'unknown' : name}";

Still returns the error, unknown variable name

A: Instead of making logic decisions within a string construct, do it outside for better performance and (far) more readable code:
name = name||'unknown';

A: I think a better method would be:
var name = name || "Unknown";
var foobar = 'Hi my name is ' + name;

A: Just put name in there. If it is undefined or null, it will be "false".
var foobar = "Hi, my name is " + name ? name : 'unknown';

A: With javascript ES6 syntax you can write this expression as follows,

const logName = (name) => `Hi, my name is ${name ? name : 'unknown'}`

console.log("foobar when name is undefined: ", logName());
console.log("foobar when name is abc: ", logName("abc"));


text:
Q: Javascript CRC16 sample code or implementation can anybody share a link or sample code to implement checksum for string in javascript?
Thanks a lot in advance

A: What do you want?
You need to be more specific.
There is a huge plethora of CRC16 algorithms, each one with its own polynomial and for a specific use. Some CRC16 algorithms are really good to create hashes ( for Redis, for example ) while others are better for wire communication.

*

*https://en.wikipedia.org/wiki/Cyclic_redundancy_check#Polynomial_representations_of_cyclic_redundancy_checks
I just want anything, I really don't care what
If this is the road you want to go with, then GitHub and NPM have many implementations that could work for you.
Their documentation is usually downright horrible or non-existent and there is no guarantee they will work as advertised, but if anything goes, you can always give them a try, and if you find a bug you can always report it in their issues page.
Here is a quick implementation I found, should be what you need:

*

*https://github.com/donvercety/node-crc16/blob/master/crc16.js


text:
Q: Wordpress wp_remote_post() gives "cURL error 6: Could not resolve host" Since this morning some function in a wordpress site I'm managing is not working anymore. I syslogged the response from it, which gives me:
{"errors":{"http_request_failed":["cURL error 6: Could not resolve host: subdomain.example.com"]},"error_data":[]}

When I manually run curl from that machine I simply get the html as a response. Since it says it could not resolve the host, I presume the problem occurs before the domain name can be resolved to an ip. So I guess (but not sure) this has something to do with the DNS.
I really don't understand what could be wrong here or how I can debug this. Does anybody have a suggestion?
All tips are welcome!

A: as mentioned here and due to this USN:
you will may need to update your dist
sudo apt-get update
sudo apt-get dist-upgrade

this fixed my issue with curl

Update
you will need to be aware of the dist-upgrade step, some packages -such as php- during the updrage will prompt you to ask you wether you want to replace the configuration files , you must be very aware of what you are doing here , keeping those files or replacing with the new -default- files.


text:
Q: Applying readmore.js functionality inside a tab content Please help. I was not able to trigger .readmore() function using the readmore.js jquery plugin inside a tab'd page, while it runs good on the first tab'd page, but not on the tabs those are inactive. Here is my issue. I have a page with 4 tabs and each tab has its own content. I read about this readmore.js that trims long text with having an option to expand it to readmore. Below is the jsp snippet -

                Project Details

                Tab 1

                Alpha

 long text here.....

 another long text here.....

 another long text here.....

Appreciate your help and suggestions here.. I tried to apply this function by binding to the tab click event, but of no help. I have also associated this to the div click event, it works only when the user clicks on the div tab (content inside the tab), which is not as expected.
Please help...

A: I was able to make it work using the following code:
$(function() {
    $(document).on( 'shown.bs.tab', 'a[data-toggle=\'tab\']', function (e) {
           $('.article').readmore({
                moreLink: 'Expand',
                maxHeight: 100
            });
        })
});

A: I made it work with this code. Putting  a "readmore" function before "tab"


text:
Q: What is 'Kill Ring' in XCode? In XCode there's a really neat feature called "Kill Ring" which I get a hint what its about here but I don't know how to use it!!
How do you use the "Insert Kill Ring" feature in XCode?

A: http://www.rattlesnake.com/intro/Yanking.html#Yanking
It's from Emacs.
Basically it's a list of copied entries which you can pop down through. If you've used later versions of Word or Excel, they have the same idea in their "paste lists" that show up when you copy things.
It allows you to copy two things in a row, then get back to the first thing.

A: If the article Customizing the Cocoa Text System has anything to do with it, then it states:

"kill ring" which large deleted blocks
  of text get copied to

NSTextKillRingSize apparently sets the size of the kill ring.
Please read the above article, you'll probably understand it better than me.

A: This article at Cocoa With Love goes into how to use OS X's kill-ring and other advanced editing features to great benefit.


text:
Q: Convert array to normal display? I set my foreach result in a array variable, the array give me some id's,
$categoryIDs = explode(',', $result->category_id);
I tried already to find solution but nothing works, any sources are:
Converting indexed array to normal or simple array
How to convert an array to object in PHP?
Display array elements as normal CSV - PHP
If i show result with print_r() i see correct result, but how can i convert it into: 32,432,21,543?

A: You can use implode for this:
implode(",", $categoryIDs);

You can read the document here.


text:
Q: Let $G$ to be abelian group and $|G|=mn$ when $(m,n)=1$. $G_m=\{g\mid g^m=e\}$,$G_n=\{g\mid g^n=e\}$, prove isomorphism I want to prove   $ f:G_n\times G_m\rightarrow G$ when $f(g,h)=gh $ is an isomorphism.
First of all I showed that $G_m,G_n$ are subgroups of $G$ (easy).
Now I want to show that for every  $  a,b, \in G$, $f(ab)=f(a)f(b) $.
Let  $a=(g_1,h_1)$ and $b=(g_2,h_2)$
$\implies f(g_1,h_1)=g_1h_1$ , $f(g_2,h_2)=g_2h_2$
$\therefore f(g_1,h_1) f(g_2,h_2)=g_1h_1g_2h_2=g_1g_2h_1h_2$ (because G is abelian) $=f\bigl((g_1g_2),(h_1h_2)\bigr)$
Then, I need to show that only $f(e)=e$.
Because $(m,n)=1$, only $f(e,e) = e e = e$.
Am I right? If not how can I prove this?
Is $f$ an isomorphism even if $G$ is not abelian?

A: Suppose
$$f(a,b):=ab=e\implies a=b^{-1}$$
Buth te last equality is impossible as $\;a\in G_n\;,\;\;b\in G_m\;$ and thus the only possible element in both of them is the unity, i.e. $\;G_n\cap G_m=\{e\}\;$ .
For a counter example with $\;G\;$ non abelian take $\;G=S_3\;$ , though in this case $\;G_2\;$ is not a subgroup.


text:
Q: Is there any matrix norm $|| \cdot ||$ such that $||A|| \le ||A||_{\infty} /n$? Matrix norms are equivalent and can bound each other like some examples on Wikipedia. I was wondering if there is a matrix norm $|| \cdot ||$ that can be upper bounded by $||\cdot ||_{\infty}/n$ ? That is, $||A|| \le \frac{||A||_{\infty}}{n}$, where $A$ is an $n \times n$ square matrix.
Since norms are equivalent, perhaps we can define a matrix norm by ourselves, only if it satisfies the definition of a matrix norm. A naive idea is just letting $|| \cdot || = ||\cdot ||_{\infty}/n$ but it is not sub-multiplicative (the last condition in the definition).

A: Since $\|I\|=\|I^2\|\le\|I\|^2$, we have $\|I\|\ge1$. So, if $\|I\|\le\frac{\|I\|_\infty}n$, then ...

A: Such a matrix norm cannot exist because let $A$ be any nonzero matrix.  Then consider $e^{tA}$.  We have that $||e^{tA}||\le ||e^{t/k A}||^k$ for all $t, k>0$.  Now take $A=I$.  Then we have that $||e^{t/k A}||^k\le e^t/n^k$ for all $k$.  Take $k \rightarrow \infty$.


text:
Q: Grouping in PHP using a character I have an array like:
    array{
     0 => string 'B.E - ECE',
     1 => string 'B.E - EEE',
     2 => string 'Msc - Maths',
     3 => string 'Msc - Social',
}

So how can I make the array into groups like:
B.E. => ECE, EEE
Msc => Maths,Social

?
I want to do it in PHP. Can anybody help me how to achieve it ?

A: So is your array split by the "-" character?
so it's Key - Value pairs split by commas?
Ok -
(edit: section removed to clarify answer)
Following conversation and some rearrangement of the question, a second try at a solution, with the above assumptions, try this:
$array = array {
     0 => string 'B.E - ECE' (length=9)
     1 => string 'B.E - EEE' (length=9)
     2 => string 'Msc - Maths' (length=11)
     3 => string 'Msc - Social' (length=12)
}

foreach ($array as $row){
$piece = explode("-",$row);
$key = $piece[0];
$newArray[$key][] = $piece[1];
unset($piece);
}
unset($row) ///tidy up

This will output two arrays each of two arrays:
$newArray[Msc] = array("Maths","Social");
$newArray[B.E] = array("ECE","EEE");

What I did was cause the Foreach loop to automatically add onto the array if the key exists with $newArray[$key][] so that the values are automatically collected by key, and the key is defined as the first half of the original array values.
Printing:
To print the result:
foreach($newArray as $key=>$newRow){
/// there are two rows in this case, [B.E] and [MSc]
print $key.":
";
print "
";
///
 HTML tag makes output use linebreaks and spaces. neater.
print_r($newRow);
///alternatively use var_dump($newRow);
print "
";
}

Alternatively if you wish to print a known named variable you can write:
print_r($newArray['B.E']);

Which will print all the data in that array. print_r is very useful.

A: what you want is php's explode. Not sure if this will give you the perfect answer but should give you an idea of what to do next.
$groupedArray = array();
foreach($array as $row){
    $split = explode(" - ",$row);
    $groupedArray[] = $split[0];
}
array_unique($groupedArray); //This will give you the two groupings

foreach($array as $row){
    $split = explode(" - ",$row);
    $pos = array_search($split[0],$groupedArray);
    if($pos !== FALSE){
        $groupedArray[$pos][] = $split[1];
    }
}

This should give you a full formatted array called $groupedArray where $array is the array you already have.
Hope this helps!


text:
Q: Text similarity Algorithms I'm doing a Java project where I have to make a text similarity program. I want it to take 2 text documents, then compare them with each other and get the similarity of it. How similar they are to each other.
I'll later put an already database which can find the synonyms for the words and go through the text to see if one of the text document writers just changed the words to other synonyms while the text is exactly the same. Same thing with moving paragrafs up or down.
Yes, as was it a plagarism program...
I want to hear from you people what kind of algoritms you would recommend.
I've found Levenstein and Cosine similarity by looking here and other places. Both of them seem to be mentioned a lot. Hamming distance is another my teacher told me about.
I got some questions related to those since I'm not really getting Wikipedia. Could someone explain those things to me?
Levenstein: This algorithm changed by sub, add and elimination the word and see how close it is to the other word in the text document. But how can that be used on a whole text file? I can see how it can be used on a word, but not on a sentence or a whole text document from one to another.
Cosine: It's measure of similarity between two vectors by measuring the cosine of the angle between them. What I don't understand here how two text can become 2 vectors and what about the words/sentence in those?
Hamming: This distance seems to work better than Levenstein but it's only on equal strings. How come it's important when 2 documents and even the sentences in those aren't two strings of equal length?
Wikipedia should make sense but it's not. I'm sorry if the questions sound too stupid but it's hanging me down and I think there's people in here who's quite capeable to explain it so even newbeginners into this field can get it.
Thanks for your time.

A: Basic idea of comparing similarity between two documents, which is a topic in information retrieval, is extracting some fingerprint and judge whether they share some information based on the fingerprint.
Just some hints, the Winnowing: Local Algorithms for Document Fingerprinting maybe a choice and a good start point to your problem.

A: Consider the example on wikipedia for Levenshtein distance:
For example, the Levenshtein distance between "kitten" and "sitting" is 3, since the following three edits change one into the other, and there is no way to do it with fewer than three edits:

   1. kitten → sitten (substitution of 's' for 'k')
   2. sitten → sittin (substitution of 'i' for 'e')
   3. sittin → sitting (insertion of 'g' at the end).

Now, replace "kitten" with "text from first paper", and "sitting" with "text from second paper".
Paper[] papers = getPapers();
for(int i = 0; i < papers.length - 1; i++) {
    for(int j = i + 1; j < papers.length; j++) {
        Paper first = papers[i];
        Paper second = papers[j];
        int dist = compareSimilarities(first.text,second.text);
        System.out.println(first.name + "'s paper compares to " + second.name + "'s paper with a similarity score of " + dist);
    }
}

Compare those results and peg the kids with the lowest distance scores.
In your compareSimilarities method, you could use any or all of the comparison algorithms. Another one you could incorporate in to the formula is "longest common substring" (which is a good method of finding plagerism.)

A: Levenstein: in theory you could use it for a whole text file, but it's really not very suitable for the task. It's really intended for single words or (at most) a short phrase.
Cosine: You start by simply counting the unique words in each document. The answers to a previous question cover the computation once you've done that.
I've never used Hamming distance for this purpose, so I can't say much about it.
I would add TFIDF (Term Frequency * Inverted Document Frequency) to the list. It's fairly similar to Cosine distance, but 1) tends to do a better job on shorter documents, and 2) does a better job of taking into account what words are extremely common in an entire corpus rather than just the ones that happen to be common to two particular documents.
One final note: for any of these to produce useful results, you nearly need to screen out stop words before you try to compute the degree of similarity (though TFIDF seems to do better than the others if yo skip this). At least in my experience, it's extremely helpful to stem the words (remove suffixes) as well. When I've done it, I used Porter's stemmer algorithm.
For your purposes, you probably want to use what I've dubbed an inverted thesaurus, which lets you look up a word, and for each word substitute a single canonical word for that meaning. I tried this on one project, and didn't find it as useful as expected, but it sounds like for your project it would probably be considerably more useful.


text:
Q: Как сделать блочный шаблон в laravel В Laravel шаблон каждой страницы прописан в полной форме ...
Что нужно мне: единая точка входа, только в ней должна быть прописана полная структура, а содержимое элемента body будет подгружаться в зависимости от страницы.
Как это можно реализовать?

A: Документация по шаблонам: https://laravel.com/docs/5.8/blade#extending-a-layout
Так же данный раздел из русской документации:

При определении дочернего представления используйте Blade-директиву
  @extends для указания макета, который должен быть «унаследован»
  дочерним представлением. Представления, которые наследуют макет Blade,
  могут внедрять содержимое в секции макета с помощью директив @section.
  Запомните, как видно из приведённого выше примера, содержимое этих
  секций будет отображено в макете при помощи @yield:
@extends('layouts.app')
@section('title', 'Page Title')
@section('sidebar')
      @parent

Это дополнение к основной боковой панели.
 @endsection

@section('content')
      Это содержимое тела страницы. @endsection

  В этом примере секция sidebar использует директиву @parent для дополнения (а не
  перезаписи) содержимого к боковой панели макета. Директива @parent
  будет заменена содержимым макета при отрисовке представления.

За наследование на странице отвечает @extends('тут шаблон body')
В самом же боди (лайауте) надо определить секцию @yield('content')


text:
Q: How to pass environment variable or string parameter in a Windows VM using jenkins as code using declarative syntax pipeline {
  agent {
    node {
      label 'xxx'
    }
  }
  environment {
    TESTPASSWORD_PSW = "${TESTPASSWORD}"
  }
  stages {
    stage("My Environemnt Pipeline")
    {
      steps {
        withCredentials([usernamePassword(credentialsId: 'MYCREDENTIAL',
          passwordVariable: 'TESTPASS', usernameVariable: 'TESTUSER')]) {
          echo "Have a look at ${TESTPASS}"
          echo "Have a look at ${TESTUSER}"
        }
      }
    }
  }
}

I tried using properties where I have defined the string and put the default value as the username above but on my Windows server VM in XXX, there is no variable such as that
even I tried the option of defining a variable in the environment with the value of this credential but the SET command in command prompt didn't list out any environment variable
How can I pass one password credentials to be used in Windows VM and use it in my code. Thanks for the help


text:
Q: Finding surjection from injection I looked at many of the similar questions, and I struggled to digest them - I'm taking my first math class that involves proofs, so I think my background was a bit weak.
The question:
             Suppose there is an injection f: A -> B. Prove there must exist a surjection g: B -> A.
My attempt:
Suppose there is an injection f: A -> B. By definition of injection,
f($a_{1}$) = f($a_{2}$) -> $a_{1}$ = $a_{2}$.
Define a function g: B -> A, g(b) = a for all b$\in$B
g $\circ$ f (a) = f(g(a)) = a for all a$\in$A.
This works because f is an injection, so f takes every element of A to a unique element of B.
Further, the domain of g $\circ$ f is able to each every element of its co-domain. So g $\circ$ f is a surjection -> g is a surjection.
Q.E.D.
Again I apologize that this question was answered in some form in the other questions - I'm operating on a simpler level than most, so I thought this question would still be of some benefit to others.

A: You're going along the right lines! An issue occurs when you're defining $g$ though - given some $b \in B$, you say that $g(b) = a$, but which $a$ are you picking for this particular $b$? How do you know that you can pick such an $a$?
However, if you can pick such an $a$, then your argument about why it's a surjection would be good.

A: I don't follow your definition of $g$. Are you picking some element $a \in A$, then defining a constant function from $B$ to $A$, mapping every element of $B$ to this one element $a$? If so, this is (in general) not a surjection!
Here's the way I'd do it. Let $C$ be the range of $f$. Note that, if we restrict the codomain of $f$ to $C$, then $f$ is a surjection too, and hence invertible. Let $h : C \to A$ be this inverse. Note that $h$ is invertible too, and hence is surjective.
All we need to do is extend $h$ to map from all of $B$ to $A$. Note that since $h$ is surjective, all elements of $A$ are currently being mapped to, so the other points in $B$ can map to literally anywhere we want in $A$.
Choose some fixed $a_0 \in A$, and define $g : B \to A$ as follows:
$$g(b) = \begin{cases} h(b) & \text{if } b \in C \\ a_0 & \text{if } b \notin C \end{cases}.$$
Then, if $a \in A$, then since $h$ is a surjection (since it is invertible), there exists some $b \in C$ such that $h(b) = a$. By definition, $g(b) = a$ too, hence $g$ is a surjection.

A: Notice that $\text{range}(f) \subset B$. Map all the elements of $B-\text{range}(f)$ to any fixed element of $A$, and the elements left in $B$ are the images of some elements of $A$. Now try to complete the proof.


text:
Q: How would I get this for loop to print prime numbers only? What I need it to do is print all of the prime numbers starting at 1 and ending at the input, if the input is also a prime number. Here's my code now:
static void primeNumbers(int n) {

boolean isPrime;

System.out.println("All the prime numbers up to " + n + " are -->");
for (int prime = 2; prime < n; prime = prime++) {
  if (n % prime == 0) {
    isPrime = false;
  }
  if(isPrime == true){
    System.out.println(prime);
  }
}
}

My teacher said that I need to make a nested for loop, but I just don't know what to put in it. I'm also getting an error saying that my last use of isPrime hasn't been initialized.

A: You need to actually check for primality, and not just see if the number is a factor of n:
static boolean isPrime(int n) {
    if (n < 2) {
        return false;
    }
    if (n % 2 == 0) {
        return n == 2;
    }
    for (int k = 3; k * k <= n; k += 2) {
        if (n % k == 0) {
            return false;
        }
    }
    return true;
}

static void primeNumber(int n) {
    System.out.println("All the prime numbers up to " + n + " are -->");
    for (int num = 2; num < n; num ++) {
        if (isPrime(num)) {
            System.out.println(num);
        }
    }
}

A: You will need to do something like this for your program to work.
static void primeNumbers(int n) {

    boolean isPrime = true;

    System.out.println("All the prime numbers up to " + n + " are -->");
    for (int prime = 2; prime < n; prime++) {
        if (n % prime == 0) {
            isPrime = false;
        }else{
            isPrime = true;
        }
        if(isPrime){
            System.out.println(prime);
        }
    }
}

A: It is necessary to initialize isPrime.
And, Eratosthenes' s sieve is famous algorithm for get prime numbers.
I think the URL below will help you.
https://www.geeksforgeeks.org/java-program-for-sieve-of-eratosthenes/

A: here is one of the solutions
 public static void main(String[] args) {
        int n = 23;
        boolean[] isPrime = new boolean[n + 1];

        for (int i = 1; i <= n; i++) {
            isPrime[i] = true;
        }

        for (int i = 2; i <= n / i; i++) {
            if (isPrime[i]) {
                for (int j = i; j <= n / i; j++) {
                    isPrime[i * j] = false;
                }
            }
        }

        for (int i = 1; i <= n; i++) {
            if (isPrime[i]) {
                System.out.println(i);
            }
        }
    }


text:
Q: How to write SFTP client using Apache MINA library I tried finding Java code for SFTP client using Apache MINA library but couldn't find it.
Could someone show me how to write a simple password authentication based SFTP client using Apache MINA library.
https://mina.apache.org/sshd-project/apidocs/org/apache/sshd/client/subsystem/sftp/SftpClient.html

A: Based on the examples in the README.md in the root of apache-sshd-2.2.0-src package:
SshClient client = SshClient.setupDefaultClient();
// override any default configuration...
client.setSomeConfiguration(...);
client.setOtherConfiguration(...);
client.start();

try (ClientSession session = client.connect(user, host, port).verify(timeout).getSession()) {
    session.addPasswordIdentity(password);
    session.auth.verify(timeout);

    // User-specific factory
    try (SftpClient sftp = DefaultSftpClientFactory.INSTANCE.createSftpClient(session)) {
        // use sftp here
    }
}


text:
Q: Do Non-Static things from Static, C#? I'm using c# to develop a small UWP app for Windows IoT that is installed on Raspberry pi 3. However, I want to this:
button.Visibility = Visibility.Visible;
button1.Visibility = Visibility.Collpsed;

That code I want to keep it inside a static method :). I haven't found any helpful answer yet. I hope you guys will give me an easy and quick solution.

A: If you want to make that static you'll have to pass in the buttons
public static void DoStuff(Button button, Button button1)
{
    button.Visibility = Visibility.Visible;
    button1.Visibility = Visibility.Collpsed;
}

A: As a second option to Kevin's already sufficient answer, similar can be done with extension methods if you are working with one button at a time. You will need a using statement for the namespace the extension method is in.
Extension methods are a way of adding an instance method to an existing class.
see MSDN - Extension Methods
eg:
public static class ButtonExtensions
{
    public static void SetVisibility(this Button button, Visibility visibility)
    {
       button.Visibility = visibility;
    }
}

usage:
public void Test()
{
    Button button = new Button();
    Visibility visibility = Visibility.Collapsed;

    button.SetVisibility(visibility);

    //or
    ButtonExtensions.SetVisibility(button, visibility);
}


text:
Q: MongoDB Conditional validation on arrays and embedded documents I have a number of documents in my database where I am applying document validation. All of these documents may have embedded documents. I can apply simple validation along the lines of SQL non NULL checks (these are essentially enforcing the primary key constraints) but what I would like to do is apply some sort of conditional validation to the optional arrays and embedded documents. By example, lets say I have a document that looks like this:
{
  "date": <<insertion date>>,
  "name" : <<the portfolio name>>,
  "assets" : << amount of money we have to trade with>>
}

Clearly I can put validation on this document to ensure that date name and assets all exist at insertion time. Lets say, however, that I'm managing a stock portfolio and the document can have future updates to show an array of stocks like this:
{
  "date"      : <<insertion date>>,
  "name"      : <<the portfolio name>>,
  "assets"    : << amount of money we have to trade with>>
  "portfolio" : [
                  { "stockName"  : "IBM",
                    "pricePaid"  : 155.39,
                    "sharesHeld" : 100
                  },
                  { "stockName"  : "Microsoft",
                    "pricePaid"  : 57.22,
                    "sharesHeld" : 250
                  }
                ]
}

Is it possible to to apply a conditional validation to this array of sub documents? It's valid for the portfolio to not be there but if it is each document in the array must contain the three fields "stockName", "pricePaid" and "sharesHeld".

A: MongoShell
db.createCollection("collectionname",
{
  validator: {
    $or: [
      {
        "portfolio": {
          $exists: false
        }
      },
      {
        $and: [
          {
            "portfolio": {
              $exists: true
            }
          },
          {
            "portfolio.stockName": {
              $type: "string",
              $exists: true
            }
          },
          {
            "portfolio.pricePaid": {
              $type: "double",
              $exists: true
            }
          },
          {
            "portfolio.sharesHeld": {
              $type: "double",
              $exists: true
            }
          }
        ]
      }
    ]
  }
})

With this above validation in place you can insert documents with or without portfolio.
After executing the validator in shell, then you can insert data of following
db.collectionname.insert({
        "_id" : ObjectId("58061aac8812662c9ae1b479"),
        "date" : ISODate("2016-10-18T12:50:52.372Z"),
        "name" : "B",
        "assets" : 200
})

db.collectionname.insert({
        "_id" : ObjectId("58061ab48812662c9ae1b47a"),
        "date" : ISODate("2016-10-18T12:51:00.747Z"),
        "name" : "A",
        "assets" : 100,
        "portfolio" : [
                {
                        "stockName" : "Microsoft",
                        "pricePaid" : 57.22,
                        "sharesHeld" : 250
                }
        ]
})

If we try to insert a document like this

db.collectionname.insert({
  "date"      : new Date(),
  "name"      : "A",
  "assets"    : 100,
  "portfolio" : [
                  { "stockName"  : "IBM",

                    "sharesHeld" : 100
                  }
                ]
})

then we will get the below error message
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 121,
                "errmsg" : "Document failed validation"
        }
})

Using Mongoose
Yes it can be done, Based on your scenario you may need to initialize the parent and the child schema.
Shown below would be a sample of child(portfolio) schema in mongoose.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var portfolioSchema = new Schema({
    "stockName" : { type : String, required : true },
    "pricePaid" : { type : Number, required : true },
    "sharesHeld" : { type : Number, required : true },
}

References:
http://mongoosejs.com/docs/guide.html
http://mongoosejs.com/docs/subdocs.html
Can I require an attribute to be set in a mongodb collection? (not null)
Hope it Helps!


text:
Q: Displayed resolution density of drawables halving on each program start I've got an Android app that uses both drawables from its own resources folder and from the resources folder of a package linked via shared user id.
I'm facing a decrease of the drawables' pixel density (resulting in interpolation artefacts) of only own resources** each time the app is run, while those linked*** appear normal.
Executing the app about the 10th time, it crashes*.
Then loading for the 1st time displays all images in their original density.
The app is based on SDK version 1.6 and no specific density dependent resources, meaning strictly designed for 320 x 480px.
The issue does appear neither on a device with a display size matching as above, nor in an emulator with both matching and larger display size. In the last case the images are correctly scaled to fit.
I don't know where (in the code) to start looking for the reasons of that bug.
Thanks in advance for any hints!

EDIT:
I should also mention that several Dialogs (e.g. ProgressDialog) are drawn in half the size as before when reloading the application.
* Log output when the app crashes:
ERROR/AndroidRuntime(23632): FATAL EXCEPTION: main
ERROR/AndroidRuntime(23632): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp/com.myapp.Paketliste}: android.view.InflateException: Binary XML file line #20: Error inflating class <unknown>
ERROR/AndroidRuntime(23632): Caused by: android.view.InflateException: Binary XML file line #20: Error inflating class <unknown>
ERROR/AndroidRuntime(23632): Caused by: java.lang.reflect.InvocationTargetException
ERROR/AndroidRuntime(23632): Caused by: android.content.res.Resources$NotFoundException: File res/drawable/buttons.png from drawable resource ID #0x7f020016
ERROR/AndroidRuntime(23632): Caused by: java.lang.IllegalArgumentException: width and height must be > 0
WARN/ActivityManager(2461):   Force finishing activity com.myapp/.Paketliste

* * The image loaded by these lines appears as described above:
ImageView imageView_IconOfAnotherPackage = (ImageView) row
  .findViewById(R.id.paketliste_installed);

imageView_IconOfAnotherPackage
  .setImageResource(R.drawable.default_icon);

* * * Loading an image which appears WITHOUT AN ISSUE:
imageView_IconOfAnotherPackage
  .setImageDrawable(this
    .getPackageManager()
    .getResourcesForApplication('com.myotherapp')
    .getDrawable(0x7f020001)
  );

A: I found a post where a guy presumably was having the same problem (and found a solution) here:
http://adrianvintu.com/blogengine/post/Force-Locale-on-Android.aspx
(via this answer: Set-up the application Language in Android Preferences)


text:
Q: sybase update trigger check In Sybase i have main table called test and audit table test_a. To update audit table i created triggers insert,update and delete. But the issue is when i do an update query with same data that is existing with no changes the update trigger gets fire and records in the audit table for every update which is creating duplication. I want to stop update trigger to fire when no changes are made when using update query.It should trigger only when new row is inserted but not existing.
my table has
test : ID | NAME | DESC
test_a : UPDATED_BY|DATE|ID|NAME|DESC

can you suggest how to stop trigger firing when no new changes are updated in the query.
Thank you.

A: You cannot stop an update trigger from firing - an UPDATE statement will always fire it. But you can compare the contents of the 'inserted' and 'deleted' table to determine whether any values were indeed updated. If not, then don't modify the audit table.


text:
Q: Loading txt file as an asset for a dart package In flutter it's easy to load a .txt asset at runtime by specifying it or its folder in the pubspec.yaml file and then loading it with rootBundle. However, i'm working on a pure dart package, and I'm struggling to work out how to get the package to load a .txt file relative to it's own directory structure.
When I use the package in a separate dart command line application i'm working on, the relative path that I specified in one of the package source code files causes an error to be thrown that the txt file doesn't exist. I understand why this error is being thrown, because the relative path is interpreted as being from the command line application's root directory instead of the package's root directory, but i'm unsure of how to solve this without specifying the absolute path for the .txt file. I'd rather not specify the absolute path as it makes the package less portable.
Is there anything similar to flutter's asset loading for a pure dart package?

A: I think you need the resolveSymbolicLinks or resolveSymbolicLinksSync methods to decode the relative path and then use the resolved path to read the txt file:
import 'dart:io';

void main() async {
  String file = '../lib/main.dart';
  var path = Uri.parse('.').resolveUri(Uri.file(file)).toFilePath();
  print(path);
  if (path == '') path = '.';
  var resolved = await File(path).resolveSymbolicLinks();
  print(resolved);

  File(resolved).readAsString().then((String contents) {
    print(contents);
  });
}


text:
Q: Unable to delete set of video files using shell script I have written a shell script to delete a set of video files (.0 format) which are 81 or more days older in putty using the following:
find /data/local_0/ -type f  -name "*.0" -mtime +80 -exec rm {}\;

When I execute this command, I'm getting the following exception.
[root@server /]# find /data/local_0/ -type f  -name "*.0" -mtime +50
find: /data/local_0/: Value too large for defined data type

I also tried to delete forcefully but same exception popped up. How to resolve  this exception?
i have added a screen shot as evidence, too.


text:
Q: If else using for setting class I want to set every first and second tr with a different class.
With my code I only get "odd" on every tr.
Does anyone knew what is wrong?
 $rowCount = 0;
 if ($rowCount++ % 2 == 1 ) :
     echo "
";
 else:
     echo "
";
 endif;

A: try this one (keep the $rowCount setting outside the loop):
for($row = 0; $row < $rowTotal; $row++)
{
   echo "
";
}

A: Your logic implementation is going in wrong direction
$rowCount = 0;//This was always initializing your count to 0

Resulting always odd class added
Change it to this:
for ($rowCount = 0;$rowCount<$total; $rowCount++) {
    if ($rowCount % 2 == 1 ) :
        echo "
";
    else:
        echo "
";
    endif;
}

OR you can simply use ternary operator as
for ($rowCount=0; $rowCount<$total; $rowCount++) {
    echo "
";
}


text:
Q: Inference in C++ Tensorflow: Session->Run hangs when ran with input and output parameters supplied I trained a FasterRCNN for point detection using TensorFlow and its python API. I was able to do the inference successfully in the same without any issues.
Now for production requirements, I need to build a standalone application or library which can perform the inference in C++.
In order to achieve that I successfully managed to build the TensorFlow library from scratch for C++ API and ran a few test programs.
Steps followed for inference on my trained model:

*

*Method #1: freeze the graph to *.pb file using modified freeze_graph.py and restore it.

*Method #2: Directly restore from checkpoint using MetaGraphDef and ReadBinaryProto.

I tried both the methods and the loading of the model seems to happen without any error. I printed the node names as well.
After loading the graph I created a handler for image input, previously the input during training was getting handled by QueueRunner, but because it's just inference I created the handler myself with appropriate modifications to it as can be seen below.
    Status fasterRcnn::CreateGraphForImage(bool unstack)
{
    fileNameVar=Placeholder(iRoot.WithOpName("input"),DT_STRING);
    auto fileReader=ReadFile(iRoot.WithOpName("fileReader"),fileNameVar);
    auto imageReader=DecodeJpeg(iRoot.WithOpName("jpegReader"),fileReader,DecodeJpeg::Channels(imageChannels));
    auto floatCaster=Cast(iRoot.WithOpName("floatCaster"),imageReader,DT_FLOAT);
    auto dimsExpander=ExpandDims(iRoot.WithOpName("dim"),floatCaster,0);
    //auto resized=ResizeBilinear(iRoot.WithOpName("size"),dimsExpander,Const(iRoot,{imageSide,imageSide}));
    //auto div=Div(iRoot.WithOpName("normalized"),resized,{255.f});
    imageTensorVar=dimsExpander;//div;
    return iRoot.status();

}

NOTE: iRoot is the private variable of fasterRcnn class-> Scope used by the graph for loading images into tensors
   class fasterRcnn
{
private:
    Scope iRoot;//graph for loading images into tensors
    const int imageSide;
    const int imageChannels;//rgb
    //load image vars
    Output fileNameVar;
    Output imageTensorVar;
    //
    std::unique_ptr<Session> fSession;//file session
    std::unique_ptr<GraphDef> graphDef;
public:
    fasterRcnn(int side,int channels):iRoot(Scope::NewRootScope()),imageSide(side),imageChannels(channels){}
    Status CreateGraphForImage(bool unstack);
    Status LoadSavedModel(string &fileName);//via frozen graph
    Status LoadSavedModel(std::string graph_fn,std::string checkpoint_fn);//via checkpoints
    Status PredictFromFrozen(Tensor &image,int&results);//
    Status ReadTensorFromImageFile(string& file_name, Tensor& outTensor);
    Status ReadFileTensors(string& folder_name,vector<Tensor>& file_tensors);

};

Now the when the time comes for Prediction when I run Session->Run with particular input node name and output node name the program hangs:
Status fasterRcnn::PredictFromFrozen(Tensor& image, int& result)
{
    vector<Tensor> outTensors;
    cout<<"Prediction about to start"<<endl;
    TF_CHECK_OK(fSession->Run({{"fasterrcnn/truncated_base_network/sub",image}},{"fasterrcnn/rcnn/rcnn_proposal/GatherV2_1"},{},&outTensors));
    cout<<"Prediction done"<<endl;
    auto output_c = outTensors[0].scalar<float>();
    for (int i=0;i<outTensors.size();i++)
    {
        cout << "Output dimension of the image" << outTensors[i].DebugString()<<"\n";
    }
    cout << "Output dimension of the image" << outTensors[0].DebugString()<<"\n";
    return Status::OK();
}

TF_CHECK_OK(fSession->Run({{"fasterrcnn/truncated_base_network/sub",image}},{"fasterrcnn/rcnn/rcnn_proposal/GatherV2_1"},{},&outTensors));
It hangs at the above statement.
Up until a few Debug thoughts:

*

*I thought maybe the QueueRunner might be creating the issue, but according to this answer I handled that as I created the image handler graph.

*I thought maybe I didn't freeze the graph well, that's I loaded directly from the checkpoints, but still, it hangs.

*The input to the VGG_16 truncated network in graph expects a 4D float tensor, which I am providing, double-checked that.

Question:

*

*Is there any step that I missing, for successful inferencing in C++.

*How to verify if my input and output node names are correct? I referred to the python code and they seem right.

*Any steps for debugging that I should follow to provide more info on this?


text:
Q: How to replace many if's statements in java? I am trying to make my code "cleaner". I have many functions with a lot of if-statements. How can I replace them?
I'm using 4 differents Hashtables that's why I have those ifs. The only thing changing is the hashtable name and the jList where I add the informations.
if(n.getCategorie().getNum() == Categorie.INTERNATIONAL.getNum())
                {
                    DefaultListModel dlm = (DefaultListModel) jListInternationales.getModel();
                    dlm.addElement(n.getTitre());
                    jListInternationales.setModel(dlm);
                    NewsInter.put(""+nNews, n);
                }
                else if(n.getCategorie().getNum() == Categorie.POLITIQUE.getNum())
                {
                    DefaultListModel dlm = (DefaultListModel) jListViePolitique.getModel();
                    dlm.addElement(n.getTitre());
                    jListViePolitique.setModel(dlm);
            NewsPolitique.put(""+nNews, n);
                }
                else if(n.getCategorie().getNum() == Categorie.RAGOT.getNum())
                {
                    DefaultListModel dlm = (DefaultListModel) jListRagotsEtPotins.getModel();
                    dlm.addElement(n.getTitre());
                    jListRagotsEtPotins.setModel(dlm);
            NewsRagot.put(""+nNews, n);
                }
                else if(n.getCategorie().getNum() == Categorie.SPORT.getNum())
                {
                    DefaultListModel dlm = (DefaultListModel) jListInfosSports.getModel();
                    dlm.addElement(n.getTitre());
                    jListInfosSports.setModel(dlm);
            NewsSport.put(""+nNews, n);
                }

A: It seems that you're using enums. Enums may be compared by instance. Checking the numbers is not required.
Those can be used in a switch case. E.g.
switch (n.getCategorie()) {
case Categorie.INTERNATIONAL:
...

That removes some clutter, but not essentially the number of 'if' statements.

A: The only difference between the if branches comes from the JList reference. Since the code is repeated you should extract it into a separate method:
private void updateList(JList list) {
  DefaultListModel dlm = (DefaultListModel) list.getModel();
  dlm.addElement(n.getTitre());
  list.setModel(dlm);
}

After that the code becomes much cleaner:
if (n.getCategorie().getNum() == Categorie.INTERNATIONAL.getNum()) {
  updateList(jListInternationales);
} else if (n.getCategorie().getNum() == Categorie.POLITIQUE.getNum()) {
  updateList(jListViePolitique);
} // etc

NewsInter.put(""+nNews, n);

A: You can replace the if, else if, else if, ... structure by changing it to the switch() structure, it looks like this:
switch(n.getCategorie().getNum()){
    case Categorie.INTERNATIONAL.getNum():
        DefaultListModel dlm = (DefaultListModel) jListInternationales.getModel();
        dlm.addElement(n.getTitre());
        jListInternationales.setModel(dlm);
        NewsInter.put(""+nNews, n);

        break;
    case Categorie.POLITIQUE.getNum():
        ...etc
}

A: in your case, you can replace it by Switch statement.
This is the structure:
switch(value) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

In your specific problem , this would be:
switch(n.getCategorie()) {
  case International:
    // your code
    break;
  case Politique:
    // code block
    break;
...

  default:
    // code block
}

A: Use a Switch Case command which takes less memory while processing