text:
Q: Why are checkboxes not reset by v-model? This is what i have:

*

*Template

    {{ value.title }}
    <input
      type="checkbox"
      v-model="filtersValues[filter.name]"
      :value="value.value"
    >

*And the part of my vue code:
data() {
  return {
    filtersList: {},
    filtersValues: {}
  }
},
beforeMount() {
  this.loadInitData();
  this.initFilters();
},
methods: {
  loadInitData() {
    const data = JSON.parse(this.$el.getAttribute('data-data'));

    this.filtersList = data.filters;
  },
  initFilters() {
    for (let i in this.filtersList) {
      if (!this.filtersList.hasOwnProperty(i)) {
        continue;
      }
      this.filtersValues[this.filtersList[i].name] = [];
    }
  }
}

It works, but when i call initFilters() method again (for reseting) checkboxes are still selected, and i don't know why.

A: The way you are assigning new, empty arrays to filterValues is not reactive.
If you change your initFilters to assign an entire new value to filterValues, you don't need to worry about using Vue.set(). For example
initFilters() {
  this.filtersValues = this.filtersList.reduce((vals, { name }) => ({
    ...vals,
    [ name ]: []
  }), {})
}

Demo ~ https://jsfiddle.net/cjx09zwt/

A: Where did filter.values come from in line 2 of template?
Anyways vue would not be able to track the changes you are making (judging from the visible code)
There are some caveats to vue 2's reactivity. Check here for more info.
TLDR; you will need to declare anything you want to be made reactive in the component's data option upfront.
HTH


text:
Q: How to intercept setter method with AOP I want to do something with a field BEFORE it gets the value assigned with a setter. I created the annotation and the aspect, but I don't know how to get the setter. This is my code:
@Aspect
public class AnnotationAspect{

    @Pointcut("@annotation(annotationVariableName)")
    public void annotationPointCutDefinition(Annotation annotationVariableName){
    }

    @Pointcut("execution(* *(..))")
    public void atExecution(){}

    @Around("annotationPointCutDefinition(annotationVariableName) && atExecution()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint, Annotation annotationVariableName) throws Throwable {
        Object returnObject = null;
        returnObject = joinPoint.proceed();

        return returnObject;
    }
}

The annotation @Annotation is applied to a field in scala, so the method is "field =" (I don't know if this can change something).
Can anyone help me?
Thanks!
EDIT
This is the annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Annotation{
}

And an example code:
class Test{

  @Annotation
  var testing: String =_

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to replace values for a group of columns and a single row in a data frame? I have a data frame as follows -
df <- cbind(c("a","b","c","d","e"),c(1,2,3,4,5),c(6,8,10,12,19))
colnames(df) <- c("c1","c2","c3")

I want to replace the values of 3rd row in column 2 and 3 to 7 and 9, respectively. I used the following code
df <- df%>%replace(list = df[,c(2:3)], values = c(7,9))

But it is not working. Could someone guide me please where I am wrong and how I can get the desired result?

A: We can pass the list as row/column indexing in a matrix and cbind creates a matrix
library(dplyr)
df <- df %>%
     replace(cbind(3, 2:3), c(7,9))

-output
df
    c1  c2  c3
[1,] "a" "1" "6"
[2,] "b" "2" "8"
[3,] "c" "7" "9"
[4,] "d" "4" "12"
[5,] "e" "5" "19"

A: A R Base solution would be:
  df[3,2:3] <- c(7,9)


text:
Q: same settings and perspective in aptana for every project/workspace Does somebody know, how to set up Aptana, to have only one .metadata setting for all projects? I don't want to change the default settings every time I start a new workspace!
Thanks for helping

A: You can export the settings through the Preferences (File -> Export -> Other -> Preferences). Than, when you create a new workspace, import those settings through the File->Import wizard.


text:
Q: Accelerate SPARQL query - filtering out rows which contain I am currently working with SPARQL (and TopBraidComposer). I have a query which only brings back matching literals, and then filters out the literals based on not wanting certain categories.
Currently, this query is taking a long time to run, and I think it is my FILTER which is causing the delay. I was wondering if someone would have a better and faster way of filtering out (NOT returning) rows which contain a set of key words (ex. cat1, cat2, cat3).
As of now, I am using;
SELECT ?category
WHERE {
   ?s1 ?p ?category .
   ?s2 ?p ?category .

    FILTER (str(?category) != "Cat1") .
    FILTER (str(?category) != "Cat2") .
    FILTER (str(?category) != "Cat3") .
    FILTER (str(?category) != "Cat4") .
    FILTER (str(?category) != "Cat6") .
    FILTER (str(?category) != "Cat8") .
}

A: It's not clear how much you've trimmed down your example, but the code you presented is doing more work than it needs to.
SELECT ?category
WHERE {
   ?s1 ?p ?category .
   ?s2 ?p ?category .

    FILTER (str(?category) != "Cat1") .
    FILTER (str(?category) != "Cat2") .
    FILTER (str(?category) != "Cat3") .
    FILTER (str(?category) != "Cat4") .
    FILTER (str(?category) != "Cat6") .
    FILTER (str(?category) != "Cat8") .
}

Suppose your data has
:a :p "Cat0" .
:b :p "Cat0" .

Then the bindings for ?s1, ?s2, ?p? and ?category can be
?s1 ?s2 ?p ?category
--------------------
:a  :a  :p "Cat0"
:a  :b  :p "Cat0"
:b  :b  :p "Cat0"
:b  :a  :p "Cat0"

That's four ways to select "Cat0".  You said that you want literals, but right now you're hitting every kind of ?category and applying str to it multiple times. You might do this instead:
SELECT DISTINCT ?category
WHERE {
   ?s ?p ?category .
   FILTER( isLiteral(?category) &&
           !(str(?category) in ("Cat1", "Cat2", "Cat3",
                                "Cat4", "Cat6", "Cat8")) )
}


text:
Q: DDD inject repository on domain service VS orchestrate flow on application service I am currently working with DDD and I have a question about application services VS domain services VS repositories interfaces
As I know:

*

*Application services are used for  handle the flow of use cases, including any additional concerns needed on top of the domain's.

*Domain services are used for encapsulate such behaviors that do not fit in a single domain object.
So, taking account into, for example, this use case:
"when you create a new Car entity(uuid,name) in the system, the car name must be unique (no more cars exist with this name) or the car name can't contains another car name from database as substring",for example, just an example of use case that forces me to take a look into other entities in the repository when I am creating an object
So the question is: Where should I do the checks and/or inject the repository Interface?
- Opt 1) In the application service, injecting the RepositoryCarInterface, do the checks and save the Car:
class CreateCarApplicationService
{
    private carRepositoryInterface $carRepository;

    public function __construct(CarRepositoryInterface $carRepository)
    {
        $this->carRepository = $carRepository;
    }

    public function __invoke(string $carUuid, string $carName): void
    {
        $this->ensureCarNameIsUnique($CarName);
        $car = new Car($carUuid,$carName);
        $this->carRepository->save($car);
    }

    private function ensureCarNameIsUnique(string $carName): void
    {
        $CarSameName = $this->carRepository->findOneByCriteria(['name' => $carName]);
        if ($carSameName) {
            throw ExceptionCarExists();
        }
    }
}

- Opt 2) Create this logic into a domain service (with the purpose of keep the domain logic near to the domain objects) and invoke it from a more simple application service which has the final responsibility of saving the model interacting with database:
class CreateCarDomainService
{
    private carRepositoryInterface $carRepository;

    public function __construct(carRepositoryInterface $carRepository)
    {
        $this->carRepository = $carRepository;
    }

    public function __invoke(string $carUuid, string $carName): Car
    {
        $this->ensureCarNameIsUnique($CarName);
        return new Car($carUuid,$carName);
    }

    private function ensureCarNameIsUnique(string $carName): void
    {
        $CarSameName = $this->carRepository->findOneByCriteria(['name' => $carName]);
        if ($carSameName) {
            throw ExceptionCarExists();
        }
    }
}

class CreateCarApplicationService
{
    private carRepositoryInterface $carRepository;
    private CreateCarDomainService $createCarDomainService;

    public function __construct(CarRepositoryInterface $carRepository)
    {
        $this->carRepository = $carRepository;
        $this->createCarDomainService = new CreateCarDomainService($carRepository)
    }

    public function __invoke(string $carUuid, string $carName): void
    {
        $car = $this->createCarDomainService($carUuid,$carName);
        $this->carRepository->save($car);
    }

}

I am not very sure about the fact of injecting repository interfaces into domain services, because of as Evans said:
A good SERVICE has three characteristics:
-The operation relates to a domain concept that is not a natural part of an entity or value object
-The interface is defined in terms of other elements of the domain model
-The operation is stateless
But I want to push my domain logic as deep as I cant
And, as I read in other StackOverflow posts, inject repository in domain object is not allowed/recommended:
Do you inject a Repository into Domain Objects?
Should domain objects have dependencies injected into them?

A: Option 1
The ideal case is that repositories are only used by your orchestration (application) layer and have absolutely nothing to do with your domain model (domain layer). Thus, your repo would be injected into your orchestrator, not into your domain model (option 1).
In your case, you have an orchestration layer that

*

*has a cars repository injected into it

*loads names of cars from the repository

*uses DDD to validate the name of the new car is not in the names of existing cars, etc.

*if yes: create the car in the domain; if no: fail domain validation

*uses the repo to persist the change in state on the domain (in this case, saving the new car using the repo)

*returns results (if a request/reply scenario)

There's a small problem with this though. You could argue that it would be more efficient to take the name of the car and pass it to a query against the repo to see if the name is unique. That's true, but the trade off is that some of your domain logic (checking for uniqueness) has been moved out of the domain to the repo and orchestration layers.
So, consider carefully which you'd prefer.
Option 1, Scenario 1: DDD as much as possible
// inefficient, but we're done with the repo immediately
var carNames = repo.GetCarNames();
// all the following calls are on our domain, easily testable
var carCreator = new CarCreator(names);
var carCreationResult = carCreator.TryCreateCar(carNames, newCar);
if (carCreationResult.Failed) return carCreationResult.Errors;
// finally save and return
repo.Save(carCreationResult.Car);
return carCreationResult.Car;

In the above, TryCreateCar could be implemented as a simple check against a dictionary inside carCreator -- totally within the domain, testable, and not relying on the repo.
Option 1, Scenario 2: Be efficient
// uniqueness check requires repo; mixes in domain concept of uniqueness with a repo query
var canCreateCar = repo.IsCarUnique(newCar.Name)
if (!canCreateCar) return error;
// creation separated from uniqueness check; wouldn't have to check uniqueness in TryCreateCar (it was checked above)
var carCreator = new CarCreator(newCar);
var carCreationResult = carCreator.TryCreateCar(carNames, newCar);
if (carCreationResult.Failed) return carCreationResult.Error;
// finally save and return
repo.Save(carCreationResult.Car);
return carCreationResult.Car;

That IsCarUnique method on the repo is hiding some domain logic though!
Option 2
We'll dismiss this option because we simply don't want a non-domain concern to be a dependency of our domain model. That's the sum-total of the reason to avoid this. When you take a non-domain concern and make it a dependency, your domain model becomes harder to test.
Worse, I've seen code that interleave concerns. Imagine the case of an orchestration layer that gets some entities via a repo, makes some changes to the domain, saves some entities, loads some more, injects the repo into the domain so it can use the repo to load some more, and then finally save. That's an untestable and hard to read/maintain mess!
In Summary
Option 1 Scenario 1 allows us to keep all of our domain concerns together and encapsulated. This is well worth it. If the rules change, we only have to modify our domain model's data and behavior, leaving the orchestration intact.


