text:
Q: What is the meaning of the specific digits in eclipse log? I need  to know what is the meaning of part of the Eclipse log. For example:
!ENTRY org.eclipse.ui.navigator 2 0 2017-03-31 13:07:11.248
!MESSAGE Warning: popupMenuId of ".....

After the plugin ID there are 2 and 0, I think the 2 is the severity, which is warning in this case but could  you tell me about the second digit?

A: The first number is the severity.
The second number is the 'bundle code' which is an error number from the code generating the error. This is usually from the IStatus getCode value. For example in:
IStatus status = new Status(IStatus.ERROR, "plugin id", 123, "message", exception);

Activator.getLog().log(status);

123 is the error number.
Some plugins such as org.eclipse.core.resources use the error number a lot to distinguish different errors (see IResourceStatus), other plugins less so.


text:
Q: Why do people say "no offense" when starting a sentence? I know what "no offense" means, but I don't think I fully understand its usage. I've seen many people saying it before they say something insulting. But does including "no offense" make the statement less offensive? I don't really get why people use it...

A: "No offense" is short for "No offense intended." I'm adding this answer because it wasn't explicitly stated in the comments and someone reading the question might not get the full idea: It means "I'm going to speak bluntly but don't mean to hurt you by saying it." Even so, as user 888379 indicates, it might not be said sincerely.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add encryption key in SHA256 algorithm in php? I want to encrypt some data uisng SHA256 hashing algorithm
<?php
 $encryption_key = "aldskfje49345rgaefa";

 echo hash('sha256', "hello world");

?>

A: Try Using hash_hmac() Like this hash_hmac('sha256',);

Read the Manual Here

Just a suggestion...

A: When you do this
echo hash('sha256', "hello world");

You are not encrypting your data but you are hashing them.
The difference between both ?
Hashing is one way. You generate an unique and irreversible hash.
Encrypting is two way. You can encrypt your data with a key and decrypt with the same key.
So in your situation, you should avoid using SHA256 algorithm. Instead, I recommand you to use Crypt facade provided by Laravel. The key used for encrypting your data is your APP_KEY environnement variable (which is generated when you install your project).
If you have not this, you can simply generate it by execute this command :
php artisan key:generate

So, you will need to share the key with your friend, and use the same algorithm. I let you read the documentation about Crypt Facade.


text:
Q: Runtime Error integrating a component lib that uses @vue/composition-api: 'You must use this function within the "setup()" method' Any help with the following problem would be greatly appreciated!
Situation:
My project contains two packages:

*

*child-component-lib

*

*contains a single view About.vue written in composition-API-style (with vue2 helper libraries @vue/composition-api and vuex-composition-helpers)

*exports a single RouteConfig

*build as a lib

views/About.vue (child)
<template>

This is an about page (as component lib)

</template>

router/index.ts (child)
export const routes: Array<RouteConfig> = [{
    path: "/",
    name: "About",
    component: () => import(/* webpackChunkName: "about" */ "../views/About.vue")
}];

lib.ts (child)
export const routes = require("@/router").routes;

