text:
Q: Composer's classmap autoload removing existing maps when new files are added I'm working on a Laravel 5 project and when adding new class files to an existing PHP project, the previously generated classmaps fail to be detected and/or several of the new class files are not detected.
There isn't a global composer.json for the environment, but this is the local package composer.json:
{
    "name": "laravel/laravel",
    "type": "project",
    "keywords": [
        "framework",
        "laravel"
    ],
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
       "classmap": [
            "database/seeds"
        ]
    }
}

composer dump-autoload is run with every attempt. This has not helped the issue of the adding the new classes, or even keeping the existing class maps.
I have tested the issue by adding files containing new classes and/or blank files to the project, and in all cases only a subset of the existing classmaps are re-generated, and in the case of the new class files some of the new files are included in generated classmap.
Sample file (existing):
AccessTypeSeeder.php
<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class AccessTypeSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('site_managements')->insert(
            [
                [
                    'meta_key' => 'access_type',
                    'meta_value' => 'all',
                    'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
                    'updated_at' => Carbon::now()->format('Y-m-d H:i:s'),
                ],
            ]
        );
    }
}

Removing the new files, and re-running dump-autoload often restores the existing classmaps, even if the files themselves are blank. Cloning(copy & paste) an existing file like the one above and renaming the class and file name to something unique like TestSeeder and TestSeeder.php, doesn't make a difference.
The existing classes are not contained in any namespace as seen above, and trying to configure the autoload via PSR-0, strangely still generates some of the classmaps (usually 1 or 2) in the autoload_classmap.php file, even if no classmap-based autoloading has been defined:
{
    "name": "laravel/laravel",
    "type": "project",
    "keywords": [
        "framework",
        "laravel"
    ],
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-0": {
            "":["database/seeds"]
        }
    }
}

Note: The project is using docker containers and composer (v1+/v2) is applied to the source files via a separate images and containers. It is preferred to get this working with the original classmap-based solution if possible, even though it is less ideal than the preferable PSR-0 or PSR-4 configurations.
I reviewed similar composer autoload issues on SO but the issue causes were not the same and the solutions recommended were not applicable to this is or did not work.

A: This issue appears to have been a result of the setup environment which was within a Docker container. Running the composer script outside of the container allowed for the full maps to get created.


text:
Q: Call a function from class I have two python file.
Unity.py, main.py
I want to call a function from main.py which is under a class
from unity import Unity
class down(Unity):
    def __init__(self,TOPIC):
      .
      .
    def xyz(self):
     .
     .

How to call xyz function in this main.py?

A: first, you need to instantiate down class after that you can all the xyz function
instance = down("topicname")
instance.xyz() # Call xyz function

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get loss values for each training instance - Keras I want to get loss values as model train with each instance.
history = model.fit(..)

for example above code returns the loss values for each epoch not mini batch or instance.
what is the best way to do this? Any suggestions?

A: If you want to get loss values for each batch, you might want to use call model.train_on_batch inside a generator. It's hard to provide a complete example without knowing your dataset, but you will have to break your dataset into batches and feed them one by one
def make_batches(...):
    ...

batches = make_batches(...)
batch_losses = [model.train_on_batch(x, y) for x, y in batches]

It's a bit more complicated with single instances. You can, of course, train on 1-sized batches, though it will most likely thrash your optimiser (by maximising gradient variance) and significantly degrade performance. Besides, since loss functions are evaluated outside of Python's domain, there is no direct way to hijack the computation without tinkering with C/C++ and CUDA sources. Even then, the backend itself evaluates the loss batch-wise (benefitting from highly vectorised matrix-operations), therefore you will severely degrade performance by forcing it to evaluate loss on each instance. Simply put, hacking the backend will only (probably) help you reduce GPU memory transfers (as compared to training on 1-sized batches from the Python interface). If you really want to get per-instance scores, I would recommend you to train on batches and evaluate on instances (this way you will avoid issues with high variance and reduce expensive gradient computations, since gradients are only estimated during training):
def make_batches(batchsize, x, y):
    ...

batchsize = n
batches = make_batches(n, ...)
batch_instances = [make_batches(1, x, y) for x, y in batches]
losses = [
    (model.train_on_batch(x, y), [model.test_on_batch(*inst) for inst in instances])
    for batch, instances in zip(batches, batch_instances)
]

A: There is exactly what you are looking for at the end of this official keras documentation page https://keras.io/callbacks/#callback
Here is the code to create a custom callback

class LossHistory(keras.callbacks.Callback):
    def on_train_begin(self, logs={}):
        self.losses = []

    def on_batch_end(self, batch, logs={}):
        self.losses.append(logs.get('loss'))

model = Sequential()
model.add(Dense(10, input_dim=784, kernel_initializer='uniform'))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')

history = LossHistory()
model.fit(x_train, y_train, batch_size=128, epochs=20, verbose=0, callbacks=[history])

print(history.losses)
# outputs
'''
[0.66047596406559383, 0.3547245744908703, ..., 0.25953155204159617, 0.25901699725311789]
'''

A: One solution is to calculate the loss function between train expectations and predictions from train input. In the case of loss = mean_squared_error and three dimensional outputs (i.e. image width x height x channels):
model.fit(train_in,train_out,...)

pred = model.predict(train_in)
loss = np.add.reduce(np.square(test_out-pred),axis=(1,2,3)) # this computes the total squared error for each sample
loss = loss / ( pred.shape[1]*pred.shape[2]*pred.shape[3]) # this computes the mean over the sample entry

np.savetxt("loss.txt",loss) # This line saves the data to file

A: After combining resources from here and here I came up with the following code. Maybe it will help you. The idea is that you can override the Callbacks class from keras and then use the on_batch_end method to check the loss value from the logs that keras will supply automatically to that method.
Here is a working code of an NN with that particular function built in. Maybe you can start from here -
import numpy as np
import pandas as pd
import seaborn as sns
import os
import matplotlib.pyplot as plt
import time
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split

import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.callbacks import Callback

# fix random seed for reproducibility
seed = 155
np.random.seed(seed)

# load pima indians dataset

# download directly from website
dataset = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data",
                      header=None).values
X_train, X_test, Y_train, Y_test = train_test_split(dataset[:,0:8], dataset[:,8], test_size=0.25, random_state=87)
class NBatchLogger(Callback):
    def __init__(self,display=100):
        '''
        display: Number of batches to wait before outputting loss
        '''
        self.seen = 0
        self.display = display

    def on_batch_end(self,batch,logs={}):
        self.seen += logs.get('size', 0)
        if self.seen % self.display == 0:
            print('\n{0}/{1} - Batch Loss: {2}'.format(self.seen,self.params['samples'],
                                                logs.get('loss')))

out_batch = NBatchLogger(display=1000)
np.random.seed(seed)
my_first_nn = Sequential() # create model
my_first_nn.add(Dense(5, input_dim=8, activation='relu')) # hidden layer
my_first_nn.add(Dense(1, activation='sigmoid')) # output layer
my_first_nn.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

my_first_nn_fitted = my_first_nn.fit(X_train, Y_train, epochs=1000, verbose=0, batch_size=128,
                                     callbacks=[out_batch], initial_epoch=0)

Please let me know if you wanted to have something like this.


text:
Q: Abstracting connection errors I've got an interface called IConnection
public interface IConnection
{

    bool IsConnected { get; }
    Task ConnectAsync(IEndPoint remoteEP);
    Task<int> SendAsync(byte[] data, int offset, int size);
    Task<int> ReceiveAsync(byte[] buffer, int offset, int size);
    void Disconnect();
    void Close();

    event EventHandler<DisconnectedEventArgs> Disconnected;

}

It is implemented by two different types of connection - a Socket based connection class and an HTTP based connection class. I also want the option of adding other connection types in future.
When initiating a connection in my main ChatClient class I will check the user's configuration and then depending on what the user prefers, will create a SocketConnection or an HTTPConnection. From that point onward I only refer to the connection using it's IConnection interface.
The IConnection class has a Disconnected event which is raised when the user calls Disconnect, or when some unexpected connection error occurs. The DisconnectedEventArgs will contain information about what caused that disconnect to occur.
What I'm wondering is, how do I abstract the different types of errors?
A socket can experience many different error conditions which would cause it to disconnect, including but not limited to -

*

*Remote side initiated a graceful disconnect (ie.. Read returns 0)

*A read/write throws a SocketException with flag SocketError.ConnectionAborted

*A read/write throws a SocketException with flag SocketError.NetworkReset

An http connection can also experience many different error conditions, for example -

*

*A failure to poll the remote server -- eg.. host suddenly disappears

*HTTP authentication credentials are rejected

How do I combine all of the possible errors for a socket and all the possible errors for an http connection into a single type?
Do I use an enum containing values for all of the possible errors?
Do I have a simple error code and a description of the error?
And how many of the many many socket error conditions am I supposed to handle? Only the ones I expect to encounter? Or all of them?

A: Why not have DisconnectEventArgs contain a public Exception Error { get; set; }.  Error is null when Disconnect is called normally, otherwise it contains a Socket or Http exception.


text:
Q: URL rewriting : css, js, and images not loading I've following rule for .htaccess
Options +FollowSymLinks

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -f [OR]

RewriteRule ^detail/([0-9]+)/?$ detail.php?id=$1

