text:
Q: Log4J2 Pattern Layout not picking up Pattern I have set up a service to use SLF4J and Log4j2 but I am unable to get the specified logs in the pattern layout specified. My dependencies are:
log4j-slf4j-impl: 2.17.2
slf4j-api: 1.7.36
When I boot my service with -Dlog4j2.debug, I see the following:
DEBUG StatusLogger PluginManager 'Lookup' found 16 plugins
DEBUG StatusLogger null null initializing configuration org.apache.logging.log4j.core.config.properties.PropertiesConfiguration@2f5ac102
DEBUG StatusLogger PluginManager 'Core' found 128 plugins
DEBUG StatusLogger PluginManager 'Level' found 0 plugins
DEBUG StatusLogger PluginManager 'Lookup' found 16 plugins
DEBUG StatusLogger Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
TRACE StatusLogger TypeConverterRegistry initializing.
DEBUG StatusLogger PluginManager 'TypeConverter' found 26 plugins
DEBUG StatusLogger createAppenderRef(ref="STDOUT", level="null", Filter=null)
DEBUG StatusLogger Building Plugin[name=root, class=org.apache.logging.log4j.core.config.LoggerConfig$RootLogger].
DEBUG StatusLogger LoggerConfig$RootLogger$Builder(additivity="null", level="INFO", levelAndRefs="null", includeLocation="null", ={STDOUT}, ={}, Configuration(PropertiesConfig), Filter=null)
DEBUG StatusLogger Building Plugin[name=loggers, class=org.apache.logging.log4j.core.config.LoggersPlugin].
DEBUG StatusLogger createLoggers(={root})
DEBUG StatusLogger Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
DEBUG StatusLogger PatternLayout$Builder(pattern="[%p] %d [%t] %c %M - %m%n", PatternSelector=null, Configuration(PropertiesConfig), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
DEBUG StatusLogger PluginManager 'Converter' found 45 plugins
DEBUG StatusLogger Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.ConsoleAppender].
DEBUG StatusLogger ConsoleAppender$Builder(target="SYSTEM_OUT", follow="null", direct="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout([%p] %d [%t] %c %M - %m%n), name="STDOUT", Configuration(PropertiesConfig), Filter=null, ={})
DEBUG StatusLogger Starting OutputStreamManager SYSTEM_OUT.false.false
DEBUG StatusLogger Building Plugin[name=appenders, class=org.apache.logging.log4j.core.config.AppendersPlugin].
DEBUG StatusLogger createAppenders(={STDOUT})
DEBUG StatusLogger Configuration org.apache.logging.log4j.core.config.properties.PropertiesConfiguration@2f5ac102 initialized
DEBUG StatusLogger Starting configuration org.apache.logging.log4j.core.config.properties.PropertiesConfiguration@2f5ac102
DEBUG StatusLogger Started configuration org.apache.logging.log4j.core.config.properties.PropertiesConfiguration@2f5ac102 OK.
TRACE StatusLogger Stopping org.apache.logging.log4j.core.config.DefaultConfiguration@3c69362a...
TRACE StatusLogger DefaultConfiguration notified 1 ReliabilityStrategies that config will be stopped.
TRACE StatusLogger DefaultConfiguration stopping root LoggerConfig.
TRACE StatusLogger DefaultConfiguration notifying ReliabilityStrategies that appenders will be stopped.
TRACE StatusLogger DefaultConfiguration stopping remaining Appenders.
DEBUG StatusLogger Shutting down OutputStreamManager SYSTEM_OUT.false.false-1
DEBUG StatusLogger OutputStream closed
DEBUG StatusLogger Shut down OutputStreamManager SYSTEM_OUT.false.false-1, all resources released: true
DEBUG StatusLogger Appender DefaultConsole-1 stopped with status true
TRACE StatusLogger DefaultConfiguration stopped 1 remaining Appenders.
TRACE StatusLogger DefaultConfiguration cleaning Appenders from 1 LoggerConfigs.
DEBUG StatusLogger Stopped org.apache.logging.log4j.core.config.DefaultConfiguration@3c69362a OK
TRACE StatusLogger Reregistering MBeans after reconfigure. Selector=org.apache.logging.log4j.core.selector.ClassLoaderContextSelector@5a1c3cb4
TRACE StatusLogger Using default SystemClock for timestamps.
DEBUG StatusLogger org.apache.logging.log4j.core.util.SystemClock does not support precise timestamps.
TRACE StatusLogger Using DummyNanoClock for nanosecond timestamps.
DEBUG StatusLogger Reconfiguration complete for context[name=Default] at URI jar:file:[redacted]/log4j2.properties (org.apache.logging.log4j.core.LoggerContext@78e22d35) with optional ClassLoader: null
DEBUG StatusLogger Shutdown hook enabled. Registering a new one.
DEBUG StatusLogger LoggerContext[name=Default, org.apache.logging.log4j.core.LoggerContext@78e22d35] started OK.

It looks like my file is picked with pattern: [%p] %d [%t] %c %M - %m%n
My Log4j2 Config:
# properties file metadata
status=error
dest=err
name=PropertiesConfig

# console appender will log to stdout
appender.consoleAppender.type=Console
appender.consoleAppender.name=STDOUT
appender.consoleAppender.target=SYSTEM_OUT
appender.consoleAppender.layout.type=PatternLayout
appender.consoleAppender.layout.pattern=[%p] %d [%t] %c %M - %m%n

# log level information
rootLogger.level=info
rootLogger.appenderRef.consoleAppender.ref=STDOUT

But all my logs are coming as:
22:10:55,360 INFO  org.eclipse.jetty.server.Server          - Started @2187ms

A: I saw your log4j config, and then I observed that your log4j config file may be the incorrect way.
log4j. must be included for each key, according to the documentation.
your log4j Config:
# properties file metadata
status=error
dest=err
name=PropertiesConfig

# console appender will log to stdout
appender.consoleAppender.type=Console
appender.consoleAppender.name=STDOUT
appender.consoleAppender.target=SYSTEM_OUT
appender.consoleAppender.layout.type=PatternLayout
appender.consoleAppender.layout.pattern=[%p] %d [%t] %c %M - %m%n

# log level information
rootLogger.level=info
rootLogger.appenderRef.consoleAppender.ref=STDOUT

Updated log4j.properties Config:
# properties file metadata
status=error
dest=err
name=PropertiesConfig

# console appender will log to stdout
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%p] %d [%t] %c %M - %m%n

# log level information
log4j.rootLogger=info,console

Note: If you are using SYSTEM_OUT in target then the warning message came on the console.
log4j:WARN [SYSTEM_OUT] should be System.out or System.err.
log4j:WARN Using previously set target, System.out by default.

in my case Pom.xml:
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.5</version>
</dependency>

Thanks.


text:
Q: Container in GKE can't ping compute instance on the same network I have created a new cluster in GKE with version 1.10.5-gke.0.
I see that my applications cannot reach IPs in the same network, basically instances running on compute.
I have ssh'd to one of the Kubernetes nodes, and by using the toolbox included i can ping those IP addresses, but I can't if I try from a container running on this cluster.
I saw that since 1.10 google disables access scopes for compute & storage, and even if I enable those scopes I still get the same.
I find it a bit puzzling, as this used to work for all other clusters in the past without any extra config needed
Am I missing something here?

A: An easy way of doing fixing this is using the Google Cloud Console.
Go to

Navigation Menu -> VPC network -> Firewall rules

.
Normally when a cluster is created, a number of rules are created automatically with certain prefixes and suffixes. Look in the table of rules with a gke- prefix and an -all suffix e.g. gke-[my_cluster_name]-all. You'll notice for this rule, it has the source ranges for your pods within the cluster and quite a few protocols (tcp, udp, imp, esp, etc.) allowed.
Select this rule and go to Edit. Under Targets, select the drop down and change to All instances in the network.
Alternatively, you can choose specified Specified target tags or Specified service account, inputing the correct values below, like your correct developer service account for the compute engine you're trying to reach.
You can also look here if you're Kubernetes is version 1.9.x and later for another alternative way. Troubleshooting
Hope all this helps.

A: I also ran into this issue.
I have mongo running on a VM on the default network, and couldn't reach it from inside pods after I recreated my kubernetes cluster on a new node that was also on the default network.
Adding this firewall rule fixed the issue:
NAME                                              NETWORK                DIRECTION  PRIORITY  SRC_RANGES                                                                                DEST_RANGES  ALLOW                         DENY  SRC_TAGS  SRC_SVC_ACCT  TARGET_TAGS                                        TARGET_SVC_ACCT
gke-seqr-cluster-dev-eb823c8e-all                 default                INGRESS    1000      10.48.0.0/24                                                                                tcp,udp,icmp,esp,ah,sctp

Here, the 10.48.0.0 subnet is based on the cbr0 network (looked up by ssh'ing into the kubernetes node and running ip address)
cbr0: <BROADCAST,MULTICAST,PROMISC,UP,LOWER_UP> mtu 1460 qdisc htb state UP group default qlen 1000
   ..
    inet 10.48.0.1/24 scope global cbr0
       valid_lft forever preferred_lft forever
   ..

Another way to get the 10.48.0.1 ip is to install and run traceroute inside a pod:
traceroute <ip of node you're trying to reach>

redpajama_set_name: RedPajamaStackExchange


text:
Q: could anti-matter black hole is sitting at the center of the universe ? that have all the aniti matter i am very curious about the space , matter and anti-matter , i am not a scientist but i have few question , can we calculate the speed of expansion of the universe? , i have made some assumption or this is already there i dont know , i dont do science :), so they are as follows.

*

*Universe when created is filled on same number of matter and anti- matter .

*Anti- matter have opposite gravity called anti – gravity .

*On the time of birth Matter and anti-Matter are created and the explosion begins.

*As because of the high temperature and pressure ,a tiny anti – matter black hole get created.

*As after few second anti – matter black hole started to eat other anti-matter and as the gravity is strong to the atomic scale matter get reaped from this anti-black hole.

*Due to this phenomena matter get repelled more and more as the anti-black hole eats more.

*Sitting on the center of the universe this anti-matter black hole has all the anti-matter of the entire universe.

*As the universe expand or matter is repelled by anti-black hole, the star is started to born , as the universe got denser and denser formation of black hole and stars repelled from anti-gravity is gets more and more , so our universe will accelerate more as more black hole will form.

To find that anti-matter black hole we have to look opposite of gravitational Lensing as this anti-black hole will repelled the light that comes from the matter-stars outwards .

A:

*

*Universe when created is filled on same number of matter and anti- matter .