text:
Q: Google Sitelinks Search Box For some reason, a search for our company name ("hometalk") does not produce the search box in the results (even though we do have sitelinks).
We are adding schema markup as outlined here, but we're not sure about:
Will adding the code make the search bar appear (or at least increase the chances), or is it only going to change the functionality of the search box (to on-site search) for results that are already showing a search bar?

A: It is only going to change the functionality of the search box (to on-site search) for results that are already showing a search bar.
As stated here: https://developers.google.com/webmasters/richsnippets/sitelinkssearch

Search box not displaying? The sitelinks search box appears only for navigational queries and when relevant for users. Google
  algorithms use a variety of factors to determine when the box appears,
  including the information on the site and different types of
  navigational queries from Search users.


text:
Q: Script to dynamically generate XML file based on most Git commit contents (Salesforce CI) I'm using DX for my Continuous Integration, but post-scratch org when I want to deploy into a traditional sandbox for staging, I'm struggling with an automated way to deploy only the new commits (as opposed to ALL of the metadata) in my Dev Branch. Is anyone using a script that archives this (dynamically creates the package.xml based on the most recent commit)?
The use case is that without this, I am deploying ALL the metadata each time, hitting the limit of 10,000 files.

A: I use the legacy/community maintained ForceCLI project to do delta deployments when not using Salesforce DX. It's pretty easy to get a basic workflow going using a shell script.
You can do something like this:
git diff [...] --name-only --diff-filter=ACM | force push -f -

What this does is get a list of changed files between two Git revisions (you'd replace [...] with either a reference to a start and end commit, or an expression like HEAD~1 for a delta of HEAD against the previous commit) and list their paths. It then pipes those paths into force, which will automatically construct a package.xml and run the delta deployment.
I've found a few issues with ForceCLI around delta-deploying unpacked Static Resources and Lightning Components (I believe the latter has already been fixed, but may not have been released yet), but those issues are more or less easily worked around with a little Bash. For static resources, I use a script that zips them up and then pipes the git diff output through sed to squash all references to static resource elements to a reference to the zip file, e.g.
sed -E 's#^src/staticresources/([^/]+)/.+#src/staticresources/\1\.resource#

Note that one thing this approach doesn't handle is deletions. I delete metadata so rarely that I have not invested the effort to script delta deletions. Since deletions can be run either pre- or post-deploy and sometimes need to be one or the other, I've felt the effort to introspect the desired delete operation off of a commit message was more than it was worth.

A: There is now sfdx-git-delta which allows you provide which commits you'd like to generate a deployment for. It can identify the changed metadata since a reference commit & build the destructiveChanges.xml from the deleted (or renamed) metadata

Install
sfdx plugins:install sfdx-git-delta

Git output of diff between latest commit (HEAD) and the previous commit (HEAD^)
sfdx sgd:source:delta --to "HEAD" --from "HEAD^" --output "."

The above generates 2 useful artifacts

*

*A package.xml file inside a package folder. This package.xml will contain the added/changed metadata to deploy

*A destructiveChange.xml file, inside a destructiveChanges folder. This contains the removed/renamed metadata to delete from the target org.

As opposed to the above generated files, you can have it generate a source folder by using --generate delta in the delta command. This is useful for objects where you just want to deploy what specifically changed vs. the entire sub-folder.
Deploy the delta metadata
sfdx force:source:deploy -x package/package.xml --postdestructivechanges destructiveChanges/destructiveChanges.xml

Or split the deploy operations up
echo "--- package.xml generated with added and modified metadata ---"
cat package/package.xml
echo
echo "---- Deploying added and modified metadata ----"
sfdx force:source:deploy -x package/package.xml

echo "--- destructiveChanges.xml generated with deleted metadata ---"
cat destructiveChanges/destructiveChanges.xml
echo
echo "--- Deleting removed metadata ---"
sfdx force:mdapi:deploy -d destructiveChanges --ignorewarnings


text:
Q: Passport not being called my passport strategy is never called. I recently added passport to my project and am using Boxes API to log a user in. I have done the example problem in another project and gotten it to work (https://github.com/smithdavedesign/OAUTH-Passport-BoxAPILogin-Example/blob/master/login/BoxLogin.js), however when I am trying to integrate it into my current project something has gone haywire. I read sessions and passport session are different and should not cause an issue, that being said I trying to figure out what middle ware is causing the issue. The box API is working correctly and returning me to my dashboard on the callback, however passport seams to be being skipped.
var products = require("../controllers/products");//get functions from product like add update delete ect
var validations = require("../controllers/validations");//get functions from product like add update delete ect
var settings = require("../config/settings");// get all things from settings we need
var Promise = require("bluebird");// adding promise mechanism
var bodyParser = require('body-parser');
var express = require('express');//web framework for node
const expressLayouts = require('express-ejs-layouts');// ejs view engine
const flash = require('connect-flash');//for error and success messages
const session = require('express-session');// holds data of users after login
const uuid = require('uuid')
var MemoryStore = require('memorystore')(session)//https://www.npmjs.com/package/memorystore
const util = require('util');
var os = require("os");
var hostname = os.hostname();//This is the users computer name
const multer = require('multer');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})
const upload = multer({ storage: storage })
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var BoxStrategy = require('passport-box').Strategy;
const app = express();//create instance of express

var BOX_CLIENT_ID = "**";
var BOX_CLIENT_SECRET = "**";

// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function (user, done) {
    console.log("serializeUser")//NEVER BEING CALLED
    done(null, user);
});
passport.deserializeUser(function (obj, done) {
    console.log("deserializeUser")//NEVER BEING CALLED
    done(null, obj);
});
passport.use(new BoxStrategy({
    clientID: BOX_CLIENT_ID,
    clientSecret: BOX_CLIENT_SECRET,
    callbackURL: "http://localhost:9000/dashboard"
},
    function (accessToken, refreshToken, profile, done) {
        // asynchronous verification, for effect...
        process.nextTick(function () {
            return done(null, profile);
        });
    }
));

//EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');//view engine

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(
    session({
        genid: (req) => {
            console.log('Inside session middleware genid function')
            console.log('Request object sessionID from client: ' + req.sessionID);
            var new_sid = uuid.v4();
            console.log('New session id generated: ' + new_sid);
            return new_sid; // use UUIDs for session IDs
        },
        store: new MemoryStore({
            checkPeriod: 86400000 // prune expired entries every 24h
        }),
        secret: 'secret',
        resave: true,
        httpOnly: false,
        saveUninitialized: false,
        cookie: {
            maxAge: 24 * 60 * 60 * 1000
        }
    })
);
// Connect flash
app.use(flash());

// Global variables
app.use(function (req, res, next) {//diferent colors
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    next();
});

//routes
app.use('/', require('./GraphRoutes'));
app.use('/', require('./dashboardRoutes'));
app.use('/', require('./index'));
app.use('/', require('./extraProccess'));

app.use(passport.initialize());
app.use(passport.session());

app.use(express.static('public'));//public folder where all templates live
app.use(express.static("."));

app.get('/', function (req, res) {
    res.render('index', { user: req.user });
});

app.get('/login', function (req, res) {
    res.render('login', { user: req.user });
});

app.get('/auth/box', passport.authenticate('box'), function (req, res) {
    console.log("box call")
    });
app.get('/auth/box/callback',
    passport.authenticate('box', { failureRedirect: '/login' }),
    function (req, res) {
        res.redirect('/dashboard');
    });

app.get('/logout', function (req, res) {
    req.logout();
    res.redirect('/login');
});

A: I was calling my routes before initializing passport, as well as having cookie parser and other middle ware not in the correct spot.


text:
Q: why call suggestDesiredDimensions method in a new thread other than call it directly new Thread("setWallpaperDimension") {
    public void run() {
        mWallpaperManager.suggestDesiredDimensions(mWallpaperWidth, mWallpaperHeight);
    }
}.start();

The code above i saw it in launcher2's source code, what i want know is why #suggestDesiredDimensions method gets called in a new thread, can i call it directly without starting a new thread?
Thanks!

A: Sure you can, only the other way around might cause trouble (calling ui-thread-only functions from non-ui threads).
But of course, it might have performance reasons why this is called in a new thread. It might be triggering some recalculations and stuff that might affect your UI responsiveness...


text:
Q: How do I permanently disable IE script debugging on Windows 10? I need to get rid of this:

I am supposed to disable this check box under "Internet Options">

However, this option doesn't exist on Windows 10 2004/20H2

A: Here is the option on Windows 10 21H1.

Try resetting IE to default values and then restart your computer and check.

A: It turns out that this option was not showing up for me due to Internet Explorer 11 being disabled under Control Panel > Programs > Turn Windows features on or off

After enabling it and restarting, the missing checkbox showed up under internet options, and upon unchecking it the problem with the scripts went away (actually, for one of the programs where the script dialog showed up, the very fact IE11 was enabled fixed the issue):


text:
Q: Redis - store CSV as value/blob? I am scraping (legally) .csv files every night.  ~20% grow by one line on any given night.
I'd like to store the whole csv as a "blob" in redis, rather than deal with FS. Is that possible, even with new lines within and such?  How?

A: This tutorial is a good start. However, I recommend taking a look at Should I use redis to store large number of binary files in redis?


text:
Q: how do i import beautifulsoup4 in Pycharm? i installed bs4 through terminal(pip3 install beautifulsoup4), and as i typed 'from bs4 import beaufitulsoup' it seemed to work but it turns out not
how can i solve this problem?
i installed bs4 through terminal(pip3 install beautifulsoup4), and as i typed 'from bs import beaufitulsoup4' it seemed to work but it turns out not. how can i solve this problem?

A: You must include the method names from bs4 and not the whole library. bs4 is the module name for BeautifulSoup4 library. We usually import its method BeautifulSoup and not the library name BeautifulSoup4. Also, there is a spelling mistake in your import statement.
The following statements would work fine.
from bs4 import BeautifulSoup

And
from bs4 import *


text:
Q: onChange dosent get triggered on first change for filter function (filterFn) onChange dosent get triggered on first change for filter function filterFn, the changeDepartmentIdFilter function dosent change the value of departmentIdFilter on first change example
if i write

apple

it consoles only

appl