It redirects http://localhost/detail/123 URL to http://localhost/detail.php?id=123. The page redirects successfully, but the problem is CSS, JS, and images are not loading,
CSS, js files are located under http://localhost/css/ and http://localhost/js/
One solution is to use absolute path (ex /CSS, or /js rather than just CSS/, /js but this does not seem a reliable solution since we've to change it on all files,
Any other solution based on .htaccess rules, which is independent of editing all PHP files and let us use "relative paths"?

A: I applied url rewriting to a project in core php. I faced the same problem. css, Js and images were not getting loaded. I used this and it worked for me. Source
# Allow any files or directories that exist to be displayed directly
RewriteCond ${REQUEST_URI} ^.+$
RewriteCond %{REQUEST_FILENAME} \.(gif|jpe?g|png|js|css|swf|php|ico|txt|pdf|xml)$ [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

A:
one solution is that use absolute path (ex /css, or /js rather than just css/, /js but this is not looks a reliable solution since we've to change it on all files,

This is because your relative URIs have their base changed. Originally, the base is / when the page is /detail.php?id=123, and the browser properly fills in relative links with the / base. But when the browser goes to a page like /detail/123 the base suddenly becomes /detail/ and it tries to append that in front of all relative URLs and thus none of them load.
You can either make your links absolute, or change the URI base in the header of your pages (inbetween the <head> </head> tags):
<base href="/">

A: Don't be lazy and change your relative URIs in your resources to root directory absolute pathing like /css/style.css. This is the best.
You can get clever and use regex and replace all the files you need which would be like a few one liners and you're done. How many places could there be to change? And you should be using a template.
This should work but I wouldn't go this way.
RewriteRule ^detail/(css|js|img)/(.*)?$ /$1/$2 [L,QSA,R=301]

A: Anthony's answer is perfectly valid, and he is actually trying to impart some good practices there.
However, since you do not seem content with that answer, here is a different solution. Just insert this line into your .htaccess before any Rewrite-Command:
RedirectMatch permanent ^/detail/((css|js)/.*)  /$1

It will redirect all the originally 404 requests for /details/css/style.css and /details/js/js.s to their actual location. Neither particluarly pretty nor elegant, but it simply works.

A: this code perfectly work for me, add before redirect rule(RewriteRule ^detail/([0-9]+)/?$ detail.php?id=$1)
RewriteRule ^(.+)/(admin|css|fonts|ico|include|js|images)/(.*)$ $2/$3 [L]

A: just exclude directory it will load automatically that's it
RewriteRule ^(css|js|fonts|images|plugins)($|/) - [L]

A: my issue resolved when i changed the style link from
 <link href="css/styles.css" rel="stylesheet" />

into   <link href="/css/styles.css" rel="stylesheet" />


text:
Q: I can't figure out this room calculator I need help on getting it to ask the shape of the room, listed below, the floor type they want, listed below, and ask these for how ever many rooms are being calculated. Along with printing the price per room, and the total for all rooms. The result of running it is below all of the code.
carpet = 25
vinyl = 17
hardwood = 31
concrete = 18

def circle():
    r = float(input('What is the radius of the room?:    '))
    pi = 3.14
    room_size = pi * r **2
    return (room_size)

def rectangle():
    b = float(input('What is the length the room?:   '))
    h = float(input('What is the width of the room?:    '))
    room_size = b * h
    return (room_size)

def regular_polygon():
    p = ('What is the perimeter of the room?:   ')
    a = ('What is the Apothegm of the room?:    ')
    room_size = p * a / 2
    return (room_size)

def trapezoid():
    b1 = float(input('What is the length of the bottom base of the room?:   '))
    b2 = float(input('What is the length of the top base of the room?:   '))
    h = float(input('How far apart are the top base and bottom base?:  '))
    room_size = h * (b1 + b2) / 2
    return (room_size)

def triangle():
    b = float(input('What is the length the room?:   '))
    h = float(input('What is the width of the room?:    '))
    room_size = (b * h) / 2
    return (room_size)

def floor(floorings):
    floorings = input('What floor type would you like?:   carpet, vinyl, hardwood, or concrete.')
    if floorings == ('carpet'):
        floor_type = carpet
    elif floorings == ('vinyl'):
        floor_type = vinyl
    elif floorings == ('hardwood'):
        floor_type = hardwood
    elif floorings == ('concrete'):
        floor_type = concrete
    else:
        raise ValueError('Invalid room shape: ' + equation_type)

    return floor_type

number_of_rooms = int(input('How many rooms will we be calculating?:   '))

def rooms(room_shape):
    total_area = 0
    for i in range(room_shape):
        equation_type = input('What is the shape of the room (circle, rectangle, regular polygon, trapezoid, triangle)?   ').lower()
        if equation_type == ('circle'):
           total = (total_area + circle())
        elif equation_type == ('rectangle'):
           total = (total_area + rectangle())
        elif equation_type == ('regular polygon'):
            total = (total_area + regular_polygon())
        elif equation_type == ('trapezoid'):
            total = (total_area + trapezoid())
        elif equation_type == ('triangle'):
            total = (total_area + triangle())
        else:
            raise ValueError('Invalid room shape: ' + equation_type)

    return total
room_count = number_of_rooms

print (('$'), rooms(room_count) * floor)

What is the width of the room?:    2
What is the shape of the room (circle, rectangle, regular polygon, trapezoid, triangle)?   rectangle
What is the length the room?:   5
What is the width of the room?:    2
Traceback (most recent call last):
File "/Users/••••••/Desktop/coputer coding/Flooring estimator.py", line 100, in
print (('$'), rooms(room_count) * floor)
TypeError: unsupported operand type(s) for *: 'float' and 'function'

A: Your current code had two issues :
1. print (('$'), rooms(room_count) * floor)

Here the floor function is called by writing floor whereas it actually should have been floor()
2. floor(floorings)

You do not need the floorings parameter since you are taking that as the input from the user.
This is the corrected code :
carpet = 25
vinyl = 17
hardwood = 31
concrete = 18

def circle():
    r = float(input('What is the radius of the room?:    '))
    pi = 3.14
    room_size = pi * r **2
    return (room_size)

def rectangle():
    b = float(input('What is the length the room?:   '))
    h = float(input('What is the width of the room?:    '))
    room_size = b * h
    return (room_size)

def regular_polygon():
    p = ('What is the perimeter of the room?:   ')
    a = ('What is the Apothegm of the room?:    ')
    room_size = p * a / 2
    return (room_size)

def trapezoid():
    b1 = float(input('What is the length of the bottom base of the room?:   '))
    b2 = float(input('What is the length of the top base of the room?:   '))
    h = float(input('How far apart are the top base and bottom base?:  '))
    room_size = h * (b1 + b2) / 2
    return (room_size)

def triangle():
    b = float(input('What is the length the room?:   '))
    h = float(input('What is the width of the room?:    '))
    room_size = (b * h) / 2
    return (room_size)

def floor():
    floorings = input('What floor type would you like?:   carpet, vinyl, hardwood, or concrete : ')
    if floorings == ('carpet'):
        floor_type = carpet
    elif floorings == ('vinyl'):
        floor_type = vinyl
    elif floorings == ('hardwood'):
        floor_type = hardwood
    elif floorings == ('concrete'):
        floor_type = concrete
    else:
        raise ValueError('Invalid room shape: ' + equation_type)

    return floor_type

number_of_rooms = int(input('How many rooms will we be calculating?:   '))

def rooms(room_shape):
    total_area = 0
    for i in range(room_shape):
        equation_type = input('What is the shape of the room (circle, rectangle, regular polygon, trapezoid, triangle)?   ').lower()
        if equation_type == ('circle'):
           total_area = (total_area + circle())
        elif equation_type == ('rectangle'):
           total_area = (total_area + rectangle())
        elif equation_type == ('regular polygon'):
            total_area = (total_area + regular_polygon())
        elif equation_type == ('trapezoid'):
            total_area = (total_area + trapezoid())
        elif equation_type == ('triangle'):
            total_area = (total_area + triangle())
        else:
            raise ValueError('Invalid room shape: ' + equation_type)

    return total_area
room_count = number_of_rooms

print (('$'), rooms(room_count) * floor())

Now here is the execution explanation for the corrected code

*

*The user is asked to input the number of rooms he wishes to calculate the results for. This value is read in the number_of_rooms variable.

*Then the total cost for the purchase/calculations is found out by summing the individual costs of flooring and total cost for all the rooms which is calculated using the rooms(room_shape) function.

*The rooms(room_shape) function repeats a set of steps for all the rooms. The steps being calculating the floor area of each room and adding it to the overall floor area which is tracked by using the total_area variable.

*Once the total area for all the rooms is calculated based on the input from user where he/she selects the type of room they wish, the value of total_area is returned.

*This is then added to the value returned from the floor variable. Thus giving you the final cost.
However this floor cost is added just once and is not at all calculated the way you expect it to be calculated. I suppose to calculate it for each room where each room may have different type of flooring such as
total_cost = room_area1 * floor1 + room_area2 * floor .... so on

For that you should use the code which looks something like this :
carpet = 25
vinyl = 17
hardwood = 31
concrete = 18

def circle():
    r = float(input('What is the radius of the room?:    '))
    pi = 3.14
    room_size = pi * r **2
    return room_size * floor()

def rectangle():
    b = float(input('What is the length the room?:   '))
    h = float(input('What is the width of the room?:    '))
    room_size = b * h
    return room_size * floor()

def regular_polygon():
    p = ('What is the perimeter of the room?:   ')
    a = ('What is the Apothegm of the room?:    ')
    room_size = p * a / 2
    return room_size * floor()

def trapezoid():
    b1 = float(input('What is the length of the bottom base of the room?:   '))
    b2 = float(input('What is the length of the top base of the room?:   '))
    h = float(input('How far apart are the top base and bottom base?:  '))
    room_size = h * (b1 + b2) / 2
    return room_size * floor()

def triangle():
    b = float(input('What is the length the room?:   '))
    h = float(input('What is the width of the room?:    '))
    room_size = (b * h) / 2
    return room_size * floor()

def floor():
    floorings = input('What floor type would you like?:   carpet, vinyl, hardwood, or concrete : ')
    if floorings == ('carpet'):
        floor_type = carpet
    elif floorings == ('vinyl'):
        floor_type = vinyl
    elif floorings == ('hardwood'):
        floor_type = hardwood
    elif floorings == ('concrete'):
        floor_type = concrete
    else:
        raise ValueError('Invalid room shape: ' + equation_type)

    return floor_type

number_of_rooms = int(input('How many rooms will we be calculating?:   '))

def rooms(room_shape):
    total_area = 0
    for i in range(room_shape):
        equation_type = input('What is the shape of the room (circle, rectangle, regular polygon, trapezoid, triangle)?   ').lower()
        if equation_type == ('circle'):
           total_area = (total_area + circle())
        elif equation_type == ('rectangle'):
           total_area = (total_area + rectangle())
        elif equation_type == ('regular polygon'):
            total_area = (total_area + regular_polygon())
        elif equation_type == ('trapezoid'):
            total_area = (total_area + trapezoid())
        elif equation_type == ('triangle'):
            total_area = (total_area + triangle())
        else:
            raise ValueError('Invalid room shape: ' + equation_type)

    return total_area
room_count = number_of_rooms

print (('$'), rooms(room_count))

Here the only change being, floor() is called for each room instead of being called once after calculation of net area.
But the current code still has an issue where total and total_count are not used correctly to add and update the net area. Instead to get the prices of individual rooms you could use the following method :
carpet = 25
vinyl = 17
hardwood = 31
concrete = 18

def circle():
    r = float(input('What is the radius of the room?:    '))
    pi = 3.14
    room_size = pi * r **2
    return room_size * floor()

def rectangle():
    b = float(input('What is the length the room?:   '))
    h = float(input('What is the width of the room?:    '))
    room_size = b * h
    return room_size * floor()

def regular_polygon():
    p = ('What is the perimeter of the room?:   ')
    a = ('What is the Apothegm of the room?:    ')
    room_size = p * a / 2
    return room_size * floor()

def trapezoid():
    b1 = float(input('What is the length of the bottom base of the room?:   '))
    b2 = float(input('What is the length of the top base of the room?:   '))
    h = float(input('How far apart are the top base and bottom base?:  '))
    room_size = h * (b1 + b2) / 2
    return room_size * floor()

def triangle():
    b = float(input('What is the length the room?:   '))
    h = float(input('What is the width of the room?:    '))
    room_size = (b * h) / 2
    return room_size * floor()

def floor():
    floorings = input('What floor type would you like?:   carpet, vinyl, hardwood, or concrete : ')
    if floorings == ('carpet'):
        floor_type = carpet
    elif floorings == ('vinyl'):
        floor_type = vinyl
    elif floorings == ('hardwood'):
        floor_type = hardwood
    elif floorings == ('concrete'):
        floor_type = concrete
    else:
        raise ValueError('Invalid room shape: ' + equation_type)

    return floor_type

number_of_rooms = int(input('How many rooms will we be calculating?:   '))

def rooms(room_shape):
    total_area = []
    for i in range(room_shape):
        equation_type = input('What is the shape of the room (circle, rectangle, regular polygon, trapezoid, triangle)?   ').lower()
        if equation_type == ('circle'):
           total_area.append(circle())
        elif equation_type == ('rectangle'):
           total_area.append(rectangle())
        elif equation_type == ('regular polygon'):
            total_area.append(regular_polygon())
        elif equation_type == ('trapezoid'):
            total_area.append(trapezoid())
        elif equation_type == ('triangle'):
            total_area.append(triangle())
        else:
            raise ValueError('Invalid room shape: ' + equation_type)

    return total_area
room_count = number_of_rooms

rooms_cost = rooms(room_count)
for room_cost in range(len(rooms_cost)):
    print (f"The cost for room {room_cost+1} is ${rooms_cost[room_cost]}")
print("\nTotal Cost : ", sum(rooms_cost))


text:
Q: Trying to check if value is in range with a counter I have a df with the windspeed and the power. I calculated 6 new columns with ranges around the power. Now I want to check if the windspeed is smaller then 7 and check than if the power is smaller than the value my column '-10' or greater then the value in my column '+10'. If it is out of this range I want to count +1 if nothing schould happens and I want to check the next power value.
x=df.T.iloc[0]
y=df.T.iloc[1]
c=result[0]
a=result[1]
b=result[2]

df['soll'] = c / (1 + (a) * np.exp(-b*(x)))

df['+3'] = df['soll'] + (c * 0.03)
df['-3'] = df['soll'] - (c * 0.03)
df['+6'] = df['soll'] + (c * 0.06)
df['-6'] = df['soll'] - (c * 0.06)
df['+10'] = df['soll'] + (c * 0.1)
df['-10'] = df['soll'] - (c * 0.1)

counter = 0

for number in df['power']:
    if df['windspeed'] <= 7:
        np.where((df['+10'] >= df['power']) & (df['-10'] <= df['power'])
                   , counter+=1,
               elif df['windspeed'] <= 15 & >7:
                    np.where((df['+6'] >= df['power']) & (df['-6'] <= df['power'])
                   , counter+=1,
                       else:
                          np.where((df['+3'] >= df['power']) & (df['-3'] <= df['power'])
                        , counter+=1
                        )
                          )
                            )

This is a part of my df:
    windspeed   power soll  +3  -3  +6  -6  +10 -10
0   6.1 230.0   210.29186534841182  266.3048877761675   154.27884292065613  322.31791020392313  98.26582049290047   397.0019401075974   23.581790589226216
1   6.4 271.0   245.18211360320805  301.19513603096374  189.16909117545237  357.20815845871937  133.1560687476967   431.89218836239365  58.47203884402245
2   6.4 270.0   245.18211360320805  301.19513603096374  189.16909117545237  357.20815845871937  133.1560687476967   431.89218836239365  58.47203884402245
3   6.0 219.0   199.6625381512033   255.675560578959    143.64951572344762  311.6885830067147   87.63649329569196   386.3726129103889   12.952463392017705
4   6.9 338.0   314.1478597411359   370.1608821688916   258.1348373133802   426.1739045966473   202.12181488562456  500.8579345003215   127.4377849819503
5   6.9 345.0   314.1478597411359   370.1608821688916   258.1348373133802   426.1739045966473   202.12181488562456  500.8579345003215   127.4377849819503
6   6.9 338.0   314.1478597411359   370.1608821688916   258.1348373133802   426.1739045966473   202.12181488562456  500.8579345003215   127.4377849819503
7   6.2 251.0   221.4119211836951   277.4249436114508   165.39889875593946  333.43796603920646  109.38587632818377  408.12199594288074  34.70184642450951


text:
Q: Jquery Tag list builder component I'm looking for help to find a jquery component that works just like the stackoverflow's tag input... I doesn't need to have a combobox underneath it, just a input that I can add tags freely... Any suggestions?

A: Try this jQuery plugin: github.com/max-favilli/tagmanager
Good luck :)


text:
Q: Geomesa: why stat method not worked? My scheme
/geomesa-accumulo describe-schema -c myNamespace.geomesa -z 10.200.217.27 -i accumulo -u root -p qweasd123 -f SignalBuilder
INFO  Describing attributes of feature 'SignalBuilder'
geo           | Point   (Spatio-temporally indexed) (Spatially indexed)
time          | Date    (Spatio-temporally indexed) (Attribute indexed)
cam           | String  (Attribute indexed) (Attribute indexed)
imei          | String
dir           | Double
alt           | Double
vlc           | Double
sl            | Integer
ds            | Integer
dir_y         | Double
poi_azimuth_x | Double
poi_azimuth_y | Double

User data:
  geomesa.attr.splits     | 4
  geomesa.feature.expiry  | time(30 days)
  geomesa.index.dtg       | time
  geomesa.indices         | z3:7:3:geo:time,z2:5:3:geo,attr:8:3:time,attr:8:3:cam,attr:8:3:cam:time
  geomesa.stats.enable    | true
  geomesa.table.partition | time
  geomesa.z.splits        | 4
  geomesa.z3.interval     | week

When I try to get count by stat methods it retuns 11:
./geomesa-accumulo stats-count -c myNamespace.geomesa -z 10.200.217.27 -i accumulo -u root -p qweasd123 -f SignalBuilder -q "cam='9f471340-dd70-4eca-a8dc-14553a4e708a'"
Estimated count: 11

but without cache:
./geomesa-accumulo stats-count -c myNamespace.geomesa -z 10.200.217.27 -i accumulo -u root -p qweasd123 -f SignalBuilder -q "cam='9f471340-dd70-4eca-a8dc-14553a4e708a'" --no-cache
INFO  Running stat query...
Count: 1436

Why stats methods not worked properly and return only estimated value?
In redis it's all ok. The problem is only in accumulo.
** Question update:
I try to recalculate statistics
 ~/bin/geomesa-accumulo_2.12-3.2.2/bin  ./geomesa-accumulo stats-analyze -c myNamespace.geomesa -z 10.200.217.27 -i accumulo -u root -p qweasd123 -f SignalBuilder
INFO  Running stat analysis for feature type SignalBuilder...
INFO  Stats analyzed:
  Total features: 11527
  Bounds for geo: [ 37.598007, 55.736623, 38.661036, 56.9189592 ] cardinality: 10634
  Bounds for time: [ 2022-01-30T15:13:58.706Z to 2022-02-09T14:16:03.000Z ] cardinality: 3779
  Bounds for cam: [ 3fe961e1-91dd-4931-b82e-d04fcaf24c3e to f767f0fa-dac5-4571-aa47-1ea6bf6e2c82 ] cardinality: 6
INFO  Use 'stats-histogram', 'stats-top-k' or 'stats-count' commands for more details
 ~/bin/geomesa-accumulo_2.12-3.2.2/bin  ./geomesa-accumulo stats-count -c myNamespace.geomesa -z 10.200.217.27 -i accumulo -u root -p qweasd123 -f SignalBuilder -q "cam='9f471340-dd70-4eca-a8dc-14553a4e708a'"
Estimated count: 14
 ~/bin/geomesa-accumulo_2.12-3.2.2/bin  ./geomesa-accumulo stats-count -c myNamespace.geomesa -z 10.200.217.27 -i accumulo -u root -p qweasd123 -f SignalBuilder -q "cam='3fe961e1-91dd-4931-b82e-d04fcaf24c3e'"
Estimated count: 0
 ~/bin/geomesa-accumulo_2.12-3.2.2/bin  ./geomesa-accumulo stats-count -c myNamespace.geomesa -z 10.200.217.27 -i accumulo -u root -p qweasd123 -f SignalBuilder -q "cam='3fe961e1-91dd-4931-b82e-d04fcaf24c3e'" --no-cache
INFO  Running stat query...
Count: 2675
 ~/bin/geomesa-accumulo_2.12-3.2.2/bin  ./geomesa-accumulo stats-analyze -c myNamespace.geomesa -z 10.200.217.27 -i accumulo -u root -p qweasd123 -f SignalBuilder
INFO  Running stat analysis for feature type SignalBuilder...
INFO  Stats analyzed:
  Total features: 11767
  Bounds for geo: [ 37.598007, 55.736623, 38.661036, 56.9189592 ] cardinality: 10942
  Bounds for time: [ 2022-01-30T15:13:58.706Z to 2022-02-09T14:17:41.000Z ] cardinality: 3841
  Bounds for cam: [ 3fe961e1-91dd-4931-b82e-d04fcaf24c3e to f767f0fa-dac5-4571-aa47-1ea6bf6e2c82 ] cardinality: 6
INFO  Use 'stats-histogram', 'stats-top-k' or 'stats-count' commands for more details
 ~/bin/geomesa-accumulo_2.12-3.2.2/bin  ./geomesa-accumulo stats-count -c myNamespace.geomesa -z 10.200.217.27 -i accumulo -u root -p qweasd123 -f SignalBuilder -q "1=1"
Estimated count: Unknown
Re-run with --no-cache to get an exact count
 ~/bin/geomesa-accumulo_2.12-3.2.2/bin  ./geomesa-accumulo stats-count -c myNamespace.geomesa -z 10.200.217.27 -i accumulo -u root -p qweasd123 -f SignalBuilder -q "1=1" --no-cache
INFO  Running stat query...
Count: 11872

But it does not help (((. The geo-events continue to arrive to geomesa. But stats does not worked.
May by I'm not using stats-count properly. Stats-top-k shows gathered statistics.
 ~/bin/geomesa-accumulo_2.12-3.2.2/bin  ./geomesa-accumulo stats-count -c myNamespace.geomesa -z 10.200.217.27 -i accumulo -u root -p qweasd123 -f SignalBuilder -q "cam like '3fe961e1-91dd-4931-b82e-d04fcaf24c3e'"
Estimated count: 0
 ~/bin/geomesa-accumulo_2.12-3.2.2/bin  ./geomesa-accumulo stats-top-k -c myNamespace.geomesa -z 10.200.217.27 -i accumulo -u root -p qweasd123 -f SignalBuilder
Top values for 'geo':
  unavailable
Top values for 'time':
  unavailable
Top values for 'cam':
  7c0cf8bc-e7e3-4023-8a00-a5f17bda3001 (2925)
  9f471340-dd70-4eca-a8dc-14553a4e708a (2924)
  f767f0fa-dac5-4571-aa47-1ea6bf6e2c82 (2922)
  bfe55ad1-5b0a-405d-9ca9-3bed6aca9313 (2921)
  3fe961e1-91dd-4931-b82e-d04fcaf24c3e (2920)
  5798a065-d51e-47a1-b04b-ab48df9f1324 (2)
Top values for 'imei':
  unavailable
Top values for 'dir':
  unavailable
Top values for 'alt':
  unavailable
Top values for 'vlc':
  unavailable
Top values for 'sl':
  unavailable
Top values for 'ds':
  unavailable
Top values for 'dir_y':
  unavailable
Top values for 'poi_azimuth_x':
  unavailable
Top values for 'poi_azimuth_y':
  unavailable

Or maybe the reason was in accumulo. When I try to get data from accumulo table. It returns
root@accumulo> scan -t myNamespace.geomesa_SignalBuilder_z3_geo_time_v7_02717
2022-02-09 17:55:12,909 [commands.ShellPluginConfigurationCommand] ERROR: Error: Could not determine the type of file "hdfs://10.200.217.27:9000/accumulo/classpath/myNamespace/[^.].*.jar".
2022-02-09 17:55:12,909 [shell.Shell] ERROR: Could not load the specified formatter. Using the DefaultFormatter
2022-02-09 17:55:12,929 [commands.ShellPluginConfigurationCommand] ERROR: Error: Could not determine the type of file "hdfs://10.200.217.27:9000/accumulo/classpath/myNamespace/[^.].*.jar".
\x01\x0A\x9Dt\x19\x84\xEF\xDD\xAF "5798a065-d51e-47a1-b04b-ab48df9f1324-1643555638706 d: []    \x03\x00\x0C\x02\x00\x1E\x000\x008\x00\\\x00g\x00o\x00w\x00\x7F\x00\x83\x00\x87\x00\x87\x00\x87\x00\x87\x00\x00\x0E\x00\x01\x01@CT\x9C\xD3\xE0\xBDE@Lu\xA0t\x7F-\xDE\x00\x00\x01~\xAB\x8C\xCD\xB25798a065-d51e-47a1-b04b-ab48df9f132\xB43333333333\xB1@f@\x00\x00\x00\x00\x00?\xF3\xAE\x14z\xE1G\xAE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x01
\x01\x0A\x9Dt\x19\x84\xEF\xDD\xBD!\x065798a065-d51e-47a1-b04b-ab48df9f1324-1643555648706 d: []    \x03\x00\x0C\x02\x00\x1E\x000\x008\x00\\\x00g\x00o\x00w\x00\x7F\x00\x83\x00\x87\x00\x87\x00\x87\x00\x87\x00\x00\x0E\x00\x01\x01@CT\x9C\xD3\xE0\xBDE@Lu\xA0t\x7F-\xDE\x00\x00\x01~\xAB\x8C\xF4\xC25798a065-d51e-47a1-b04b-ab48df9f132\xB43333333333\xB1@f@\x00\x00\x00\x00\x00?\xF3\xAE\x14z\xE1G\xAE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x01

A: Stats are gathered during ingestion, but are only written on a "best effort" basis (for example, if your ingest dies, stats may not be written). There are also code paths that don't update stats, for example if you disable them via system property or if you ingest through a bulk map/reduce job. In your particular case, it's hard to say why your stats don't match your data without a detailed description of everything you did to ingest it. However, if you want to re-calculate the cached statistics, you can always run the stats-analyze CLI command.
If you can re-create the issue, please feel free to file a ticket in the GeoMesa JIRA with the steps to re-create.


text:
Q: Can´t delete with JPA native query I´m trying to delete a row from a mysql table ( registros ) with jpa, but the query is not working.
Testing with postman deliver 500 error, fixed ( for testing only ) using return(null) in the PostMapping. Test again, no error, but the record in the database is still here.
What im doing wrong?
Interface for the query :
public interface Eliminar extends JpaRepository<registros, Long> {

    @Modifying(clearAutomatically = true, flushAutomatically = true)
    @Query (value = "DELETE FROM registros WHERE ID like :id", nativeQuery = true)
    List<registros> borrarreg(@Param("id") Long id) ;
}

PostMapping that call the "borrareg" method:

private Eliminar borrarregistro;
               @PostMapping(path="borrarreg")
               public @ResponseBody List<registros> borrarreg(@RequestParam Long id)
               {
                 return borrarregistro.borrarreg(id);
                 }

Model registros ( database ):
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name ="registros")
public class registros {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)

    private int id ;
    private int numerocliente ;
    private String nombrecliente ;
    private String maccpe ;
    private String direccionip ;

public int getId() {
    return id;
}

public int getnumerocliente() {
    return numerocliente;
}
public void setnumerocliente(int numerocliente) {
    this.numerocliente = numerocliente;
}
public String getnombrecliente() {
    return nombrecliente;
}
public void setnombrecliente(String nombrecliente) {
    this.nombrecliente = nombrecliente;
}
public String getmaccpe() {
    return maccpe;
}
public void setmaccpe(String maccpe) {
    this.maccpe = maccpe;
}
public String getdireccionip() {
    return direccionip;
}
public void setdireccionip(String direccionip) {
    this.direccionip = direccionip;
}

}

Crud interface for add:
import org.springframework.data.repository.CrudRepository;
import bookip.demo.models.registros;

public interface Registros extends CrudRepository<registros, Integer> {
}

Add, and search methods work with no problem. Only delete is not working.
Thanks in advance


text:
Q: pasar datos de un checkbox a caja de texto Quiero pasar una palabra cuando se acciona un checkbox a una caja de texto.
Ejemplo de palabra a pasar: DATOS.
Lo he probado pero no funciona.
Alguna sugerencia?
  <script language="javascript"> function PasarValor() {
 document.getElementById("nombre2").value = 'DATOS'; }

 </script>

 <form class="form-inline" method="POST" action="">

 <input type="checkbox" id="nombre1" value="PasarValor();"
 class="form-control">

 <input type="text"  id="nombre2" placeholder="Recibe contenido"
 class="form-control">

 </form>

A: Es un error de sintaxis, si te fijas has puesto la llamada al método en la propiedad value de tu input, lo correcto seria usar la propiedad onClick, de esta manera:
<input type="checkbox" id="nombre1" onClick="PasarValor()" class="formcontrol">


text:
Q: Android: Align many buttons nicely I have a RelativeLayout with 12 buttons, I want to align them nicely in the center of the screen and with equal distance to each others and equal left and right margins (like calculator buttons or telephone buttons). What I have done is in this XML file and the result in the pic, but it is still not perfect. Do you guys have any better solution for this?

 <RelativeLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/tabview1">
    <TextView
        android:id="@+id/logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="www.fasttest.me"
        android:textColor="@android:color/white"/>

    <Button
        android:id="@+id/ql0"
        android:layout_width="@dimen/qlbutton_width"
        android:layout_height="@dimen/qlbutton_height"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="10dp"
        android:text="b0" />
   <Button
        android:id="@+id/ql1"
        android:layout_width="@dimen/qlbutton_width"
        android:layout_height="@dimen/qlbutton_height"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="80dp"
        android:text="b1" />
   <Button
        android:id="@+id/ql2"
        android:layout_width="@dimen/qlbutton_width"
        android:layout_height="@dimen/qlbutton_height"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="150dp"
        android:text="b2" />
    <Button
        android:id="@+id/ql3"
        android:layout_width="@dimen/qlbutton_width"
        android:layout_height="@dimen/qlbutton_height"
        android:layout_marginTop="100dp"
       android:layout_marginLeft="220dp"
        android:text="b3" />
    <Button
        android:id="@+id/ql4"
        android:layout_width="@dimen/qlbutton_width"
        android:layout_height="@dimen/qlbutton_height"
        android:layout_marginTop="180dp"
        android:layout_marginLeft="10dp"
        android:text="b4" />
   <Button
        android:id="@+id/ql5"
        android:layout_width="@dimen/qlbutton_width"
        android:layout_height="@dimen/qlbutton_height"
        android:layout_marginTop="180dp"
        android:layout_marginLeft="80dp"
        android:text="b5" />
   <Button
        android:id="@+id/ql6"
         android:layout_width="@dimen/qlbutton_width"
        android:layout_height="@dimen/qlbutton_height"
        android:layout_marginTop="180dp"
        android:layout_marginLeft="150dp"
        android:text="b6" />
    <Button
        android:id="@+id/ql7"
        android:layout_width="@dimen/qlbutton_width"
        android:layout_height="@dimen/qlbutton_height"
        android:layout_marginTop="180dp"
        android:layout_marginLeft="220dp"
        android:text="b7" />
   <Button
        android:id="@+id/ql8"
        android:layout_width="@dimen/qlbutton_width"
        android:layout_height="@dimen/qlbutton_height"
        android:layout_marginTop="260dp"
       android:layout_marginLeft="10dp"
        android:text="b8" />
   <Button
        android:id="@+id/ql9"
        android:layout_width="@dimen/qlbutton_width"
        android:layout_height="@dimen/qlbutton_height"
        android:layout_marginTop="260dp"
        android:layout_marginLeft="80dp"
        android:text="b9" />
   <Button
        android:id="@+id/ql10"
        android:layout_width="@dimen/qlbutton_width"
        android:layout_height="@dimen/qlbutton_height"
        android:layout_marginTop="260dp"
       android:layout_marginLeft="150dp"
        android:text="b10" />
    <Button
        android:id="@+id/ql11"
        android:layout_width="@dimen/qlbutton_width"
        android:layout_height="@dimen/qlbutton_height"
        android:layout_marginTop="260dp"
       android:layout_marginLeft="2dp"
        android:text="b11" />
   </RelativeLayout>

A: I suggest you use buttons inside a GridView. Give each button the same weigh so it stretches itself:
<Button
    android:id="@+id/ql3"
    android:layout_height="@dime/button_height"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:padding="@dimen/buttons_padding"
    android:text="b3" />

A: You can use this custom GridLayout from Romain Guy. Specifiy the number of rows and columns. And the screen will be divided into equally sized cells.
Here is the link

A: I finally get it done with a gridview of buttons. Here is the code:
public class MainActivity extends Activity {
    public String[] filenames ={"B1","B2","B3","B4","B5","B6"};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GridView gridView = (GridView) findViewById(R.id.gridview);
        gridView.setAdapter(new ButtonAdapter(this));
        gridView.setOnItemClickListener(new OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent,
            View v, int position, long id){
                Toast.makeText(getBaseContext(),
                        "pic" + (position + 1) + " selected",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    public class ButtonAdapter extends BaseAdapter {
        private Context context;
        public ButtonAdapter(Context c){
            context = c;
        }
        public int getCount() {
            return filenames.length;
        }
        public Object getItem(int position) {
            return position;
        }
        public long getItemId(int position) {
            return position;
        }
        public View getView(int position, View convertView, ViewGroup parent){
              Button btn;
                 if (convertView == null) {
                  btn = new Button(context);
                  btn.setLayoutParams(new GridView.LayoutParams(100, 100));
                  btn.setPadding(8, 8, 8, 8);
                  btn.setFOcusable(false);
                  btn.setClickable(false);
                  }else {
                  btn = (Button) convertView;
                 }
                 btn.setText(filenames[position]);
                 btn.setTextColor(Color.WHITE);
                 btn.setId(position);
                 return btn;
        }
    }
}


text:
Q: How to pass a super long argument in the terminal? I wrote a Python programme, that accepts an argument I pass to it. But when I pass a very very long argument, it automatically shortens my argument.  How can I fix it?

A: Put all of the arguments in a text file, one per line. Then,
xargs python myprogram.py < argslist.txt

xargs reads in a list of tab, newline, or space-delimited arguments from standard in, and then feeds it to the utility to be executed after additional arguments on the command line.
So where here we have xargs utility arg1 < extraArgs.txt, xargs is going to execute utility, pass arg1 as the first argument and then since we are redirecting the contents of extraArgs.txt to xargs' standard in stream, it will append the arguments after arg1.


text:
Q: How to Print Total number of households based on income brackets. Keeps repeating This is what I'm getting. The code repeats per how many households sum to each particular bracket:

This is what I'm trying to achieve:

Code:
print("Welcome to the San Diego Community Survey")
total_people=[]
total_households=[]
total=[]
count=0
income_total_list = []
new_analysis="yes"
print()
print("Let's get started!")
print()
while new_analysis.lower().strip() =="yes":

    print()
    houses=int(input("How many households would you like to report? "))
    print()
    for i in range(0,houses,1):
        household_n=int(input("How many people in household {}? ".format(i+1)))
        total_households.append(household_n)

        print()
        income_total =0
        for i in range(0,household_n,1):
            x=float(input("What was person {}'s income last year? ".format(i+1)))
            total_people.append(household_n)
            total.append(x)
            income_total = income_total + x
            income_total_list.append(income_total)

        print()
    print()
    print("_________________________________________________________")
    count = len(total_households)
    print("Households analyzed: ", count)
    running_total = 0
    for element in total_households :
        running_total = running_total + element

    print("Number of people in census:", running_total)
    average = sum(total_households) / count
    print("Average people per household:", round(average))
    print()
    print("Average individual income: $",round(sum(total)/len(total),2))

    print("Average household income: $",round(sum(total)/len(total_households),2))
    print()
    print("Income distribution: ")
    for element in income_total_list:

        #print(element)
        if 20000 <= element < 40000:
            print("        At least $20,000 but less than $40,000: household(s)")
        elif 40000 <= element < 60000:
            print("        At least $40,000 but less than $60,000: household(s)")
        elif 60000 <= element <80000:
            print("        At least $60,000 but less than $80,000: household(s)")
        elif 80000 <= element :
            print("        At least $80,000: household(s)")
            print()
    new_analysis= input("Would you like to analyze another area (yes/no): ")
    print()

print("Thanks for participating in our survey!")

A: I would restructure the if statements as follows:
  if element>=20000 and element<40000:
        print("        At least $20,000 but less than $40,000: household(s)")
    elif element >=40000 and element<60000:
        print("        At least $40,000 but less than $60,000: household(s)")
.
.
.
and so on

A: At the end of the code, try putting the print statements outside of the for loop as they only need to occur once. Then inside of the for loop do your calculations on what each loop should produce:
small = 0
medium = 0
large = 0
xlarge = 0
for element in income_total_list:

    #print(element)
    if 20000 <= element < 40000:
        small += 1
    elif 40000 <= element < 60000:
        medium += 1
    elif 60000 <= element <80000:
        large += 1
    elif 80000 <= element :
        xlarge += 1

print(f"        At least $20,000 but less than $40,000: {small} household(s)")
print(f"        At least $40,000 but less than $60,000: {medium} household(s)")
print(f"        At least $60,000 but less than $80,000: {large} household(s)")
print(f"        At least $80,000: {xlarge} household(s)")


text:
Q: How to send Firebase Notifications with URIs to implement deep linking? tr;dr
Just realized that this question only applies to Android because iOS handles notification a bit differently and you can do what you want with your notification.
With my understanding now I can simplify my question to the following:

How to make an Android device display a notification with a deep link configured from a URI without coding at all?

We need to show notifications with deep links on the system tray of Android and iOS platforms, each notification has to open a specific screen of the apps.
The deep link has to be configured using URIs.

On Android, when the app is in the foreground the message from Firebase has to be handled manually. This way we are able to read all the data from the remote message and build a notification with a deep link configured using the URI.
But when the app is in the background the notification is displayed automatically by Firebase. It's not possible to configure a deep link on it.

We know it's possible to send data messages instead of notification messages. This would be a solution on Android because every message has to be handled manually making it possible to build the notification as we please with URI, deep links, and everything.
But this won't work on iOS. On iOS it is mandatory to send notifications messages.

This is the basic JSON that Firebase accepts:
{
  "message": {
    "notification": {
      "title": "Lorem",
      "body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit"
    },
    "token": "..."
  }
}

We tried setting several combinations of message.uri, message.link, message.action, message.click, message.click_action but none of them worked.
We also tried with data.uri, data.link, data.action, data.click, data.click_action but again we had no luck.
Reading the Firebase source code (NotificationsParams:212) we found that there is a way to configure a link on the notification, but we didn't find anything about it on the docs.
Where and how can we specify the URI so that the notification is automatically built using it and also available when the app is in the foreground?

A: It seems that sending gcm.n.link in the data object works.
With the following json, Firebase Messaging 20.2.4 will automatically build a notification with the value of gcm.n.link in its data:
{
  "message": {
    "notification": {
      "title": "Lorem",
      "body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit"
    },
    "data": {
      "gcm.n.link": "app://details/identifier"
    },
    "token": "..."
  }
}

Configuring an Intent Filter that matches that URI on an Activity will make Android open that Activity when the notification is tapped.
I haven't found anything related to it in the docs, found this going through their source code. So not sure if gcm.n.link it's supposed to be used or what but, it works so I'm happy.
If someone knows something about this please comment.


text:
Q: Decrypt AES-256-CFB in PHP with openssl instead mcrypt The function below correctly decrypt the data in php5
function decrypt_mcrypt($key, $str) {
  $str = base64_decode($str);
  $iv = substr($str, 0, 16);
  $str = substr($str, 16);
  return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_CFB, $iv);
}

I tried to use openssl instead of mcrypt (in php7), but got garbage on the output.
function decrypt_openssl($key, $str) {
  $str = base64_decode($str);
  $iv = substr($str, 0, 16);
  $str = substr($str, 16);
  return openssl_decrypt($str, 'AES-256-CFB', $key, OPENSSL_RAW_DATA, $iv);
}

What could be the problem?

A: openssl_decrypt uses PKCS#5 padding, where as mcrypt pads messages with zeros.
Try using the OPENSSL_ZERO_PADDING option when using openssl_decrypt as per the docs.


text:
Q: create table in sql server specific to sql database I have 2 databases which work together to monitor the doors being opened. The structure of the databases is similar to the below:
Database 1- Events Table:

*

*EventId (Autonumber)

*EventDateTime (Date and time)

*DoorId (int)

*Person (int) - Stores the PersonId

Database 2 - Persons table:

*

*PersonId (Autonumber)

*Person FirstName

*PersonLastName

Using php I need help to return the following information:

*

*EventDateTime (from Events table in Database 1).

*Person Name (From Persons table in Database 2).

Is it possible to return data from 2 seperate (but related) databases?


text:
Q: How to use {section} in smarty to print an associative array? I want to print an associative array using section but I'm not able to do so.Following is the PHP and Smarty code :
PHP Code :
  $smarty->assign('$all_latest_news',       $grid_data);

In the above code $grid_data is an associative array which is assigned to the smarty template. For your information the array looks like this after printing using print_r($grid_data):
Array ( [0] => Array ( [news_id] => 1 [news_title] => News Channel URL [news_link] => http://indiatoday.intoday.in/ [news_added_date] => 2013-02-26 ) [1] => Array ( [news_id] => 2 [news_title] => News Paper Web Address [news_link] => http://www.bhaskar.com/ [news_added_date] => 2013-02-25 ) )

Now I want to print this array in smarty template the code snippet for this is as follows :

                    News Title
                    News Link
                    Option

                {section name=news loop=$all_latest_news}

                    {$all_latest_news[news].news_title}
                    {$all_latest_news[news].news_link|truncate:350:" ...":true}

                    Edit
                      Delete

                {sectionelse}

                    No News Available

                {/section}

Using this code I'm not able to print the array values to the respective columns. The column headings getting printed properly. After that the {sectionelse} part is executed and the message "No News Available" gets printed.
Actually I want to print the values in array. Can anyone help me out to resolve this issue? Thanks in advance.

A: When you assign the values to variables in Smarty, you don't want to put '$' symbol. Change your code to,
$smarty->assign('all_latest_news', $grid_data);

A: Change $smarty->assign('$all_latest_news',       $grid_data);
to :
$smarty->assign('all_latest_news',       $grid_data);
Use this :
{foreach from=$all_latest_news item=news name=news}
   {$news.news_title}
{/foreach}

Ref: http://www.smarty.net/docsv2/en/language.function.foreach


text:
Q: Multiple try-catch blocks inside async function I have an async function where there is some operations like this:
async function myAsyncFunction(argument) {

  let arrayTasks = [
    {
      const run = async () => {
        let response = await getDataAsync();
      }
    },
    {
      const run = async () => {
        let response = await getDataAsync();
      }
    }
  ]

  for (const index in arrayTasks) {
      await arrayTasks[index].run();
  }
}

The function above is a simplified version of my code, it works. But I am not sure where do I need to put  try-catch block:
Wrapping all content function:
async function myAsyncFunction(argument) {
  try{
    // All code
  }catch (e) {
    // catch code
  }
}

Or inside my asyncs functions and for operator:
async function myAsyncFunction(argument) {

  let arrayTasks = [
    {
      const run = async () => {
        try{
          let response = await getDataAsync();
        }catch (e) {
          // catch code
        }
      }
    },
    {
      const run = async () => {
        try{
          let response = await getDataAsync();
        }catch (e) {
          // catch code
        }
      }
    }
  ]

  for (const index in arrayTasks) {
    try{
      await arrayTasks[index].run();
   }catch (e) {
     // catch code
   }

  }
}

What is a correct way?
 The arrayTasks variable is dynamic length on my original code.

A: Depends how and where you want to handle failure.
One approach to "an array of asynchronous tasks whose execution may fail" is a pattern like this:
async function myAsyncFunction(argument) {

  const success = async res => ({ success: await res }) // Promise<{success: res}>
  const error = async err => ({ error: await err }) // Promise<{error: e}>

  const arrayTasks = [
    {
      run: async () => getDataAsync()
      }
    },
    {
      run: async () => getDataAsync()
    }
  ]

   const runWithResult = task => task.run().then(success).catch(error)

   const outcomes = await Promise.all(arrayTasks.map(runWithResult))

   console.log(outcomes) // array of {error: e} | {success: res}

}

You can chain a .catch() handler on an async function, and it has the same effect as wrapping it in try/catch.
More here, if you are interested. The section "Refactor without fp-ts" shows how to reduce that array from [{error: e} | {success: res}] to {error: [], success: []}, which is way easier to work with:
const { error, success } = outcomes.reduce((acc, o) => o.error ?
    { error: [...acc.error, o.error], success: acc.success } :
    { error: acc.error, success: [...acc.success, o.success] },
    { error: [], success: [] })

This is an FP type called Either - an operation may return "either" (in this case) a value or an error.
Your code doesn't throw with this approach.
If you know that something may fail, it's not exceptional. Exceptions are when some unexpected failure occurs, IMHO.
"Tasks that may fail" that are known ahead of time just need the error path code written.
If you take this approach, I recommend building it as a first-class state reducing machine, like this:
// Takes an array of async tasks that may throw of shape {run: () => Promise<result>}
// Returns Promise<{error: error[], success: result[]}>

async function executeAsyncTasks(arrayOfAsyncTasks) {
  const success = async res => ({ success: await res }) // Promise<{success: res}>
  const error = async err => ({ error: await err }) // Promise<{error: e}>

  const runWithResult = task => task.run().then(success).catch(error)
  const outcomes = await Promise.all(arrayOfAsyncTasks.map(runWithResult))

  const outcomesFlat = outcomes.reduce((acc, o) => o.error ?
    { error: [...acc.error, o.error], success: acc.success } :
    { error: acc.error, success: [...acc.success, o.success] },
    { error: [], success: [] })
  return outcomesFlat
}

A: It all depends... My rule of thumb is only catch something if you intend on doing something with it, i.e some error handling.  If the handling of the error is going to be the same across all cases, wrap the it all with one try/catch, else wrap individual cases, with their own error handling code.


text:
Q: How to capitalize every string in Java? I'm working on this java method trying to capitalize the nth word in a string and got stuck on not being able to return a value for retVal variable
class MyTesting
{
public static void main (String[] args) throws java.lang.Exception
{
    capitalizeEveryNthWord("this is a String", 3, 3);
}

// Take a single-spaced <sentence>, and capitalize every <n> word starting   with <offset>.

public static String capitalizeEveryNthWord(String sentence, Integer offset,     Integer n) {
String[] parts = sentence.split(" ");
String retVal = "";
for (int idx = 0; idx < offset; idx++)
{
    retVal.concat(parts[idx] + " ");
}
for (int idx = offset; idx < parts.length; idx++)
{
    if (idx - offset % n == 0)
    {
        retVal.concat(parts[idx] + "-");
    }
    else
    {
        retVal.concat(parts[idx] + " ");
    }
}
System.out.println(retVal);
return retVal;
}
}

A: concat() returns a value, it doesn't modify the string on which you're calling the method. You need to use it as retVal = retVal.concat(...) or simply retVal += ...

A: Java's String class is immutable. String.concat() will return the concatenation as a new String object.
You can either use retVal = retVal.concat(...), or use a StringBuilder.
The following works:
class MyTesting
{
  public static void main (String[] args) throws java.lang.Exception
  {
    capitalizeEveryNthWord("this is a sentence that is being tested", 3, 3);
  }

  // Take a single-spaced <sentence>, and capitalize every <n> word starting   with <offset>.
  public static String capitalizeEveryNthWord(String sentence, Integer offset, Integer n) {
    String[] parts = sentence.split(" ");
    String retVal = "";
    for (int idx = 0; idx < offset; idx++)
    {
        retVal += parts[idx] + " ";
    }
    for (int idx = offset; idx < parts.length; idx++)
    {
        if ((idx - offset) % n == 0) // added parantheses
        {
            retVal += Character.toUpperCase(parts[idx].charAt(0)) + parts[idx].substring(1) + " "; // make the first character uppercase.
        }
        else
        {
            retVal += parts[idx] + " ";
        }
    }
    System.out.println(retVal);
    return retVal;
  }
}

A more efficient approach would be something like:
public static String capitalizeEveryNthWord(String sentence, Integer offset, Integer n) {
  StringBuilder sb = new StringBuilder(sentence);
  int wordIdx = 0;
  boolean newWord = true;
  for (int i = 0; i < sb.length(); i++) {
    char c = sb.charAt(i);
    if (c == ' ') {
      wordIdx++; // assumes single space between words.
      newWord = true;
    } else if (newWord) {
      if (wordIdx >= offset && (wordIdx - offset) % n == 0) {
        sb.setCharAt(i, Character.toUpperCase(c));
      }
      newWord = false;
    }
  }
  return sb.toString();
}

This second approach only allocates one buffer which is then modified in-place to capitalize words. The previous approach allocates new String objects with every call to += (this can occasionally be optimized away by compilers but it's not guaranteed, as far as I know).

A: Use toUpperCase() method and use the returned value :
String retVal = retVal.concat(...).toUpperCase();


text:
Q: Why my add friend testing route goes through in insomina with 200 OK, but it's not nested when I call to get all users? I am working with mondoDB and moongose NoSQL. When I try to add a friend to a user, I have this code.
 addFriend({ params }, res) {
   User.updateOne
   ({ _id: params.friendId })
     .then(dbUserData => res.json(dbUserData))
     .catch(err => res.json(err));
 },

http://localhost:3001/api/users/61286c3285a0afa77a1b869e/friends/6128178de88611885576fdd6
That's the testing route and I get this:
{
  "driver": true,
  "name": "MongoError",
  "index": 0,
  "code": 66
}

The goal is to have it added in the main route:
http://localhost:3001/api/users
This is what I get:
 {
    "_id": "61286c3285a0afa77a1b869e",
    "username": "testing",
    "email": "testing@gmail.com",
    "friends": []
  },

The goal is to have it nested into the friend's array.

A: for updating doc you must query to specific doc userId and update the doc push friendId to friend field
addFriend({ params }, res) {
   User.updateOne
   ({ _id: params.userId },{$push:{friends:params.friendId})
     .then(dbUserData => res.json(dbUserData))
     .catch(err => res.json(err));
 },


text:
Q: Am I adding Spring Security to my project correctly? Access error after authorization Spring-MVC project. There are 3 classes Cook, Cytomer andes Admin. All of them are inherited through @OneToOne from User. I added Spring-Security on tutorials and guides. But after authorization, no entity method is available to me. For example, if I log in as Cook, he does not call his methods, gives json an error:
403 FORBIDDEN

I don't know what to do. Looked at all the documentation. I checked the bugs, but I can't figure out what I'm doing wrong.
WebSecConfig:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    // Поля
    //
    private UserService userService;

    private PasswordEncoder passwordEncoder;

    // Injects in SETTERS
    //
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    // Methods
    //
    // Тут мы переопределяем метод конфигураций
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

    // Тут мы переопределяем для работы с внешней БД
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder);
    }

    // Beans
    //
    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userService);
        authenticationProvider.setPasswordEncoder(passwordEncoder);
        return authenticationProvider;
    }

    @Bean
    public static PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder(8);
    }

}

User
@ApiModel
@Data
@Entity
@Table(name = "pg_user", schema = "public")
public class User implements UserDetails {

    // Roles
    //
    public static final String ROLE_ADMIN = "ADMIN";
    public static final String ROLE_CUSTOMER = "CUSTOMER";
    public static final String ROLE_COOK = "COOK";
    //

    public User() { // Пустой конструктор для Hibernate

    }

    // Поля
    private @Id
    @GeneratedValue
    Long id;

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

    @Size(min = 5, max = 30)
    @Column(name = "password")
    private String password;

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

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

    @Column(name = "last_name")
    private String lastName;

    // Методы
    //
    // GrantedAuthority
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + role));
    }

    // userName == login (одно и тоже)
    @Override
    public String getUsername() {
        return login;
    }

    // Во всех флагах стоит TRUE, так как они не используются
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
    //
}