package.json (child)
"scripts": {
  "build": "vue-cli-service build --target lib --name child-component-lib src/lib.ts"
...

*parent-app

*

*imports the route from child-component-lib into its router

*contains a simple view that displays one line of text and a <router-view />
package.json (parent)
"dependencies": {
    "@tholst/child-component-lib": "file:../child-component-lib",

router/index.ts (parent)
import { routes as childComponentRoutes } from "@tholst/child-component-lib";

const routes: Array<RouteConfig> = [...childComponentRoutes];
const router = new VueRouter({routes});
export default router;

App.vue (parent)
<template>

    <Home />
    <router-view />

</template>

Expected behavior
It works without problems.
Actual behavior
I see an error output in the console. [Vue warn]: Error in data(): "Error: You must use this function within the "setup()" method, or insert the store as first argument." The error message is misleading, because the error is actually thrown inside setup() method. It can be traced back to getCurrentInstance() returning undefined (inside @vue/composition-api).

Investigation:

*

*It turns out that the error disappears when I include the same About.vue in the parent-app itself (just switch the route, to try it out), i.e., it works when we avoid the import from the built library.

*So it looks like it's a problem with the build setup
(one of vue.config.js, webpack, babel, typescript, ...)

Reproduce the error:
1. Clone, install, run
git clone git@github.com:tholst/vue-composition-api-comp-lib.git && cd vue-composition-api-comp-lib/child-component-lib && npm install && npm run build && cd ../parent-app/ && npm install && npm run serve

or one by one
git clone git@github.com:tholst/vue-composition-api-comp-lib.git
cd vue-composition-api-comp-lib/child-component-lib
npm install
npm run build
cd ../parent-app/
npm install
npm run serve

2. Open Browser

*

*Go to http://localhost:8080/

3. Open Dev Tools to See Error
[Vue warn]: Error in data(): "Error: You must use this function within the "setup()" method, or insert the store as first argument."

found in

---> <Anonymous>
       <App> at src/App.vue
         <Root>

Error Screenshot

Environment Info:
Node: 14.2.0
npm: 6.14.8
Chrome: 86.0.4240.198

npmPackages:
    @vue/babel-sugar-composition-api-inject-h:  1.2.1
    @vue/babel-sugar-composition-api-render-instance:  1.2.4
    ...
    @vue/cli-overlay:  4.5.8
    @vue/cli-plugin-babel: 4.5.8
    @vue/cli-plugin-router: 4.5.8
    @vue/cli-plugin-typescript: 4.5.8
    @vue/cli-plugin-vuex:4.5.8
    @vue/cli-service: 4.5.8
    @vue/cli-shared-utils:  4.5.8
    @vue/component-compiler-utils:  3.2.0
    @vue/composition-api: 1.0.0-beta.19
    @vue/preload-webpack-plugin:  1.1.2
    typescript: 3.9.7
    vue: 2.6.12
    vue-loader:  15.9.5 (16.0.0-rc.1)
    vue-router: 3.4.9
    vue-template-compiler: 2.6.12
    vue-template-es2015-compiler:  1.9.1
    vuex: 3.5.1
    vuex-composition-helpers: 1.0.21

npmGlobalPackages:
    @vue/cli: 4.5.8

A: I finally understood what the problems were. First, there was the actual problem. Second, there was a problem in the local development setup that made solutions to the actual problem look like they were not working.
The Actual Problem + Solution
The child-component-lib was bundling their own versions of the npm packages @vue/composition-api and vuex-composition-helpers. This had the following effect: When I was running the parent-app there were actually two instances of those libraries and the vue component from the child-component-lib was accessing the wrong object that had not been properly initialized.
The solution was to prevent the bundling of those libraries in the child-component-lib, by

*

*making them devDependencies and peerDependencies.

*instructing webpack not to bundle them on npm run build.
package.json
"dependencies": {
    ...
},
"devDependencies": {
    "@vue/composition-api": "^1.0.0-beta.19",
    "vuex-composition-helpers": "^1.0.21",
    ...
},
"peerDependencies": {
    "@vue/composition-api": "^1.0.0-beta.19",
    "vuex-composition-helpers": "^1.0.21"
},

vue.config.js
configureWebpack: {
    externals: {
        "@vue/composition-api": "@vue/composition-api",
        "vuex-composition-helpers": "vuex-composition-helpers"
    },
    ...
}

The Tricky Problem that Made Things Difficult
I was trying to fix this problem locally, without actually publishing the package. And it seemed to work, because I was seeing the same problem locally that I also saw in the published packages.
I did local development by directly linking the parent-app and child-component-libs. I tried both

*

*a direct folder dependency
package.json
"dependencies": {
    "@tholst/child-component-lib": "file:../child-component-lib",
},

*npm link
cd child-component-lib
npm link
cd ../parent-app
npm link @tholst/child-component-lib

Both approaches have the effect that they actually import (=symlink to) the child-component-lib's folder with all files and folders (instead of only the files that would be published in the npm package).
And that meant the following: Even though I had excluded the two composition-API libs from the bundle and made them dev/peer dependencies (see solution to actual problem), they were still installed and present in the child-component-lib's node_modules. And that node_modules folder was symlinked into the parent-app package. And in this way the child-component-lib still had access to their own copy of the libraries that we wanted to exclude from the build (see actual problem). And I was still seeing the error as before.
And this way my local development approach obscured the fact that the solution to the actual problem was actually working.


text:
Q: What are the possible events for amp-story? Is there one place to see all of the events for amp-story, events in the pipeline, and events that are never going to go live?
sample topics

*

*clipboard events

*drag events

*mouse events

*keyboard events

*window event attributes

*form events

*media events

*miscellaneous events such as ontoggle, which fires in HTML5 when the user opens or closes the  element

A: I don't think such a list exists, but there are not currently any events that publishers can hook into, nor are there any pending.
You can always file a feature request with any specific use cases you might have.


text:
Q: How often/when does C execute content within if/else statements? I'm working on an embedded (avr) project, and basically I want to print out a few different things based on how long a pin has been pressed down. I can't figure out what happens as the value passes through and satisfies if statements along the way (button is still pressed so counter increments).
The setup is as follows:

if overflows is between 7-48 (button pressed for 30ms-200ms), print out a '.'
  if overflows is greater than 48 (button pressed for greater than 200ms), print out a '-'
  if overflows is greater than 97 (button has not been pressed in over 400ms), print out a ' '

My current code is as follows:
static inline void isr(char type) {
static unsigned int overflows = 0;
static unsigned char idx = 0;
if (type == 'e') { // edge captured
    if (TCCR1B & 0x40) { // rising edge
        if (overflows < 7) {
            // do nothing
        } else if (overflows < 49) {
            buffer[idx++] = '.';
            size++;
        } else {
            buffer[idx++] = '-';
            size++;
        }
    }
    overflows = 0; // restart counting overflows at each edge
} else { // overflow occured
    overflows++;
    if (buffer[idx-1] != ' ' && !(TCCR1B & 0x40) && overflows > 97) {
        buffer[idx++] = ' ';
        size++;
    }
}

I'm not sure if this is correct though, since it would seem that there would always be a '.' preceding a '-', since as the overflow value is incremented, it satisfies the <49 condition.
Any thoughts?

A: if you want to count no.of times switch pressed, you can use while loop.
 for example,
    if(sw==0) //sw is switch connected with I/O pin
    {
      while(sw==0)
      {
       led=1; //LED is output
       delay(); // use delay function
       led=0;
       delay();
       count++;
       }
     }

by using while loop, you can avoid from getting multiple times switch pressed. if you make one on and off switch, the count will be increased by one.

A:
I'm not sure if this is correct though, since it would seem that there would always be a '.' preceding a '-', since as the overflow
  value is incremented, it satisfies the <49 condition.

But the tests are performed only on the rising edge - when both type == 'e' and (TCCR1B & 0x40) != 0.  So the overflow count is evaluated only when the button is released, so you will not see the intermediate . before -.
So to answer your question, a conditional statement or block is executed when the condition is true.  Here you have nested conditionals, so all preceding conditions must be true for the inner condition to be evaluated.

A: According to your description I assume you have a button on your pin, so in this case the first thing what I would recommend before doing anything is to implement a debounce for the button signal.
I would solve the problem something like this:
#define BUTTON_UNKNOWN  0
#define BUTTON_DOWN     1
#define BUTTON_UP       2

#define FALSE           0
#define TRUE            1

static inline unsigned char debounce( unsigned char current_state)
{
static unsigned char ret_value;
unsigned char state_changed = FALSE;
// Counter for number of equal states
static unsigned char count = 0;
// Keeps track of current (de-bounced) state
static unsigned char button_state = 0;
// Check if button is high or low for the moment
if (current_state != button_state)
{
    // Button state is about to be changed, increase counter
    count++;
    if (count >= 3)
        {
        // The button have not bounced for four checks, change state
        button_state = current_state;
        // If the button was pressed (not released), tell main so
        count = 0;
        state_changed = TRUE;
        }
}
else
{
state_changed = FALSE;
// Reset counter
count = 0;
}

//if butten press or release detected
if (state_changed == TRUE)
{
    //check for the current state of the button
    if (current_state != 0)
        {
        ret_value = BUTTON_DOWN;
        }
    else
        {
        ret_value = BUTTON_UP;
        }
}

return ret_value;
}

int main(void)
{
//perform proper initialization of your pin

unsigned char button = BUTTON_UNKNOWN;
unsigned char cycle_count  = 0;
unsigned char idx = 0;
unsigned char buffer[255];
unsigned char current_state;
unsigned char no_activity;
//unsigned char current_state = (~BUTTON_PIN & BUTTON_MASK) != 0;

while(1)
{
//read the button state
current_state = (~BUTTON_PIN & BUTTON_MASK) != 0;
// Update button_state
button = debounce(current_state);
// Check if the button is pressed.
if (button == BUTTON_DOWN)
{
    //count cycles in which the button was pressed
    //one cycle is 10 ms - see delay below
    cycle_count++;
}
else
{
    //check if the button was pressed before
    if ((button != BUTTON_UNKNOWN) && (cycle_count != 0))
    {
        //if button was pressed for 200ms
        if (cycle_count <= 20)
        {
            buffer[idx] = '.';
            idx++;
        }
        else
        {
            //if the button was pressed between 200 and 400 ms
            if ((cycle_count > 20) && (cycle_count <= 40))
            {
               buffer[idx] = '-';
               idx++;
            }
            //the button was pressed for more than 400ms, uncomment if you need it

            /*else
            {
               buffer[idx] = ' ';
               idx++;
            }*/

        }
        //reset counting mechanism
        cycle_count = 0;
        no_activity = 0;
    }
    else
    {
        no_activity++;
        if (no_activity >= 40)
        {
            buffer[idx] = ' ';
            idx++;
            no_activity = 0;
        }
    }
}

// Delay for a while so we don't check to button too often
_delay_ms(10);
}
}

You can adapt this code according to your needs:
change the line current_state = (~BUTTON_PIN & BUTTON_MASK) != 0; so that to read your pin state, and change the declaration of the buffer to suite your needs unsigned char buffer[255];
Please note that due to the debounce the time measured is not exactly 200ms ( it is 200ms + 2*debounce_time = 260ms (debounce time is 3 cycles, each cycle is 10ms, see delay at the end), but you may compensate these errors by reducing the contants in the cycle_count comparisons in the end.
Hope this helps!
If you really stick to your solution, then to avoid the problem what you experience is to not evaluate the overflow value continuously, do not try to determine the length of the button push on the fly, try instead to measure the length of the push and after that evaluate it and put the char in the buffer. You need to wait for the 'release button' and then evaluate how much time the button was pressed. Something like this:
static inline void isr(char type) {
static unsigned int overflows = 0;
static unsigned char idx = 0;
unsiged char button_status;

if (type == 'e') { // edge captured
    if (TCCR1B & 0x40) { // rising edge
        //perform a debounce otherwise wont be good
        button_status = 1;

    }
    overflows = 0; // restart counting overflows at each edge
} else { // overflow occured
    overflows++;
     //if button was pressed and its now released evaluate result
    if (!(TCCR1B & 0x40) && (button_status == 1))
    {
        if (overflows < 7) {
            // do nothing
        } else if (overflows < 49) {
            buffer[idx++] = '.';
            size++;
        } else {
            buffer[idx++] = '-';
            size++;
        }
        button_status = 0;
    }
    if (buffer[idx-1] != ' ' && !(TCCR1B & 0x40) && overflows > 97) {
        buffer[idx++] = ' ';
        size++;
    }
}


text:
Q: Is it possible to disable Plotly showing pie chart textinfo if the value is equal to 0 I am building a react application that uses Plotly to display some charts. One of the pie charts that contains variables that have value 0. I was wondering can I only show the textinfo the variable that has a value larger than 0.
The current Chart looks like this:
pie chart (I can't embed image in the post)
What I would like to achieve is only showing the 'Radio 100%' text and 'TV 0%' will be hidden.
Current Code Implementation:
import React from 'react';
import Plot from 'react-plotly.js';

/...rest of code .../

<Plot
    data={[
          {
            values: [100, 0, 0],
            labels: ['Radio, 'TV', 'Newspaper'],
            type: 'pie',
            sort: false,
            textinfo: 'label+percent',
            textposition: 'outside',
            hoverinfo: 'label+percent',
          },
        ]}
    layout={layout}
    config={{ responsive: true }}
  />

A: One of the workaround I find is set textposition to be inside, so that the label with 0% would show on the graph. It would be great if plotly can add auto to textposition variable so label with 0% won't show


text:
Q: ORA-00911: invalid character Error in C# Application I'm created app to connect Oracle Database XE 11g with ODAC 12, and take an error called "invalid character".
This is my ConnectionString:
connectionString="Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));User Id=hr;Password=12345;"

and code here
    private void BtnConnect_OnClick(object sender, RoutedEventArgs e)
    {
        var sql = @"SELECT FIRST_NAME FROM EMPLOYEES
                    WHERE EMPLOYEE_ID = 120;";
        var command = new OracleCommand(sql, Connection.Connect);
        try
        {
            command.Connection.Open();
            var reader = command.ExecuteScalar();
            if (reader != null)
            {
                LblMessage.Content = "Connect Succeeded ";
                LblMessage.Foreground = Brushes.Green;
            }
            else
            {
                LblMessage.Content = "Connect Failed";
                LblMessage.Foreground = Brushes.Red;
            }
        }
        catch (Exception ex)
        {

            throw ex;
        }
        finally
        {
            command.Connection.Close();
        }
    }

Somebody help me!

A: Standalone queries executed from your C# application shouldn't include the semicolon ; at the end.  If you remove that, the ORA-00911 error should go away.


text:
Q: difference between embedded opc ua server/client and normal opc ua server/client Can you please tell me what is the difference between the embedded opc ua and normal opc ua.
Actually i have search over internet but dint able to find the exact difference
if anyone knows???

A: If you approach from OPC UA Profiles point of view, then look at this web site: OPC UA Profiles
It contains what exactly should support Embedded UA Server vs Standard UA Server.

A: Embedded OPC UA server runs in a device such as a PLC (Programmable Logic Controller), smart sensor, IoT gadget or so.
"Normal" OPC UA server runs on a PC or comparable general-purpose computer.

A: It all depends on what profiles a server is required to implement. Most likely, an embedded OPC UA Server will support less of the specified functionality. (site quoted by @ravil has moved: OPC foundation profiles)
Some characteristic differences: supported security policies, required amount of supported parallel sessions, continuation points per session, ... So mostly stuff that relates to the limited resources typical for an embedded environment.


text:
Q: What's the best difficulty to farm a "Ring of Royal Grandeur"? The Ring of Royal Grandeur only drops from Act I bounty caches.  From various places online, I've heard:

*

*Torment I, because they're all the same

*Torment VI, because you're guaranteed a legendary drop from the cache

*Torment VIII, because you get "added bonus" (???)

*Normal(!?!), because almost no other legendaries drop at that level (but the post is downvoted so it seems that might not be true)
Which is it?

A: At the moment, on this patch (2.5.0), act bonus doesn't exit anymore. If you complete 5 bounties on any Act you will get a Large horadric chest, that contains the same drops as the Horadric and Bonus Caches together.
With this Large chest. The Ring can only be obtain on Large chest for act 1 and 4.
And now, the question about best difficulty its simple: It is true that on T6 you obtain always a legendary, but if you can do T13, do it. Can appear more legendary so more chances of obtaining the Ring. Do the most difficulty you can do faster. It is just lucky of getting it on the first chest or on the 100th.
On my Hardcore season, I get around 20-30 chest and 0 rings, doing the last 10 on Torment +10.
Source of changes and patch : https://us.battle.net/d3/en/game/patch-notes/


text:
Q: Create buttons from instances of a class So I am trying to build a restaurant menu.
I want to create buttons based on instances of class Food:
class Food:
    instances=[]
    def __init__(self,name,price):
        self.name=name
        self.price=price
        Food.instances.append(self)

    def __iter__(self):
        for item in Food.instances:
            yield item
    def get_name(self)
        return self.name

The code I have right now, works, but it also changes the Food.instances to button object, I want it to stay as Food objects, so I can call functions to get their name and price.
This is what I have right now:
def read_data():    #reads data from json file
    global data
    with open("restaurant\menu.json",'r') as f:
        data=json.loads(f.read())

def get_instances(json_data): #gets Food instances based on data loaded from json file
    for u in json_data:
        x=Food(**u)

def get_buttons(frame,list_aux): #makes buttons based on instances of Food class
    column=0
    rows=0
    for index,obj in enumerate(list_aux):
        if column<3:
            list_aux[index]=Button(frame,text=obj.get_name())
            list_aux[index].grid(row=rows,column=column)
            column+=1
        else:
            column=0
            rows+=1
            list_aux[index]=Button(frame,text=obj.get_name())
            list_aux[index].grid(row=rows,column=column)
            column+=1

read_data()
get_instances(data)
print(Food.instances)
list_aux=Food.instances #makes a copy of Food.instances to HOPEFULLY not mess up the class
root=Tk()
get_buttons(root,list_aux)
root.mainloop()

Before running get_buttons() function, when I print Food.instances I get:
[<__main__.Food object at 0x000001C0F0113E50>, <__main__.Food object at 0x000001C0EFD51960>, <__main__.Food object at 0x000001C0F0115A20>]
After running the function, printing list_aux results in:
[<tkinter.Button object .!button>, <tkinter.Button object .!button2>, <tkinter.Button object .!button3>]
But also, when print Food.instances, I get the same output and I lose all of the class methods written (get_name() and others I did not include here because are not relevant).
How can I keep creating those buttons, but not change Food.instances?
One workaround I have found is to modify the get_instances() function to:
def get_instances(json_data):
    Food.instances=[] #this is the line that is added
    for u in json_data:
        x=Food(**u)

So I can call it again after get_buttons() function, deleting those tkinter.Button objects, creating Food objects again, and I can use the class methods as before, but I feel like this is extremly inefficient. How can I fix this?

A: All i did was adding
list_aux = Food.instances.copy()

In the get_buttons() function
And removing it from the global space to not pollute it. This will create the buttons from the class, get all the information I wanted to get when creating the buttons, and still keep the original array in place so i can have access to the class methods


text:
Q: SSRS 2008 Web service I need to get all on-demand reports name from report server
SSRS: Get list of all reports and parameters in a single web service call?
That link specify how to do it in sql server 2005 report server.
I have sql server 2008
i have tried http://10.230.193.131/ReportServer/ReportService2008.asmx?wsdl
but it gives
"The path of the item 'wsdl' is not valid. The full path must be less than 260 characters long; other restrictions apply. If the report server is in native mode, the path must start with slash. (rsInvalidItemPath) Get Online Help"
But I am able to  see  http://10.230.193.131/ReportServer/ReportService2010.asmx?wsdl
But I am not able to find the node where i get names of all reports
In short how can i get the name of all reports by consuming a service of  SSRS 2008

A: *

*Did you try using the ListChildren method in the ReportService2010 web service?
http://msdn.microsoft.com/en-us/library/reportservice2010.reportingservice2010.listchildren.aspx

*Your question was specific to using the SSRS web service interface, but you could also query the SSRS tables directly in sql:
SELECT
   [Path]        [ReportPath],
   Name          [ReportName],
   Type          [ReportType],
   [Description] [ReportDescription]
FROM
   dbo.[Catalog]
WHERE
   [Type] = 2   -- 1= Folder, 2= Report

A: Mention like
ReportViewer1.ServerReport.ReportPath = @"/EmployeeData";

@ symbol as single / is treated as special character.

A: I believe you do it in the same way as in the link you provided.
You can't access "http://10.230.193.131/ReportServer/ReportService2008.asmx?wsdl" because such thing does not exist. There are 3 endpoints for SQL Server 2008 (I'll assume you have the R2 version) and they are mentioned here:
http://www.blograndom.com/blog/2011/03/reportservice2010-asmx-is-not-the-only-end-point/
All you should do is generate ReportService2010 proxy using wsdl and proceed as in the link you provided.


text:
Q: Total de Subregistros - MySql Em meu banco de tenho várias tabelas, mas vou fazer um exemplo simples do que quero fazer:
Supondo duas tabelas:

*

*Tabela 1

id | loja | data

*

*Tabela 2

id_2 | id_tab1_2 | produto

Percebam que o id_tab1_2 é uma chave estrangeira, ligado ao campo id da tabela 1.
O que eu quero é EM UMA ÚNICA QUERY trazer todos os registros da Tabela 1 e a quantidade de sub registros da Tabela 2, ex:
SELECT * FROM tabela_1 ...
E o resultado fosse algo parecido com isso:
id | loja |   data     | quant_tab_2
1  |   X  | 23/07/2018 |      2
2  |   Y  | 23/07/2018 |      1
3  |   Z  | 23/07/2018 |      0
No campo quant_tab_2 vem a quantidade se sub registros na Tabela 2 de cada registro da Tabela 1
Não que tenha que vir uma coluna com o nome quant_tab_2, é só um exemplo, eu não quero ter que fazer pra cada registro da Tabela 1, uma nova query pra saber quantos sub registros dela há na Tabela 2, é possível fazer isso? Alguém pode me ajudar?

A: Com base na sua suposição, a query ficaria dessa forma:
SELECT
tabela_1.id,
tabela_1.loja,
tabela_1.data,
COUNT(tabela_2.id_2) as quant_tab_2
FROM tabela_1
LEFT JOIN tabela_2 ON (tabela_1.id = tabela_2.id_tab1_2)
GROUP BY tabela_1.id

A: Você pode fazer algo do tipo:
select t1.*, count(t2.produto) from tabela1 as t1
inner join tabela2  as t2 on t2.id_tab1_2 = t1.id
group by t2.id_tab1_2


text:
Q: Use a VPN/... only for a specific port on windows? I would like to know if there is a way to use another a software to redirect only some ports to another site?
In my case I would like that the port 80(web) goes through a connection, and the other still use my local network.


text:
Q: getting the latest data from prisma client by id datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model Data {
  id        Int     @id @default(autoincrement())
  longitude Float
  latitude  Float
  distance  Int
}

How can I get the latest data by id?
I am using @prisma/client and postgresql.

A: Basically you just want to order data by id in descending order?
Here we go:
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

const data = await prisma.data.findMany({ orderBy: { id: 'desc' } });


text:
Q: codeigniter change third party application language My thirdparty app comes with languages support in it.
Do I have to 'manually' copy the language folder to 'application/language' ?
Is so, what the use of $autoload['language'] = array('thirdparty'); ?

A: You need to add the package path to the codeigniter loader:
$this->load->add_package_path(APPPATH.'third_party/foo_bar/');

After you will be able to load it's language file normally:
$this->lang->load('filename', 'language');

Take a look at: CodeIgniter Loader Class


text:
Q: PHP - sleep() cannot continue execute after time has passed currently I implement the sleep() in my PHP script to pause the execution for 15 minutes to give some buffer for other tasks to finish before continue to execute the script.
<?php

------do something here-----

   file_put_contents("logs/pre_sleep.log", "$id sleep in $datetime", FILE_APPEND);

   sleep(900);

----continue do something here----

   file_put_contents("logs/done.log", "$id done in $datetime", FILE_APPEND);

?>

When the PHP is called from client, the process will be logged in "pre_sleep.log" and before the script finish will be logged in "done.log". However, based on the log I write, I notice the some execution will not continue even has passed for 15 minutes. The process has been logged in "pre_sleep.log" where "done.log" couldn't find the same process.
Is it possible the process been killed by others within 15 minutes? This happens seem like very randomly, because most of the processes logged in both log files but some appear in only one.

A: It is possible the process gets shut down after the sleep (or even before the sleep).
My best guess is, your PHP timeout is in play. Put the following at the top of your script file.
set_time_limit(0);
// or
ini_set('max_execution_time', 0);

It will allow for scripts to run forever


text:
Q: I want to find out what result is most often won from a track with that Name Have a question that is my problem
It is the case that I have about 40 columns with information in almost all fields of which 22 are
only numbers, and the others are either only text or text and numbers.
Previously had it in an excel sheet.
It's about Race
I want to be able to search for a Name if it is in " N1 | N2 | N3 | N4 | N5 "
partly get the total number of the name and group the most common results from 2 other columners
| R1 | R2 | R3 | R4 | R5 | - | S1 | S2 | S3 | S4 | S5 |
Rx is results
Sx is track
I want to find out what result is most often won from a track with that Name
Is it possible to sum/group together in that way ?
Am retired and thought this could be nice to learn something new, haven't tested anything but want to ask the question if it is possible and maybe some kind soul can get me on the right track.
I can take everything separately and add it up but that's how I did it in the excel sheet
Thanks in Advice


text:
Q: Is AutoHotkey capable of defining Arrays in a zero based order? I've often been frustrated by the fact that AutoHotkey is not a zero based language. It doesn't match well when you are translating code from other languages, or even interacting with them such as in JScript through COM ScriptControl. Even parsing DOM elements you have to account for them being zero based, it just seems that most languages have adopted zero based arrays.
Now you can declare an array and make it zero based by doing this:
arr := []
arr[0] := 1

The above works, if I asked for arr[0] it would return 1. But if I use length() method it returns 0, even though there is a value in there!
If we declare and then push():
arr := []
arr.push(3)

It's always stored starting from 1, I want this changed!
Is this possible to do?

A: Because AutoHotkey is a prototype OOP language (like JavaScript) you can override any function, even built in ones. Below is demonstration of overriding Array(), which according to Lexikos is an undocumented fact that it overrides defining an array as such [].
I didn't believe it possible as there are several threads on the forums asking for zero based to implemented natively, but none offered a solution. Even the thread where an override of Array() was demonstrated made no mention that this would be possible!
As a bonus, I included split() (zero based StrSplit() function), to help demonstrate further the endless possibilities of this feature.
Just to note, I haven't unit tested or implemented ever method override, it's possible I've overlooked something but I felt it was enough for a proof of concept. Further, I have no doubts that this will affect performance on large arrays, particularly because of how I implemented Length() for this demo.
x := [] ; declare empty array
x.push("Zero Based rocks!") ; push message to the array.
msgbox % x[0]

x := "" ; clear our Object
x := split("AutoHotkey with Zero Based Arrays")
msgbox % x.2 " " x.3 " " x.4 " " x.1 " " x.0

Array(prm*) {
    x := {}
    loop % prm.length()
        x[A_Index -1] := prm[A_Index]
    x.base := _Array
    return x
}

split(x, dlm:="", opt:="") {
    r := []
    for k,v in StrSplit(x, dlm, opt)
        r.push(v)
    return r
}

Class _Array {

    ; Modified .length() to account for 0 index
    length() {
        c:=0
        for k in this
            c++
        return c
    }

    ; Modified .push() to start at 0
    push(x) {
        if (this.0 == "" && this.length() == 0)
            return this.0 := x
        else
            return this[this.MaxIndex()+1] := x
    }
}


text:
Q: Throwing fair dice, what can I say about the following two Random variables? Droping 2 times fair dice, Let $X$ be the number of drops that got even number, Let $Y$ be the number of drops got a number that is divided by $3$ what is true from the following?
A. $\mathbb{E}[X^2Y]= 1$ and $X$ , $Y$ are independant
B.$\mathbb{E}[X^2Y]= \frac{2}{3}$ and $X$ , $Y$ are independant
C.$\mathbb{E}[X^2Y]= \frac{2}{3}$ and $X$ , $Y$ are Not independant
D.$\mathbb{E}[X^2Y]= 1$ and $X$ , $Y$ are Not independant
How should I approach this question? Do I really need to calculate the probability function or there is an efficient way to approach it?

A: To calculate the expectation is is easy to find out the distribution but it is very immediate...
First observe that
$$\mathbb{P}[\text{Even}]=\frac{1}{2}$$
$$\mathbb{P}[\text{Div 3}]=\frac{12}{36}=\frac{1}{3}$$
and
$$\mathbb{P}[\text{Div 3}|\text{Even}]=\frac{6}{18}=\frac{1}{3}$$
Thus being
$$\mathbb{P}[\text{Div 3}|\text{Even}]=\mathbb{P}[\text{Div 3}]$$
These events are independent.
Given this property also $X\perp \!\!\!\!\!\!\perp Y$ and $X^2\perp \!\!\!\!\!\!\perp Y$
Thus
$$\mathbb{E}[X^2Y]= \mathbb{E}[X^2]\cdot\mathbb{E}[Y]=\Bigg(\frac{2}{4}+1 \Bigg)\Bigg(\frac{4}{9}+\frac{2}{9}\Bigg)=1$$


text:
Q: How to look back to the previous moment I am reading a button's state (whether being pressed or not) every moment:
readButton :: IO Boolean
readButton = ...

main = do
    (add, fire) <- newAddHandler
    network <- compile (desc add)
    actuate network
    forever $ do
        buttonState <- readButton
        fire buttonState

desc addButtonEvent = do
    eButtonState <- fromAddHandler addButtonEvent
    ...

All the read states are stored into eButtonState in the network description desc.
The button is considered to be newly pressed when the current moment's state is 1 with the previous moment's being 0. So, if the event sequence was a list, the function would be written like this:
f :: [Bool] -> Bool
f (True:False:_) = True
f _              = False

I want to apply this function to eButtonState so I would know whether the button is newly pressed or not in the moment.
Is it ever possible? How would you do it? I would appreciate if there is a better or more common idea or method to achieve this goal.

A: Here is one way (this is a runnable demo):
import Reactive.Banana
import Reactive.Banana.Frameworks
import Control.Monad
import Control.Applicative -- Needed if you aren't on GHC 7.10.

desc addDriver = do
    -- Refreshes the button state. Presumably fired by external IO.
    eButtonDriver <- fromAddHandler addDriver
    let -- Canonical repersentation of the button state.
        bButtonState = stepper False eButtonDriver
        -- Observes the button just before changing its state.
        ePreviousState = bButtonState <@ eButtonDriver
        -- Performs the test your f function would do.
        newlyPressed :: Bool -> Bool -> Bool
        newlyPressed previous current = not previous && current
        -- Applies the test. This works because eButtonDriver and
        -- ePreviousState are fired simultaneously.
        eNewlyPressed = unionWith newlyPressed
            ePreviousState eButtonDriver
        -- The same but more compactly, without needing ePreviousState.
        {-
        eNewlyPressed = newlyPressed <$> bButtonState <@> eButtonDriver
        -}
    reactimate (print <$> eNewlyPressed)

main = do
    (addDriver, fireDriver) <- newAddHandler
    network <- compile (desc addDriver)
    actuate network
    -- Demo: enter y to turn the button on, and any other string to
    -- turn it off.
    forever $ do
        buttonState <- (== "y") <$> getLine
        fireDriver buttonState

Notes:

*

*Events are transient, behaviors are permanent is a good general rule to decide whether you need a behavior or an event stream. In this case, you need to look at what the button state was before the update in order to decide whether it was newly updated. The natural thing to do, then, is to represent the button state with a behavior (bButtonState), which is updated by an event fired externally (eButtonDriver).

*For details about what the combinators are doing, see Reactive.Banana.Combinators.

*For the fine print on the timing of events and behavior updates in reactive-banana, see this question.

*Depending on what you are trying to do, the changes function might be useful. Be aware of the caveats related to it mentioned by the documentation.


text:
Q: Explain scoping for functions called from PowerShell closures The following PowerShell code displays unexpected scoping behavior for functions called from closures.  Can you explain whether this is "by design", or is a defect?
function runblock($block) {
    $x = 4
    & $block
}

function printx() {
    "  in printx: x=" + $x
}

"PSVersion $($PSVersionTable.PSVersion)"

$x = 1
$b = {"In block x=" + $x ; $x = 3 ; printx}
$x = 2
runblock $b

$x = 1
$b = {"In closure x=" + $x ; $x = 3 ; printx}.GetNewClosure()
$x = 2
runblock $b

Output from the above is

PSVersion 3.0
In block x=4
  in printx: x=3
In closure x=1
  in printx: x=4

Most of the output makes sense to me:
The script block outputs In block x=4 since its parent scope is the runblock function. The printx function outputs x=3 since its parent scope is the script block scope.
The closure outputs In closure x=1 since the value of $x was captured by GetNewClosure call.  All as expected.
BUT:
The call to printx from the closure outputs in printx: x=4.  So the scope that printx executes within is unaffected by the scope of the closure where $x = 3.
It seems strange to me that a function called from a normal script block does see the variables in the script block scope, but a function called from a closure does not see the variables in the closure.

A: Consider following code:
function Run {
    param($ScriptBlock)
    $a = 3
    # Picture 4
    & $ScriptBlock
}
function Print {
    # Picture 6
    "Print `$a=$a"
    "Print `$b=$b"
}
$a = 1
$b = 1
# Picture 1
$SB = {
    # Picture 5
    "Closure `$a=$a"
    "Closure `$b=$b"
    Print
}.GetNewClosure()
# Picture 2
$a = 2
$b = 2
# Picture 3
Run $SB

It prints:
Closure $a=1
Closure $b=1
Print $a=3
Print $b=2

Picture 1: you start from global scope, where you define some variables.

Picture 2: GetNewClosure() create new module and copy variables to it. (red arrow show parent scope relationship)

Picture 3: you change value of variables. Module scope not affected.

Picture 4: function Run called. It create local variable $a. (blue arrow show call direction)

Picture 5: $SB script block called. Script block bound to module session state, so you transit to it.

Picture 6: function Print called. Function bound to global session state, so you return to it.


text:
Q: MySql self join unexpected result inner join I am learning about SQL joins from this tutorial: http://www.programmerinterview.com/index.php/database-sql/what-is-a-self-join/
The table they are using is:
+---------------+-------------------+
| employee_name | employee_location |
+---------------+-------------------+
| Joe           | New York          |
| Sunil         | India             |
| Alex          | Russia            |
| Albert        | Canada            |
| Jack          | New York          |
+---------------+-------------------+

I decided to experiment with the queries by leaving out certain parts like this:
select * from
employee t1, employee t2
where t1.employee_location = t2.employee_location

This query seemed pretty straightforward. "Match up people with the same location. I thought ok, the result will be this:
+---------------+-------------------++---------------+-------------------+
| employee_name | employee_location || employee_name | employee_location |
+---------------+-------------------++---------------+-------------------+
| Joe           | New York          || Joe           | New York          |
| Sunil         | India             || Sunil         | India             |
| Alex          | Russia            || Alex          | Russia            |
| Albert        | Canada            || Albert        | Canada            |
| Jack          | New York          || Jack          | New York          |
+---------------+-------------------++---------------+-------------------+

But instead of the above I got this:
+---------------+-------------------+---------------+-------------------+
| employee_name | employee_location | employee_name | employee_location |
+---------------+-------------------+---------------+-------------------+
| Joe           | New York          | Joe           | New York          |
| Jack          | New York          | Joe           | New York          |
| Sunil         | India             | Sunil         | India             |
| Alex          | Russia            | Alex          | Russia            |
| Albert        | Canada            | Albert        | Canada            |
| Joe           | New York          | Jack          | New York          |
| Jack          | New York          | Jack          | New York          |
+---------------+-------------------+---------------+-------------------+

It works fine for Sunil, Alex and Albert. The combinations of Joe and Jack I do not understand. Can someone explain in detail how this works aside from the solution? I would like to understand the logic behind this result.

A: Each of the New York rows from t1 matches against two rows in t2 since all you're requiring is that the cities be the same. So you get 2 x 2 total matches (pairs) for New York. If you added a third New York then you'd get 9 rows.
To see the behavior you're expecting try adding and t1.employee_name = t2.employee.name. You can't uniquely identify all people by location alone even though with most of them you can and so your result appears to almost work.

A: The answer lies in within the "where" statement:
where t1.employee_location = t2.employee_location
Joe and Jack both match New York so are multiplied.
You can see this better by adding another New York entry and re-running. You will get 9 New York results.
To get what you expected you would need to add "and where t1.employee_name = t2.employee_name.


text:
Q: How to determine whether a polynomial has roots modulo a prime?
How to determine if a polynomial has roots modulo a prime?

I was attempting to find solutions to this polynomial $x^3+x^2-4\equiv 0$ mod($7$)
The only method I currently know to determine solutions is to try every element in the complete residue system. There are none.
However given $x^3+x^2-4\equiv 0$ mod($10007$), ($10007$ is a prime)
I would have no idea how to find roots of this polynomial or if they even exist.

A: One way to count the solutions for $f(x)\equiv0\pmod p$ (where $p$ is prime) is to compute the gcd of $f(x)$ and $x^p-x$ over the field $\Bbb F_p$ of $p$
elements. This gcd is $g(x)=\prod_{a\in R}(x-a)$ where $R$ is the set of roots of $f$ in $\Bbb F_p$.
This may seem daunting if $p$ is large. But as long as $f$ has small degree
one can start by reducing $x^p-x$ modulo $f(x)$ over $\Bbb F_p$. Doing the
$x^p$ modulo $f(x)$ is just like computing $a^k$ modulo $m$ for large $m$
and can be done by the binary powering algorithm.


text:
Q: React Native fetch for HTTP2 endpoint can not get body I use React Native fetch to POST to endpoint which is AWS Lambda. By default it's HTTP/2. That works perfectly fine with curl:
% curl -X POST https://yyyyyy.execute-api.eu-central-1.amazonaws.com/Test/stripe_payment -H "x-api-key: xxxxx"
% {"errorCode": "OK", "client_secret": "zzzz"}

But the same from react native:
    try {
      response = await fetch(`${API_URL}/stripe_payment`, {
        method: 'POST',
        headers: {
          'x-api-key': API_KEY,
        },
      });
    }
    catch (error) {
      console.error(error);
    }

    console.log('API response', response);

Returns only Lambda headers, not body:
API response {"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "dce744f2-6755-47e0-9a9d-74921ae64eba", "offset": 0, "size": 100}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "dce744f2-6755-47e0-9a9d-74921ae64eba", "offset": 0, "size": 100}}, "bodyUsed": false, "headers": {"map": {"content-length": "100", "content-type": "application/json", "date": "Fri, 11 Nov 2022 19:33:22 GMT", "x-amz-apigw-id": "bc58SFhsFiAFp1A=", "x-amzn-requestid": "fc157dbb-72d2-459e-a391-1ece0ff9680f", "x-amzn-trace-id": "Root=1-636ea381-0c40c8ec31bb9c4f52d0e44b;Sampled=0"}}, "ok": true, "status": 200, "statusText": "", "type": "default", "url": "https://yyyyyy.execute-api.eu-central-1.amazonaws.com/Test/stripe_payment"}

Above response is correct, but it contains only headers, no body.
I do suspect that is because of HTTP/2 binary protocol, looking at some discussions looks like react native did not support it correctly in the past.
Any hints ?
Thanks,
Mark

A: ok, looks like i have found the answer: https://github.com/facebook/react-native/issues/24520


text:
Q: Android Virtual Device getting crashed after applying Validation to a Form I am working on a Login activity and Submit form activity. After applying validation to submit form I came across few runtime errors like...

*

*Duplicate class android.support.v4.app.INotificationSideChannel found in modules

*Duplicate class com.google.common.util.concurrent.ListenableFuture found in modules jetified-guava-26.0-android (com.google.guava:guava:26.0-android) and jetified-listenablefuture-1.0 (com.google.guava:listenablefuture:1.0)

I found its solution and added.....

*

*implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava' --- in build.gradle file

*android.enableJetifier=true --- in gradle.properties file

This solve the runtime errors but after running app it is getting crashed.
What could be possible solution to this?


text:
Q: Calculating divergence of function containing mollyfier Let $(\phi_\alpha)_{\alpha>0}$ be a familiy of mollyfiers, $\phi_\alpha:\mathbb{R}^n \rightarrow \mathbb{R}$ defined as:
\begin{align}
\phi_1(x)=\left\{\begin{array}{rcl}
 c \cdot exp(\frac{-1}{1-\vert x\vert^2}) &,& \vert x \vert < 1\\
 0 &,& \text{otherwise}
 \end{array}\right.
\end{align}
with $c>0$ such that $\int_{R^n} \phi_1(x) dx=1$ and $\phi_\alpha(x)=\alpha^{-n} \phi_1(x/\alpha)$
Consider the function $w(x)=(y_1-y_2) \int_0^1 \phi_\epsilon(x-y_1+t(y_1-y_2)) ~dt$ with $y_1,y_2 \in \mathbb{R}^n $ and calculate its divergence
$div~ w(x)= \sum_{i=1}^n \frac {\partial w_i(x)}{\partial x_i}.$
The result should be
$div ~w(x) = \phi_\epsilon(x-y_2)-\phi_\epsilon(x-y_1)$.
How do I calculate the divergence in this case? So far I tried to use the fundamental theorem of calculus, however the result was not the same.

A: If $v$ is a constant vector and $f$ a function, then $\mathrm{div} \,(vf)=v\cdot \nabla f$. Applying this to $f=w$ and $v=y_1-y_2$, you have to differentiate under the integral sign and get
$$
\mathrm{div}\, w = \int_0^1 (y_1-y_2)\cdot \nabla \phi_\epsilon(x-y_1+t(y_1-y_2))\, dt
$$
Now you just need to note that the integrand is equal to
$$
\frac{d}{dt}\phi_\epsilon(x-y_1+t(y_1-y_2))
$$
and then your claim follows from the fundamental theorem of calculus.


text:
Q: How to return missing rows from LEFT JOIN in BigQuery How can we get BigQuery to return the rows in a LEFT JOIN which exist in TABLE A but are NULL in TABLE B?
-- find missing users. return rows which exist in A but not in B
select          a.user_id
from            database_a a
left outer join database_b b on a.user_id = b.user_id
where           b.user_id is null

A: Your query should work fine, but there's another approach which is slightly more specific and, at least in some RDBMS, slightly better perfoming:
SELECT
    user_id
FROM
    database_a.users AS A
WHERE
    NOT EXISTS (SELECT * FROM database_b.users AS B WHERE A.user_id = B.user_id);

Note that the database does not actually retrieve any records from B, so this is one rare case where SELECT * is legitimate.  You could just make it SELECT TRUE or something as well.


text:
Q: Filter against an array condition Let's say I have an array of userIds
const userIds = ['1234', '3212', '1122']

And then I have an array of objects
const arrayOfObjects = [
  {
    _source: {itemId: ['1234'] }
  },
  {
    _source: {itemId: ['3212'] }
  },
  {
    _source: {itemId: ['1111'] }
  }
]

I want to filter my array of objects by matching ids to the userIds array
arrayOfObjects.filter(item => item._source.itemId === "what goes here?")

A: Try this
arrayOfObjects.filter(item => userIds.includes(item._source.itemId[0]))

A: Array.prototype.includes isn't supported by Internet Explorer. If you want a cross browser solution you could use Array.prototype.filter and Array.prototype.indexOf methods:

const userIds = ['1234', '3212', '1122'];
const arrayOfObjects = [{
    _source: {
      itemId: ['1234']
    }
  },
  {
    _source: {
      itemId: ['3212']
    }
  },
  {
    _source: {
      itemId: ['1111']
    }
  }
];

const filtered = arrayOfObjects.filter(o => userIds.indexOf(o['_source'].itemId[0]) > -1);

console.log(filtered)


text: Q: I can't edit my posts I am able to sign in to my site and it shows my posts. When I open one of them it looks okay. Above the content is the usual links including "edit" but when I click edit it says it cannot find my site


text:
Q: Select Distinct on Inner Join Query filtering by multiple values on a single column? So, i have to say, SQL is by far my weakest side as a developer. Perhaps what i'm trying to accomplish is pretty easy. I have something like this (It's not the real model, but in order to make it simple to understand without wasting too much time explaining it, i've come up with an example that mimics exactly the table relations i have to use).
On one hand, a table, let's call it, "Users". Columns such as a primary key "UserId", "UserName", and so on.
Next, another Table, "Licenses". Relates 1:N with user, each license belongs to a single user, a user may have multiple licenses. So, we'd have a PK IdLicense, a FK IdUser, and so on.
Next, a table called "Equipments". here we have defined different equipments. IdEquipment, EquipmentName. Not much more to say about it.
Lastly, a table that creates a N:M relation between "Licenses" and "Equipments". when a user defines a license, they can specify the different equipments that licence allows them to manipulate. So, a license can relate to several equipments, and a piece of equipment can relate to multiple licenses.
The real deal comes here. I've been ordered to implement some kind of search system that allows you to get users based on the equipment they are qualified to handle.It's possible to make a multiple selection, so that you search for users that are qualified to handle equipment "A", "B" and "C". For example, we have 2 users, James and, Dave. James has 2 licenses, Dave has one. James is qualified to use machines "A" and "D" on his first license, "B" and "C" on the second one. Dave is qualififed to handle equipment type "B" and "C" on his only license. If someone tries to search for users being able to handle equipment "A","B" AND "C", only James would be the returning record.
So far i assumed i'd have to do something like
SELECT DISTINCT IdUser
FROM  Users
INNER JOIN Licenses
   ON Licenses.IdUser = Users.idUser
INNER JOIN LicensesEquipments
   ON LicensesEquipments.IdLicense = Licenses.IdLicense
INNER JOIN Equipment
   ON Equipment.IdEquipment = LicensesEquipments.IdEquipment

WHERE Equipment.IdEquipment = ??

How can i filter this on the all 3 different idEquipments for "A" "B" and "C".?
Obviously, i can't make
WHERE Equipment.IdEquipment = 1 and Equipment.IdEquipment = 2 since a cell can't be equal to 2 different values.
Neither i can do
WHERE Equipment.IdEquipment = 1 or Equipment.IdEquipment = 2 since using an OR would mean that any user holding at least ONE of the possibilities would be considered a valid result, and i'm looking for one that has ALL 3 different equipments on this case.
At first I assumed I'd have to create multiple inner joins with the table equipment, using alias, doing it as many times as filters on equipment i may have, and using each alias with a different filter. But then my code supervisor came by and told me to forget about it, since he said that would render too costly as more and more filters where added (though he gave me no better alternative...)

A: SELECT Users.idUser
FROM Users
INNER JOIN Licenses ON Licenses.IdUser = Users.idUser
INNER JOIN LicensesEquipments ON LicensesEquipments.IdLicense = Licenses.IdLicense
INNER JOIN Equipment ON Equipment.IdEquipment = LicensesEquipments.IdEquipment
WHERE Equipment.IdEquipment IN ('A', 'B', 'C')
GROUP BY IdUser
HAVING COUNT(DISTINCT Equipment.IdEquipment) = 3 <--must be # of unique items in IN clause

If you really just need the user ID, you can drop the Users and Licenses tables from your query:
SELECT Licenses.IdUser
FROM Licenses
INNER JOIN LicensesEquipments ON LicensesEquipments.IdLicense = Licenses.IdLicense
WHERE LicensesEquipments.IdEquipment in ('A', 'B', 'C')
GROUP BY Licenses.IdUser
HAVING COUNT(DISTINCT LicensesEquipments.IdEquipment) = 3

Also, some aliases makes it easier to read:
SELECT l.IdUser
FROM Licenses l
INNER JOIN LicensesEquipments le ON le.IdLicense = l.IdLicense
WHERE le.IdEquipment in ('A', 'B', 'C')
GROUP BY l.IdUser
HAVING COUNT(DISTINCT le.IdEquipment) = 3

A: SELECT l.IdUser
FROM Licenses l
INNER JOIN LicensesEquipments le ON le.IdLicense = l.IdLicense
WHERE le.IdEquipment in (`enter code here`'A', 'B', 'C')
GROUP BY l.IdUser
HAVING COUNT(DISTINCT le.IdEquipment) = 3


text:
Q: How to add devices to provisioning profile for sharing to Diawi I need to archive a build of my iOS app for distribution on Diawi.
I need to add the UDIDs of the testers to my provisioning profile first and I am afraid of messing up the current provisioning profile which are working for the app.
First I just want to check if these steps are still valid for what I would like to do:

First add the device udid in devices list by clicking on '+' button
  in the devices list.
Then, after adding device udid, go to the provisioning profile list.
  There, select the provisioning profile to which you want to add the
  device.
Afterwards, you get an edit option that you want to use for adding the
  new UDID, which you previously added to the devices list. You find
  this option at the bottom.

I found these steps at this answer (2013) but I think they may have been when Apple were still adding devices with UDIDs (whereas now it is done via apple ID (email): How to add new Device UDID to an existing provisioning profile in the new pattern
Secondly, after I click add device in my apple developer account, they are asking for the device name. I only have the UDID of the testers phones - do I need their phones name also?


text:
Q: If a differential operator $C$ factors as $AB$, then every solution of $C(y)=0$ has the form $y=y_1+y_2$ with $A(y_1)=0$ and $B(y_2)=0$ Given two constant-coefficient operators $A$ and $B$ whose characteristic polynomials have no zeros in common. Let $C = A B$. First part of question is

Prove that every solution of the differential equation $C(y)=0$ has the form $y=y_1+y_2$, where $A(y_1)=0$ and $B(y_2)=0$.

I proved this part using the fact that they do not have zeros in common. solution of $A$ can not be a solution of $B$ and therefore $y_1$ and $y_2$ are independent for every $y_1$ and $y_2$
Second part is

Prove that the functions $y_1$ and $y_2$ are uniquely determined. That is, there is only one pair $y_1$, $y_2$.

I don't really understand second part.
Please help me..

A: Since you mention characteristic polynomials for a constant coefficient differential equation, the underlying DE is linear. But then a constant multiple of a solution is again a solution, so $A(y_1)=0\implies A(ky_1)=0$ for any $k$ (and similarly for $B$ with $y_2$). So I'm not buying the uniqueness statement (at least as stated).


text:
Q: android in app billing using version 3 - onIabPurchaseFinished never invoked Have looked at this link :
onIabPurchaseFinished never called.
     and ....
I have looked at the following link in so - which is the exact issue that I am facing :
IabHelper PurchaseFinishedListener
The issue stated by 'kevinl' in one of the answers in the above second link - is the issue I have i.e.
I have the 'onActivityResult' coded in my activity
The control does come into this method - but yet - it does not go to - onIabPurchaseFinished
I am invoking the Purchase flow as below:
public void onClickIap(View v) {

    if(isAlreadyPurchased){
        Log.d(TAG, "In onClickIap >>> The app is purchased ");
    }else{
        Log.d(TAG, "In onClickIap >>> The app is NOT purchased: ");

        /** we need to check if this item was purchased from google store details **/
        /** makes synchronous call -return control to callback method in listener **/
        /** this is the heart of in app - where all the activity starts **/
        mHelper.launchPurchaseFlow(this, ITEM_SKU_TEST_4, 10001,mPurchaseFinishedListener, "mypurchasetoken");

        mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
            public void onIabPurchaseFinished(IabResult result, Purchase purchase){
                Log.d(TAG, "In onIabPurchaseFinished  ");
                if (result.isFailure()) {
                    Log.d(TAG, "In onIabPurchaseFinished  >>> purchase error ");
                    return;
                }else if (purchase.getSku().equals(ITEM_SKU_TEST_4)) {
                    Log.d(TAG, "In onIabPurchaseFinished  purchase success ");

                    /**TODO update the db **/
                    DbClass dbDbClass = new DbClass(getApplicationContext());
                    dbHelper.updatePurchasedQuiz(2);
                    /** set the flag **/
                    isAlreadyPurchased = true;

                    Log.d(TAG, "The app after all the shebang: ");
                    Intent intent = new Intent(getApplicationContext(),ExamActivity.class);
                    intent.putExtra("quizId", "2");
                    startActivity(intent);
                }else{
                    Log.d(TAG, " ");
                    Log.d(TAG, "In onIabPurchaseFinished  in a weird condition  ");
                }
            }
        };
    }
}

My implementation of onActivityResult ( where I can see the debug logs )
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d(TAG, " ");
    Log.d(TAG, "<<<<<< in IAP ONACTIVITYRESULT >>>>>>");
    Log.d(TAG, "onActivityResult " + requestCode + "," + resultCode + "," + data);
    if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

Dont know if this would be the cause but the way I am invoking / initiatlizing the mHelper is :

1 In my activity onCreate - I start a thread ( AsyncTask )
  2 In the method - doInBackground - I am initializing this helper :

mHelper = new IabHelper(ExamHomeActivity.this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { .... }

3 Then when this async task completes - I show some buttons on the screen
  4 Clicking on any button invokes the method described above - onClickIap

Thanks
shankar

A: You are passing the mPurchaseFinishedListener before you have initialized it (which happens right after you call launchPurchaseFlow).
Also, initializing the listener in the onClick is not a very good idea. You will be doing this every time the button is pressed. Take that out from the onClickIap() method.
You can do that statically in your Activity, just like it is done in Google's sample app Trivial Drive:
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
            public void onIabPurchaseFinished(IabResult result, Purchase purchase){
                Log.d(TAG, "In onIabPurchaseFinished  ");
                ...
                ...
                ...
            }
        };

Initializing the IabHelper is probably best to be done in the onCreate() of the activity:
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subscribe);

        mHelper = new IabHelper(this);
}

Then do not forget to dispose of it in onDestory():
 @Override
    protected void onDestroy() {
        super.onDestroy();
        // very important:
        if (mHelper != null) {
            mHelper.dispose();
            mHelper = null;
        }
    }

Also, there is no need to set up the IabHelper from a background thread. Just call mHelper.startSetup from your UI thread whenever you are ready.


text:
Q: Why my own created apache config file is not showing colorful text for directive keywords with vim I have centoS operating system.
I am creating my own apache config file like /usr/local/apache/conf/my.conf
There are more files like httpd.conf and php.conf in that directory
Now when i see those files then keywords of apache directives like LoadModule are shown in different colors. But in my created conf file tey show like normal text.
Why is that

A: Here's the relevant part from my (unmodified) filetype.vim:
" Apache config file
au BufNewFile,BufRead .htaccess,/etc/httpd/*.conf        setf apache
au BufNewFile,BufRead httpd.conf*,srm.conf*,access.conf*,apache.conf*,apache2.conf*,/etc/apache2/*.conf*,/etc/httpd/conf.d/*.conf* call s:StarSetf('apache')

As you can see, it only matches specific .conf files such as httpd.conf, and .conf files in particular directories. This is because Apache is not the only software that uses .conf files.
You can either add an autocommand for your own .conf file, or if this is just a one-off, run :setf apache.

A: You could use a modeline in the top or bottom 5 lines of your config files:
# vim: set filetype=apache:

See ":help modeline".


text:
Q: Excel selective increment Hi I'm trying to write a script in excel that returns a correlating job serial number (which resides on a different sheet) when a cell is filled with the job name.
=IF(D5="Misc",Jobs!A2,IF(D5=1715,Jobs!A3,IF(D5=1725,Jobs!A4,IF(D5=5640,Jobs!A5,IF(D5=6121,Jobs!A7,IF(D5=6150,Jobs!A8,IF(D5="6161-IDC",Jobs!A10,IF(D5="6161-JM",Jobs!A11,IF(D5=6161,Jobs!A12,IF(D5=6535,Jobs!A14,IF(D5="Hudson",Jobs!A14,IF(D5="Berendo",Jobs!A15,IF(D5="Berendo-Move",Jobs!A16,IF(D5="Bungalos",Jobs!A17,IF(D5="Bungalo",Jobs!A17,IF(D5="Camarillo",Jobs!A18,IF(D5="Indio",Jobs!A19,IF(D5="Lillian",Jobs!A20,IF(D5="6161-Beam",Jobs!A21,IF(D5="6161-Roof",Jobs!A22))))))))))))))))))))
The above script does what I need it to do, the problem is I need it copied to 30+ rows with ONLY the "D5" value incrementing. When I hover in the cell corner and drag down to new cells it increments other references besides the "D5" value.
I did a search and replace and manually copied the script to each of the 30 cells to get it functional for now but I'm going to have to do that every time I add a job. I'd like to just add the new job condition and use the fill handle to drag it to all cells, I feel like I need an escape character though to limit what cells are being incremented, I'm just not sure what that would be (it's always going to be column "D", I just need the row incremented to "d6, d7," etc)- thank you in advance for your help!

A: Seems a case sensitive replacement of A$ for A may be adequate:
=IF(D5="Misc",Jobs!A$2,IF(D5=1715,Jobs!A$3,IF(D5=1725,Jobs!A$4,IF(D5=5640,Jobs!A$5,IF(D5=6121,Jobs!A$7,IF(D5=6150,Jobs!A$8,IF(D5="6161-IDC",Jobs!A$10,IF(D5="6161-JM",Jobs!A$11,IF(D5=6161,Jobs!A$12,IF(D5=6535,Jobs!A$14,IF(D5="Hudson",Jobs!A$14,IF(D5="Berendo",Jobs!A$15,IF(D5="Berendo-Move",Jobs!A$16,IF(D5="Bungalos",Jobs!A$17,IF(D5="Bungalo",Jobs!A$17,IF(D5="Camarillo",Jobs!A$18,IF(D5="Indio",Jobs!A$19,IF(D5="Lillian",Jobs!A$20,IF(D5="6161-Beam",Jobs!A$21,IF(D5="6161-Roof",Jobs!A$22))))))))))))))))))))


text:
Q: Using SammyJS with requireJS to route Modules Im just wondering if anyone has setup SammyJS with requireJS to route creation of modules depending on the provided hash address?
Is it possible? Advice?
Thanks

A: In BoilerplateJS we have used crossroads.js to implement creation of modules depending on the provided hash address. This is the router which we use to implement that.
I believe sammyJS can be used in a similar manner.


text:
Q: Combining Blocking and NonBlocking in Verilog If I want statements to happen in parallel and another statement to happen when all other statements are done with, for example:
task read;
 begin
    if (de_if==NOP) begin
        dp_op    <= 3'b000;
        dp_phase =  EXEC;
    end
    else begin
        if (de_if==EXEC_THEN) begin
            dp_const <= de_src3[0];
            dp_src   <= de_src3;
            dp_op    <= {NOP,de_ctrl3};
            dp_dest  <= de_dest1;
        end
        else if (get_value(de_ctrl1,de_src1)==dp_mem[de_src2]) begin
            dp_const <= de_src3[0];
            dp_src   <= de_src3;
            dp_op    <= {NOP,de_ctrl3};
            dp_dest  <= de_dest1;
        end
        else begin
            dp_const <= de_src4[0];
            dp_src   <= de_src4;
            dp_op    <= {NOP,de_ctrl4};
            dp_dest  <= de_dest2;
        end
        #1 dp_phase=READ;
    end
 end
endtask

In this code I want the statement dp_phase = READ to only be executed after all other assignments are done, how do I do it?
As you can see what I did is wait 1 clock before the assignment but i do not know if this is how its done ...

A: You need a state machine. That's the canonical way to make things happen in a certain sequence. Try to remember that using a hardware description language is not like a regular programming language...you are just describing the kind of behavior that you would like the hardware to have.
To make a state machine you will need a state register, one or more flip-flops that keep track of where you are in the desired sequence of events. The flip-flops should be updated on the rising clock edge but the rest of your logic can be purely combinational.


text:
Q: Mean value theorem of integrals
Let $f: [1, 2] \rightarrow \mathbb{R}$ be an integrable function. Let $\bar{f} \in \mathbb{R}$ be the mean of the integral. So $$\bar{f} = \frac{1}{b-a} \int_{a}^{b} f(t) dt$$
Show that $$\int_{a}^{b} (f(x)-\bar{f}) dx = 0$$

How should one approach this? I know from the Fundamental theorem of calculus that we can express $\frac{1}{b-a} \int_{a}^{b} f(t) dt$ as $\frac{F(b)-F(a)}{b-a}$, but does that help us here?

A: $$\int_a^b(f(x)-\overline{f})\mathrm{d}x = \int_a^bf(x)\mathrm{d}x-\int_a^b\overline{f}\mathrm{d}x$$
$$ = (b-a)\overline{f}-\overline{f}(b-a)$$
$$=0$$

A: Note that, as you wrote
$$\bar f=\frac1{b-a}\int_a^b f(x)dx=\frac{F(b)-F(a)}{b-a}$$
So $\bar f$ is a constant, then
$$\int_a^b\left(f(x)-\bar f\right)dx$$
$$\int_a^b f(x)dx -\int_a^b\bar fdx$$
$$\int_a^b f(x)dx -\int_a^b\frac{F(b)-F(a)}{b-a}dx$$
$$\int_a^b f(x)dx -\frac{F(b)-F(a)}{b-a}\int_a^b dx$$
$$(F(b)-F(a)) -\frac{F(b)-F(a)}{b-a}(b-a)$$
$$(F(b)-F(a)) -(F(b)-F(a))$$
$$0$$


text:
Q: scikit learn on jupyter notebook
I tried to run something on jupyter notebook and I got this problem.
 does anyone know how to solve it?

A: You are trying to load the dataset without having imported it first.
You need to import sklearn datasets.

Use this:
from sklearn.datasets import load_breast_cancer

data = load_breast_cancer()

This should work fine.


text:
Q: allowing dropdown to overflow outside of div and extend as far as it needs I am using the react-multi-carousel library in conjuction with the react select library like this:
import Carousel from "react-multi-carousel";
import "react-multi-carousel/lib/styles.css";

        <Carousel
          swipeable={false}
          draggable={false}
          showDots={true}
          responsive={responsive}
          ssr={true} // means to render carousel on server-side.
          infinite={true}
          autoPlaySpeed={1000}
          keyBoardControl={true}
          customTransition="all .5"
          transitionDuration={500}
          containerClass="carousel-container"
          removeArrowOnDeviceType={["tablet", "mobile"]}
          dotListClass="custom-dot-list-style"
          itemClass="carousel-item-padding-40-px"
          centerMode={true}
          renderDotsOutside={true}
          >
          {dmtfs.map((fl) =>
{(ivrDests.length !== 0) && <StoryCarouselItem key={fl.value} dest_id={fl.value} ivr_dests={ivrDests} options={props.options} />}
)}

        </Carousel>

StoryCarouselItem rendering:
  return (

                {dtmf}

            {name}

            <Select styles={customStyles}
                    options={props.options}
                    placeholder={IVRSound}
                    value={selectedIVROption}
                    onChange={updateIVR}
            />

The code above works fine and looks good before dropping down as you can see below:
Carousel
However, when I click the dropdown, it does not overflow outside of the div and spill into other sections to reveal the whole dropdown like I want it to. Instead, it gets caught within the dropdown and only shows a little bit.
Example:
Carousel 2
Any idea how I can change the styling to accommodate this change?
Here's the relevant styling I have right now:
.StorySelection{
    color: #392F5A;
    font-family: 'Poppins';
    font-weight: 700;
    font-size: 20px;
    margin-top: 5%;
}
.StoryCarousel{
    margin-top: 5%;
    padding-bottom: 10%;
    padding-left: 5%;
    padding-right: 5%;
}
.StoryCarouselBorder{
    background: #fff;
    border-style: solid;
    border-color: #ABABAB;
    border-width: 10px;
    padding-top: 2.3%;
    padding-bottom: 1.3%;
}
.StoryCarouselItem{
    height: 20%;
    width: 75%;
    margin-top: 5%;
    background: #392F5A;
}

.StoryCarouselItemCounter {

    margin-top: 10%;
    height: 60px;
    width: 60px;
    background-color: #EEC8E0;
    border-radius: 50%;
    display: inline-block;
}

.StoryCarouselItemCounterText{
    color: #fff;
    font-size: 24px;
    text-align: center;
    margin-top: 20%;
}

.StoryCarouselItemName {
    color: #fff;
    margin-top: 8%;
}
.StoryDropdown{
    padding-bottom: 10%;
    z-index: 20;
    overflow: visible;
}

.react-multi-carousel-dot-list {
    position: static !important;
    margin-top: 1% !important;
    margin-bottom: 0 !important;
}

A: Use the menuPortalTaget prop to portal the menu. This will allow it to overflow outside of the div. Other than that you may require a custom MenuList component to adjust the listing styling.


text:
Q: PHP - File Streaming problem I have a website that has a downloads section.  I need for the files not to be accessed directly by an annonymous user, so I am putting them in a directory not accessable to users, but is accessible to the web server.  When the user clicks the link to download the file, I need it to redirect to a download page that will stream the file to the user without him knowing the location of the directory or the file and it will ask him to save it to his computer.  I found the following code on a previous post, but I can't get it to work correctly.  Could be that I don't know the correct names of the variables that it wants to be passed to it.  Please include an explanation of how to use your code.
$filename='Firefox%20Setup%203.6.13.exe';
$file_path='http://ftp.byfly.by/pub/mozilla.org/firefox/releases/3.6.13/win32/fr';
$file= $file_path."/".$filename;
$len=filesize($file);
header("content-type: application/save");
header("content-length: $len");
header("content-disposition: attachment; filename=$filename");
$fp=fopen($file, "r");
fpassthru($fp);

A: This is how I would do it.
<?php

function getFile($file_location) {
    header('Content-Description: File Transfer');
    header('Content-type: application/exe');
    header('Content-Disposition: attachment; filename="supercoolFF.exe"');
    header('Content-Transfer-Encoding: binary');
    ob_end_clean();
    $url_info = parse_url($file_location);
    if (!isset($url_info['query'])) $url_info['query'] = '';
    $http = fsockopen($url_info['host'],$url_info['port']);
    $req = "GET " . $url_info['path'] . "?" . $url_info['query'] . " HTTP/1.1\r\n";
    $req .= "Host: " . $url_info['host'] . ":" . $url_info['port'] . "\r\n";
    $req .= "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
    $req .= "User-Agent  Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8\r\n";
    $req .= "Accept-Language: en-us,en;q=0.5\r\n";
    $req .= "Accept-Encoding: gzip,deflate\r\n";
    $req .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
    if ($len = strlen($url_info['query']) {
        $req .= 'Content-Length: ' . $len . "\r\n";
        $req .= "Connection: Close\r\n\r\n";
        $req .= $query . "\r\n\r\n";
    } else {
        $req .= "Connection: Keep-Alive\r\n\r\n";
    }
    fputs($http, $req);

    $content = "";
    $content_encountered = FALSE;
    ob_end_clean();
    while(strlen($part = fgets($http, 4096))) {
        if ($content_encountered) {
            echo $part;
            $content .= $part;
        }
        if ($part == "\r\n") {
            $content_encountered = TRUE;
        }
    }
    fclose($http);
    exit;
}

$filename='Firefox%20Setup%203.6.13.exe?';
$file_path='http://ftp.byfly.by:80/pub/mozilla.org/firefox/releases/3.6.13/win32/fr';

getFile($file_path . '/' . $filename);

Of course, it would be better to do a HEAD request first to get the filesize and include a Content-Length header in the response so the user can have some idea about how long it is going to take.  Or, you can hardcode that number, if you are always going to be serving up the same file.

A: Let's say you have a file in a directory called "hiddenaccess" and the file name is "test.mp3" you can load the path in php variable and let it for download
<?php
$file = "./hiddenaccess/test.mp3";
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));

@readfile($file);

?>

Note: Do NOT have any other echo or print statements in this file.

A: Here's a function I (Apparently Others?!!?) developed to do just that, it's a meaty function but it checks and does everything.  To call it is simple though, the important part.  I have this inside a class but you can just make it a php function as there is no other class functions it depends on.  Hope this helps you.
   public static function output_file($path, $filename, $mime_type='') {

    $err = 'Sorry, the file you are requesting is unavailable.';

    $filename = rawurldecode($filename);

    // check that file exists and is readable
    if (file_exists($path) && is_readable($path)) {

        /* Figure out the MIME type (if not specified) */
        $known_mime_types=array(
         "pdf" => "application/pdf",
         "txt" => "text/plain",
         "html" => "text/html",
         "htm" => "text/html",
         "exe" => "application/octet-stream",
         "zip" => "application/zip",
         "doc" => "application/msword",
         "xls" => "application/vnd.ms-excel",
         "ppt" => "application/vnd.ms-powerpoint",
         "gif" => "image/gif",
         "png" => "image/png",
         "jpeg"=> "image/jpg",
         "jpg" =>  "image/jpg",
         "php" => "text/plain"
        );

        if($mime_type==''){
            $file_extension = strtolower(substr(strrchr($filename,"."),1));
            if(array_key_exists($file_extension, $known_mime_types)){
             $mime_type=$known_mime_types[$file_extension];
            } else {
             $mime_type="application/force-download";
            };
        };

        @ob_end_clean(); //turn off output buffering to decrease cpu usage

        if(ini_get('zlib.output_compression')) { //otherwise the filesize is way off
            ini_set('zlib.output_compression', 'Off');
        }

        // get the file size and send the http headers
        $size = filesize($path);
        header("Content-Type: $mime_type");
        header('Content-Disposition: attachment; filename="'.$filename.'"');
        header('Content-Transfer-Encoding: binary');
        header('Accept-Ranges: bytes');
        header('Cache-control: private');
        header('Pragma: private');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

        // multipart-download and download resuming support
        if(isset($_SERVER['HTTP_RANGE'])) {

            list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2);
            list($range) = explode(",", $range, 2);
            list($range, $range_end) = explode("-", $range);

            $range=intval($range);

            if(!$range_end) {
                $range_end = $size-1;
            } else {
                $range_end = intval($range_end);
            }

            $new_length = $range_end-$range+1;

            header("HTTP/1.1 206 Partial Content");
            header("Content-Length: $new_length");
            header("Content-Range: bytes $range-$range_end/$size");
        } else {
            $new_length = $size;
            header("Content-Length: " . $size);
        }

        /* output the file itself */
        $chunksize = 1*(1024*1024); //may want to change this
        $bytes_send = 0;

        if ($file = fopen($path, 'r')) {
            if(isset($_SERVER['HTTP_RANGE'])) {
                fseek($file, $range);
            }

            while(!feof($file) && (!connection_aborted()) && ($bytes_send<$new_length)) {
                $buffer = fread($file, $chunksize);
                print($buffer); //echo($buffer); // is also possible
                flush();
                $bytes_send += strlen($buffer);
            }

            fclose($file);

        } else {
            die($err);
        }

    } else {

        die($err);

    }

    die();
}

To use it would be something like this.
$path = '/var/www/site/httpdocs/upload/private/myfile.txt';
$dl_filename = 'NDA_'.time();
$mime_type = 'doc';
output_file($path,$dl_filename,$mime_type);


text:
Q: D/InMobiBanner: Ad request successful but no ad served keep on getting integrating inmobi with admob
D/InMobiBanner: Ad request successful but no ad served.
works OK if test mode is turned on for inmobi placement.

A: Hi if the Ad Server doesn't have an ad for the user then it will return with no-fill in that case you can see this message. On the dashboard, you can find out a number of requests made and number of ads filled.


text:
Q: Deleting with NOT EXISTS vs NOT IN gives different results I'm working with an older schema, and don't understand why my delete operation (to clear out orphan records) doesn't work as expected in some cases.  In others both of the queries return identical results :-/
For example, I have 3 models: house, office, and address.  house and office both have a nullable reference to an address.id, so an address record can belong to either of them but the address itself doesn't indicate which.
-- query 1
DELETE FROM address adr
WHERE
  NOT EXISTS(SELECT * FROM house  H WHERE H.address_id = adr.id) AND
  NOT EXISTS(SELECT * FROM office O WHERE O.address_id = adr.id);

-- query 2
DELETE FROM address adr
WHERE
  NOT adr.id IN (select address_id from house) AND
  NOT adr.id IN (select address_id from office);

query 1: deletes 3000 records (correct)
query 2: deletes 0 records
What is the obvious problem with query #2?  When I check the records deleted by #1 they really do not exist in either house or office.

A: Your address_id columns contain nulls, and thus you got caught by the three-valued logic of SQL.
https://www.postgresql.org/docs/current/static/functions-subquery.html#functions-subquery-in describes the behaviour of IN:

Note that if the left-hand expression yields null, or if there are no equal right-hand values and at least one right-hand row yields null, the result of the IN construct will be null, not false. This is in accordance with SQL's normal rules for Boolean combinations of null values.

And of course NOT applied to null is null, not true, see https://www.postgresql.org/docs/current/static/functions-logical.html

A: Well, I hate having to do this, but I figured it out.  Its all about the NULLs.
In query 2 I needed to add where address_id is not NULL to each subquery.  Those nulls screw up the matching when the value does not exist, though I've never been clear exactly why.
Corrected query:
-- query 2
DELETE FROM address adr
WHERE
  NOT adr.id IN (select address_id from house where address_id is not NULL) AND
  NOT adr.id IN (select address_id from office where address_id is not NULL);


text:
Q: Is it good practice to implement virtual methods using multiple inheritance? I have:
class A {
    virtual void foo() = 0;
    virtual void bar() = 0;
};

class Fooing {
    virtual void foo() = 0;
};

class Barring {
    virtual void bar() = 0;
};

class TallFooing : public Fooing {
    void foo(){ std::cout << "tall foo" << std::endl; }
};

class ShortFooing : public Fooing {
    void foo(){ std::cout << "short foo" << std::endl; }
};

class BlueBarring : public Barring {
    void bar() { std::cout << "blue bar" << std::endl; }
};

class RedBarring : public Barring {
    void bar() { std::cout << "red bar" << std::endl; }
};

template <typename S, typename T>
class B : public A, public S, public T { };

int main() {
    A* a1 = new B<TallFooing, RedBarring>();
    A* a2 = new B<ShortFooing, BlueBarring>();

    a1->foo(); a1->bar();
    a1->foo(); a2->bar();
};

Is mixing in the Barring classes a "Good Idea" (TM)?  Am I doing it right? If not, can you suggest alternatives/improvements for doing the same?
Also, what about the following:
class Fooing {
    virtual void foo() = 0;
};

class Barring {
    virtual void bar() = 0;
};
class A : public virtual Fooing, public virtual Barring { };

class TallFooing : public Fooing {
    void foo(){ std::cout << "tall foo" << std::endl; }
};

class ShortFooing : public Fooing {
    void foo(){ std::cout << "short foo" << std::endl; }
};

class BlueBarring : public Barring {
    void bar() { std::cout << "blue bar" << std::endl; }
};

class RedBarring : public Barring {
    void bar() { std::cout << "red bar" << std::endl; }
};

template <typename S, typename T>
class B : public virtual A, public S, public T { };

and the same main()?
Notes:

*

*foo() and bar() are, indeed, independent, and any combination goes. That is, nothing will break.

A: Your code does not compile (even after I fixed the syntax errors). The instantiations of B are abstract because they derive from A which has pure virtual functions and doesn't implement those. The function of same name from one parent doesn't implement a pure virtual function of another.
You could implement A in B with your template approach like this (I use struct for brevity, your code tries to access private members outside the class):
template<class S, class T>
struct B: A, S, T {
    void foo() {
        this->S::foo();
    }
    void bar() {
        this->T::bar();
    }
};

A perhaps more common approach would be to use virtual inheritance. It would probably make sense to define A in terms of the other interfaces:
struct A: virtual Fooing, virtual Barring {

Notice the use of virtual. This gives you the diamond which is mentioned in the comments. It is necessary in order for the compiler to make the connection between the foo's in separate interfaces. You must also inherit virtually in all the implementation classes:
struct TallFooing: virtual Fooing {

These changes should make your code compile. Whether multiple / virtual inheritance is a good idea is very much opinion based. Using it for anything other than pure virtual interfaces is often frowned upon.
Also, please make the destructor of the interface classes private or declare it virtual. Otherwise you'll probably end up with leaky code (compiler might hopefully notice that).

A: I fixed all the compilation errors I could (missing include, missing public), but the child class B still doesn't inplement A::foo and A::bar so the program fails to compile even then. You just can't use multiple inheritance in C++ to implement an abstract interface in this way.


text:
Q: IIS: Feature has been locked or read only when changing authentication We are currently migrating .net websites from 2008 to 2012. Most of these websites use anonymous authentication on the root, and forms authentication on an admin folder.
I noticed that I'm unable to change these permissions in IIS. I keep receiving that the feature has been locked or is read only. I have checked my web.config to ensure there is no  section that would block this. Converting that subfolder to a separate website is not an option.

A: You have two options here.
1.Store  section in applicationhost.config file by using location element. Open IIS Manager, high-light your site, navigate to Content view, right-click the particular page, click Switch to Feature View, click Authentication icon, enable/disable Windows Authentication.
2.Adjust the Feature Delegation settings. Open IIS Manager, high-light the sever name on Connections pane in IIS manager, click Feature Delegation icon under Management section on the Home pane, high-light authentication- Windows/Anonymous, then click Read/Write on the right Actions pane.
Answer taken from - https://forums.iis.net/t/1170130.aspx?IIS+7+Windows+Authentication+This+feature+has+been+locked+or+Read+Only


text:
Q: FullPage.js - Slider auto scrolling to the top section everytime So I have a simple 2 slider section using fullpage.js.
Problem: I want to add a scrollbar, which I have done using autoScrolling (because not only can you scroll by clicking the scrollbar but also with the roller on your mouse). The problem is that the page jumps to the top section when the slider is auto moving.
For example if I am viewing the footer section (Anything below the slider) it will auto jump to the top section.
Html

                <picture>
                    <source media="(max-width: 620px)" srcset="img/hero-slider-mobile.jpg">
                    <source media="(min-width: 621)" srcset="img/hero-slider-tablet.jpg">

                </picture>

                <picture>
                    <source media="(max-width: 620px)" srcset="img/slide-2-mobile.jpg">
                    <source media="(min-width: 621)" srcset="img/slide-2-tablet.jpg">

                </picture>

JAVASCRIPT

Any ideas why this is happening?
Additionally: Also is it possible to make the slider arrows smaller? It is too big on the mobile screen.

A: Use the fullpage.js option fitToSection:false


text:
Q: Alertmanager Match vs Match_re match:
  [ <labelname>: <labelvalue>, ... ]

# A set of regex-matchers an alert has to fulfill to match the node.
match_re:
  [ <labelname>: <regex>, ... ]

My question is what is the difference between a match and a match_re statement?
I have used both of the within prometheus and the effect they have is the same.
Any help is very much appreciated!!

A: With "match_re" you can use regular expression like in the following examples:
service: "mysql|postgre"

system: ".*_(foo|boo)$"

recipient: "(.*,)?customer/sms(,.*)?"

alertname: "watchdog.*alert"

A: From the v0.22.2 both match and match_re are deprecated in favor of matchers. A nice new feature is the possibility to define negative matchers.
# DEPRECATED: Use matchers below.
# A set of equality matchers an alert has to fulfill to match the node.
match:
  [ <labelname>: <labelvalue>, ... ]

# DEPRECATED: Use matchers below.
# A set of regex-matchers an alert has to fulfill to match the node.
match_re:
  [ <labelname>: <regex>, ... ]

# A list of matchers that an alert has to fulfill to match the node.
matchers:
  [ - <matcher> ... ]

Source

A: Use matchers instead of them:
  routes:
  - receiver: 'database-pager'
    group_wait: 10s
    matchers:
    - service=~"mysql|cassandra"
  - receiver: 'frontend-pager'
    group_by: [product, environment]
    matchers:
    - team="frontend"

In newer versions match and match_re are deprecated in favor of matchers.


text:
Q: How to pass region to the SKLearnProcessor - botocore.exceptions.NoRegionError: You must specify a region I'm using the following code to do a sklearn transformation job in sagemaker:
region = boto3.session.Session().region_name
role = sagemaker.get_execution_role()
sklearn_processor = SKLearnProcessor(
    framework_version="1.0-1", role=role,
    instance_type="ml.m5.xlarge", instance_count=1,
    # sagemaker_session = Session()
)
out_path = os.path.join(bucket, prefix, f'test_transform/data.csv')
sklearn_processor.run(
    code="preprocess.py",
    inputs = [
        ProcessingInput(source = 'my_package/', destination = '/opt/ml/processing/input/code/my_package/')
    ],
    outputs=[
        ProcessingOutput(output_name="test_transform_data",
                         source = '/opt/ml/processing/output/test_transform',
                         destination = out_path),
    ],
    arguments=["--time-slot-minutes", "30min"]
)

Within the above code, it's running preprocess.py, and (within) preprocess.py loads the data from snowflake database using the credentials saved in aws secretsmanager:
region = boto3.Session().region_name
secrets_client = boto3.client(service_name='secretsmanager', region_name=region)

So here's where error happen: first line above returns region as None, so the the second line of code raises botocore.exceptions.NoRegionError: You must specify a region
In this case, how can I pass the region to SKLearnProcessor or is there any other way to make the code working within the processing job instance?
FYI:
the source of input 'my_package/' is in the structure below to install packages and include py dependencies used in preprocess.py
├── my_package
│   ├── file1.py
│   ├── file2.py
│   └── requirements.txt
└── preprocess.py

Thanks

A: The two easiest ways are to to either set it in your ~/.aws/config
[default]
region=us-west-2

or you can use an environment variable as in:
export AWS_DEFAULT_REGION=us-west-2
but you do need to tell boto3 which region to use.
Check out the documentation about how to input variables to boto3:
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html

A: set following in the code preprocess.py solved the issue:
os.environ['AWS_DEFAULT_REGION'] = 'us-west-2'


text:
Q: How to solve NoClassDefFoundError preconditions? I create NFC reader when I run it has stopped and logcat show java.lang.NoClassDefFoundError: com.google.common.base.Precondition
How to solve it?
Please support me.

A: It sounds like you are using or modifying one of the SDK samples and need these libraries:
http://code.google.com/p/guava-libraries/


text:
Q: would have + past participle presumption Could we use "would have +  past participle" to express the speak's belief about something ?
For example :

*

*I'm sure he would have killed her.

*He definitely would have been listening when we fought yesterday.

A: Yes you can use would have + past principle.
It can have several things:

*

*Being a conditional (describes a situation that didn't happen and imagines the results of this situation)

*Talk about something you wanted to do but didn't
Here the sentence are a conditional.
An example in context:

If she saw him, I'm sure she would have killed her

Here its describing a situation that didn't happen an imaging the results of such a situation. But here the written expresses more certainty that that is what happened, but as it didn't happen you can't be 100% sure.


text:
Q: How to make proper alignment with printf I am trying to make output that should look like this:

I am using this statement:
FILE_TYPES.each_key {|key| printf "%20s %s\n", "--[no]" + key.to_s, FILE_TYPES[key.to_sym]}

Its result looks like this:

A: If you do not insist on using printf,
puts "--[no]" + key.to_s.ljust(20) + FILE_TYPES[key.to_sym]

A: Use \t to give tab spaces for formatting strings. e.g.
printf "Name:\t Shahzad\nGender:\tMale\nAge:\t25\n"

and it would print result as
Name:    Shahzad
Gender: Male
Age:    25
=> nil


text:
Q: How to immediately (temporarily) install a Windows Server 2012 R2 Foundation and upgrade later to the ROK version? A friend of mine has to set up a Windows server box and is in a hurry – the server must be running asap. He has successfully ordered a IBM System x3100 M5 with appropriate RAM and HDDs. However, there are difficulties in the delivery of the recommended operating system version, which is IBM Windows Server 2012 R2 Foundation, ROK, 1 CPU (the OS can be delivered but it will arrive a couple of days too late).
Because of the fact that I am a Linux guy, I am not too familiar with Microsofts licensing options and restrictions. Firstly, I am not sure if I really need IBM's ROK version for successful operation of the server (does it include important drivers that other distributions lack?). Secondly, I am not entirely sure if I could simply install an evaluation version first, and later on use the product key of the IBM Windows Server 2012 R2 Foundation, ROK, 1 CPU as soon as it has arrived (there seem to be only evaluation versions of the Essentials/Standard/DataCenter, but not for the Foundation). Would a Windows Server 2012 R2 Essentials work as well for my server? Does it include all required drivers?
So how should I tackle this situation? My favorite option would be to (of course legally) buy-download-burn the IBM Windows Server 2012 R2 Foundation, ROK, 1 CPU somewhere, but it seems that this is not offered. My second favorite alternative would be to download and burn a Windows Server version which can be migrated later on to the supported version. But I am a bit lost in Microsofts version and license jungle.