here is the code :
const Department = () => {

    let [department, setDepartment] = useState([])
    let [filteredDepartment, setFilteredDepartment] = useState([])

    let [values, setValues] = useState({
        modalTitle: '',
        departmentName: '',
        departmentId: 0,

        departmentIdFilter: "",
        departmentNameFilter: "",
        departmentsWithoutFilter: [],
    })

    useEffect (() => {
        getDepartments()
    }, [])

    let filterFn = () =>{
        let departmentIdFilter = values.departmentIdFilter
        let departmentNameFilter = values.departmentNameFilter

        let filteredData = filteredDepartment.filter(
            function(el){
                return el.DepartmentId.toString().toLowerCase().includes(
                    departmentIdFilter.toString().trim().toLowerCase()
                ) &&
                el.DepartmentName.toString().toLowerCase().includes(
                    departmentNameFilter.toString().trim().toLowerCase()
                )

            }
        )
        setDepartment(filteredData)

    }

    let changeDepartmentIdFilter = (e) => {
        setValues({...values, 'departmentIdFilter': e.target.value})
        filterFn()
    }

    let changeDepartmentNameFilter = (e) => {
        console.log(e.target.value)
        setValues({...values, 'departmentNameFilter': e.target.value})
        filterFn()
    }

    let getDepartments = async () => {
        let response = await fetch (variables.API_URL + "department")
        let data = await response.json()

        setDepartment(data)
        setFilteredDepartment(data)
    }

    return (

            <button type="button" className="btn btn-primary m-2 float-end" data-bs-toggle="modal" data-bs-target="#exampleModal" onClick={() => addClick()}>Add Department</button>

                            <input className="form-control m-2" onChange={(e) => {changeDepartmentIdFilter(e)}} placeholder='Filter' />
                            DepartmentId

                            <input className="form-control m-2" onChange={(e) => {changeDepartmentNameFilter(e)}} placeholder='Filter' />
                            DepartmentName

                            Options

                    {department.map((dep) =>

                            {dep.DepartmentId}
                            {dep.DepartmentName}

                                <button type="button" className="btn btn-light mr-1" data-bs-toggle="modal" data-bs-target="#exampleModal" onClick={() => editClick(dep)}>

                                </button>

                                <button type="button" className="btn btn-light mr-1" onClick={() => deleteClick(dep.DepartmentId)}>

                                </button>

                        )}

{values.modalTitle}

                            <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close">
                            </button>

                                Department Name
                                <input name = 'departmentName' type="text" className="form-control" value={values.departmentName} onChange={(e) => {changeDepartmentName(e)}} />
                                {/* <input type="text" className="form-control" value={departmentName} onChange={changeDepartmentName} /> */}

                            {values.departmentId == 0 ?
                                <button type="button" className="btn btn-primary float-start" onClick={() => createClick()}>Create</button> :
                                null
                            }

                            {values.departmentId != 0 ?
                                <button type="button" className="btn btn-primary float-start" onClick={() => updateClick()}>Edit</button> :
                                null
                            }

    )
}

export default Department

Reduced Code with only relevant code:
const Department = () => {

let [department, setDepartment] = useState([])
let [filteredDepartment, setFilteredDepartment] = useState([])

let [values, setValues] = useState({
    modalTitle: '',
    departmentName: '',
    departmentId: 0,

    departmentIdFilter: "",
    departmentNameFilter: "",
    departmentsWithoutFilter: [],
})

useEffect (() => {
    getDepartments()
}, [])

let filterFn = () =>{
    let departmentIdFilter = values.departmentIdFilter
    let departmentNameFilter = values.departmentNameFilter

    let filteredData = filteredDepartment.filter(
        function(el){
            return el.DepartmentId.toString().toLowerCase().includes(
                departmentIdFilter.toString().trim().toLowerCase()
            ) &&
            el.DepartmentName.toString().toLowerCase().includes(
                departmentNameFilter.toString().trim().toLowerCase()
            )

        }
    )
    setDepartment(filteredData)

}

let changeDepartmentIdFilter = (e) => {
    setValues({...values, 'departmentIdFilter': e.target.value})
    filterFn()
}

let changeDepartmentNameFilter = (e) => {
    console.log(e.target.value)
    setValues({...values, 'departmentNameFilter': e.target.value})
    filterFn()
}

 return (

            <button type="button" className="btn btn-primary m-2 float-end" data-bs-toggle="modal" data-bs-target="#exampleModal" onClick={() => addClick()}>Add Department</button>

                            <input className="form-control m-2" onChange={(e) => {changeDepartmentIdFilter(e)}} placeholder='Filter' />
                            DepartmentId

                            <input className="form-control m-2" onChange={(e) => {changeDepartmentNameFilter(e)}} placeholder='Filter' />
                            DepartmentName

                            Options

                    {department.map((dep) =>

                            {dep.DepartmentId}
                            {dep.DepartmentName}

                                {/* >>>>>>EDIT BUTTON<<<<<< */}
                                <button type="button" className="btn btn-light mr-1" data-bs-toggle="modal" data-bs-target="#exampleModal" onClick={() => editClick(dep)}>
                                </button>

                                {/* >>>>>>>DELETE BUTTON<<<<<<<<<<< */}
                                <button type="button" className="btn btn-light mr-1" onClick={() => deleteClick(dep.DepartmentId)}>
                                </button>

                        )}

{values.modalTitle}

                            <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close">
                            </button>

                                Department Name
                                <input name = 'departmentName' type="text" className="form-control" value={values.departmentName} onChange={(e) => {changeDepartmentName(e)}} />

                            {values.departmentId == 0 ?
                                <button type="button" className="btn btn-primary float-start" onClick={() => createClick()}>Create</button> :
                                null
                            }

                            {values.departmentId != 0 ?
                                <button type="button" className="btn btn-primary float-start" onClick={() => updateClick()}>Edit</button> :
                                null
                            }

    )
}

export default Department

A: I think the problem you are having is related to the fact that you invoke filterFn immediately after changing the state:
let changeDepartmentNameFilter = (e) => {
    console.log(e.target.value)
    setValues({...values, 'departmentNameFilter': e.target.value})
    filterFn()
}

departmentNameFilter will not be updated synchronously. It means that filterFn() will be called with the previous state.
There are different approaches to your problem. For instance, you can pass values you want to filter into filterFn(newState) and use it as an argument:

let filterFn = (newValues) =>{
    let departmentIdFilter = newValues.departmentIdFilter
    let departmentNameFilter = newValues.departmentNameFilter

    let filteredData = filteredDepartment.filter(
        function(el){
            return el.DepartmentId.toString().toLowerCase().includes(
                departmentIdFilter.toString().trim().toLowerCase()
            ) &&
            el.DepartmentName.toString().toLowerCase().includes(
                departmentNameFilter.toString().trim().toLowerCase()
            )

        }
    )
    setDepartment(filteredData)
}

let changeDepartmentNameFilter = (e) => {
    console.log(e.target.value)
    const newValues = {...values, 'departmentNameFilter': e.target.value};
    setValues(newValues)
    filterFn(newValues)
}