UserServ:
@Service
public class UserService implements UserDetailsService {

    // Fields
    //
    private UserRepository userRepository;

    private PasswordEncoder passwordEncoder;

    // Injects are here
    //
    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Autowired
    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    // Методы
    //
    //
    public static User getCurrentUser() {
        return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    // Сменить пароль !!!!!!!!!!!!!!! РАЗОБРАТЬСЯ ЧТО ТАК А ЧТО НЕТ
    public void changePassword(String login, String newPass) {
        /**НПЕ из того что не находит юзера с таким логином**/
        User user = userRepository.getByLogin(login);

        try {
            user.setPassword(newPass);
            userRepository.save(user);
        } catch (NullPointerException e) {
            throw new NullPointerException("Ошибка! Указанный Вами логин не существует!"); // Надо посмотреть в чем дело
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException();
        } catch (NotFoundException e) {
            throw new NotFoundException(user.getId());
        }
    }

    // Загрузка пользователя по login (метод от интерфейса)
    @Override
    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
        User user = getUserDataByLogin(login);
        if (user == null) {
            throw new UsernameNotFoundException("не нашли" + login);
        }
        return user;
    }

    private User getUserDataByLogin(String login) {
        User user = userRepository.getByLogin(login);
        return user;
    }
}

A: When calling your API from the browser, this error can occur due to CORS/CSRF issues. You can disable both in your WebSecurityConfig inside the configure(HttpSecurity http) method:
@Configuration
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    // Methods
    //
    // Тут мы переопределяем метод конфигураций
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors().disable()
            .csrf().disable()
            .authorizeRequests()
            ...
    }
}