Maybe. Some particles, like photons, are their own antiparticles, others like electrons and positrons are anti-particles of each other. There is no real, objective, way to say which is matter and which is antimatter. We just said that up and down quarks were matter because we see them more often and same with electrons. The physics is that they come in pairs (except for things like photons that don't come in pairs). So you could say it is natural to have a total pairing. But there wasn't an empty universe and then a bunch of matter and energy with every thing paired up. That is not a thing we think happens, and is not a scientific conclusion.

*Anti- matter have opposite gravity called anti – gravity .

That's wrong. Matter and antimatter both attract each other and themselves. You need exotic matter (not antimatter) if you want weird gravitational effects.

*On the time of birth Matter and anti-Matter are created and the explosion begins.

This is wrong. There wasn't an empty universe and then an explosion of matter and antimatter.

*As because of the high temperature and pressure ,a tiny anti – matter black hole get created.

Even if a bunch of antimatter was rushing towards each other, you wouldn't see a black hole form you'd see huge time dilation affecting the antimatter rushing together.

*As after few second anti – matter black hole started to eat other anti-matter and as the gravity is strong to the atomic scale matter get reaped from this anti-black hole.

Matter and antimatter would be attracted equally strongly to the energy dense region where the antimatter is rushing towards each other.

*Due to this phenomena matter get repelled more and more as the anti-black hole eats more.

Nope.

*Sitting on the center of the universe this anti-matter black hole has all the anti-matter of the entire universe.

There is no center of the universe. That's connected to there being no explosion and how there was no sitting around with nothing. The universe is 4d and the 4th dimension is time. Imagine a balloon with time as the distance from the center. As time goes on the universe gets bigger and it expands. Where does it expand? The future. Now imagine a 3d spherical surface in a 4d spacetime, similar thing. With time as the distance to the 4d center. Not every model is that simple but you can see that there is no center every point of positive nonzero time is equally good to every other one that had the same positive nonzero time, and none of them is "the center."

To find that anti-matter black hole we have to look opposite of gravitational Lensing as this anti-black hole will repelled the light that comes from the matter-stars outwards .

We look out and see that on really large scales the universe looks the same everywhere. Just like the surface of a balloon where time is the distance from the center looks the same at every point at that time. It is not like there is some direction we forgot to point our telescopes. Did you really think we did? Because it's hard to figure out what you are trying to say.
And light isn't repelled by a dense collection of antimatter. Light is antimatter (and matter) it is its own antiparticle.

A: The universe does not have a centre. See http://math.ucr.edu/home/baez/physics/Relativity/GR/centre.html


text:
Q: Upgrade Bind 9.4.1-P1-1 on Debian Etch Since "Debian Etch" has been superseded by Debian Lenny, I wonder if it is possible just to upgrade Bind 9.4.1-P1-1 package already installed on an Etch box, to a more recent therefore secure version?

A: All support for Etch ended a year after Lenny was released. Squeeze has also already been released so support for Lenny now has a fixed end date. If you want to run newer versions of services you really should just upgrade to a newer version of Debian that is still being supported by the Debian Security Team.
Otherwise your only other real option is to compile from source.


text:
Q: Docker Compose MySQL 8 SequelizeJS ER_NOT_SUPPORTED_AUTH_MODE I don't know how unique my problem is but I see similar issues throughout the web but I have the scenario that doesn't match any of the problems I've seen.
I have a pretty standard Express app that uses SequelizeJS and MySQL 8. Sequlize has migration which I run using entrypoint.sh that runs sequelize migration command.
# Run migrations
npx sequelize-cli db:migrate

# Preload initial data
npx sequelize-cli db:seed:all

When I run docker compose command the project builds without any issues and sequelize migration and seeds runs. Database connection from sequelize command line works perfectly!
But when I load my homepage the SQL query from the application throws error. The error itself is quite common
{
  code: 'ER_NOT_SUPPORTED_AUTH_MODE',
  errno: 1251,
  sqlMessage: 'Client does not support authentication protocol requested by server; consider upgrading MySQL client',
  sqlState: '08004',
  fatal: true
}

I have seen this error while mysql 8 and the package mysql used together with sequlizejs. The common solution is to use mysql2 which I am using in my project. I've also tried to run command --default-authentication-plugin=mysql_native_password inside mysql container which didn't help.
Docker Compose
version: '3.9'

services:
  linkfy-dashboard:
    container_name: linkfy-dashboard
    restart: always
    depends_on:
      - linkfy-mysql
    build:
      context: .
      dockerfile: Dockerfile.dev
    ports:
      - '10200:3000'
    environment:
      APP_NAME: Linkfy
      DB_HOST: linkfy-mysql
      DB_USER: linkfy
      DB_PASS: password
      DB_NAME: linkfy
      COOKIE_SECRET: secret
      NONCE_SECRET: secret
      COOKIE_SECURE: 'false'
    volumes:
      - /app/node_modules
      - .:/app
    networks:
      - linkfy
  linkfy-mysql:
    container_name: linkfy-mysql
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    image: mysql:8
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: linkfy
      MYSQL_USER: linkfy
      MYSQL_PASSWORD: password
    volumes:
      - database:/var/lib/mysql
    networks:
      - linkfy
  adminer:
    image: adminer
    restart: always
    ports:
      - 10210:8080
    networks:
      - linkfy
networks:
  linkfy:
    name: linkfy
volumes:
  database:

Dockerfile
FROM node:14.17-alpine

# source directory
WORKDIR /app
# global dependancy
RUN yarn global add sequelize-cli nodemon

# dependency file (package.json and package-lock.json)
COPY package.json .

RUN apk add --update python2 make g++ && rm -rf /var/cache/apk/*
RUN yarn install

# copy the sources
COPY . .

# listener
EXPOSE 3000

ENTRYPOINT ["./entrypoint.sh"]

# command to run
CMD [ "npm", "run", "dev" ]

I need some direction how to troubleshoot this.


text:
Q: How exactly work the @OneToMany JPA annotation in this example? Is it related to a table column or an entity class field? I have 2 DB tables named respectivelly T_ACCOUNT and T_ACCOUNT_BENEFICIARY.
These tables have the following structure:
create table T_ACCOUNT (ID integer identity primary key, NUMBER varchar(9), NAME varchar(50) not null, CREDIT_CARD varchar(16), unique(NUMBER));

create table T_ACCOUNT_BENEFICIARY (ID integer identity primary key, ACCOUNT_ID integer, NAME varchar(50), ALLOCATION_PERCENTAGE decimal(5,2) not null, SAVINGS decimal(8,2) not null, unique(ACCOUNT_ID, NAME));

And the T_ACCOUNT table is bound to the T_ACCOUNT_BENEFICIARY table with a one to many relationship, this is the graphical representation:

So this is the first class named Account that map the T_ACCOUNT table:
@Entity
@Table(name="T_ACCOUNT")
public class Account {

    @Id
    @GeneratedValue
    @Column(name="id")
    private Long entityId;

    @Column(name="NUMBER")
    private String number;

    @Column(name="NAME")
    private String name;

    @OneToMany
    @JoinColumn(name="ACCOUNT_ID")
    private Set<Beneficiary> beneficiaries = new HashSet<Beneficiary>();

    @Column(name="CREDIT_CARD")
    private String creditCardNumber;

    // GETTERS & SETTERS
}

And this is the Beneficiary class that map the T_ACCOUNT_BENEFICIARY table:
/**
 * A single beneficiary allocated to an account. Each beneficiary has a name (e.g. Annabelle) and a savings balance
 * tracking how much money has been saved for he or she to date (e.g. $1000).
 */
@Entity
@Table(name="T_ACCOUNT_BENEFICIARY")
public class Beneficiary {

    @Id
    @GeneratedValue
    @Column(name="ID")
    private Long entityId;

    @Column(name="NAME")
    private String name;

    @Embedded
    @AttributeOverride(name="value",column=@Column(name="ALLOCATION_PERCENTAGE"))
    private Percentage allocationPercentage;

    @Embedded
    @AttributeOverride(name="value",column=@Column(name="SAVINGS"))
    private MonetaryAmount savings = MonetaryAmount.zero();

As you can see into the Account I have the beneficiaries field that implement the one to may relationship
@OneToMany
@JoinColumn(name="ACCOUNT_ID")
private Set<Beneficiary> beneficiaries = new HashSet<Beneficiary>();

I know that, on the DB, this relationship is implemented by the ACCOUNT_ID field of the T_ACCOUNT_BENEFICIARY table (so multiple row of the T_ACCOUNT_BENEFICIARY table can have the same value of the ACCOUNT_ID field and this means that a single row of the T_ACCOUNT table can be associated to more than one rows of T_ACCOUNT_BENEFICIARY table).
As you can see in the previous sippet there is the @JoinColumn(name="ACCOUNT_ID") annotation.
My doubt is generated by the fact that I have an ACCOUNT_ID column on my T_ACCOUNT_BENEFICIARY table, infact:
create table T_ACCOUNT_BENEFICIARY (ID integer identity primary key, ACCOUNT_ID integer, NAME varchar(50), ALLOCATION_PERCENTAGE decimal(5,2) not null, SAVINGS decimal(8,2) not null, unique(ACCOUNT_ID, NAME));

but this column seems to not be mapped on the Beneficiary that map this T_ACCOUNT_BENEFICIARY table.
So my doubts is: the @JoinColumn(name="ACCOUNT_ID") is working at relational level performing the join operation on the ACCOUNT_ID column of the table mapped by the Beneficiary entity (T_ACCOUNT_BENEFICIARY) or am I missing something? How exactly is performed this join?
If my interpretation is right can I work at entity level and say to join the beneficiaries field of my Account entity class to a new accountId field inserted into my Beneficiary entity class and mapping the ACCOUNT_ID column of the T_ACCOUNT_BENEFICIARY table?
Tnx

A: It seems is a Unidirectional OneToMany relationship
In JPA 2.0 a @JoinColumn can be used on a OneToMany to define the foreign key

A: I'm not sure if I understand your question. But what you have done with your @JoinColumn annotation is correct and Hibernate will execute appropriate SQL statements when you have multiple beneficiaries for your account. For example executing multiple INSERTS if you have two Beneficiaries for an Account. And yes using the @JoinColumn annotation is at the hibernate level. If you want to access an Account from a Beneficiary entity you would need to define a Bidirectional relationship in the Beneficiary class like below.
@Entity
@Table("T_ACCOUNT_BENEFICIARY")
public class Beneficiary {
 @ManyToOne(mappedBy = "beneficiaries")
 Account account;
 ...
}


text:
Q: Batch Apex Too many SOQL Queries: 201 on a relationship query REQUIREMENT
Create a batch apex class that needs to update all of the accounts based on the number of contracts and opportunities for that certain account.
Here is what I have so far. However, I am receiving "Too many soql queries: 201" error.
global class AccountBatchJob implements Database.Batchable<sObject>, Schedulable{
//Batch Apex
global Database.QueryLocator start(Database.BatchableContext BC){
    Date dateToday = system.today();
    Date lastDayOfTheMonth = dateToday.addMonths(1).toStartofMonth().addDays(-1);
    return Database.getQueryLocator([SELECT Id, Name, Date_Customer_Churned__c, BillingAddress, BillingCity, BillingCountry, BillingPostalCode, BillingState, (SELECT Id, StartDate, EndDate FROM Contracts WHERE Status = 'Activated'), (SELECT Id, Start_Date_Primary_Quote__c FROM Opportunities WHERE SBQQ__Renewal__c = TRUE AND StageName = 'Closed Lost' AND Start_Date_Primary_Quote__c = THIS_MONTH ORDER BY Start_Date_Primary_Quote__c DESC) FROM Account]);
}
global void execute(Database.BatchableContext BC, List<Account> scope){
    Date dateToday = system.today();
    Date lastDayOfTheMonth = dateToday.addMonths(1).toStartofMonth().addDays(-1);
    //Accounts to update
    List<Account> accToUpdate = new List<Account>();
    for(Account ac : scope){
        //# of Closed Lost Opp for the Month
        ac.No_of_Closed_Lost_Oppty_for_the_Month__c = ac.Opportunities.size();
        Integer newActiveContThisMonth = 0;
        Integer activeContracts = 0;
        for(Contract cnt :ac.Contracts){
            if(cnt.StartDate <= lastDayOfTheMonth && cnt.endDate >= lastDayOfTheMonth){
                activeContracts +=1;
            } else if(cnt.StartDate >= dateToday.toStartofMonth() && cnt.endDate <= lastDayOfTheMonth){
                newActiveContThisMonth +=1;
            }
        }
        //# of Active Contracts
        ac.Active_Contracts__c = activeContracts;
        //# of New Active Contracts for the Month
        ac.New_Active_Contracts_for_the_Month__c = newActiveContThisMonth;

        //Date Customer Churned (IF THE ACCOUNT HAS ONE OR MORE CLOSED LOST OPP AND HAS NO ACTIVE CONTRACT)
        if(activeContracts == 0 && newActiveContThisMonth == 0 && ac.Opportunities.size() > 0){
            //THIS IS A TEST (GET ONLY THE LATEST START DATE IN LIST IF THERE ARE ONE OR MORE OPPTY)
            Date sDatePrimaryQuote = ac.Opportunities[0].Start_Date_Primary_Quote__c;
            ac.Date_Customer_Churned__c = sDatePrimaryQuote;
            system.debug('churned customer' + ac.Date_Customer_Churned__c);
        }
        //TEMPORARY CODE ONLY FOR BILLING1 SANDBOX
        if(ac.BillingAddress == null){
            ac.BillingCity = '15 Moore St.';
            ac.BillingCountry = 'Australia';
            ac.BillingPostalCode = '2601';
            ac.BillingState = 'AU';
        }
        accToUpdate.add(ac);
    }
    if(accToUpdate.size() > 0){
        system.debug(accToUpdate.size());
        update accToUpdate;
    }
}
global void finish(Database.BatchableContext BC){

}
//Schedule this Batch Apex Class
global void execute(SchedulableContext ctx){
    AccountBatchJob abj = new AccountBatchJob();
    database.executeBatch(abj, 200);
}

}
As per my situation, I have child relationship query both on Contract and Opportunity objects at the start method. Based from similar problems, I suspect that is the culprit to the error.
Anyone has a workaround to this one? Thanks for the help.


text:
Q: argparse add mandatory argument, possibly without add_subparsers Following is the code snippet -
parser = argparse.ArgumentParser()
#External Modules
parser.add_argument('--foo', action='store_true', dest='FOO_OPTION', help='builds foo')
parser.add_argument('--bar', action='store_true', dest='BAR_OPTION', help='builds bar')
parser.add_argument('--xyz', action='store_true', dest='XyZ_OPTION', help='builds xyz')

Invoking the command
program.py --foo
program.py --bar
program.py --xyz

works perfectly.
However, there is another mandatory arguement for --foo like
program.py --foo -d /usr/local/include

This additional arguement is just for --foo. How can this be achieved in the easiest possible way?

A: You can use the nargs argument, with a caveat.
For example,
parser.add_argument('--foo', nargs=2)
args = parser.parse_args()
print(args.foo)

Then, python program.py --foo bar baz gives ['bar', 'baz'].
The caveat is that you couldn't use -d as a value for foo because of the dash.


text:
Q: Removing sequence character from string JAVA The input will be like,

hiii, i love java soooo much

and the expected output will be like

hi, i love java so much

For my vague coding is as follows,
List<String> wordList = Arrays.asList(word.split(""));
String previousCharacter;
boolean inneFlag = false;
boolean flag = false;
int iterator = 0;
int characterIterator = 0;
String finalizedWord = "";
previousCharacter = wordList.get(0);
for(String character : wordList){
    if((wordList.size()-1)==characterIterator){
          inneFlag = true;
     }
     if(flag){
         if(character.equalsIgnoreCase(previousCharacter)){
              iterator++;
              if(inneFlag){
                   if(iterator>2){
                        finalizedWord = finalizedWord.substring(0,(finalizedWord.length()-iterator));
                    }
               }
         }else{
              previousCharacter = character;
              if(iterator>=2){
                  finalizedWord = finalizedWord.substring(0,(finalizedWord.length()-iterator));
              }
              iterator = 0;
           }
       }else{
            flag = true;
       }
    characterIterator++;
    finalizedWord += character;
}

Can anyone give better solution??

A: A simple regex will do this job.
string.replaceAll("([A-Za-z])\\1+", "$1");

or
string.replaceAll("(.)\\1+", "$1");

DEMO


text:
Q: Deallocate memory with free() does not work Here is a small program which fills some arrays and prints its content on the screen:
#include <stdlib.h>
#include <stdio.h>

typedef struct{
    double **plist;
    int plistSize;
} ParticleList;

void sendPar(int *n, int np){
    // allocate memory for struct pl
    ParticleList pl;

    // allocate memory  for ParticleList np times
    pl.plist = malloc(sizeof(ParticleList) * np);

    // allocate memory for lists of size n[k]
    for(int k=0; k<np; k++){
        pl.plist[k] = malloc(sizeof(double) * n[k]);
    }

    // write some data to the list
    for(int k=0; k<np; k++){
        for(int l=0; l<n[k]; l++){
            pl.plist[k][l] = 100000*k+100*l;
        }
        pl.plistSize = n[k];
    }

    // print data to check
    for(int k=0; k<np; k++){
        printf("Listsize: %d\n", n[k]);
        for(int l=0; l<n[k]; l++){
            printf("Processor %d, Entry %d, Value %lf\n", k, l, pl.plist[k][l]);
        }
    }

    free(pl.plist);
}

int main(){
    int np = 3;

    int n[np];
    n[0] = 2;
    n[1] = 4;
    n[2] = 7;

    sendPar(n, np);
}

This is the output:
Listsize: 2
Processor 0, Entry 0, Value 0.000000
Processor 0, Entry 1, Value 100.000000
Listsize: 4
Processor 1, Entry 0, Value 100000.000000
Processor 1, Entry 1, Value 100100.000000
Processor 1, Entry 2, Value 100200.000000
Processor 1, Entry 3, Value 100300.000000
Listsize: 7
Processor 2, Entry 0, Value 200000.000000
Processor 2, Entry 1, Value 200100.000000
Processor 2, Entry 2, Value 200200.000000
Processor 2, Entry 3, Value 200300.000000
Processor 2, Entry 4, Value 200400.000000
Processor 2, Entry 5, Value 200500.000000

If I now want to deallocate the memory, using free(pl) does not work. I tried also free(pl.plist) which does work. But than I have still memory of plistSize which is not deallocated. What is the right thing to free the memory here?

A: This memory allocation
pl.plist = malloc(sizeof(ParticleList) * np);
                  ^^^^^^^^^^^^^^^^^^^

does not make sense. I think you mean
pl.plist = malloc( sizeof( double * ) * np);
                  ^^^^^^^^^^^^^^^^

The last statement in this loop
// write some data to the list
for(int k=0; k<np; k++){
    for(int l=0; l<n[k]; l++){
        pl.plist[k][l] = 100000*k+100*l;
    }
    pl.plistSize = n[k];
    ^^^^^^^^^^^^^^^^^^^^
}

also does not make sense because the scalar object pl.plistSize is overwritten in each iteration of the outer loop.
To free the allocated memory you can write
for(int k=0; k<np; k++){
    free( pl.plist[k] )
}

free( pl.plist );

A: Pl is a variabile declared statically which contains a pointer to a memory location. It is the array in the structure that needs to be freed.

A: The problem as I see it, you're leaving each pl.plist[k] allocated, leading to the memory leak.
Once you've free()-d pl.plist, there will be no way you can free the individual pl.plist[k]s, so the deallocation has to be in reverse order of allocation.
First free each pl.plist[k]s, then, free up the pl.plist  itself.

A: The problem could be that you misunderstand how malloc and free works.
The variable pl and its member plistSize are not allocated by you. It's allocated by the compiler when it compiles your code. You should not try to free it.
Only free what you malloc.


text:
Q: Div no tamanho do body Tenho uma div que fica no meu rodapé da pagina, parecido com um footer, o problema e que esta div esta dentro de outras divs, eu queria que ela ficasse com o tamanho exato do meu body, sem mexer no html somente no css.
Exemplo:

A: Sim, para poder ter esse resultado uma vez que as divs anteriores interferem no width da div desejada podes retirar da posição estática(a usada normalmente) para absoluta e posiciona-la. ex:
<style>
div#inner-div{
position: absolute;
width: 100%;
bottom : 0px;
}
<style>

Acredito que possa resolver o problema de não estar com o tamanho do body, mas existem algumas precauções que deves levar em conta:

*

*Se a div que pretender colocar com tamanho do body tiver conteúdo
acima e a baixo, ira sair do espaço qual estava e se quiseres que
esteja no mesmo local de antes deveras dar esse espaço através das
areas que la ficaram, ou usar position relative

*Poderas position relative caso o pai(selector) antecedente tenha
position absolute


text:
Q: Is there an easier way than this to edit a table in my database? I'm trying to update a row in a table. I found a way to make it work but I'm wondering if there is an easier or better way.  Please help me with any ideas that you may have. Thanks
Here's the code…
   var courseRubics = from r in db.Rubrics where r.DepartmentID == 2 select r;
        var selectedRubrics = courseRubics.Select(r => r.RubricID);
        List<int> rubricsList = selectedRubrics.ToList();

        foreach (var rub in courseRubics.ToList())

        {

            if (!String.IsNullOrEmpty(formCollection["item.Weight"]))
            {
                Rubric aRubic1 = db.Rubrics.Find(1);
                Rubric updateRubic1 = (Rubric)aRubic1;
                int rubric1 = Convert.ToInt32(totlrubric[0]);
                updateRubic1.Weight = rubric1;

                Rubric aRubic2 = db.Rubrics.Find(2);
                Rubric updateRubic2 = (Rubric)aRubic2;
                int rubric2 = Convert.ToInt32(totlrubric[1]);
                updateRubic2.Weight = rubric2;

                Rubric aRubic3 = db.Rubrics.Find(4);
                Rubric updateRubic3 = (Rubric)aRubic3;
                int rubric3 = Convert.ToInt32(totlrubric[2]);
                updateRubic3.Weight = rubric3;

            }

            db.SaveChanges();

        }

A: Couple of ideas / observations

*

*Your initial set of selects could be narrowed down to (sorry for the alternate syntax)
var list = db.Rubrics.Where(r => r.DepartmentId == 2).Select(x => x.RubricId).ToList()

*You iterate over foreach (var rub in courseRubics.ToList()) but don't seem to be doing anything with rub

*The contents of the if... could be tightened up a little.  I don't see any reason why you need to do the casting or why you can't just inline the creation of rubricX,
if (!String.IsNullOrEmpty(formCollection["item.Weight"]))
    {
        Rubric aRubic1 = db.Rubrics.Find(1);
        aRubic1.Weight = Convert.ToInt32(totlrubric[0]);

        Rubric aRubic2 = db.Rubrics.Find(2);
        aRubic2.Weight = Convert.ToInt32(totlrubric[1]);

        Rubric aRubic3 = db.Rubrics.Find(4);
        aRubic3.Weight = Convert.ToInt32(totlrubric[2]);
    }


text:
Q: How to accumulate unique sum of columns across pandas index I have a pandas DateFrame, df which I created with
df = pd.read_table('sorted_df_changes.txt', index_col=0, parse_dates=True, names=['date', 'rev_id', 'score'])

which is structured like so:
                     page_id     score
date
2001-05-23 19:50:14  2430        7.632989
2001-05-25 11:53:55  1814033     18.946234
2001-05-27 17:36:37  2115        3.398154
2001-08-04 21:00:51  311         19.386016
2001-08-04 21:07:42  314         14.886722

date is the index and is of type DatetimeIndex.
Every page_id may appear in one or more dates (not unique) and is large in size ~1 million. All of the pages together make up the document.
I need to get a score for the entire document at every time in date while only counting the latest score for any given page_id.
Example
Example Data
                     page_id     score
date
2001-05-23 19:50:14  1           3
2001-05-25 11:53:55  2           4
2001-05-27 17:36:37  1           5
2001-05-28 19:36:37  1           1

Example Solution
                     score
date
2001-05-23 19:50:14  3
2001-05-25 11:53:55  7 (3 + 4)
2001-05-27 17:36:37  9 (5 + 4)
2001-05-28 19:36:37  5 (1 + 4)

The entry for 2 is counted continuously since it is not repeated but each time id 1 is repeated the new score replaces the old score.

A: Edit:
Finally, I found a solution that don't need for loop:
df.score.groupby(df.page_id).transform(lambda s:s.diff().combine_first(s)).cumsum()

I think a for loop is needed:
from StringIO import StringIO
txt = """date,page_id,score
2001-05-23 19:50:14,  1,3
2001-05-25 11:53:55,  2,4
2001-05-27 17:36:37,  1,5
2001-05-28 19:36:37,  1,1
2001-05-28 19:36:38,  3,6
2001-05-28 19:36:39,  3,9
"""

df = pd.read_csv(StringIO(txt), index_col=0)

def score_sum_py(page_id, scores):
    from itertools import izip
    score_sum = 0
    last_score = [0]*(np.max(page_id)+1)
    result = np.empty_like(scores)
    for i, (pid, score) in enumerate(izip(page_id, scores)):
        score_sum = score_sum - last_score[pid] + score
        last_score[pid] = score
        result[i] = score_sum
    result.name = "score_sum"
    return result

print score_sum_py(pd.factorize(df.page_id)[0], df.score)

output:
date
2001-05-23 19:50:14     3
2001-05-25 11:53:55     7
2001-05-27 17:36:37     9
2001-05-28 19:36:37     5
2001-05-28 19:36:38    11
2001-05-28 19:36:39    14
Name: score_sum

If the loop in python is slow, you can try to convert the two series page_id, scores to python list first, loop over list and calculation with python's native integer maybe faster.
If speed is important, you can also try cython:
%%cython
cimport cython
cimport numpy as np
import numpy as np

@cython.wraparound(False)
@cython.boundscheck(False)
def score_sum(np.ndarray[int] page_id, np.ndarray[long long] scores):
    cdef int i
    cdef long long score_sum, pid, score
    cdef np.ndarray[long long] last_score, result

    score_sum = 0
    last_score = np.zeros(np.max(page_id)+1, dtype=np.int64)
    result = np.empty_like(scores)

    for i in range(len(page_id)):
        pid = page_id[i]
        score = scores[i]
        score_sum = score_sum - last_score[pid] + score
        last_score[pid] = score
        result[i] = score_sum

    result.name = "score_sum"
    return result

Here I use pandas.factorize() to convert the page_id to an array in range 0 and N. where N is the unique count of elements in page_id. You can also use a dict to cache the last_score of every page_id without using pandas.factorize().

A: An alternative datastructure makes this calculation easier to reason about, performance won't be as good as other answers, but I thought worth mentioning (mainly because it uses my favourite pandas function...):
In [11]: scores = pd.get_dummies(df['page_id']).mul(df['score'], axis=0).where(x!=0, np.nan)

In [12]: scores
Out[12]:
                      1   2   3
date
2001-05-23 19:50:14   3 NaN NaN
2001-05-25 11:53:55 NaN   4 NaN
2001-05-27 17:36:37   5 NaN NaN
2001-05-28 19:36:37   1 NaN NaN
2001-05-28 19:36:38 NaN NaN   6
2001-05-28 19:36:39 NaN NaN   9

In [13]: scores.ffill()
Out[13]:
                     1   2   3
date
2001-05-23 19:50:14  3 NaN NaN
2001-05-25 11:53:55  3   4 NaN
2001-05-27 17:36:37  5   4 NaN
2001-05-28 19:36:37  1   4 NaN
2001-05-28 19:36:38  1   4   6
2001-05-28 19:36:39  1   4   9

In [14]: scores.ffill().sum(axis=1)
Out[14]:
date
2001-05-23 19:50:14     3
2001-05-25 11:53:55     7
2001-05-27 17:36:37     9
2001-05-28 19:36:37     5
2001-05-28 19:36:38    11
2001-05-28 19:36:39    14

A: Is this what you want? But I think it's a stupid solution.
In [164]: df['result'] = [df[:i+1].groupby('page_id').last().sum()[0] for i in range(len(df))]

In [165]: df
Out[165]:
                     page_id  score  result
date
2001-05-23 19:50:14        1      3       3
2001-05-25 11:53:55        2      4       7
2001-05-27 17:36:37        1      5       9
2001-05-28 19:36:37        1      1       5

A: Here is an interim solution I put together using the standard library. I would like to see an elegant efficient solution using pandas.
import csv
from collections import defaultdict

page_scores = defaultdict(lambda: 0)
date_scores = [] # [(date, score)]

def get_and_update_score_diff(page_id, new_score):
    diff = new_score - page_scores[page_id]
    page_scores[page_id] = new_score
    return diff

# Note: there are some duplicate dates and the file is sorted by date.
# Format: 2001-05-23T19:50:14Z, 2430, 7.632989
with open('sorted_df_changes.txt') as f:
    reader = csv.reader(f, delimiter='\t')

    first = reader.next()
    date_string, page_id, score = first[0], first[1], float(first[2])
    page_scores[page_id] = score
    date_scores.append((date_string, score))

    for date_string, page_id, score in reader:
        score = float(score)
        score_diff = get_and_update_score_diff(page_id, score)
        if date_scores[-1][0] == date_string:
            date_scores[-1] = (date_string, date_scores[-1][1] + score_diff)
        else:
            date_scores.append((date_string, date_scores[-1][1] + score_diff))


text:
Q: openCV Configuring incomplete, errors occurred I'm trying to install Python OpenCV being new to Python I got the error below and need to know what it means (and maybe how to solve)?
I installed like this (Mac running python 2.7 in virtualenv).
sudo port selfupdate
sudo port install opencv
sudo port -v install opencv +python27

Then:
sudo pip install pyopencv

... and I got this error:
Error:

-- Configuring incomplete, errors occurred!

Configuring PyOpenCV via CMake...

Error: error occurred while running CMake to configure PyOpenCV.

You may want to manually configure PyOpenCV by running cmake's tools:

    mkdir build

    cd build

    cmake-gui ..    OR    cmake ..

    cd ..


text:
Q: WCF Message Contract custom serialization First of all, sorry for my english.
For a 3rd party web service, Visual Studio "Add Service Reference" is generating proxy classes as Message Contract although "Always generate service contracts" is unchecked. For me this is not a problem except because I don't know how to prevent a long field being serialized when its value equals 0.
I've tried creating a Specified field or with method marked as [OnSerializing].
This field in XSD appears as:
<xs:element minOccurs="0" name="folder" type="xs:long"/>

In proxy classes, Visual Studio generates:
[MessageBodyMemberAttribute(Namespace="http://foo", Order=1)]
[XmlElementAttribute(Form=XmlSchemaForm.Unqualified)]
public long folder;

Any idea of how I can prevent it from being serialized when folder=0?.
Thanks in advance.

A: You can modify generated code manually and add nullable data type.
[MessageBodyMemberAttribute(Namespace="http://foo", Order=1)]
[XmlElementAttribute(Form=XmlSchemaForm.Unqualified)]
public long? folder;


text:
Q: Fire event when vimeo video stops playing? I was just wondering if it was possible to fire an event once a vimeo video has finished playing?
Currently I have a Vimeo embed in an overlay, that I want to remove once the video has stopped. Hope this makes sense!
I dont really have any code that would be of use, but would like to know if you can add event listeners to the video, fire an event once the video has finished, and how you would go about doing this?
Thanks
Ryan

A: Firstly you need to include the path to Vimeo's 'Frogaloop library, in your HTML (after your Jquery include):
<script src="https://f.vimeocdn.com/js/froogaloop2.min.js"></script>
Then you need to embed your Vimeo video (again in your HTML):
<iframe id="PLAYER1" src="https://player.vimeo.com/video/76979871?api=1&player_id=PLAYER1" width="630" height="354" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
Here 'api=1' turns on the api - this is turned off by default for performance. And, player_id='PLAYER1' is the id of your iframe.
Then in your JavaScript file, you need the following:
$(function() {

    //Gets the iframe by id
    var iframe = $('#PLAYER1');
    //Creates a player var using the iframe
    var player = $f(iframe);

    // When the player is ready/loaded, add a finish event listener
    player.addEvent('ready', function() {
        //Adds an event 'finish' that executes a function 'onFinish' when the video has ended.
        player.addEvent('finish', onFinish);
    });

    //Define the onFinish function that will be called
    function onFinish(id) {
        console.log('THE VIDEO HAS FINISHED PLAYING');
    }

});

Then simply just play the video, and check the console output.
Here is a link to the appropriate part of the documentation.
Thanks to @Raptor for pointing me towards the api docs.

A: http://developer.vimeo.com/player/js-api
Check this page out, especially the event listner part. I'm sure i could write some code on it aswell, if you need any more help?

A: Previous answer is now obsolete since Vimeo launching the new Video Player API.
Important: Be sure to remove the ?api=1 from the URL in your iframe. This was previously required when using the Froogaloop library and is no longer needed. If you leave it in, the 'ended', 'seeked' and other events will never fire.
Include the new script:
<script src="https://player.vimeo.com/api/player.js"></script>

And then use the following example:
$(document).ready(function(){

    var iframe = $('#container iframe');
    var player = new Vimeo.Player(iframe);

    player.on('ended', function() {
        console.log('Finished.');
    });

});


text:
Q: Aclarando las limitaciones de la API de twitter Estoy interesado en incluir la nueva API de twitter en mi aplicación Android.
He estado leyendo la documentación y hay algo que no me queda claro con respecto a las limitaciones.
En mi aplicación, con la API incluida, el usuario introducirá su cuenta de twitter para funcionar.
Realmente, son muy pocos los datos que voy a necesitar más allá del nombre de usuario y el número de seguidores, la cifra, no las ido ni nada por el estilo.
La llamada que tendría que usar para ese fin, según la documentación es la de GET users/show, la cual tiene una limitación de 900 requerimientos por cada 15 minutos.
Mi pregunta es:
Pongamos que mi aplicación está instalada en 1.000 móviles, esas 900 llamadas son por cada móvil que tenga instalada la aplicación o por la propia aplicación, sumando las llamadas que puedan hacer los 1.000 móviles.
Agradezco cualquier información que me aclare el camino.
Saludos y gracias!


text:
Q: How to make half-square background in css
Is it possible to make in pure css background for half square like on the image.
I know that it can be done with an image as background, but I need to use 5 different colours, and maybe in future the colours can be changed.

A: You can use transform if you don't need to worry about old browser support.

.container {
  position: relative;
  overflow: hidden;
  width: 100px;
}
.square {
  width: 100px;
  height: 100px;
  background-color: #E30606;
}
.overlay {
  width: 171px;
  height: 72px;
  background-color: #D0CBCB;
  -webkit-transform: rotate(225deg);
  -moz-transform: rotate(225deg);
  -ms-transform: rotate(225deg);
  transform: rotate(225deg);
}

http://jsfiddle.net/hT9vP/13/

A: If your divs have fixed sizes, you can use borders to make two triangles as described in  How do CSS triangles work?:

div{
  display:inline-block;
  border-top:100px solid red;
  border-right:100px solid grey;
  }

To make other sizes, colors, you need to tweak the border properties :

div {
  display: inline-block;
}
div:nth-child(1) {
  border-right: 100px solid red;
  border-top: 100px solid grey;
}
div:nth-child(2) {
  border-left: 100px solid red;
  border-top: 100px solid grey;
}
div:nth-child(3) {
  border-right: 50px solid red;
  border-top: 100px solid grey;
}
div:nth-child(4) {
  border-right: 100px solid red;
  border-bottom: 50px solid grey;
}

A: You can also try linear-gradient

div {
  width: 200px;
  height: 200px;
  background: rgba(248, 80, 50, 1);
  background:linear-gradient(to bottom right,grey 50%,red 50%);
}


text:
Q: Not able to fetch User who is having Permission as part of CERTIFICATE as Securable in SQL Server Purpose of the query is to fetch all permissions for Particular user with all the details.
Please find my query below :
 SELECT 'permUser1@master'                      AS dbUserName,
       dp.NAME COLLATE database_default        AS principal_name,
       dp.principal_id,
       dp.type_desc COLLATE database_default   AS principal_type_desc,
       grantor.NAME COLLATE database_default   AS grantor,
       class_desc = CASE p.class_desc
                      WHEN 'ASYMMETRIC_KEY' THEN 'ASYMMETRIC KEY'
                      WHEN 'SYMMETRIC_KEYS' THEN 'SYMMETRIC KEY'
                      ELSE p.class_desc
                    END,
       p.major_id,
       Object_schema_name(p.major_id)          fun_object_schema,
       Object_name(p.major_id, 1)              AS fun_object_name,
       (SELECT NAME COLLATE database_default
        FROM   [master].sys.server_principals
        WHERE  principal_id = p.major_id)      AS ser_object_name,
       (SELECT NAME COLLATE database_default
        FROM   [master].sys.database_principals
        WHERE  principal_id = p.major_id)      AS object_name,
       (SELECT NAME COLLATE database_default
        FROM   [master].sys.symmetric_keys
        WHERE  symmetric_key_id = p.major_id)  AS symmetric_key,
       (SELECT NAME COLLATE database_default
        FROM   [master].sys.asymmetric_keys
        WHERE  asymmetric_key_id = p.major_id) AS asymmetric_key,
       (SELECT NAME COLLATE database_default
        FROM   [master].sys.assemblies
        WHERE  assembly_id = p.major_id)       AS assembly_name,
       (SELECT CASE type_desc
                 WHEN 'SQL_USER' THEN 'USER'
                 WHEN 'CERTIFICATE_MAPPED_USER' THEN 'USER'
                 WHEN 'DATABASE_ROLE' THEN 'DATABASE ROLE'
                 WHEN 'ASYMMETRIC_KEY' THEN 'ASYMMETRIC KEY'
                 WHEN 'SYMMETRIC_KEYS' THEN 'SYMMETRIC KEY'
                 ELSE 'DATABASE'
               END
        FROM   [master].sys.database_principals
        WHERE  principal_id = p.major_id)      AS securable,
       p.permission_name,
       ao.type_desc                            AS object_desc,
       p.state_desc                            AS permission_state_desc,
       dp.sid
FROM   [master].sys.database_permissions p
       INNER JOIN [master].sys.database_principals dp
               ON p.grantee_principal_id = dp.principal_id
       LEFT JOIN [master].sys.database_principals grantor
              ON p.grantor_principal_id = grantor.principal_id
       INNER JOIN [master].sys.database_principals excludeAppRoles
               ON excludeAppRoles.principal_id = grantor.principal_id
                  AND excludeAppRoles.type_desc <> 'APPLICATION_ROLE'
       LEFT JOIN [master].sys.all_objects ao
              ON p.major_id = ao.object_id
WHERE  dp.principal_id = 40  AND class_desc = 'CERTIFICATE'

My output :

I was expecting to find this user in the above result:

When I debug I found that 104 value is not at all present in database_principle table. For this user wheres he is present with 6 value.
SELECT *
FROM [master].sys.database_principals
WHERE principal_id = 6;

Also value 101 is coming right from server_principle table but
How can I find user linking with 104 value ? I totally got stuck


text:
Q: Realtime Database vs Firestore I am building an app related to online bookings of Barbers in my city.I am planning to use Firebase to store my data and showing realtime updates. What will be the right option i.e. Realtime Database or Firestore. As much as I read, Firestore is great but it costs the developers according to number of queries and in my case query numbers will be much higher as I am planning to show realtime update to clients for their booking status.
And I am a naive in this area so suggest which one will be easy to learn.

A: It's up to you in the end, so I'll just name some main points:

*

*Realtime Database is basically one giant JSON file, while Cloud Firestore is based on collections of documents.

*Both offer realtime updating.

*Cloud Firestore has better ways to filter and sort data.

*Cloud Firestore has more advanced ways of writing and updating information.

*Realtime Database is based on a single region, while Cloud Firestore can scale to multiple regions automatically.

*They have different security options.

*Realtime Database charges based on bandwidth and storage, but at a higher rate. As you mentioned in your question, Cloud Firestore charges based on operations on your database (read, write, etc.)

In the end, it all depends on how you want to work in your code. For example, do you want to work with one large JSON tree, or do you want to work with separate documents? Cloud Firestore is the newer of the two, but that doesn't necessarily mean it's better in your scenario.


text:
Q: UIView.animate with limited repeat and autoreverse glitches on a real device I'm trying to make a simple scale animation of a button 1.0 -> 1.4, repeat 3 times and then stop, but I'm experiencing a glitch on a real device.
The code below works smoothly on a simulator, but on a real device (iPhone 12 Pro with iOS 16) it glitches and I can see the jump to scale 1.4 after animation is done, and then it jumps to scale 1.0 on completion where I set transform = .identity.
I've suspected UIView.modifyAnimations, but the same problem happens with the now deprecated UIView.setAnimationRepeatCount(3).
Here is the video of the glitch on the real device:
https://i.imgur.com/x1LJ9Ox.mp4
UIView.animate(withDuration: 0.5, delay: 0, animations: {
    UIView.modifyAnimations(withRepeatCount: 3, autoreverses: true) {
        self.titleButton.transform = CGAffineTransformMakeScale(1.4, 1.4)
    // self.titleButton.layoutIfNeeded()  // doesn't change anything
    }
}, completion: { _ in
    self.titleButton.transform = .identity
})

A: I've tested on my iphone 13 iOS 16, it glitches like you said above.
Maybe I'm wrong or misunderstand something but looks like something is changing in modifyAnimations(withRepeatCount:autoreverses:animations:).
In simulator, after the animation in modifyAnimations is done, it  immediately go to completion. If in completion do nothing with the view, it will turn back to CGAffineTransformMakeScale(1.4, 1.4). But if the view has transform anything, it will turn to that transform.
But in real device, after the animation in modifyAnimations is done, the view will immediately turn back to the final of animation which here is CGAffineTransformMakeScale(1.4, 1.4) ( the simulator doesn't have this step) then after that go to completion. This cause the glitches like you said.
I have a workaround for this situation
UIView.animate(withDuration: 0.5, animations: {
    // stop at the half of the final repeat means no autoreverses accur at the end
    UIView.modifyAnimations(withRepeatCount: 2.5, autoreverses: true) {
        self.secondView.transform = CGAffineTransformMakeScale(1.4, 1.4)
     }
}, completion: { _ in
    // make final scale back here
    UIView.animate(withDuration: 0.5, animations: {
        self.secondView.transform = .identity
    })
})

A: It looks like iOS 16 is updating the transform 1 event loop after the animation resulting in the glitch.  One way to work around this is to leave the scale at 1.0 at the end of the animation itself by using a keyframe animation (which I found at this answer) and adding the code to repeat 3 times:
   UIView.animateKeyframes(withDuration: 1, delay: 0, options: [], animations: {
        UIView.modifyAnimations(withRepeatCount: 3, autoreverses: false) {

            UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5) {
                self.titleButton.transform = CGAffineTransformMakeScale(1.4, 1.4)
            }
            UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5) {
                self.titleButton.transform = .identity
            }
        }
    }) { (isFinished) in

    }