Or you can have a useMemo hook to filter the array each time the values change:
const filteredDepartment = useMemo(() =>{
    let departmentIdFilter = values.departmentIdFilter
    let departmentNameFilter = values.departmentNameFilter

    // Note, I renamed filteredDepartment to department
    return department.filter(
        function(el){
            return el.DepartmentId.toString().toLowerCase().includes(
                departmentIdFilter.toString().trim().toLowerCase()
            ) &&
            el.DepartmentName.toString().toLowerCase().includes(
                departmentNameFilter.toString().trim().toLowerCase()
            )

        }
    )

}, [values, department]


text:
Q: Javascript Jquery Dropdown hides on whitespace, however it breaks the dropdown until refresh $('button.dropnav-toggle').on('click', function(e) {
            $('#parent-dropnav').toggleClass('parent-open');
            $('.not-header').on('click', function(e) {
            if (!$(event.target).closest('.drop-menu').length) {
                $('.drop-menu').hide();
            };
        });
        });

I have a dropdown hamburger with bootstrap. This code works for the most part, however I'm running into a wall. It successfully drops down and becomes hidden when clicking on anything besides the header. After clicking off the dropdown it successfully hides, however the only way to be able to click and have it dropdown again is after a page refresh.

A: You are setting new listener every time user opens a dropdown. Make it simplier.
You need one listener which toggles menu:
$(document).on('click', '.dropnav-toggle', function(e) {

    e.stopPropagation(); //stop propagation of the event
    $('.drop-menu').toggle();
    $('#parent-dropnav').toggleClass('parent-open'); //not sure if you need this one
});

And another one which closes  dropdown
   $('body').on('click', function(e) {

          $('.drop-menu').hide();
   });

Now if user clicks on any element with class .dropnav-toggle your dropdown will toggle - open or close depending on previous state. Any other click on body will close the menu. Not tested but should work.


text:
Q: Uploadify onUploadSuccess not returning my data On the backend I'm sending: res.send(JSON.stringify(back)); where back, after being stringified is:
{"success":true,"data":{"success":true,"data":{"name":"-kkWjmTLb","version":1,"dateCreated":1407448946239,"dateUpdated":1407448946239,"vidLoc":"rtmp://xxxxxxx.cloudfront.net/cfx/st/vid_-kkWjmTLb","thumbLoc":"https://xxxxxxxxxxx.cloudfront.net/big_icon.png","author":"53a47a469c52c9d83a2d71d9","videoBucket":"xx.xxxxxxxx","thumbBucket":"xx.xxxxxxxx","scenario":false,"fakeName":xxxxxxxxxx.flv"}}}

`
On the frontend I'm doing this:
$(htmlId).uploadify('settings','onUploadSuccess', function(file, data, res) {
            console.log('uploadSuccess',data);

And the console log tells me that data is OK
Not that big string up there, but simply OK.
How can I get my string to the frontend as a response to uploadify?

The full bakend code:
app.post('/uploadVideo',function(req,res){
    console.log("hit video upload");
    checkProperties(req.query,['name','ext','tenant'],function(results){
        if(!results.error){
            var form = new formidable.IncomingForm();
            form.uploadDir = __dirname+'/uploads';
            form.keepExtensions = true;

            console.log('queries are ',req.query);

            form.on('file',function(field,file){
                var data = {};
                var uid = shortId.generate();
                var renamed = form.uploadDir + "/vid_"+uid;
                fs.rename(file.path,renamed);

                if(typeof req.query.tenant !== 'undefined'){
                    console.log('setting data');
                    data.tenant = req.query.tenant;
                    data.fakeName = req.query.name;
                    data.name = uid;
                    console.log('data set',data);
                }else{
                    console.log('no tenant');
                    res.send(400);
                    return;
                }

                console.log('calling uploadVideoS3',data);
                uploadVideoS3(renamed,req.query.ext,data,fs.readFileSync(renamed),function(back){
                    if(back.success){
                        console.log('done uploaded to S3',JSON.stringify(back));
                        res.send(JSON.stringify(back));
                    }else{
                        console.log('video upload S3 failed');
                        res.send(400);
                    }
                });
            });

            form.on('error',function(err){
                console.log("error with file upload " + err);
                res.send(400);
                res.end();
            });

            form.on('end',function(){
                console.log("done");
            });

            form.parse(req, function(err, fields, files) {
                res.send(200);
                res.end();
            });
        }else{
            res.send(400);
            res.send(results.message);
        }
    });
});

The frontend code:
$scope.initVideoUploader = function(){
        uploadifyService.videoUploadInit('#videoUpload',function(back){
            if(back.data){
                console.log('file selected is:',back.data.name);
                var name = back.data.name;
                var ext = back.data.name.substring(back.data.name.lastIndexOf('.')+1);
                uploadifyService.uploadVideo('#videoUpload',name,ext);
            }

            if(back.identifier){
                console.log(back);
                // var item = _.findWhere($scope.content.myContent.videos, {name: recorderInfo.id.toString()});
                // console.log(recorderInfo.id, item);
                // $scope.content.openItem(item);
            }
        });
    };

uploadifyService.js:
videoUploadInit: function(htmlId,callback){
            $(htmlId).uploadify({
                'scriptAccess': 'always',
                'multi': false,
                'auto': true,
                'swf': '/js/plugins/uploadify.swf',
                'buttonText': 'Upload Video',
                'fileTypeExts': '*.flv;',
                'fileSizeLimit': '20MB',
                'onSelect': function(file, queueId) {
                    console.log('videoUploadInit onSelect hit');
                    callback({
                        data: file,
                        queueId: queueId
                    });
                },
                'onUploadSuccess': function(file, data, res) {
                    console.log('upload success from videoUploadInit',res);
                    callback({
                        identifier:true,
                        data2:data,
                        response:res
                    });
                },
            });
        },

        uploadVideo:function(htmlId,name,ext){
            $(htmlId).uploadify('settings','uploader',configService.getNodeSocketApi() + "/uploadVideo?tenant=" + sessionService.getCustomerId() + sessionService.getUserId()+'&ext='+ext+'&name='+name);
            $(htmlId).uploadify('settings','script',configService.getNodeSocketApi() + "/uploadVideo?tenant=" + sessionService.getCustomerId() + sessionService.getUserId()+'&ext='+ext+'&name='+name);
            $(htmlId).uploadify('upload', '*');
        },

A: It was because I had this on the backend:
form.parse(req, function(err, fields, files) {
    res.send(200);
    res.end();
});
Which was sending a response before I intended it to.


text:
Q: Legendary Badge Description needs updated: "Earned at least 200 reputation on 150 days" This may indeed be the most earth shattering problem with Stackoverflow. I don't think I need to point out that this is big deal, but I just did.
The Legendary Badge's FAQ description is difficult to interpret.
I propose "Earned at least 200 reputation on each of 150 individual days"
This ought to remove the confusion regarding "on 150 days" as in "on half a year????"
It should also remove the confusion regarding "is it consecutive days or not?"
Good day

A: This interpretation of the Legendary badge is exactly what my interpretation was, until I read Legendary badge calculation, which explained that the badge is earned when you've hit the daily reputation cap 150 times.
Until I read that, I planned on pulling an all-nighter on my 150th day to stay up and answer as many questions as I could in anticipation of hitting the reputation cap.
In short, it probably would  be a good idea to update the badge description.  I support this feature-request.


text:
Q: Render .obj Files with OpenGl I want to load .obj files with c++ and draw it's shapes and materiels to the scene with OpenGl. To do the loading I am using the tinyobjectloader by syoyo. The loading works very well and I am able to draw the obect with a static color or a static diffuse texture.
So I am able to give all the vericies and texture coordinates into the shader using buffers.
My Problem now is how to set the right color in the pixel shader.
The shapes given by the loader class have a mesh and a meterial, which are defined as follows:
typedef struct {
    std::string name;

    float ambient[3];
    float diffuse[3];
    float specular[3];
    float transmittance[3];
    float emission[3];
    float shininess;
    float ior;                // index of refraction
    float dissolve;           // 1 == opaque; 0 == fully transparent
    // illumination model (see http://www.fileformat.info/format/material/)
    int illum;

    std::string ambient_texname;
    std::string diffuse_texname;
    std::string specular_texname;
    std::string normal_texname;
    std::map<std::string, std::string> unknown_parameter;
} material_t;

typedef struct
{
    std::vector<float>          positions;
    std::vector<float>          normals;
    std::vector<float>          texcoords;
    std::vector<unsigned int>   indices;
} mesh_t;

I would like to set all the colos and different textures as uniforms.
For example, the diffuse color would be set like this:
GLuint diffColLocation = glGetUniformLocation(programmId, "diffuseColor");
glUniform3f(diffColLocation, this->material.diffuse[0], this->material.diffuse[1], this->material.diffuse[2]);

And the Textures like this:
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->ambientTextureID);
glUniform1i(this->diffuseTextureUniformIndex, 0);

glActiveTexture(GL_TEXTURE0 + 1);
glBindTexture(GL_TEXTURE_2D, this->diffuseTextureID);
glUniform1i(this->diffuseTextureUniformIndex, 0);
etc.

I was also able to load an object, where all shapes had a diffuse texture given. So no problem here. My problem ist, how to deal with unset textures. For example many objects don't have an specular texture set. Can I somehow create an default texture?
My Pixel shader looks like this at the moment:
#version 150 core
#extension GL_ARB_explicit_attrib_location: enable

// output to the (default) FBO in color buffer 0
layout (location = 0) out vec4 outColor;

in vec2 fragTextCoords;

uniform sampler2D ambientTex;
uniform sampler2D diffuseTex;
uniform sampler2D specularTex;

uniform vec3 ambientColor;
uniform vec3 diffuseColor;
uniform vec3 specularColor;

// main entry point for the fragment shader
void main() {
    //vec3 tempColor ambientColor + diffuseTex * specularTex;     //Is that correct?
    //outcolor = tempColor * texture(diffuseTex, fragTextCoords); //Then this?
      outcolor = texture(diffuseTex, fragTextCoords);
}

So only the texture is being shown and this only works if every shape has a diffuse texture. But how to I combine every color and texture together in such a way, that the object looks just like in my 3d software? What happens if one of the colors is null or when an sampler2D is null?

A: The values you mention are configuration values for the various materials of your model. They are used in the Phong lighting model to calculate the final colour of a pixel when rendering the model. You have to set the light and material settings in advance using the glMaterial() and glLight() functions, respectively.
Regarding turning settings on and off, try to avoid if statements at all costs unless there is no other way to accomplish what you are trying to do. You also want to avoid looking up the location of uniforms every time you want to set one. The locations do not change, and the operation is quite expensive.
On another note, if you set the texture ID of the uniform variable several times, like in your example, you don't need to keep setting it to 0 every time. The variable will retain its value, and simply refer to the last texture you set as the last one you bound with glBindTexture()
If it helps, here's the shader combo I use for phong lighting. You should be able to modify them to turn textures on or off at will quite easily. Otherwise, lighthouse3d is a great resource on getting started with GLSL.
Vertex shader:
varying vec3 normal;
varying vec3 position;

void main( void )
{
    gl_Position = ftransform();
    gl_TexCoord[0] = gl_MultiTexCoord0;

    normal = gl_NormalMatrix * gl_Normal;
    position = ( gl_ModelViewMatrix * gl_Vertex ).xyz;
}

Fragment shader:
varying vec3 normal;
varying vec3 position;

uniform sampler2D diffuseTexture;

vec4 lightSource(vec3 norm, vec3 view, gl_LightSourceParameters light)
{
    vec3 lightVector = normalize(light.position.xyz - view);
    vec3 reflection = normalize(lightVector - normalize(view.xyz));

    float diffuseFactor = max(0, dot(norm, lightVector));
    float specularDot = max(0, dot(norm, reflection));

    float specularFactor = pow(specularDot, gl_FrontMaterial.shininess);

    return
        gl_FrontMaterial.ambient * light.ambient +
        gl_FrontMaterial.diffuse * light.diffuse * diffuseFactor +
        gl_FrontMaterial.specular * light.specular * specularFactor;
}

vec4 lighting()
{
    // normal might be damaged by linear interpolation.
    vec3 norm = normalize(normal);

    return
        gl_FrontMaterial.emission +
        gl_FrontMaterial.ambient * gl_LightModel.ambient +
        lightSource(norm, position, gl_LightSource[0]);
}

void main()
{
    gl_FragColor = texture2D(diffuseTexture, gl_TexCoord[0].st) * lighting();
}


text:
Q: php EOF ignoring new line <?php

$mytext = <<<EOF
test {
    gl: 100;
    mkd: 0;
    sld: 0;
}
EOF;

echo $mytext;

?>

the output is :
test { aaa: black; bbb: yellow; ccc: red; }

and I want the output exactly how it's wrote inside the eof segments.
test {
    gl: 100;
    mkd: 0;
    sld: 0;
}

Any idea ?

A: Use
 to format the text like that:
<?php

$mytext = <<<EOF

test {
    gl: 100;
    mkd: 0;
    sld: 0;
}

EOF;

echo $mytext;

?>

A: Browser usually ignores control characters, like whitespaces in HTML.
Another solution would be using echo(nl2br($mytext)) instead. Which would convert all \n into
.
Converting manually might help You dealing with another kind of whitespaces. Something like this:
$replacee = array("\n", "\t");
$replacement = array("
", "    ");
$mytext = str_replace($replacee, $replacement, $mytext);

Really similar problem linked here and here (mostly client side solutions).


text:
Q: Conceptual question regarding suspend and Deferred I have a question about when to use suspend and when not. My APIRepo class has a function like this -
override suspend fun retrieveDataFromRemote(): MyResult {
        if (utility.checkDeviceInternetConnection()) {
            try {
                val result = remoteInterface.getData().await()
                return ...
            } catch (t: Throwable) {
                return ...
            }
        } else {
            return ...
        }
    }

My Remote interface code looks like this -
@GET("/data/mydata")
fun getData(): Deferred<Response<MyModel>>

As you can see my RemoteInterface has no suspend keyword and returns a Deferred. This works totally fine. But when I add a suspend keyword to getData(), then I dont get the API response. Why is it like that? Does it have something to do with the Deferred?

A: Retrofit 2.6.0 or newer has built-in suspend support.
Probably you are using Kotlin Coroutine Adapter. This library depends on reflection to detect whether the return type is Deffered or not. See here.
Here is an example using Retrofit 2.6.0 :
interface RemoteInterface{

  @GET("/data/mydata")
  suspend fun getData(): MyModel
}

And in your ViewModel:
fun retrieveDataFromRemote() {
  viewModelScope.launch {
      val model = remoteInterface.getData()
      // do something with model
  }
}

A: *

*When to use suspend and when not? You can refer to suspend

*From Retrofit 2.6.0 or newer and it's built-in suspend support, not use Deferred


text:
Q: simple Lie groups A Lie group is a group which is a smooth manifold such that the multiplication and inversion are smooth.
When does a Lie group become simple?
What is the difference between simple and semi-simple Lie group?
Just want a quick answer here.
Thanks

A: A simple Lie group is a Lie group that contains no $connected$ normal subgroups.  This is not the same as being a Lie group which is simple as an abstract group.  For example the real numbers under addition are a simple Lie group, but have plenty of discrete normal subgroups (the integers for example), and even dense normal subgroups (like the rational numbers) which are disconnected under the subspace topology.


text:
Q: Gaussian on an oblique ray with Tikz
I try to draw a generic Gaussian over a ray, to indicate a possible generic trend. At the moment I have managed to draw both the ray and the Gaussian, but I can't get it to lay on the ray, as changing the coordinates changes the whole graph. In the image it is as I would like it to look, as it came is in the code.
\documentclass[border=2cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.8}

\begin{document}

\pgfmathdeclarefunction{gauss}{3}{%
\pgfmathparse{1/(#3*sqrt(2*pi))*exp(-((#1-#2)^2)/(2*#3^2))}%
}

\begin{tikzpicture}
\begin{axis}[
  no markers,
  domain=0:6,
  samples=100,
  ymin=0,
  xmin=0,
  axis lines*=left,
  every axis y label/.style={at=(current axis.above origin),anchor=south},
  every axis x label/.style={at=(current axis.right of origin),anchor=west},
  height=12cm,
  width=12cm,
  xtick=thick,
  ytick=thick,
  enlargelimits=false,
  clip=false,
  axis on top,
  grid = major,
  ]
\begin{scope}[yshift=-\pgflinewidth]

\clip (axis cs:0,0) rectangle (axis cs:6,1);
\addplot [draw=none,fill=lightgray!50!] {gauss(x, 3, 0.8)};
\end{scope}

\addplot [very thick,black!50!] {gauss (x, 3, 0.8)};
\pgfmathsetmacro\valueB{gauss(1,3,0.09)}
\pgfmathsetmacro\valueA{gauss(1,3,0.8)}
\pgfmathsetmacro\valueC{gauss(1,3,0.8)}

\node[coordinate, pin={Spatial and cognitive distance}] at (axis cs: 3, 0.5){};

\addplot[black!50!, thick](x,x);

\end{axis}

\end{tikzpicture}
\end{document}

Any tips? Thanks a lot <3

A: Welcome to TeX.SE!!!
If you can use a TikZ picture, it would be very easy. You only have to draw you gaussian function and rotate it.
Like the following example:
\documentclass[border=2mm,tikz]{standalone}

\pgfmathdeclarefunction{gauss}{3}{\pgfmathparse{1/(#3*sqrt(2*pi))*exp(-((#1-#2)^2)/(2*#3^2))}}

\begin{document}
\begin{tikzpicture}
% grid
\draw[help lines]  (0,0) grid[step=0.5] (6,6);
% axes
\draw[latex-latex] (0,6) node [above] {$y$} |- (6,0) node [right] {$x$};
% gaussian function
\draw[rotate=45,red,fill=red,fill opacity=0.2] plot[domain=0:{6*sqrt(2)},samples=100] (\x,{gauss(\x,{3*sqrt(2)},0.7)});
% line
\draw (0,0) -- (6,6);
% axes labels
\foreach\i in {1,...,5}
{
  \node at (\i,0) [below] {$\i$};
  \node at (0,\i) [left]  {$\i$};
}
\end{tikzpicture}
\end{document}


text:
Q: Joint distribution of $\max(X, Z)$ and $\max(Y, Z)$ where $X$, $Y$, $Z$ are independent exponential variables with mean $1$ Assume there are three independent exponential random variables $X$, $Y$, and $Z$ with mean $1$. I am trying to look at the joint distribution of $[U = \max(X, Z), V = \max(Y, Z)]$.
I want to find $F_{\, U,V}(u, v)$ which is the cumulative distribution function of joint distribution $(U,V)$.
What I am doing is diving the possible relations of $X$, $Y$, $Z$  like $X < Y < Z$, $X < Z < Y$, etc. But I'm getting stuck at cases like $u < v$ and $Z < X < Y$. What is some other way(s) to find the cumulative distribution of this joint distribution?

A: $P(U \leq u, V \leq v) = P(\max(X,Z) \leq u, \max(Y,Z) \leq v) = P(X \leq u, Y \leq v, Z \leq \min(u,v)) = P(X \leq u) \times P(Y \leq v) \times P(Z \leq \min(u,v)) = (1-e^{-u}) \times (1-e^{-v}) \times (1-e^{-\min(u,v)})$

A: I like your solution. As you mentioned, $$P(U<V \textrm{ and } Z<X<Y)= P(Z<X<Y) = P(Z=\min(X,Y,Z))P(X<Y) = \frac{1}{3}\cdot \frac{1}{2}$$
because the event $Z<X<Y$ is contained in the event $U<V$.
Now, you can consider all 6 cases,
$$P(U<V \textrm{ and } Z<X<Y)$$
$$P(U<V \textrm{ and } X<Z<Y)$$
$$P(V<U \textrm{ and } Z<Y<X)$$
$$P(V<U \textrm{ and } Y<Z<X)$$
$$P(U<V \textrm{ and } X<Y<Z)$$
$$P(U<V \textrm{ and } Y<X<Z)$$
Does that make sense?
Here is another idea:
\begin{align}
&P(U<u, V<v, z<Z<z+dz) \\& =P(U<u, V<v |z<Z<z+dz) P(z<Z<z+dz) =\\
 &=P(U<u |z<Z<z+dz) P(V<v|z<Z<z+dz) P(z<Z<z+dz)  \end{align}
Therefore,
\begin{align}
&P(U<u, V<v, z<Z<z+dz) \\& =P(X<u, Z<u |z<Z<z+dz) P(Y<v, Z<v |z<Z<z+dz)  \exp(-z)dz\end{align}
If $u>z$ and $v>z$
\begin{align}
&P(U<u, V<v, z<Z<z+dz) \\& =(1-\exp(-u) )(1-\exp(-v) ) \exp(-z)dz\end{align}
Do the other cases follow similarly?


text:
Q: Clip child to parent element with border-radius How do I force clip a child to a parent element that has rounded corners.

Tile

Click me

Details

When animating the child, its ignores the border-radius of the parent element. Is there a way to fix the two corners on the top?
.item{
  text-align: center;
  cursor: pointer;
  overflow: hidden;
  height: 280px;
  width: 280px;
  float: left;
  border-radius: 5px;
  background: white;
  margin: 10px;
  position: absolute;
}
.top{
  z-index: 1;
  position: absolute;
  height: 280px;
  width: 280px;
  background: #ed844b;
  transition: 0.3s;
  border-radius: 5px;
}
.behind{
  z-index: 0;
  position: absolute;
  width: 100%;
  top: 136px;
  height: 138px;
  padding: 10px 16px;
  background: #DDDDDD;
  box-sizing: border-box;
  border-radius: 5px;
}
.slide-up{
  transform: translate3d(0, -136px, 0);
  border-radius: 0px;
}

Here is a little demo:
http://codepen.io/Koopa/pen/xbaMez
Thanks
Koopa

A: When you add a css 3d transform to the child, you kinda move it to the separate GPU layer. You can move parent element to GPU layer instead adding null-transform hack transform: translateZ(0) to .item. Or you can replace translate with translateY (In this case child is clipped only when not being animated).


text:
Q: Converting a returned SETOF into An Array in PL/PgSQL (specifically) I know there is the process of SELECT array_agg(f) FROM (SELECT blah FROM stuff) f, which is great in SQL, but when writing functions in PL/pgSQL, is there a shorthand method??
I'm trying to put JSON keys into an array I can use to look at the length.
Something like...
v_len := array_length( array_agg(json_object_keys(myjson)), 1);
instead of the long, DECLARE a variable, do a SELECT array_agg(f) INTO ..., which I've been doing.  I've seem hundreds of implementations using the same SQL string, but I really want to cut down my code, my fingers are going numb from all the redundant typing.
What am I missing with that shorthand method?

A: you can use a ARRAY(subselect) constructor
DO $$
DECLARE a int[];
BEGIN
  a := ARRAY(SELECT * FROM generate_series(1,10));
  RAISE NOTICE 'result: %', a;
END;
$$;


text:
Q: Website will not load on iPad or iPhone but loads great everywhere else I built https://billmykids.com recently and launched it.  However the site will not load on an iPad or iPhone.  I tried Safari and Chrome but both just hang and never load the site.  The site loads fine on an android phone and a PC.
Any ideas?

A: I tried going to the site on my iPhone X and was able to reach the site fairly quickly on both chrome and safari.
Have you tried going into private browsing/incognito mode on both?
Another thing you can do if you have a Mac is to download the developers version of safari https://developer.apple.com/safari/technology-preview/ and plug your device into your computer to see if the device is throwing any error/console messages along with looking at the network tab.
Other than that, without seeing more or knowing what the errors are, I'm not sure that I can do much more to help.

A: It loads fine on Safari5.1.7 on Win7 64-bit however there is an error message in the console: /php/minify_js.php?_minify_=materialize_M360499812P1T2TI1127656722V1:1422 SyntaxError: Expected an identifier but found 'tlist' instead.
I've found Apple browsers to be particularly fussy about syntax errors - one of my sites didn't work on Safari until I fixed a trivial error that other browsers (Chrome/Firefox/IE) all ignored.


text:
Q: Is there a way to solve this internal error in Intellij I just wrote a simple hello world program in Intellij and this is the output when I tried to run the program.
Error:Internal error: (java.lang.IllegalAccessError) class com.intellij.util.io.FileChannelUtil (in unnamed module @0x306279ee) cannot access class sun.nio.ch.FileChannelImpl (in module java.base) because module java.base does not export sun.nio.ch to unnamed module @0x306279ee


text:
Q: Vista de datos php mysqli Tengo un problema al mostrar los datos en la vista, me explico, tengo un formulario de modificación de datos, los cuales editan y actualizan los datos de la base de datos sin problemas, pero cuando regreso a la vista para mostrar todos los datos de la tabla, no me muestra ninguno de los previamente editados  (valga la aclaración: si se almacenan los datos editados en la db y solo me muestra los datos que inserte desde el script sql), ni cuando le doy a actualizar, ni refrescando el servidor. Estoy realizando una web POO MVC con PHP y mysqli. Algo que este haciendo mal??
Es esta tabla a la cual realizo la consulta.
CREATE TABLE estudiante (
    rude VARCHAR(20) PRIMARY KEY,
    nombres VARCHAR(50) NOT NULL,
    apellidos VARCHAR(50) NOT NULL,
    telefono VARCHAR(30),
    grado ENUM('1', '2', '3', '4', '5', '6') NOT NULL,
    paralelo ENUM('A', 'B') NOT NULL
)ENGINE=InnoDB DEFAULT CHARSET=UTF8;
/* --------------------------*/

y tengo otra tabla asistencia:
CREATE TABLE asistencia (
asistencia_id INT PRIMARY KEY AUTO_INCREMENT,
fecha_asistencia DATE NOT NULL,
tipo_asistencia ENUM('P','F','A','L') NOT NULL,
rude VARCHAR(20),
CONSTRAINT FOREIGN KEY (rude) REFERENCES estudiante(rude)
    ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=UTF8;

Para actualizar los datos uso la siguiente consulta:
REPLACE INTO estudiante SET
        rude = '$rude',
        nombres = '$nombres',
        apellidos = '$apellidos',
        telefono = '$telefono',
        grado = '$grado',
        paralelo = '$paralelo'

Para obtener los datos a la db uso lo siguiente:
public function get( $es = '' ) {

    $this->query = ($es != '')
        ?"SELECT es.rude, es.nombres, es.apellidos, es.telefono, es.grado, es.paralelo
        FROM estudiante as es
        INNER JOIN asistencia as a
        on es.rude = a.rude
        WHERE es.rude = '$es' ORDER BY es.rude ASC"
        :"SELECT *
        FROM estudiante as es
        INNER JOIN asistencia as a
        on es.rude = a.rude";

    $this->get_query();

    $num_rows = count($this->rows);

    $data = array();

    foreach ($this->rows as $key => $value) {
        array_push($data, $value);
    }

    return $data;
}


text:
Q: Declare error handler not valid in MySQL? I'm trying to write my first stored procedure that uses an error handler, but It doesn't seem to accept my syntax. Here's what I'm using:
DELIMITER //

CREATE PROCEDURE min_list_valid (OUT pass CHAR
                                ,OUT errs VARCHAR(50)
                                ,IN `@list_id` INT
                                ,IN `@min_input` INT)
BEGIN
    BEGIN
        DROP TABLE IF EXISTS `errors_table`;
        CREATE TEMPORARY TABLE `errors_table`(error VARCHAR(30))ENGINE=MEMORY;
    END;

    BEGIN
        DECLARE error_holder VARCHAR(30);
        DECLARE error_checker VARCHAR(30);
        SET error_checker = 0;

        DECLARE CONTINUE HANDLER FOR SQLSTATE, SQLEXCEPTION
        BEGIN
            SELECT 'The user input is less than the minimum for this list' INTO error_holder;
            SELECT error_holder INTO `errors_table`;
            SET error_checker = 1;
        END;

        SELECT      IF(MAX(CAST(`peg_num` AS UNSIGNED))<`@min_input`,'pass',NULL) AS `key`
        FROM        `game_lists`
        WHERE       `list_id` = `@list_id`
        INTO        pass;

        IF error_checker <> 0 THEN
            SELECT * FROM `errors_table`
        END IF;
    END;
END; //

It gives me back the error message:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE CONTINUE HANDLER FOR SQLSTATE, SQLEXCEPTION BEGIN ' at line 16
But that's strange, it's telling me the declare is wrong but the line in error is line 16 (the one with SET error_checker = 0). I believe I'm following the correct syntax so... what's wrong?
What this stored proc just does is select some maximum value from a list, and everything else is just me trying to create an error handler and an error table to store the generated errors. I wanted to try a simple functionality first with the "full blown" error handling so there's not too many debug points.
My MySQL version is 5.6.14 - MySQL Community Server (GPL)

A: Your corrected procedure should look like below. Few mistakes as pointed below
DELIMITER //
CREATE PROCEDURE min_list_valid (OUT pass CHAR
                                ,OUT errs VARCHAR(50)
                                ,IN `@list_id` INT
                                ,IN `@min_input` INT)
BEGIN
        DECLARE error_holder VARCHAR(30); <--Move this declare statement above here
        DECLARE error_checker VARCHAR(30);
        SET error_checker = 0;
    BEGIN
        DROP TABLE IF EXISTS `errors_table`;
        CREATE TEMPORARY TABLE `errors_table`(`error` VARCHAR(30))ENGINE=MEMORY;

END;

BEGIN <-- after begin you should declare only the error handler
    DECLARE CONTINUE HANDLER FOR SQLSTATE '23000', SQLEXCEPTION
                                            <-- Provide a valid SQL State
    BEGIN
        SELECT 'The user input is less than the minimum for this list' INTO error_holder;
        INSERT INTO `errors_table`(`error`) SELECT error_holder;
        SET error_checker = 1;
    END;

    SELECT      CASE WHEN MAX(CAST(`peg_num` AS UNSIGNED)) < @min_input THEN 'pass'
                ELSE NULL END AS `key`
    FROM        `game_lists`
    WHERE       `list_id` = `@list_id`
    INTO        pass;

    IF error_checker <> 0 THEN
        SELECT * FROM `errors_table`;
    END IF;
END;
END; //


text:
Q: Не работает Swagger в браузере (OpenApi), микросервис SpringBoot Коллеги нужна ваша помощь, обычный Rest микросервис SpringBoot, хочу сделать документацию, подключил зависимость:
<dependency>
 <groupId>org.springdoc</groupId>
 <artifactId>springdoc-openapi-ui</artifactId>
 <version>1.5.6</version>
</dependency>

В большинстве "мануалов", расположенных в Интернете сказано, что этого достаточно, чтобы после запуска микросервиса и перехода по адресу:
http://localhost:8080/swagger-ui.html
в браузере отобразилась стандартная форма Swagger, с методами RestController'в.
Моя проблема в том, что при переходе по указанному адресу, осуществляется redirect на страницу:
http://localhost:8080/swagger-ui/index.html?configUrl=/v3/api-docs/swagger-config
и отображается пустая страница.
В консоли приложения (использую Idea) вижу следующее сообщение:
GET "/swagger-ui.html", parameters={}
Mapped to org.springdoc.webmvc.ui.SwaggerWelcomeWebMvc#redirectToUi(HttpServletRequest)
Using 'application/json', given [text/html, application/xhtml+xml, image/jxr, */*] and supported [application/json, application/*+json, application/json, application/*+json]
Nothing to write: null body
Completed 302 FOUND

Подскажите пожалуйста, что я неправильно делаю, и как можно исправить ситуацию?

A: Одно из решений использовать спринг до версии 2.6.х
Я сам постоянно использую сваггер и уже думал что головой поехал так как брал зависимости и бины с настройками из рабочих проектов которые делал сам. Но вылетала эта ошибка))) на днях нашёл такое решение. Идея по умолчанию создаёт на версии 2.6.8 сегодня а тут не работает


text:
Q: How to replace a string with another string using regex? INPUT TEXT FROM FILE :
someother block {
  enable route yes;
  dhcp auto;
  ....
}
options {
  dnssec-enable yes;
  dnssec-validation yes;
  dnssec-lookaside auto;
 .....
}

I would like to replace all the "yes" and "auto" text in options block ONLY with "no" and "manual" respectively.
How can I accomplish this?
Here is my execution but the text is not replaced.
String dataPattern  = "\noptions \\{\\s*\n(dnssec-[a-z]+ ([a-z]+));";
Pattern filePattern = Pattern.compile(dataPattern, Pattern.DOTALL);
Matcher filePatternMatcher = filePattern.matcher(input);
if(filePatternMatcher.find()){
        System.out.println("0 - "+filePatternMatcher.group(0)); //0 - \ndnssec-enable yes;
        System.out.println("1 - "+filePatternMatcher.group(1)); //1 - dnssec-enable yes

        System.out.println("2 - "+filePatternMatcher.group(2)); //2 - yes
        String value = filePatternMatcher.group(2);
        value.replaceAll("\ndnssec-enable ([a-z]+);", "$1somethingelse");
        System.out.println("new replaced text:"+value); \\ new-replaced text: yes
}

A: I think you could complete it with just Replace function!
    String test="someother block {" +
            "  enable route yes;" +
            "  dhcp auto;" +
            "  ...." +
            "}" +
            "options { " +
            "  dnssec-enable yes;" +
            "  dnssec-validation yes;" +
            "  dnssec-lookaside auto;" +
            " ....." +
            "}";

    String result;

    int opStartIndex=test.indexOf("options");
    int opEndIndex=opStartIndex+ test.substring(opStartIndex).indexOf("}");
    result=test.substring(0,opStartIndex)+test.substring(opStartIndex, opEndIndex).replace("yes","no").replace("auto","manual")+test.substring(opEndIndex);
    System.out.println(result);


text:
Q: summation of numbers in a vector without loop in matlab I have a vector with length L. I want to sum each N numbers without a loop in MATLAB for saving time in my simulation.
For example, if L=10 and N=2 for the matrix
A=[1,1,3,3,0,2,4,4,6,2]

the matrix B should be
B=[2,6,2,8,8]

where
B(1)=A(1)+A(2)=2
B(2)=A(3)+A(4)=6

A: B = sum(reshape(A, 2, []));

If length of A could be odd number:
n = floor(numel(A)/2) * 2;
B = sum(reshape(A(1:n), 2, []));

A: You might also be considering movsum.
C = movsum(A,2);
B = C(2:2:end);

I evaluated its performance to B = sum(reshape(A, 2, [])); Movsum takes roughly 2x the time of reshaping. But it offers some flexibility and runs for non-even length vectors.


text:
Q: Django Rest Framework: Access item detail by slug instead of ID Is it possible to use a object's slug (or any other field) to access the details of an item, instead of using the ID?
For example, if I have an item with the slug "lorem" and ID 1. By default the URL is http://localhost:9999/items/1/. I want to access it via http://localhost:9999/items/lorem/ instead.
Adding lookup_field in the serializer's Meta class did nothing to change the automatically generated URL nor did it allow me to access the item by manually writing the slug instead of the ID in the URL.
models.py
class Item(models.Model):
    slug = models.CharField(max_length=100, unique=True)
    title = models.CharField(max_length=100, blank=True, default='')
    # An arbitrary, user provided, URL
    item_url = models.URLField(unique=True)

serializers.py
class ClassItemSerializer(serializers.HyperlinkedModelSerializer):
     class Meta:
        model = Item
        fields = ('url', 'slug', 'title', 'item_url')

views.py
class ItemViewSet(viewsets.ModelViewSet):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer

urls.py
router = DefaultRouter()
router.register(r'items', views.ItemViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
]

Generated JSON:
[
    {
        "url": "http://localhost:9999/items/1/",
        "slug": "lorem",
        "title": "Lorem",
        "item_url": "http://example.com"
    }
]

A: You should set lookup_field in your serializer:
class ItemSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Item
        fields = ('url', 'slug', 'title', 'item_url')
        lookup_field = 'slug'
        extra_kwargs = {
            'url': {'lookup_field': 'slug'}
        }

and in your view:
class ItemViewSet(viewsets.ModelViewSet):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer
    lookup_field = 'slug'

I got this result:
~ curl http://127.0.0.1:8000/items/testslug/ | python -mjson.tool
{
    "item_url": "https://example.com/",
    "slug": "testslug",
    "title": "Test Title",
    "url": "http://127.0.0.1:8000/items/testslug/"
}

A: In some scenarios you may want to have both the "low level" pk value and the more semantic slug. I like to have both options personally and do this by setting the lookup_field later in the viewset as_view() method in my urls.py.

Note: the following defaults to pk with an optional slug lookup. To combine this with previous answer you would change the lookup_field below to be "pk" instead of "slug".

from django.conf.urls import *
from rest_framework.urlpatterns import format_suffix_patterns

from myobjects import views as myviews

# simplify the view definitions by splitting out the options
REQDICT = {
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
}

# define the pk detail view
myobject_detail = myviews.MyObjectViewset.as_view(REQDICT)
# define the slug detail view
myobject_slug_detail = myviews.MyObjectViewset.as_view(REQDICT, lookup_field='slug')

urlpatterns = [
    url(r"^myobjects/(?P<pk>\d*)/$",
           myobject_detail,
           name = 'myobject-detail'),
    url(r"^myobjects/(?P<slug>[-\w]+)/$",
           myobject_slug_detail,
           name = 'myobject-slug-detail'),
]

urlpatterns = format_suffix_patterns(urlpatterns)

This could also be in your views.py - my preference is to see it beside the urlpatterns list.


text:
Q: SQL request - SELECT with multiple empty values I have a database with multiple columns. Now i have a Java program where i can search for different rows in my database. But i need help for the SQL SELECT request.
I have some texfields and some checkboxes. Now i want if the textfields are empty, or "any" is selected in one of the checkboxes , the select request should select ALL from this column.
Here is my request right now:
resultSet = sqlStatement.executeQuery("SELECT * FROM Messgerate WHERE COLUMN1 LIKE '%"+sColumn1+"%'" +
"AND COLUMN2 LIKE '%"+sColumn2+"%'" +
"AND COLUMN3 LIKE '%"+sColumn3+"%'" +
"AND COLUMN4 LIKE '%"+sColumn4+"%'" +
"AND COLUMN5 LIKE '%"+sColumn5+"%'" +
"AND COLUMN6 LIKE '%"+sColumn6+"%'" +"");

This request ist working if i type in something in all of the textfields and checkboxes.
Can someone help me please?

A: Can you replace AND with OR. It ll solve your issue. Because the AND operator displays a record if both the first condition AND the second condition are true.
The OR operator displays a record if either the first condition OR the second condition is true.
"SELECT * FROM Messgerate WHERE COLUMN1 LIKE '%"+sColumn1+"%'" +
"OR COLUMN2 LIKE '%"+sColumn2+"%'"
"OR COLUMN3 LIKE '%"+sColumn3+"%'" +
"OR COLUMN4 LIKE '%"+sColumn4+"%'" +
"OR COLUMN5 LIKE '%"+sColumn5+"%'" +
"OR COLUMN6 LIKE '%"+sColumn6+"%'" +"");

A: You should pass an empty string when Any is selected in the dropdown. And then you can use this:
resultSet = sqlStatement.executeQuery("SELECT * FROM Messgerate WHERE COLUMN1 LIKE '%"+sColumn1+"%'" +
"OR COLUMN2 LIKE '%"+sColumn2+"%'" +
"OR COLUMN3 LIKE '%"+sColumn3+"%'" +
"OR COLUMN4 LIKE '%"+sColumn4+"%'" +
"OR COLUMN5 LIKE '%"+sColumn5+"%'" +
"OR COLUMN6 LIKE '%"+sColumn6+"%'" +"");

A: select * from messgerate where case when isnull(sColumn1,'') = '' then '' when isnull(sColumn1,'') = 'any' then '' else COLUMN1 end LIKE '%"+sColumn1+"%'"

Repeat the case statement for the rest of the columns


text:
Q: How can I make this javascript playlist skip missing tracks? Let me just start from the beginning. This here below is the script that recognizes the html as a playlist:
var audio;
var library;
var tracks;
var current;
init();
function init() {
    current = 0;
    audio = $('.player');
    library = $('.album_tracks_container');
    tracks = library.find('.span-link');
    len = tracks.length;
    var playlist;
    library.find('.span-link').click(function(e) {
        e.preventDefault();
        link = $(this);
        current = link.parent().index();
        playlist = link.closest('.album_tracks_container');
        run(link, audio[0]);
    });
    audio[0].addEventListener('ended',function(e) {
        current++;
        if(current == len){
            current = 0;
            link = playlist.find('.span-link')[0];
        } else {
            link = playlist.find('.span-link')[current];
        }
        run($(link),audio[0]);
    });
}
function run(link, player) {
    player.src = link.attr('data');
    audio[0].load();
    audio[0].play();
}

It works great with a html like this one below, and it will play the next track in the list when done playing the current one:

It also seem to work fine if I have a html like this, it will skip the third container and start playing the fourth:

But say I have a html like this one below, it doesn't seem to work. After playing track 02, it will not switch to track 03:

Any ideas?
-edit-
I'm still having troubles figuring this out, but as of previous edit I found out that it has little to do with a missing track, but more to do with whether or not the first track is there or not. If 01.wav is there, the playlist works, but if it isn't, the playlist breaks.

A: You can check if it has a file link or not:
 playlist.find('.span-link').click(function(e) {
    if($(this).attr("data").length>0){
            e.preventDefault();
            link = $(this);
            current = link.parent().index();
            currentplaylist = link.closest('.album_tracks_container');
            run(link, audio[0]);
       } });

A: I think the problem is in your end listener.
We should check the data link here and if it is not exist, just go to the next one.
Maybe something like this:
audio[0].addEventListener('ended',function(e) {
    current++;
    while(current < len){
        link = playlist.find('.span-link')[current];
        if(!link.attr("data").length) current++;
    }

    if(current == len) {
        current = 0;
        link = playlist.find('.span-link')[0];
    }

    run($(link),audio[0]);
});

Another thing is, if your playlist is not change, it is better to cache
playlist.find('.span-link'), then use it every time.
Have fun. :)


text:
Q: How to test a async ComponentDidMount in React Native? I do have a SplashContainer with a async componentDidMount
export class SplashContainer extends Component {

  async componentDidMount() {
    let token = await AsyncStorage.getItem('@XXX:token')
    if (token !== null) {
      await this.props.setTokenAvalability(true)
      await this.props.getUserDetails()
    }
    await this.props.navToNextScreen()
  }

  render() {
    return <Splash />
  }
}

function mapDispatchToProps(dispatch) {
  return {
    navToNextScreen: () => dispatch(navToNextScreen(...)),
    setTokenAvalability: (status) => dispatch(setTokenAvalability(status)),
    getUserDetails: () => dispatch(getUserDetails()),
  }
}
export default connect(null, mapDispatchToProps)(SplashContainer);

I do have two questions here.
1. I wanted to test setTokenAvalability and getUserDetails is been dispatched or not. I do know how to test if there is no async/await, like below.
it('test SplashContainer', () => {
  const store = mockStore({});
  const props = {
    dispatch: store.dispatch
  }
  const tree = renderer.create(
    <SplashContainer {...props}/>
  ).toJSON();
  const expectedAction = [
    ...
  ]
  expect(store.getActions()).toEqual(expectedAction);
});

2. How to stub value for AsyncStorage.getItem()
Thanks,

A: Well, componentDidMount is not an async function, the only thing you can do here I think is to use the componentDidUpdate method which will give you an update of your component.
Reading the this.props.navToNextScreen() function, I think you misunderstand how redux works here.
You probably don't need to wait for the navToNextScreen function, it should just send a global event and your main component should listen to a change in your store to show / hide your Splash screen


text:
Q: Stop Typescript prettier to remove type in catch TypeScript enforce specifing the type in catch to be any:
try {
...
}catch (e: any)

Otherwise, typescript will complain

Object is of type 'unknown'

However, prettier will remove any when I run this:
prettier --write '**/*.{js,ts}'

How could it be stopped?
And interesting prettier doesn't remove any on format on save.


text:
Q: Iterate two arrays simultaneously - bash n sed I need help with executing two arrays simulataneously in bash and using sed to replace a word with the words in the second array in each separate file. There are two lists:
List1 - contains the names of the directories, which have similar parameter file "surfnet.par" in each directory (the file in different directories have the same name "surfnet.par")
List1.txt
3IT6_1
3IT6_3
3IT6_6
3IT6_9
3IT6_11
3IT6_12
3IT6_19
3IT6_23
3IT6_54
3IT6_62

List2 - contains numbers corresponding to each directory which has to be replaced with a specific word (single occurrence) in the file "surfnet.par" existing in different directories
List2.txt
11351
11357
11371
11384
11350
11373
11383
11365
11377
11382

To make it still clear
I want to replace a word "Resnum" in "surfnet.par" in the directory "3IT6_1" of List1 with "11351" of List2, likewise, replace the same word in "surfnet.par" of 3IT6_2 with 11357, 3IT6_3 with 11357, 3IT6_6 with 11371 and so on.
I have tried pushing the list to array and then using a for loop to replace the word, but failed in doing so, as it took the first value of List2 and replace in all "surfnet.par" files in different directories. The script I have been using is as below:
#!/bin/bash

declare -a dir
declare -a res

dir=(`cat "List1.txt" `)
res=(`cat 'List2.txt'`)

for i in "${dir[@]}"
    do
        echo $i
        cd $i
        sed -e "s/Resnum/${res$[0]}/g" surfnet.par > surfnet2.par
        cd ..
    done

I will appreciate it very much, if any of you can help me resolve this code and point out the modification that needs to be done. In case, my code doesn't make any sense please provide me the solution using bash, awk, sed or perl

A: I think you may have been a whole lot closer to a solution than you thought. This is one situation in bash where making use of a c-style loop and iterating on an index can come in very handy. The following slight changes to your code should work, give it a try (note: I added a check on cd and used the starting directory as current to enable use of absolute paths):
#!/bin/bash

declare -a dir
declare -a res

dir=( $(<List1.txt) )
res=( $(<List2.txt) )

current="$PWD"

for ((i = 0; i < ${#dir[@]}; i++))
    do
        cd "$current/${dir[i]}" || {
            echo "failed to change to ${dir[i]}"
            continue
        }
        printf "%3d  %-8s Resnum -> %s\n" $i ${dir[i]} ${res[i]}
        sed -e "s/Resnum/${res[i]}/g" surfnet.par > surfnet2.par
    done

Example Use
Tested with your ListX.txt files with cd and sed calls commented out.
$ bash resnum.sh
  0  3IT6_1   Resnum -> 11351
  1  3IT6_3   Resnum -> 11357
  2  3IT6_6   Resnum -> 11371
  3  3IT6_9   Resnum -> 11384
  4  3IT6_11  Resnum -> 11350
  5  3IT6_12  Resnum -> 11373
  6  3IT6_19  Resnum -> 11383
  7  3IT6_23  Resnum -> 11365
  8  3IT6_54  Resnum -> 11377
  9  3IT6_62  Resnum -> 11382

Note: in bash for indexed arrays, the use of the $ on the index variable is not required. (e.g. ${dir[$i]} is fine as ${dir[i]}. It is treated the same as if it were enclosed in ((..)) as in the loop declaration.
Note2: you should probably add a validation that both values are available at the top of the loop before calling cd to change to the desired directory:
        ## validate both values available
        [ -z ${dir[i]} -o -z ${res[i]} ] && {
            echo "'${dir[i]}' or '${res[i]}' missing."
            continue
        }

A: Your question bears a Perl tag so I assume that Perl solutions are acceptable
Your question isn't very clear, but I think this program should help you
use strict;
use warnings;
use v5.10.1;
use autodie;

my @dirs = slurp('Listdirs204.txt');
my @res  = slurp('LastHetatmRes.txt');

die "File sizes don't match" unless @dirs == @res;

for my $i ( 0 .. $#dirs ) {

    my ($dir, $res) = ($dirs[$i], $res[$i]);
    my $file        = "$dir/surfnet.par";

    my @lines = slurp($file);
    s/Resnum/$res/g for @lines;

    open my $fh, '>', $file;
    print $fh "$_\n" for @lines;
    close $fh;
}

sub slurp {
    open my $fh, '<', shift;
    my @lines = <$fh>;
    chomp @lines;
    @lines;
}

A: If you don't like to type too much, you can do this
while read d s; do sed 's/target/'"$s"'/g' "$d"/f.txt > "$d"/f2.txt; done < <(paste list1 list2)

appropriately replace target with your search word, f.txt f2.txt list1 and list2 with the file names you use.  It should be clear which is which.


text:
Q: SQL syntax ERROR in ALTER TABLE while trying to delete a coloumn and add again i am getting this error.
coding php with mysql
ERROR:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version                                                                                for the right syntax to use near 'ALTER TABLE logindatabase DROP COLOUMN id' at line 1
CODE:
$con = mysqli_connect('localhost','root','','sagar');//connecting database
//resting our table.....deleting error rows.....reseting autoincremented values
$q_reset_table="DELETE FROM logindatabase WHERE username = NULL;
            ALTER TABLE logindatabase DROP COLOUMN id ;
            ALTER TABLE logindatabase ADD id int(10) PRIMARY KEY NOT NULL auto_increment; ";
mysqli_query($con, $q_reset_table) or die(mysqli_error($con));

A: Sql for deleting should be
DELETE FROM logindatabase WHERE username IS NULL;

A: If you're trying to reset the autoincrement values try
ALTER TABLE logindatabase AUTO_INCREMENT = 1

A:
ALTER TABLE logindatabase DROP COLOUMN id

COLOUMN is wrong, COLUMN is the word to use.


text:
Q: Preloading data into core data I am following a tutorial on preloading an existing database into core data. the code compiles fine until I get to this line:
NSEntityDescription *entity = [NSEntityDescription    insertNewObjectForEntityForName:@"FailedBankInfo" inManagedObjectContext:context];

where it returns the following error: 2012-11-19 12:45:02.247 CoreDatTutorial2[2049:403] -[FailedBankInfo subentitiesByName]: unrecognized selector sent to instance 0x100301010'
I've checked to make sure the is not empty and that it has been saved into the the product directory. Any idea what I'm doing wrong? If I comment out that line of code, the project compiles without a problem.
here's the rest of the code:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription insertNewObjectForEntityForName:@"FailedBankInfo" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    for (FailedBankInfo *info in fetchedObjects){
    {

A: insertNewObjectForEntityForName:inManagedObjectContext:

creates a new managed object and inserts it into the managed object context. In particular, it returns an object of the class FailedBankInfo (in your case), and not a NSEntityDescription.
To create a NSEntityDescription, use entityForName:inManagedObjectContext::
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"FailedBankInfo"
                                inManagedObjectContext:context];
[fetchRequest setEntity:entity];

Note that (starting with iOS 5.0) you can simplify this to
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"FailedBankInfo"];


text:
Q: jVector - Italian regions I'm trying to use the Italy's map in jVector, but i can't assign a value to a specific region or an array of regions.
I've tried and tried... but nothing.
The map is displayed but i can't assign, for example
"Veneto": 100,
"Lazio": 200,
"Sicilia": 350,
"Sardegna": 400....

I've tried also:
"IT-Veneto": 100,
"IT-Lazio": 200,
"IT-Sicilia": 350,
"IT-Sardegna": 400....

or
"VENETO": 100,
"LAZIO": 200,
"SICILIA": 350,
"SARDEGNA": 400....

and other possible combinations.
can you help me please?
Thanks in advance.

A: jVectorMap follows iso-3166 standard. To set values for italian regions you need to use codes described here.


text:
Q: Excel opens by himself I have a problem with Excel. When I work on my computer, this problem happens when I take a pause or when I don't work on my computer, or when I work on my computer. Excel opens by itself.
Excel starting a session unexpectedly and therefore unsolicited and displays the message below. This has happened 5 to 6 times since this morning.
This problem occurs since many months and I didn't find a solution.
When Excel opens, it opens a blank spreadsheet and I get this error:

"Insufficient memory. Microsoft Excel, can no longer open or save documents.
-To increase available memory, close workbooks or programs that you no longer need.
-To free up disk space, delete files that you no longer need. "
Can you help me?

A: I suggest you go to this folder:
C:\Users<UserName>\AppData\Roaming\Microsoft\Excel
Delete all Files and Folders from this folder, and restart Excel.


text:
Q: How -exactly- do I remove a specific directory, from my PATH, in OSX, Mavericks? Ok - so this issue has become somewhat of a white whale for me. I have browsed some of the questions here, but I cannot seem to figure out how to, very simply, delete a directory from my PATH. (I should also add that I am very to to Mac, making the transition from Windows).
So: I have gathered that I can make a .bashrc, .bash_profile, etc etc, to ADD files to my PATH. I think I get that.
However what I cannot seem to find a direct answer to, is: How do I simply delete a specific existing directory, from my PATH? This is all I would honestly like to do.
Thank you.
EDIT: Why I want to remove a directory from PATH:
Long story short, homebrew put a directory into my PATH, that it no longer needs. It says I can remove it from PATH, and so this is why I would like to remove it. Here is a screen shot:

A: It depends where the PATH is being set. If you use bash, the path could be set in any of the following:
/etc/profile
/etc/bashrc
~/.bash_profile
~/.bash_login
~/.profile
~/.bashrc

This list is in the order that the files are read (by bash). Later files override earlier files.
Check the above in reverse order for export PATH which will write your PATH variable.
You should be able to find where it's set by launching your shell with -x.
Also check /etc/paths and /etc/paths.d for paths that are set before your shell is started.
If all else fails, you can set the PATH yourself to override its current contents. Run echo $PATH, then paste your PATH after export PATH in your ~/.bashrc and make your desired modifications. As ~/.bashrc is the last one read, it will override any earlier modifications to your PATH.
If you use zsh, it's probably in ~/.zshrc or a sourced file.


text:
Q: How to access a nested array of arrays ( matrix ) in rethinkQL by index I am relatively new to RethinkDB and I am working on a system that stores data as arrays of arrays, as shown below.
[
  {
  symbol:"BTCUSDT",
  "5m":
            [
    [
        1654202400000,
        30282.1,
        30330.95,
        30273.46,
        30323.22,
        91.66759
    ],
    [
        1654202700000,
        30323.22,
        30323.23,
        30278.84,
        30278.85,
        259.51072
    ],
  ...
   ]
  }
]

Right now I have written a query that gets me the data but I want to be able to filter this data the more without fetching everything and handling it on the javascript side. Here is my query
r.db("candleSticks").table("pair").filter({symbol:"BTCUSDT"}).getField("5m")

So I am left with something like this
   [
        1654202400000,
        30282.1,
        30330.95,
        30273.46,
        30323.22,
        91.66759
    ],
    [
        1654202700000,
        30323.22,
        30323.23,
        30278.84,
        30278.85,
        259.51072
    ],
    [
        1654203000000,
        30278.84,
        30298.66,
        30274.94,
        30277.7,
        65.74652
    ],
]

But I would like to filter by their first index. Like
data.filter(line => line[0] >= 1654202700000)

I don't know if it is possible to achieve such in RethinkQL. Thank you


text:
Q: How does Mathematica solve this 2D piecewise function from constraints? I am interested in learning the technique(s) used to solve the following 2D piecewise equation for $x, y$ when given $z$, where $z = f(x, y)$.
$\text{Given that $x \in \mathbb{Z}$, $y \in \mathbb{Z}$}$
$$
f(x, y) =
\begin{cases}
    x(4x - 3) + y & \text{$y < x$ and $y > -x$} \\
    y(4y - 3) + x & \text{$y < x$ and $y \leq -x$} \\
    y(4y - 1) - x & \text{$y \geq x$ and $y > -x$} \\
    x(4x - 1) - y & \text{$y \geq x$ and $y \leq -x$} \\
\end{cases} \\
$$
Mathematica is able to solve it easily using the following code:
f[x_, y_] = ConditionalExpression[Piecewise[{
     {x (4 x - 3) + y, y < x && y > -x},
     {y (4 y - 3) + x, y < x && y <= -x},
     {y (4 y - 1) - x, y >= x && y > -x},
     {x (4 x - 1) - y, y >= x && y <= -x}
     }, Undefined],
   x \[Element] Integers && y \[Element] Integers];

Solve[f[x, y] == 1000000000000000000000000000000000000, {x, y}] // Timing
(*Output: {0.03125, {{x -> -500000000000000000, y -> 500000000000000000}}}*)

My main question is how Mathematica solves this problem, as well as general mathematical techniques one could use to solve these types of problems.
I was not able to find any hints from Google, as the search results mostly yielded calculus related problems. Rather than having a second equation to solve for $x$ and $y$, Mathematica solves the equation from using the inequalities and the restriction of $x, y$ to $\mathbb{Z}$ instead.
The large $z$ value in Solve was chosen to see if Mathematica was simply iterating through all possible solutions, which was the approach I had attempted. It seems that Mathematica is employing a smarter technique, as the timing remains fairly consistent regardless of input size. Iterating through that many values would also probably take longer than 30–50 ms. The ideal speed, however, should be faster by a factor of 10.
I would like to learn the techniques for solving this equation, in order to apply the solution in other programs for visualization purposes.

A: If I had do guess, I'd say that Mathematica grabs each of the 4 cases and applies Solve to each individual one.
rhs = 1000000000000000000000000000000000000;
cond = {
   {x (4 x - 3) + y == rhs, y < x, y > -x},
   {y (4 y - 3) + x == rhs, y < x, y <= -x},
   {y (4 y - 1) - x == rhs, y >= x, y > -x},
   {x (4 x - 1) - y == rhs, y >= x, y <= -x}
   };
Join @@ (Solve[#, {x, y}, Integers] & /@ cond) // Timing

{0.009538, {{x -> -500000000000000000, y -> 500000000000000000}}}

Being not an expert in diophantine equations, I cannot tell exactly how Mathematica solves each of these cases. But I guess, the first equation is used to eliminate one of the variables. Since only one unknown variable is left afterwards, quick numerical methods can be used to provide coarse bounds for the regions to so search for. If done clever enough, these regions are so small that they can be search exhaustively.


text:
Q: Aplicar setItemOnClickListener no GridView de Botões. Kotlin ou Java Eu fiz um gridView de botões, porém quando eu utilizo o método setOnItemClickListener para acionar os respectivos botões, ele não funciona.
Quero utilizar os botões para que eu possa acionar uma intent, sabendo que só se pode acionar uma intent dentro de uma activity. Eu consigo fazer o botão funcionar dentro do Adapter da Grid, porém fora não.

A:
sabendo que só se pode acionar uma intent dentro de uma activity.

Isso não é verdade. É possível em qualquer lado, desde que tenha um Context disponível.
Se quer implementar, no Adapter, o OnClickListener de cada botão, apenas necessita de passar um Context no construtor e usá-lo para criar o Intent.
Caso deseje usar OnItemClickListener veja esta resposta. Nela é explicado porque ele não funciona nesse tipo de caso e como fazer para funcionar.


text:
Q: Delete a folder from Github New to Github.I am in the development branch not the master branch and i have pushed a folder few days and
now i want to delete that folder.Tried git rm -r FolderNameand git rm -rf FolderName
but it is saying fatal: pathspec 'FolderName' didn't match any files

A: Git doesn't store specific information about folders, only about files. A folder is automatically removed if it is empty (empty means if also doesn't contain ignored files!). So just remove all files inside it and done. In your case, it seems you already removed all files (after git rm -r FolderName, this is the case). Whenever you do a git checkout from a commit which contains to folder to one which doesn't, your folder should disappear automatically.


text:
Q: Periodic function such that integral of $|x(t)|$ is finite I'm wondering if there is a periodic function such that the integral of $|x(t)|$ is finite.
I tried with various functions, but the result is always infinite.
Thank you in advance.

A: $\int |x(t)|\, dt= \sum\limits_{n=-\infty}^{\infty} \int_{nT}^{(n+1)T} |x(t)|\, dt$. Use a change of variable to show that all the terms are equal to $\int_0^{T} |x(t)|\, dt$. Can you now conclude that $|x|$ is integrable iff it is $0$ almost everywhere?

A: $f(x)=0$ has period $T$ for all $T\in\mathbb{R}_{>0}$.

A: Hint: suppose that $x$ has period $T$. Then what would the integral of $|x|$ look like in terms of its integral over one period?


text:
Q: how to disable android 7.0 signature v2 to install a modified apk? i modified a apk with deleted some sound  & so files for slim the file size, and install successly in android 5.0, but it doesn't work on android 7.0, the phone will show "apk is broked" . so how to disable android 7.0 signature v2 to install a modified apk?

A: I think it should be and Android6.0 above permissions