Please be aware that disabling cors and/or csrf might be a security issue in a prod environment.


text:
Q: How to upgrade my facebook Graph API app from v2.1 to v2.8 directly? Facebook message :Currently you has access to Graph API v2.1 which will reach the end of its 2-year lifetime on 30 October, 2016. To ensure a smooth transition, please migrate all calls to Graph API v2.2 or higher.

A: There is no way to do that, app will upgrade one step at a time but specify the API version explicitly in all calls. If SDK is being used , that should be configurable in one specific place. If not, modification is needed in multiple places.


text:
Q: What is the difference between i+=d and i=i+d in Java? Duplicate:

java += question
Why aren't op-assign operators type safe in java?

When i is an integer and d is a double, i+=d works but i= i+d does not.
Why is this?

A: i = i + d does not work because you would be assigning a double to an int and that is not allowed.
The += operator casts the double automatically to an int, so that is why it works.
This is the link to the information on the spec:
http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#5304


text:
Q: Discord bot hosted on heroku, doesn't run So I made a discord bot and I hosted it on heroku using github. I added some more functions, edited the code on github and finally deployed the bot again. And now the bot won't run.
Just exits process with Process exited with status code 0, not running the bot.
I tried running it with a different bot token and it works.
Here is the output when I use a different bot token.
2020-10-29T09:45:32.309985+00:00 heroku[worker.1]: State changed from starting to up
2020-10-29T09:45:37.359078+00:00 app[worker.1]: Running as another music bot
2020-10-29T09:45:37.431057+00:00 app[worker.1]: Reddit Cog Loaded
2020-10-29T09:45:37.434029+00:00 app[worker.1]: Help Cog Loaded
2020-10-29T09:45:37.445268+00:00 app[worker.1]: Booru Cog Loaded
2020-10-29T09:45:38.848149+00:00 heroku[worker.1]: Process exited with status 0