text:
Q: Scoped transaction started in stored procedure is incomplete and it was rolled back (snowflake) class Database:
   cls.db_conn = create_engine(
   URL(user='xxx', password='xxx', account='xxx',
   database='xxx', schema='xxx', warehouse='xxx',
   role_name='xxx', ), pool_size=4,
    max_overflow=8, pool_pre_ping=True)

   Session = sessionmaker(bind=cls.db_conn, autocommit=True)
   cls.session_maker = scoped_session(Session)

def get_session(self):
    session = Database.session_maker()
    return session

def execute_query(self, query, values=None, with_result=True):
       session = None
       result = "No result"
       try:
           session = self.get_session()
           output = session.execute(query, values)
           if with_result:
               result = output.fetchall()
           session.commit()
           return result
       except Exception as e:
           session.rollback()
           raise e
       finally:
           self.close_session(session)

  def change(self, id, name, status, data):
           query = "call extraction_process(:b_id, :na, :status_1, :data_source)"
           values = {'b_id': id, 'na': name, 'status_1': status, 'data_source': data}
           execute_query(query, values)

when select query is used to fetch some results it works fine but to insert any values using query its throwing stored procedure execution error. hope this is the right way to create session for snowflake if not help me new to this .Tried many ways to fix it. Is it because of session creation , connection or any other ? someone pl's help me.
this is the error i'm getting
Exception while executing this query call expraction_process(:batch_id, :job_name, :job_status, :data_source_id): (snowflake.connector.errors.ProgrammingError) 090232 (25000): Stored procedure execution error: Scoped transaction started in stored procedure is incomplete and it was rolled back.
[SQL: call expraction_process(%(batch_id)s, %(job_name)s, %(job_status)s, %(data_source_id)s, )]
[parameters: {'batch_id': 1, 'job_name': 'access', 'job_status': 'processid', 'data_source_id': 1, : 'h'}]
(Background on this error at: https://sqlalche.me/e/14/f405)
Traceback (most recent call last):
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1900, in _execute_context
    self.dialect.do_execute(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 732, in do_execute
    cursor.execute(statement, parameters)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/cursor.py", line 789, in execute
    Error.errorhandler_wrapper(self.connection, self, error_class, errvalue)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/errors.py", line 273, in errorhandler_wrapper
    handed_over = Error.hand_to_other_handler(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/errors.py", line 328, in hand_to_other_handler
    cursor.errorhandler(connection, cursor, error_class, error_value)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/errors.py", line 207, in default_errorhandler
    raise error_class(
snowflake.connector.errors.ProgrammingError: 090232 (25000): Stored procedure execution error: Scoped transaction started in stored procedure is incomplete and it was rolled back.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/ONE/extraction-process-sevices1/application/modules/db_module/database.py", line 63, in execute_query
    output = session.execute(query, values)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/orm/session.py", line 1712, in execute
    result = conn._execute_20(statement, params or {}, execution_options)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1705, in _execute_20
    return meth(self, args_10style, kwargs_10style, execution_options)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/sql/elements.py", line 333, in _execute_on_connection
    return connection._execute_clauseelement(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1572, in _execute_clauseelement
    ret = self._execute_context(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1943, in _execute_context
    self._handle_dbapi_exception(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 2124, in _handle_dbapi_exception
    util.raise_(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/util/compat.py", line 208, in raise_
    raise exception
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1900, in _execute_context
    self.dialect.do_execute(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 732, in do_execute
    cursor.execute(statement, parameters)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/cursor.py", line 789, in execute
    Error.errorhandler_wrapper(self.connection, self, error_class, errvalue)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/errors.py", line 273, in errorhandler_wrapper
    handed_over = Error.hand_to_other_handler(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/errors.py", line 328, in hand_to_other_handler
    cursor.errorhandler(connection, cursor, error_class, error_value)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/errors.py", line 207, in default_errorhandler
    raise error_class(
sqlalchemy.exc.ProgrammingError: (snowflake.connector.errors.ProgrammingError) 090232 (25000): Stored procedure execution error: Scoped transaction started in stored procedure is incomplete and it was rolled back.
[SQL: call expraction_process(%(batch_id)s, %(job_name)s, %(job_status)s, %(data_source_id)s, )]
[parameters: {'batch_id': 1, 'job_name': 'access', 'job_status': 'processid', 'data_source_id': 1, : 'h'}]
(Background on this error at: https://sqlalche.me/e/14/f405)

Traceback (most recent call last):
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1900, in _execute_context
    self.dialect.do_execute(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 732, in do_execute
    cursor.execute(statement, parameters)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/cursor.py", line 789, in execute
    Error.errorhandler_wrapper(self.connection, self, error_class, errvalue)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/errors.py", line 273, in errorhandler_wrapper
    handed_over = Error.hand_to_other_handler(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/errors.py", line 328, in hand_to_other_handler
    cursor.errorhandler(connection, cursor, error_class, error_value)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/errors.py", line 207, in default_errorhandler
    raise error_class(snowflake.connector.errors.ProgrammingError: 090232 (25000): Stored procedure execution error: Scoped transaction started in stored procedure is incomplete and it was rolled back.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/ONE/extraction-process-sevices1/test.py", line 10, in <module>
    print(ob.change(1,"access","processid",1,"h"))
  File "/home/ONE/extraction-process-sevices1/application/modules/db_module/db_calls.py", line 14, in change
    self.database.execute_query(query, values)
  File "/home/ONE/extraction-process-sevices1/application/modules/db_module/database.py", line 75, in execute_query
    raise e

File "/home/ONE/extraction-process-sevices1/application/modules/db_module/database.py", line 63, in execute_query
    output = session.execute(query, values)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/orm/session.py", line 1712, in execute
    result = conn._execute_20(statement, params or {}, execution_options)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1705, in _execute_20
    return meth(self, args_10style, kwargs_10style, execution_options)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/sql/elements.py", line 333, in _execute_on_connection
    return connection._execute_clauseelement(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1572, in _execute_clauseelement
    ret = self._execute_context(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1943, in _execute_context
    self._handle_dbapi_exception(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 2124, in _handle_dbapi_exception
    util.raise_(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/util/compat.py", line 208, in raise_
    raise exception
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1900, in _execute_context
    self.dialect.do_execute(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 732, in do_execute
    cursor.execute(statement, parameters)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/cursor.py", line 789, in execute
    Error.errorhandler_wrapper(self.connection, self, error_class, errvalue)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/errors.py", line 273, in errorhandler_wrapper
    handed_over = Error.hand_to_other_handler(
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/errors.py", line 328, in hand_to_other_handler
    cursor.errorhandler(connection, cursor, error_class, error_value)
  File "/home/ONE/extraction-process-sevices1/venv/lib/python3.10/site-packages/snowflake/connector/errors.py", line 207, in default_errorhandler
    raise error_class(
sqlalchemy.exc.ProgrammingError: (snowflake.connector.errors.ProgrammingError) 090232 (25000): Stored procedure execution error: Scoped transaction started in stored procedure is incomplete and it was rolled back.
[SQL: extraction_processbatch_id)s, %(job_name)s, %(job_status)s, %(source_id)s)]
[parameters: {'b_id': 1, 'na': 'access', 'status_1': 'processid', 'data_source': 1,}]
(Background on this error at: https://sqlalche.me/e/14/f405)


text:
Q: uninitialized constant ApplicationRecord rspec 1) created a model called Skill
2) ran some seeds
3) ran rspec --init
4) created file skill_spec.rb with the code below
require_relative "../app/models/skill"

describe Skill do
  describe "database" do
    it "should have 42 skills" do
      expect(Skill.all.count).to eq(42)
    end
  end
end

5) when I run rspec in console get error:

Failure/Error: class Skill < ApplicationRecordNameError:
  uninitialized constant ApplicationRecord

I already have a file application_record.rb with the following code
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end

A: For rails specs use require 'rails-helper' at beginning of each spec file (it is generated by bin/rails generate rspec:install from rspec-rails gem)
It contains line require File.expand_path('../config/environment', __dir__) that will load your rails environment and you'll have autoloading and all other rails parts working.


text:
Q: How can you add multiple users in a Kotlin Login? I'm trying to figure out how to add more users in a Login app made with Kotlin, there's no database or whatever, the accounts are hardcoded into the program, I heard about using arrays but I'm not too sure on how to implement it in this context.
Thank you to anyone who reads this.
package com.example.textandviewbinding

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.example.textandviewbinding.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar
import java.util.*
import kotlin.system.exitProcess

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        binding.btnSubmit.setOnClickListener {
            validateUser(it)
        }
    }

    private fun addTextView(text:String){
        val textView1 = TextView(this)
        textView1.text = text
        textView1.textSize = 16f
        textView1.textAlignment = View.TEXT_ALIGNMENT_CENTER
        binding.myLayout.addView(textView1)
    }

    private fun validateUser(it: View) {
        val username = binding.editUsername.text
        val password = binding.editPassword.text
        if (username.toString().equals("joed", ignoreCase = true) && password.toString().equals("1234")) {

    //              Toast.makeText(this, "Logged In!", Toast.LENGTH_SHORT).show()
        val message = getString(R.string.welcome_message,username)

         Snackbar.make(it, message, Snackbar.LENGTH_LONG)
            .setAction("Show details.. ", { addTextView("Login Successful: ${Calendar.getInstance().time}" ) })
            .show()
        } else {
            Toast.makeText(this, "Invalid Details", Toast.LENGTH_SHORT).show()
            exitProcess(-1)
        }
    }

    private fun displayToast() {
        Toast.makeText(this, "Login Successful ${Calendar.getInstance().time}", Toast.LENGTH_SHORT).show()
    }
}

A: 1- Create a class called User , ex:
data class User(
var id : Int
var name : String
)

2- Create an Array of users using the User model in your MainActivity :
private val users = ArrayList<User>()

3- Add users to the array :
users.add(User(1,"Alex"))
users.add(User(2,"Andrei"))


text:
Q: Getting to the end of a line of code I follow along in totoreals all the time and the instructor is so quick to get to the end of the line of code and add a semicolon.
The only ways I know how to do this is to hit the end key and that is not easy to reach, use arrow keys and push twice or more or use my mouse. For a time I remapped by end key and my cap lock key.
What are most coders using to get to the end of a line?

A: It works like this: Home/End takes you to the beginning/end of a line, Ctrl+Home/End to the beginning/end of document.
Mac might be an exception: Command+Left/Right arrow to go to the beginning/end of the line. If that doesn't work, try using Fn or Fn+Command instead of Command in the previous shortcut.


text:
Q: BigQuery position function I'm trying to use the position function and it doesn't seem to work as expected:
POSITION(field) - Returns the one-based, sequential position of field within a set of repeated fields.
I expect the position to give the original position in the data loaded, while I get the position in the result set (i.e - after the where clause ran).
Is there a way to get the position in the original data loaded?
Compare the two queries below to see the issue.
SELECT
  ngram,
  cell.value,
  position(cell.volume_count) as pos,
FROM [publicdata:samples.trigrams]
where ngram contains ", says Blake"

SELECT
  ngram,
  cell.value,
  position(cell.volume_count) as pos,
FROM [publicdata:samples.trigrams]
where ngram contains ", says Blake" and integer(cell.value) % 5 = 0

A: The issue is that the position function gets evaluated after the where clause filters the nested values. You can fix this with a nested select:
select
  ngram,
  value,
  pos,
from (
  select
    ngram,
    cell.value as value,
    position(cell.volume_count) as pos,
  from [publicdata:samples.trigrams]
  where ngram contains ", says Blake"
)
where integer(cell.value) % 5 == 0


text:
Q: Get waveform data from audio file using FFMPEG I am writing an application that needs to get the raw waveform data of an audio file so I can render it in an application (C#/.NET). I am using ffmpeg to offload this task but it looks like ffmpeg can only output the waveform data as a png or as a stream to gnuplot.
I have looked at other libraries to do this (NAudio/CSCore) however they require windows/microsoft media foundation and since this app is going to be deployed to azure as a web app I can not use them.
My strategy was to just read the waveform data from the png itself but this seems hacky and over the top. The ideal output would be a fix sampled series of peaks in an array where each value in the array is the peak value (ranging from 1-100 or something, like this for example).

A: Sabona budi,
Wrote about the manual way to get waveform but then to show you an example, I found this code  which does what you want (or at the least, you can learn something from it).
1) Use FFmpeg to get array of samples
Try the example code shown here : http://blog.wudilabs.org/entry/c3d357ed/?lang=en-US
Experiment with it, try tweaking with suggestions from manual etc... In that shown code just change string path to point to your own file-path. Edit the proc.StartInfo.Arguments section to replace the last section to look like:
proc.StartInfo.Arguments = "-i \"" + path + "\" -vn -ac 1 -filter:a aresample=myNum -map 0:a -c:a pcm_s16le -f data -";

That myNum from the part aresample=myNum is calculated by :
44100 * total Seconds = X.
myNum = X / WaveForm Width.

Finally use the ProcessBuffer function with this logic :
static void ProcessBuffer(byte[] buffer, int length)
{
    float val; //amplitude value of a sample
    int index = 0; //position within sample bytes
    int slicePos = 0; //horizontal (X-axis) position for pixels of next slice

    while (index < length)
    {
        val = BitConverter.ToInt16(buffer, index);
        index += sizeof(short);

        // use number in va to do something...
        // eg: Draw a line on canvas for part of waveform's pixels
        // eg: myBitmap.SetPixel(slicePos, val, Color.Green);

        slicePos++;
    }
}

If you want to do it manually without FFmpeg. You could try...
2) Decode audio to PCM
You could just load the audio file (mp3) into your app and first decode that to PCM (ie: raw digital audio). Then read just the PCM numbers to make the waveform. Don't read numbers directly from bytes of compression math like MP3.
These PCM data values (about audio amplitudes) go into a byte array. If your sound is 16-bit then you extract the PCM value by reading each sample as a short (ie: getting value of two consecutive bytes at once since 16 bits == 2 bytes length).
Basically when you have 16-bit audio PCM inside a byte array, every two bytes represents an audio sample's amplitude value. This value becomes your height (loudness) at each slice. A slice is a 1-pixel vertical line from a time in the waveform.
Now sample rate means how many samples per-second. Usually 44100 samples (44.1 khz). You can see that using 44 thousand pixels to represent one second of sound is not feasible, so divide total seconds by required waveform width. Take the result & multiply by 2 (to cover two bytes) and that is how you much you jump-&-sample the amplitudes as you form the waveform. Do this in a while loop.

A: You can use the function described in this tutorial to get the raw data decoded from an audio file as an array of double values.
Summarizing from the link:
The function decode_audio_file takes 4 parameters:

*

*path: the path of the file to decode

*sample_rate: the desired sample rate for the output data

*data: a pointer to a pointer to double precision values, where the extracted data will be stored

*size: a pointer to the length of the final extracted values array (number of samples)

It returns 0 upon success, and -1 in case of failure, assorted with error message written to the stderr stream.
The function code is below:
#include <stdio.h>
#include <stdlib.h>

#include <libavutil/opt.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswresample/swresample.h>

int decode_audio_file(const char* path, const int sample_rate, double** data, int* size) {

    // initialize all muxers, demuxers and protocols for libavformat
    // (does nothing if called twice during the course of one program execution)
    av_register_all();

    // get format from audio file
    AVFormatContext* format = avformat_alloc_context();
    if (avformat_open_input(&format, path, NULL, NULL) != 0) {
        fprintf(stderr, "Could not open file '%s'\n", path);
        return -1;
    }
    if (avformat_find_stream_info(format, NULL) < 0) {
        fprintf(stderr, "Could not retrieve stream info from file '%s'\n", path);
        return -1;
    }

    // Find the index of the first audio stream
    int stream_index =- 1;
    for (int i=0; i<format->nb_streams; i++) {
        if (format->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
            stream_index = i;
            break;
        }
    }
    if (stream_index == -1) {
        fprintf(stderr, "Could not retrieve audio stream from file '%s'\n", path);
        return -1;
    }
    AVStream* stream = format->streams[stream_index];

    // find & open codec
    AVCodecContext* codec = stream->codec;
    if (avcodec_open2(codec, avcodec_find_decoder(codec->codec_id), NULL) < 0) {
        fprintf(stderr, "Failed to open decoder for stream #%u in file '%s'\n", stream_index, path);
        return -1;
    }

    // prepare resampler
    struct SwrContext* swr = swr_alloc();
    av_opt_set_int(swr, "in_channel_count",  codec->channels, 0);
    av_opt_set_int(swr, "out_channel_count", 1, 0);
    av_opt_set_int(swr, "in_channel_layout",  codec->channel_layout, 0);
    av_opt_set_int(swr, "out_channel_layout", AV_CH_LAYOUT_MONO, 0);
    av_opt_set_int(swr, "in_sample_rate", codec->sample_rate, 0);
    av_opt_set_int(swr, "out_sample_rate", sample_rate, 0);
    av_opt_set_sample_fmt(swr, "in_sample_fmt",  codec->sample_fmt, 0);
    av_opt_set_sample_fmt(swr, "out_sample_fmt", AV_SAMPLE_FMT_DBL,  0);
    swr_init(swr);
    if (!swr_is_initialized(swr)) {
        fprintf(stderr, "Resampler has not been properly initialized\n");
        return -1;
    }

    // prepare to read data
    AVPacket packet;
    av_init_packet(&packet);
    AVFrame* frame = av_frame_alloc();
    if (!frame) {
        fprintf(stderr, "Error allocating the frame\n");
        return -1;
    }

    // iterate through frames
    *data = NULL;
    *size = 0;
    while (av_read_frame(format, &packet) >= 0) {
        // decode one frame
        int gotFrame;
        if (avcodec_decode_audio4(codec, frame, &gotFrame, &packet) < 0) {
            break;
        }
        if (!gotFrame) {
            continue;
        }
        // resample frames
        double* buffer;
        av_samples_alloc((uint8_t**) &buffer, NULL, 1, frame->nb_samples, AV_SAMPLE_FMT_DBL, 0);
        int frame_count = swr_convert(swr, (uint8_t**) &buffer, frame->nb_samples, (const uint8_t**) frame->data, frame->nb_samples);
        // append resampled frames to data
        *data = (double*) realloc(*data, (*size + frame->nb_samples) * sizeof(double));
        memcpy(*data + *size, buffer, frame_count * sizeof(double));
        *size += frame_count;
    }

    // clean up
    av_frame_free(&frame);
    swr_free(&swr);
    avcodec_close(codec);
    avformat_free_context(format);

    // success
    return 0;

}

You will need the following flags to compile a program that uses : -lavcodec-ffmpeg -lavformat-ffmpeg -lavutil -lswresample
Depending on your system and installation, it could also be: -lavcodec -lavformat -lavutil -lswresample

and its usage is below:
int main(int argc, char const *argv[]) {

    // check parameters
    if (argc < 2) {
        fprintf(stderr, "Please provide the path to an audio file as first command-line argument.\n");
        return -1;
    }

    // decode data
    int sample_rate = 44100;
    double* data;
    int size;
    if (decode_audio_file(argv[1], sample_rate, &data, &size) != 0) {
        return -1;
    }

    // sum data
    double sum = 0.0;
    for (int i=0; i<size; ++i) {
        sum += data[i];
    }

    // display result and exit cleanly
    printf("sum is %f", sum);
    free(data);
    return 0;
}


text:
Q: Calling a php webservice from .net with a cert I'm using this code from c# to call a php web service that is secured by user/password and certificate:
string wsurl = ConfigurationManager.AppSettings["Url"];
string wsuser = ConfigurationManager.AppSettings["User"];
string wspass = ConfigurationManager.AppSettings["Pass"];

string url = string.Format(wsurl, param1, param2);

System.Net.CredentialCache oCredentialCache = new System.Net.CredentialCache();
oCredentialCache.Add(new System.Uri(url), "Basic",
    new System.Net.NetworkCredential(wsuser, wspass));

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = TIMEOUT;
req.Credentials = oCredentialCache;
req.Method = "GET";

AttachCert(req);

//Get the data as an HttpWebResponse object
WebResponse resp = req.GetResponse();

This works as expected when run from my devel machine but when we upload this to the server I get a Timeout error on the call to GetResponse().
The AttachCert() call is where I attach the certificate to the request, and if I comment this line I don't get the timeout but a correct error saying the call could not be completed because of the missing certificate.
This is the AttachCert code:
public static void AttachCert(HttpWebRequest Request)
{
    // Obtain the certificate.
    string certpath = ConfigurationManager.AppSettings["CertPath"];

    X509Certificate Cert = X509Certificate.CreateFromCertFile(certpath);
    ServicePointManager.CertificatePolicy = new CertPolicy();

    Request.ClientCertificates.Add(Cert);
}

Any idea why this would work on my machine but not on the server? We tried to remove the certificate on the webservice and the it worked as expected. So there's clearly something strange on that call but I cannot figure what.
Thanks
Vicenç

A: Try registering this callback and watch for any errors.
public static bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
  // check for errors
  // just return true to accept any certificate (self signed etc)
}

ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(MyClass.ValidateRemoteCertificate);

I hope it helps.


text:
Q: okhttp3 passing parameter with "--data {json}" How can I pass parameter with "--data {json}" on okHttp3?  Do I need to add it in the headers like below?  Or its not on the header, it need to be on another object?
Request request = new Request.Builder()
            .header("Content-Type", "application/json; charset=utf-8")
            .addHeader("data", "{json}")
            .url(url)

Please let me know.

A: You must add to RequestBody :
final String BOUNDARY = String.valueOf(System.currentTimeMillis());
RequestBody requestBody = new MultipartBody.Builder(BOUNDARY)
                                    .setType(MultipartBody.FORM)
                                    .addFormDataPart("data", JsonData)
                                    //.addFormDataPart("otherPara", otherPara)
                                    .build();
    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();


text:
Q: Additional Include Directories Difficulties I'm trying to include the FTGL library into my graphics project, but I keep getting c1083 error whenever I try to include the main header file:
#include <include/FTGL/ftgl.h>

I have added the path $(Project1)include\FTGL to "Additional Include Directories" and VC++ Include Directories to no avail. Project1 is the main solution folder and "include" is the folder where the headers for glew and whatnot are.
What am I doing wrong? Thanks for the help.

A: The rules here are very simple. Say you have a file on your hard drive:
C:\abc\def\include\FTGL\ftgl.h

Then you need to add an include path C:\abc\def to your project and the include statement:
#include <include/FTGL/ftgl.h>

This was tested 1000 times. Works fine! Once you will make this working, start experimenting with $(Project1) and other VS variables.


text:
Q: Sending data stream from python program to web app I have a python program appending lines to a .csv file every few seconds. I also have a web app that was created using Django. My goal is to continuously read the data from the python program as it runs and display it on the website without having to refresh.
My proposed solution is to send the python output to a server using requests.put(), and then read from the server using AJAX.
1.) Is this the best solution, or is there a better manner to connect the program and the site.
2.) If this is a good solution, what's the easiest way to get a server running to POST, PUT, and GET from? It can be local and will never expect heavy traffic.
Thank you!

A: Reading from csv is not good solution,message quene is suitable solution for this context。

*

*python program can post a data message to django when adding lines
to csv.

*django webapp can send data message to browser when getting
message by SSE or socket.io lib


text:
Q: Section - CSS não funciona Estou tendo um problema com a section do meu código. Ele está todo sem formatação, limpei o cachê do navegador para ver se funcionava e continua não pegando o CSS.

.newsletter {
  width: 100%;
  float: left;
  text-align: center;
  padding: 3% 4%;
  background-color: #130400;
}

.newsletter h2 {
  font-size: 1.5em;
  color: #fff;
  font-weight: 700;
}

.newsletter h3 {
  color: #fff;
}

.newsletter form {
  margin-top: 2%;
}
<section class="newsletter">
  <h2> Inscreva-se agora! </h2>
  <h3> Receba novidades, dicas e muito mais. </h3>
  <form>
    <input type="email" name="email" placeholder="digite seu email">
    <button> Cadastrar </button>
  </form>
</section>


text:
Q: php firebird/interbase external database connection I am trying to connect with an external database (which is located on the same network of mine) via PHP and Firebird, so I used ibase_connect(), but I'm not able to connect to the external database.
Below there is my PHP connection :
$db = '\\SHARE-NAME\PATH\DATABASE.GDB';
$con = ibase_connect($db , $user , $password) or die(ibase_errmsg());

Error message :

Warning: ibase_connect(): in C:\path\connection.php on line 16
I/O error during "CreateFile (open)" operation for file "C:\SHARE-NAME\PATH\DATABASE.GDB" Error while trying to open file Le chemin d'accès spécifié est introuvable.

Does ibase_connect allow external connection ?

A: You need a Firebird server installed on that remote external database and then you can connect with
HOSTNAME:C:/PATH/DATABASE.FDB

Firebird can't access databases on remote windows shares
http://www.firebirdfaq.org/faq46/


text:
Q: serialising rows in a table I have a table which contains header information for transactions. The transactions belong to different projects.
In the header I have columns:
rhguid - uniqueidentifier
rhserial - int
rh_projectID - int

First I insert the row (there's more columns)
Then I calculate the serial number for that project:
update responseheader
set rhSerial = 1 + (select isnull(max(rhSerial), 0)
                    from responseheader
                    where (rhstatus = 0) AND (rh_projectID = 1234))
where
   (rhGUID = <preassignedGUID>);

However when there are many transactions happening at the same time for a project I am finding duplicate rhserial values.
I'm doing this in classic ASP with SQL Server 2008.
Is there a better way?

A: From your example, it doesn't look like you're using a transaction.  My guess is that the SELECT portion of the statement is running as READ UNCOMMITTED, otherwise you would not see duplicates.  There are ways to start transactions with ADO, but I prefer using stored procedures instead.
Try implementing something like this:
CREATE PROC dbo.ResponseHeader_Insert
  <more data to insert>,
  @ProjectID INT,
  @Status SMALLINT
as

insert responseheader (column names here)
select <param values here>, isnull(max(rhSerial), 0) + 1
from responseheader
where (rhstatus = @Status) AND (rh_projectID = @ProjectID))

If this doesn't work for ya, try creating sequence tables (one for each sequence).
create table <tablename> (
      SeqID int identity(1,1) primary key,
      SeqVal varchar(1)
)

Create a procedure to get the next identity:
create procedure GetNewSeqVal_<tablename>
as
begin
      declare @NewSeqValue int

      set NOCOUNT ON

      insert into <tablename> (SeqVal) values ('a')
      set @NewSeqValue = scope_identity()
      delete from <tablename> WITH (READPAST)
return @NewSeqValue
end

If there are too many sequence tables that need to be created or you want to create sequences on the fly, try this approach:
Create table AllSequences (
      SeqName nvarchar(255) primary key, -- name of the sequence
      Seed int not null default(1), -- seed value
      Incr int not null default(1), -- incremental
      Currval int
)
Go

create procedure usp_CreateNewSeq
      @SeqName nvarchar(255),
      @seed int = 0,
      @incr int = 1
as

begin

      declare @currval int
      if exists (
            select 1 from AllSequences
            where SeqName = @SeqName )

      begin
            print 'Sequence already exists.'
            return 1
      end

      if @seed is null set @seed = 1
      if @incr is null set @incr = 1
      set @currval = @seed

      insert into AllSequences (SeqName, Seed, Incr, CurrVal)
      values (@SeqName, @Seed, @Incr, @CurrVal)
end
go

create procedure usp_GetNewSeqVal

      @SeqName nvarchar(255)
as

begin
      declare @NewSeqVal int
      set NOCOUNT ON

      update AllSequences
      set @NewSeqVal = CurrVal = CurrVal+Incr
      where SeqName = @SeqName

      if @@rowcount = 0 begin
            print 'Sequence does not exist'
            return
      end
      return @NewSeqVal
end
go


text:
Q: Always be logged in to gmail in puppeteer's chromium I want to reduce risk of having google recaptcha to solve, so I want to be always logged in on gmail, just like on normal chrome. I dont want to manually login every browser start. How can I do that?

A: You can use 'userDataDir' option ,while launching puppeteer. 'userDataDir' is a path to browser's user data directory. Find user directory by using "chrome://version" URL. UserDataDir is parent of Profile path.
refer [https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions]2


text:
Q: Dart - get the nearest(larger) value from List? How can I find the closest value in a list, which will return me the higher value?
Example: List of [3,7,12,19] if my value is 8 how can I get the nearest(larger) value 12? i want this logic in dart.

A: Just filter the List only for the values higher or equal to your number and get the lowest value:
var n = 8; // Number to match
var l = [3, 7, 12, 19]; // List of values

var greater = l.where((e) => e >= n).toList()..sort(); //List of the greater values

print(greater.first); // Print the first value. -> 12

A: Mattia's answer is already good enough. (although the list cant have the length 0 and it might be not as efficient, as you have a where() as well as sort() in there). Here is a different approach, that solves those concerns:
Nearest value to target (larger favored)
final nearestLarger = list.isEmpty ? null : list.reduce(
      (a, b) => (a-target).abs() < (b -target).abs() ? a : b);

Nearest value to target (smaller favoured)
final nearestSmaller = list.isEmpty ? null : list.reduce(
      (a, b) => (a-target).abs() <= (b -target).abs() ? a : b);

Note that both functions retrieve the nearest value to the target, but in case of ambiguity (eg. [3,4,5]) either the bigger or smaller value is favored.

A: To get Closest Value of number
import 'dart:math';
import 'dart:collection';

void main(){
List<double> value = [1,4,6,3,7,9,12,34,12,-12,-91];
    print(value.getCloseValue(8));    // 7
    print(value.getCloseValue(6));    // 6
    print(value.getCloseValue(-11));  // -12

}

extension on List<num> {
  num getCloseValue(num x) {
    if (isEmpty) return 0;
    Map<num, num> values = {};
    forEach((e) {
      values[e] = (e - x).abs();
    });
  var sortedKeys = values.keys.toList(growable:false)
    ..sort((k1, k2) => values[k1]!.compareTo(values[k2]!));
    final sortedMap = LinkedHashMap
      .fromIterable(sortedKeys, key: (k) => k, value: (k) => values[k]);
    return sortedMap.keys.first;
  }
}

A: List<int> arr = [6, 12, 11, 18, 24,5,6,99,10,9];
    arr.sort((a, b) => a.compareTo(b));
    print(arr);
    print(Utils.getNextLargerNumber(8, arr));

and below is the logic:
static int getNextLargerNumber(int number, List<int> array)
  {
    for (var i = 0; i < array.length; i++) {
      if (number < array[i]) {
        return array[i];
      }
    }
    return -1;
  }


text:
Q: how to fix this aggregation issue in mongodb redact i have people dataset in mongodb,  where i want to get all people whom friends has id greater than 1. i tried using $redact aggregation pipeline but it is not working. here is sample data
{
"_id" : "5d7a16904d08c0c435e4255b",
"name" : {
    "first" : "Roberta",
    "last" : "Jackson"
},
"company" : "YURTURE",
"email" : "roberta.jackson@yurture.io",
"age":26,
"registered" : "Sunday, May 5, 2019 2:44 PM",
"latitude" : "36.56389",
"longitude" : "-72.518115",
"friends" : [
    {
        "id" : 0,
        "name" : "Vicki Peck"
    },
    {
        "id" : 1,
        "name" : "Jeanie Boyd"
    },
    {
        "id" : 2,
        "name" : "Terra Curtis"
    }
],

}
i tried using aggregation pipeline redact but i am not getting any data in friends list.
db.getCollection('test_redact').aggregate([  {    $project:{
"name" : 1,
      "friends" : 1,
      "greeting" : 1,
      }},
       {
           $redact:{
               $cond: {
                    if: { $gte: [ "$friends.id", 1 ] },
                   then: "$$DESCEND",
                   else: "$$PRUNE"
                   }
                   }
           }
])

here is sample output i am getting after executing aggregation
    {
    "_id" : "5d7a16904d08c0c435e4255b",
    "age" : 26,
    "friends" : [],
    "greeting" : "Hello, Roberta! You have 9 unread messages."
}

A: The following query can get us the expected output:
db.getCollection("collection").find({"friends.id":{$gte:1}},{"name":1,"friends":1,"greeting":1}).pretty()

To get only those friends which has id greater than 1:
db.getCollection("collection").aggregate([
  {
    $match:{
      "friends.id":{
        $gte:1
      }
    }
  },
  {
    $project:{
      "name":1,
      "friends":{
        $filter:{
          "input":"$friends",
          "as":"friend",
          "cond":{
            $gte:["$$friend.id",1]
          }
        }
      },
      "greeting":1
    }
  }
]).pretty()

Using $redact:
db.getCollection("collection").aggregate([
  {
    $redact:{
      $cond:[
        {
          $or:[
            {
              $gte:["$id",1]
            },
            {
              $eq:["$id",undefined]
            }
          ]
        },
        "$$DESCEND",
        "$$PRUNE"
      ]
    }
  },
  {
    $project:{
      "name":1,
      "friends":1,
      "greeting":1
    }
  }
]).pretty()


text:
Q: Invalid Operands to binary expression(const point and const point     map<pair<int,int>,int>pairOfNumbers;
pairOfNumbers.insert(pair<pair<int,int>,int>({1,2},2));

this is working, but
    map<pair<point,point>,int>PointsOnLine;
PointsOnLine.insert(pair<pair<point,point>,int>(make_pair(points[i],points[j]),count));

this doesn't.
point is just a structure of two ints x and y;
I keep getting the error 'Invalid Operands to binary expression(const point and const point' this is the structure of point.
    struct point
{
    int x;
    int y;
public:
    bool operator==(const point& p)
    {
        if(x==p.x && y==p.y)
            return true;
        else
            return false;
    }
    bool operator!=(const point& p)
    {
        if(x==p.x &&y==p.y)
            return false;
        else
            return true;
    }
};

how do I insert two points and distance between them in the map?
in Xcode I get this error

A: Your point type does not support weak-ordering. It has no method of determining is-less-than. You may think you don't need that because your point is actually tucked into a std::pair<point,point> but you do.
std::pair<T1,T2> supports weak ordering only if T1 and T2 do. In your case, they're the same type, so for a std::pair<point,point> to be used as key in a std::map<std::pair<point,pint>,T>, point must support weak ordering.
To support weak ordering, you must either provide an operator< that compares two of your objects in question, or a comparator functor type that does the same thing. The easiest way for you to do this would be:
#include <tuple>

struct point
{
    int x;
    int y;

    bool operator <(const point& p) const
    {
        return std::tie(x, y) < std::tie(p.x, p.y);
    }

    bool operator ==(const point& p) const
    {
        return !(*this < p || p < *this);
    }

    bool operator !=(const point& p) const
    {
        return *this < p || p < *this;
    }
};

I took liberty to redefine operator == and operator != to utilize the weak order properties of the proper operator <. It wasn't necessary, but ultimately it's just easier if operators root to as basic code as possible. With the above change you should be able to use both point and std::pair<point,point> as key types in std::map and std::set. In truth, a strict weak ordering can define all of the basic comparators  (<=, >, >=, !=, ==) as derivations from operator < in one form or another (or relative to something that does). I challenge you to consider them, try implementing them, and above all, writing some test harnesses that verify your implementation.