And here is the output when I use the original bot token. (Tried regenerating the token too, but no, nothing.)
2020-10-29T10:14:46.286805+00:00 heroku[worker.1]: State changed from starting to up
2020-10-29T10:14:52.890101+00:00 heroku[worker.1]: Process exited with status 0

The problem is not that the code doesn't work, but that it works with a different bot's token.
Meaning there are no errors in the code, I guess?
I know the status 0 means no errors but as you can see the bot doesn't even start to print those lines...
Not knowing what to do, here I am...


text:
Q: Why can't we directly observe homogeneity because we "observe down the past light cone"? Homogeneity is the idea that the universe looks roughly the same no matter where the observer is. This paper on whether the universe is homogeneous includes this line:

A common misconception is that 'homogeneity is obvious from the cosmic microwave background (CMB) and the galaxy distribution'. In fact, we cannot directly observe or test homogeneity—since we observe down the past light cone, and not on spatial surfaces that intersect that light cone (figure 1).

It comes with this figure:

Which has the caption: Figure 1. We observe down the past light cone and therefore cannot directly confirm homogeneity. (Online version in colour.)
I don't understand this argument. My intuitive understanding for why we can't directly observe homogeneity is simply that we're on Earth and can't just fly a telescope to e.g. Andromeda to see what the universe looks like from another galaxy. The argument in the paper seems to be saying that we cannot directly observe homogeneity because everything we see is in the past; however it still seems to me that if the universe was homogeneous in the past then we would expect it to be homogeneous today. Alternatively, we could in principle measure the positions & velocities of all the other galaxies in the past, evolve them forward using GR, and therefore tell if our universe is homogeneous today.
Can someone explain how the paper's argument works?

A: This is a very good question. I hope I can explain it clearly to you here. I'll try to be pedagogical.
Consider a tabletop spread of seeds. You can say that the distribution of seeds is homogogeneous at some length scale $L$ if the number of seeds per area $L^2$ (or unit volume $L^3$) is constant throughout the spread.
You are allowed to make this statement because you can see the entire system from a global perspective at any instance of time. Furthermore the dynamics of this small arrangement is for this purpose instantaneous.
In cosmology, this "Newtonian" notion of instantaneity is abolished. (ignoring quantum effects) This means that no two events where one influences the other are ever spacelike seperated and therefore never on the same spacelike hypersurface. This is simple the causal nature of spacetime. (Note that the effect of time evolution in GR is basically acting a time evolution operator on every spacelike hypersurface, leading to a  foliation of spacetime.)
Given this knowledge: What this means is that if you are observing any other system in the universe, it necessarily exists on a different spatial hypersurface and in the past light cone.
Coming back to our analogy of seeds on a table: Now if you try to define homogeneity here, it is like trying to compare the distribution of seeds with some population density $P_A$ on table A with the distribution of seeds with some other population density $P_B$ on some other table B. It doesn't make sense anymore.
What does alleviate this problem is isotropy. Isotropy of the universe basically states that if you look at any direction in the sky i.e. at any direction in the past light cone, changing the direction doesn't really change the observation. That means that all the points $d_1$ light years away look similar, all the points $d_2$ light years away look similar and so on and so forth. This allows us to extrapolate and make the claim that if we were capable of viewing the universe as a whole, by this logic, it should be homogeneous.
Bottom line is that you need isotropy for homogeneity. We can't observe homogeneity, we can only infer it through isotropy.


text:
Q: How to test and edit someone's pull request using Visual Studio Code and push sugggested edits to existing PR? I have a public GitHub repository.
Someone submitted a pull request.
I would like to test and edit pull request in Visual Studio Code and push suggested edits to existing pull request so they can be discussed and merged on GitHub.
I use Visual Studio Code as my code editor, but question isn't specific to Visual Studio Code.
Is this possible using git command?

A: I have to admit that I never tried it, but as far as I could see, you need to:

*

*Install the GitHub Pull Requests and Issues from the Marketplace.

*Select your pull request from the list within Visual Studio Code.

*Click "Checkout".

*Review the pull request and finish your review.

There is also a cool demo on the code.visualstudio.com blog
.

A: Since the Pull Request is from a fork, you can't push changes to the PR yourself unless you also have access to the fork, or the PR creator grants you permission. You can make suggestions in a PR review though.
However, you can check out and test the PR yourself using git:
git fetch origin refs/pull/2/head:pr/2
git checkout pr/2

Source: GitHub clone from pull request?


text:
Q: Altering Fake Columns based on Query Values I am trying to run a query and change fake column values based on whether the internal queries return anything.
Basically I want the below code to be able to change WI to a 1 if id is in table2 and SI to 1 if id is in table3
SELECT name, grade, id, 0 as WI, 0 as SI FROM students
WHERE id in table1
AND (id in table2
OR id in table3)

I've been googling around but haven't run across anything, I think mostly because I don't know what the "fake" columns are actually called.
Any help would be appreciated, thank you!
Edit:
Data looks something like this:
name  grade  id
s1    1      0
s2    1      1
s3    2      7

and the goal would be to have something like this come out after the query:
name  grade  id  WI  SI
s1    1      0   0   1
s2    1      1   1   1
s3    2      7   1   0

EDIT 2:
Here is my actual query:
SELECT CARE1.students.first_name, CARE1.students.grade, CARE1.students.id,
CARE1.student_test_info.test_num, CARE1.student_test_info.date_of_testing,
0 as WI, 0 as SI, 0 as OC, 0 as SL
FROM CARE1.students INNER JOIN CARE1.student_test_info ON CARE1.students.id = CARE1.student_test_info.student_id

WHERE id IN (SELECT DISTINCT studentID from CARE1.WI)
AND (id NOT IN (SELECT DISTINCT studentID from CARE1.SI)
OR id NOT IN (SELECT DISTINCT studentID from CARE1.OC))

Basically each of the tables (WI, SI, etc) have test info in them and we are trying to make sure everyone took all of the tests. The query works in giving me the list of people that missed a test, but doesn't tell me what tests they missed, that is what I am trying to figure out.

A: SELECT name, grade, id, 1 as WI, 0 as SI FROM students
WHERE id in table1
AND id in table2
UNION
SELECT name, grade, id, 0 as WI, 1 as SI FROM students
WHERE id in table1 AND
id in table3

A: INNER JOIN to table1 to get ids that exist there only. LEFT JOIN to tables 2 & 3. Using a case statement will give you the flexibility to display any custom value based on this logic if you need anything other than 0 or 1...
SELECT name,
        grade,
        id,
        CASE WHEN t2.ID IS NOT NULL THEN 1 ELSE 0 END as WI --update with any value you want to display,
        CASE WHEN t3.ID IS NOT NULL THEN 1 ELSE 0 END as SI
    FROM
        students s INNER JOIN
        table1 t1 on s.id = t1.id LEFT OUTER JOIN
        table2 t2 on s.id = t2.id LEFT OUTER JOIN
        table3 t3 on s.id = t3.id

A: SELECT s.name, s.grade, s.id,
 MAX(t2.id IS NOT NULL) AS WI,
 MAX(t3.id IS NOT NULL) AS SI
FROM students s
LEFT JOIN table2 t2
ON s.id = t1.id
LEFT JOIN table3 t3
ON s.id = t3.id
GROUP BY s.id

A: Assuming the WHERE conditions are correct - You can use the same conditions in the SELECT clause:
SELECT
    CARE1.students.first_name,
    CARE1.students.grade,
    CARE1.students.id,
    CARE1.student_test_info.test_num,
    CARE1.student_test_info.date_of_testing,
    id IN (SELECT DISTINCT studentID from CARE1.WI) as WI, -- is always 1 due to WHERE condition
    id IN (SELECT DISTINCT studentID from CARE1.SI) as SI,
    id IN (SELECT DISTINCT studentID from CARE1.OC) as OC,
    0 as SL -- What is SL?
FROM CARE1.students
INNER JOIN CARE1.student_test_info
    ON CARE1.students.id = ARE1.student_test_info.student_id
WHERE id IN (SELECT DISTINCT studentID from CARE1.WI)
  AND (id NOT IN (SELECT DISTINCT studentID from CARE1.SI)
    OR id NOT IN (SELECT DISTINCT studentID from CARE1.OC))

However - I would suggest to use EXISTS subqueries instead of IN. And also use a HAVING clause with aliases of calculated colums to avoid code duplication:
SELECT
    CARE1.students.first_name,
    CARE1.students.grade,
    CARE1.students.id,
    CARE1.student_test_info.test_num,
    CARE1.student_test_info.date_of_testing,
    1 as WI, -- is always 1 due to WHERE condition
    EXISTS (SELECT * from CARE1.SI WHERE CARE1.SI.studentID = CARE1.students.id) as SI,
    EXISTS (SELECT * from CARE1.OC WHERE CARE1.OC.studentID = CARE1.students.id) as OC,
    0 as SL -- What is SL?
FROM CARE1.students
INNER JOIN CARE1.student_test_info
    ON CARE1.students.id = ARE1.student_test_info.student_id
WHERE EXISTS (SELECT * from CARE1.WI WHERE CARE1.WI.studentID = CARE1.students.id)
HAVING SI = 0
    OR OC = 0


text:
Q: EXCEL VBA VLOOKUP when the source is QUERY TABLE (or ListObject) I'm stuck, I used to run a code that perform a vlookup from a query (data from web power query) - see example in the code below).
It all ran smooth, until i tried to add more queries, and then I needed to change the function to perform the vlookup from varies queries, and for that I needed the queryName to be a var. no matter what I try, it doesn't work for me (replacing the "US" in the vlookup):
Function doVlookup(selectedSheet As String)

Dim queryName As ListObject
Set queryName = Worksheets("US API").ListObjects(1)

Debug.Print queryName.Name

Sheets(selectedSheet).Select
Range("A1").Select

Selection.End(xlToRight).Select
ActiveCell.Offset(0, 1).Columns("A:A").EntireColumn.Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
ActiveCell.Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "=IF(VLOOKUP(RC1,US,5,0)<>0, VLOOKUP(RC1,US,5,0),""-"")"
ActiveCell.Offset(-1, 0).Select
ActiveCell.FormulaR1C1 = "=TODAY()"
ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
Selection.End(xlUp).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Range("A1").Select
End Function

the var queryName, does have the desired table, but when I run the code it just return #NAME! for all keywords.
If I hard code it back to "US" (in the example, it is hard-coded) it runs without a problem.
I tried:

*

*queryName

*Range(queryName)

*queryName.Range

*queryName!R1:R100

*queryName.Range.Select

*queryName.DataBodyRange

For clarification "queryName" suppose to replace the "US" in the following: "=IF(VLOOKUP(RC1,US,5,0)<>0, VLOOKUP(RC1,US,5,0),""-"")" Just that I am not sure how it's done. "US" is a name of a table that is loaded from a connection of "data from web" to the sheet "US API".
any idea what should bet put in the place of the hard-coded US to make it work?

A: I realize it's a month after the fact, and you've likely moved on to bigger and better things, but I think I may know how to tackle this.  Here is an example of a dumbed-down spreadsheet and the VBA code that will implement a vlookup on various listobjects.

In this example, I use the corresponding table values from the first, second and third tables (listobjects) in each of the lookups for G7-9, just to show how each can be declared dynamically.
Dim lo As ListObjects
Set lo = ActiveSheet.ListObjects

Range("G7").FormulaR1C1 = "=VLOOKUP(RC[-1]," & lo(1).Name & "[#All],2,FALSE)"
Range("G8").FormulaR1C1 = "=VLOOKUP(RC[-1]," & lo(2).Name & "[#All],2,FALSE)"
Range("G9").FormulaR1C1 = "=VLOOKUP(RC[-1]," & lo(3).Name & "[#All],2,FALSE)"

I suspect the missing link in your code above is the [] following the listobject name, which indicates the range within the table to use.


text:
Q: Problema al mandar parametros en React por medio de un dispatch Tengo un componente que falla en mi componentDidMount al momento de hacer un dispatch a un action de Redux que tengo.
Componente.
constructor(props){
  super(props);

  this.state = {
     orders: {
      status: 1
     }
   }
 }
componentDidMount(){
  const { dispatch } = this.props;
  let { orders } = this.state;

  dispatch(orders.showOrders(orders));
}

Action
export const orders = {
  showOrders
}

function showOrders(params){
   console.log(params);
}

El problema es que me tira el siguiente error:
TypeError: orders.showOrders is not a function

Sin embargo, me di cuenta que cuando comento la línea de let { orders } y añado un objeto donde mando a llamar la función (action) de showOrders funciona, el código se ejecuta correctamente.
Curiosamente, trate de asignar a una variable un objeto y añadirla donde mando a llamar la función de showOrders y me tira el mismo error. ¿A qué se debe?

A: Tu mismo te respondiste jeje, el problema es que en la función componentDidMount declaraste una variable orders, y en ese ámbito orders no es el objeto con tu action, sino que es la porción del state del componente!
Cambiale el nombre al objeto de tus actions (a ordersActions por ejemplo) o al objeto de tu state para arreglar el problema.


text:
Q: How to create a variable in IIB which has scope for each single flow? I need to create a variable in IIB flow which has to be available through out the flow. I have gone through the variables creation in documentation. As per my understanding, I should create a SHARED variable in ESQL module. But in documentation its mentioned as "Subsequent messages can access the data left by a previous message." which I didn't understand.
Could anyone please suggest how to create a variable which should have scope only for that flow(only per each request/instance)?
For example if I have to capture total value of some elements in payload and store calculated value in the created variable which I can use across all the nodes throughout the flow .

A: The Environment tree structure can be used for your use case:

The environment tree differs from the local environment tree in that a single instance of it is maintained throughout the message flow.
When the message flow processing is complete, the Environment tree is discarded.


text:
Q: Custom mode in Brace wrapper for Ace Editor I am using Ace Editor with Angular 8: Brace wraps Ace Editor, and the ngx-ace-wrapper wraps Brace for Angular.
It is possible to create a custom mode for Ace Editor with ace.define(). However, Ace has a default folder for modes. It appears that this can be customized with a function called setModuleUrl in the config, but it doesn't appear to be accessible with the Brace wrapper.
I have tried setOption() with options like $moduleUrls, modePath and others, but these don't appear to be valid configuration options (Ace returns something like: misspelled option "modePath").
I cannot put the custom mode definition file inside the correct directory because it is not part of my module/repository. What is the correct way to do configure a custom mode path in Brace/ngx-ace-wrapper?


text:
Q: PHP curl headers(?) issue There is an addon for firefox called httprequester. (https://addons.mozilla.org/en-US/firefox/addon/httprequester/)
When I use the addon to send a GET request with a specific cookie, everything works fine.
Request header:
GET https://store.steampowered.com/account/
Cookie: steamLogin=*removed because of obvious reasons*

Response header:
200 OK
Server:  Apache
... (continued, not important)

And then I am trying to do the same thing with cURL:
$ch = curl_init("https://store.steampowered.com/account/");
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: steamLogin=*removed because of obvious reasons*"));
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
$response = curl_exec($ch);
$request_header = curl_getinfo($ch, CURLINFO_HEADER_OUT);

echo "
$request_header
";
echo "
$response
";

Request header:
GET /account/ HTTP/1.1
Host: store.steampowered.com
Accept: */*
Cookie: steamLogin=*removed because of obvious reasons*

Response header:
HTTP/1.1 302 Moved Temporarily
Server: Apache
... (continued, not important)

I don't know if it has anything to do with my problem, but a thing I noticed is that the first lines of the request headers are different
GET https://store.steampowered.com/account/

and
GET /account/ HTTP/1.1
Host: store.steampowered.com

My problem is that I get 200 http code with the addon and 302 with curl, however I'm sending (or trying to send) the same request.

A: If i really understand your problem, the thing is cURL is not following the redirect. He don't do that by default, you need to set a option:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

With this, cURL is able to follow the redirects.
To set the Cookies to the request use, (You may need pass the user agent):
curl_setopt($ch, CURLOPT_COOKIE, "Cookie: steamLogin=*removed because of obvious reasons*; User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");

A: The page is doing some redirect, so you must follow it
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

A: I think your addon sends the useragent string by default from the browser. If you add useragent string with your curl request, I believe your problem will resolve!
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Cookie: steamLogin=*removed because of obvious reasons*",
    "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0"
));


text:
Q: Installed and Portable version of a software on windows 11 Hello and happy new year.
I have a problem with my software. I've installed Visual Studio Code on my windows 11 and commonly I've installed some extensions on it.
also I have my Portable VS Code on an USB flash, but here's my problem. when I plug in my USB into my pc and open the VS Code, I don't know why windows open the installed version,  because I want to install some extensions on the portable VS Code manually but I can't because of this problem,so is there a way to solve it?


text:
Q: HTML 5 page navigation What is the preferred way to navigate between HTML5 web pages without using any server side scripting language. Would Jquery be a good choice?
Consider a user logs in and lands at home page. Home page contains many links to navigate to other pages.
Edit 1
I need to communicate to server via AJAX to perform some operations and pass on variables and data between web pages. But I cannot use JSP or PHP to create HTML dynamically.

A: for link to your different pages in HTML5 you use this code.
link 1
link 1
link 1

A: HTML

  Index
  Contact

jQuery
$(function(){
  $('nav a').on('click', function(e) {
    var htmlFile = $(this).attr('href');
    e.preventDefault();
    $('#content').load(htmlFile);
  });
});

A: I would say anchor tags are the best choice to do this because of their universal and flexible DOM use:
Page 1
Page 2
Page 3

If users will be logging in then you will have to use a scripting language such as PHP and establish database connections with MySQL.
jQuery has a very easy to use AJAX implementation.

A: It sounds like you're wanting to create a single page application that gets it's data from a third party service?
I would recommend Sammy.js for intercepting routes, and jQuery to do your actual ajax calling.
If you're doing a lot of dynamic content dynamic content I would also recommend Knockout.js

A: Great for use will be:
Page 1
Page 2
Page 3

It's more faster than using this:
Page 1

Of course, you'll need to have html subpages (page1...) in the same folder as your index.html.


text:
Q: Table View out of the window screen iOS objective C I have set constraint for my text field in story board. I want to create a table view under the text field with the following code. Setting the width similar to the textfield.frame.size.width brings the tableView all the way out of the screen, why? Please help.
-(void)cofigureAutoComTableView
{

    autocompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.txtActivity.frame.origin.x,self.txtActivity.frame.origin.y+32,self.txtActivity.frame.size.width, 200) style:UITableViewStylePlain];

    autocompleteTableView.delegate = self;
    autocompleteTableView.dataSource = self;
    autocompleteTableView.scrollEnabled = YES;
    //autocompleteTableView.
    autocompleteTableView.hidden = YES;
    [self.view addSubview:autocompleteTableView];

    CALayer *layer = autocompleteTableView.layer;
    [layer setMasksToBounds:YES];
    [layer setCornerRadius: 4.0];
    [layer setBorderWidth:1.0];
    [layer setBorderColor:[[UIColor blackColor] CGColor]];
}

A: It looks ike that because you are calling function when textview is that long, use it in viewDidAppear
[self cofigureAutoComTableView];

A: You can try
 -(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    if(once)
    {
        once = NO;

        [self conf];

   }

}

A: The problem is that in viewDidLoad the frames are not in the final form. Only in viewDidAppear the frames are final.
The best solution in this case is to update the autocompleteTableView's frame in viewDidLayoutSubviews.
viewDidLayoutSubviews is called every time the viewController's view frame is updated.
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    autocompleteTableView.frame = CGRectMake(self.txtActivity.frame.origin.x,self.txtActivity.frame.origin.y+32,self.txtActivity.frame.size.width, 200);

}