text:
Q: Codeigniter, Join and Case When Query Trying to Execute this query.
$sql ="SELECT '*' FROM
            'osp_job_details'
                LEFT JOIN
            'osp_job_status_track' ON 'osp_job_status_track'.'JobID' = 'osp_job_details'.'JobID'
                LEFT JOIN
            'osp_job_status' ON 'osp_job_status'.'StatusID' = 'osp_job_status_track'.'StatusID'
                LEFT JOIN
            'osp_job_sub_status' ON 'osp_job_sub_status'.'SubStatusID' = 'osp_job_status_track'.'SubStatusID'
                LEFT JOIN
            'hr_employee_details' ON 'hr_employee_details'.'EmployeeID' = 'osp_job_details'.'AssignToEmployeeID'
                LEFT JOIN
            'osp_job_type' ON 'osp_job_type'.'JobTypeID' = 'osp_job_details'.'JobtypeID'
            WHERE 'isDefault' = 0 AND

            CASE WHEN 'osp_job_status'.'StatusID' = '2'
            THEN  'osp_job_sub_status'.'CurrentStatus' = '3'
            ELSE 'osp_job_status'.'StatusID' >= '2'
                END;";

        $query = $this->db->query($sql);
        return $query->result();

But i am getting this below error on running the above query.
Error Number: 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 ''osp_job_details' LEFT JOIN 'osp_job_status_track'' at line 2

SELECT '*' FROM 'osp_job_details' LEFT JOIN 'osp_job_status_track' ON 'osp_job_status_track'.'JobID' = 'osp_job_details'.'JobID' LEFT JOIN 'osp_job_status' ON 'osp_job_status'.'StatusID' = 'osp_job_status_track'.'StatusID' LEFT JOIN 'osp_job_sub_status' ON 'osp_job_sub_status'.'SubStatusID' = 'osp_job_status_track'.'SubStatusID' LEFT JOIN 'hr_employee_details' ON 'hr_employee_details'.'EmployeeID' = 'osp_job_details'.'AssignToEmployeeID' LEFT JOIN 'osp_job_type' ON 'osp_job_type'.'JobTypeID' = 'osp_job_details'.'JobtypeID' WHERE 'isDefault' = 0 AND CASE WHEN 'osp_job_status'.'StatusID' = '2' THEN 'osp_job_sub_status'.'CurrentStatus' = '3' ELSE 'osp_job_status'.'StatusID' >= '2' END;

Filename: C:\xampp\htdocs\projects\zorkif_new\system\database\DB_driver.php

Line Number: 330

Can Anyone tell what is wrong in my query and how to solve it?
++++++++++++++++++++++++++++++++++++++++++++++++
Update:
Removed the Single Quotes
$sql ="SELECT * FROM
    osp_job_details
        LEFT JOIN
    osp_job_status_track ON osp_job_status_track.JobID = osp_job_details.JobID
        LEFT JOIN
    osp_job_status ON osp_job_status.StatusID = osp_job_status_track.StatusID
        LEFT JOIN
    osp_job_sub_status ON osp_job_sub_status.SubStatusID = osp_job_status_track.SubStatusID
        LEFT JOIN
    hr_employee_details ON hr_employee_details.EmployeeID = osp_job_details.AssignToEmployeeID
        LEFT JOIN
    osp_job_type ON osp_job_type.JobTypeID = osp_job_details.JobtypeID
    WHERE isDefault = 0 AND

    CASE WHEN osp_job_status.StatusID = 2
    THEN  osp_job_sub_status.CurrentStatus = 3
    ELSE osp_job_status.StatusID >= 2
        END;";

But getting this below error now..
Error Number: 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 'isDefault` = 1 AND CASE WHEN `osp_job_status`.`StatusID` = 2 THEN `osp_job' at line 8

SELECT `osp_job_details`.*, `osp_job_type`.`JobTypeName`, `status`, `Substatus`, `osp_job_status`.`StatusID`, `osp_job_sub_status`.`SubStatusID`, `FirstName`, `MiddleNames`, `LastName`, `hr_employee_details`.`EmployeeID`, `osp_job_status_track`.`StatusTrackID` FROM (`osp_job_details`) LEFT JOIN `osp_job_status_track` ON `osp_job_status_track`.`JobID` = `osp_job_details`.`JobID` LEFT JOIN `osp_job_status` ON `osp_job_status`.`StatusID` = `osp_job_status_track`.`StatusID` LEFT JOIN `osp_job_sub_status` ON `osp_job_sub_status`.`SubStatusID` = `osp_job_status_track`.`SubStatusID` LEFT JOIN `hr_employee_details` ON `hr_employee_details`.`EmployeeID` = `osp_job_details`.`AssignToEmployeeID` LEFT JOIN `osp_job_type` ON `osp_job_type`.`JobTypeID` = `osp_job_details`.`JobtypeID` WHERE ` ` isDefault` = 1 AND CASE WHEN `osp_job_status`.`StatusID` = 2 THEN `osp_job_sub_status`.`CurrentStatus` = 3 ELSE `osp_job_status`.`StatusID` >= 2 END ;

Filename: C:\xampp\htdocs\projects\zorkif_new\system\database\DB_driver.php

Line Number: 330

A: Just remove the quotes around your tables name.
SELECT *
FROM osp_job_details
(...)

And for what it's worth, you should try using activerecord for codeigniter. You won't have to worry with the SQL:
$this->db
    ->from('osp_job_details')
    ->join('osp_job_status_track', 'osp_job_status_track.JobID = osp_job_details.JobID', 'left')
    ->join('osp_job_status', 'osp_job_status.StatusID = osp_job_status_track.StatusID', 'left')
    ->join('osp_job_sub_status', 'osp_job_sub_status.SubStatusID = osp_job_status_track.SubStatusID', 'left')
    ->join('hr_employee_details', 'hr_employee_details.EmployeeID = osp_job_details.AssignToEmployeeID', 'left')
    ->join('osp_job_type', 'osp_job_type.JobTypeID = osp_job_details.JobtypeID', 'left')
    ->where('isDefault', 0)
    ->where("osp_job_status.StatusID = '2' AND osp_job_sub_status.CurrentStatus = '3' OR osp_job_status.StatusID >= '2'")
    ->result();

And if it doesn't work, add brackets around your CASE WHEN ;)

A: Remove all the single quotes :
SELECT * FROM
            osp_job_details
                LEFT JOIN
            osp_job_status_track ON osp_job_status_track.JobID = osp_job_details.JobID
                LEFT JOIN
            osp_job_status ON osp_job_status.StatusID = osp_job_status_track.StatusID
                LEFT JOIN
            osp_job_sub_status ON osp_job_sub_status.SubStatusID = osp_job_status_track.SubStatusID
                LEFT JOIN
            hr_employee_details ON hr_employee_details.EmployeeID = osp_job_details.AssignToEmployeeID
                LEFT JOIN
            osp_job_type ON osp_job_type.JobTypeID = osp_job_details.JobtypeID
            WHERE isDefault = 0 AND

            CASE WHEN osp_job_status.StatusID = 2
            THEN  osp_job_sub_status.CurrentStatus = 3
            ELSE osp_job_status.StatusID >= 2
                END;

If you want to escape the table names and fields you can use like "`"
UPDATE: replace the case :
CASE WHEN osp_job_status.StatusID = 2
THEN  osp_job_sub_status.CurrentStatus = 3
ELSE osp_job_status.StatusID >= 2
    END;

with:
(
    (
        osp_job_status.StatusID = 2
        AND
        osp_job_sub_status.CurrentStatus = 3
    )
    OR
    osp_job_status.StatusID >= 2
)

A: In your query you are using '' single quota in table name and column name by which it is treated as a string so replace the single quota with the `` tag.
Here is replaced code:
$sql ="SELECT * FROM
            `osp_job_details`
                LEFT JOIN
            `osp_job_status_track` ON `osp_job_status_track`.`JobID` = `osp_job_details`.`JobID`
                LEFT JOIN
            `osp_job_status` ON `osp_job_status`.`StatusID` = `osp_job_status_track`.`StatusID`
                LEFT JOIN
            `osp_job_sub_status` ON `osp_job_sub_status`.`SubStatusID` = `osp_job_status_track`.`SubStatusID`
                LEFT JOIN
            `hr_employee_details` ON `hr_employee_details`.`EmployeeID` = `osp_job_details`.`AssignToEmployeeID`
                LEFT JOIN
            `osp_job_type` ON `osp_job_type`.`JobTypeID` = `osp_job_details`.`JobtypeID`
            WHERE `isDefault` = 0 AND

            CASE WHEN `osp_job_status`.`StatusID` = '2'
            THEN  `osp_job_sub_status`.`CurrentStatus` = '3'
            ELSE `osp_job_status`.`StatusID` >= '2'
                END;";

A: use alias to simplify
$sql ="SELECT [specific column names ] FROM `osp_job_details` jd
    LEFT JOIN
            `osp_job_status_track` jst ON (`jst`.`JobID` = `jd`.`JobID`)
    LEFT JOIN
            `osp_job_status` js ON (`js`.`StatusID` = `jst`.`StatusID`)
    LEFT JOIN
            `osp_job_sub_status` jss ON (`jss`.`SubStatusID` = `jst`.`SubStatusID`)
    LEFT JOIN
            `hr_employee_details` hed ON (`hed`.`EmployeeID` = `jd`.`AssignToEmployeeID`)
    LEFT JOIN
            `osp_job_type` jt ON (`jt`.`JobTypeID` = `jd`.`JobtypeID`)

    WHERE `isDefault` = '0'
     AND CASE
                WHEN `js`.`StatusID` = '2' THEN  `jss`.`CurrentStatus` = '3'
                ELSE `jd`.`StatusID` >= '2'
            END ";
  $this->db->query($qry);

NOTE: wrap column name and table name with `  not with ' and also when referencing tablename. column name exclude the dot . from \
use  `tablename`.`column_name`

A: Hi Simply Add This Condition in your where clause
CORE QUERY
(CASE
        WHEN
            tbl_account.account_type = 4
        THEN
            1
   ELSE
     `tbl_acc_company`.`acc_comp_status` = 'ACTIVE'
   END
)

CI QUERY
$this->db->where("(CASE WHEN tbl_account.account_type = 4 THEN  1 ELSE tbl_acc_company.acc_comp_status = 'ACTIVE' END)");

A: this is an example of what I did to solve a problem in my system that needed a case, and the codeigniter inserted the ` in the query and returned an error. My solution was to put the parentheses => () in the case.
$this->db->select("(case when c.my_column THEN c.my_column ELSE c.other_column END as my_column_name)")


text:
Q: npm ERR! Cannot read property '0' of undefined λ npm i
npm ERR! Cannot read property '0' of undefined

I checked all similar questions, e.g. this one and many more. So far, what I have tried:

*

*delete node_modules folder and package-lock.json, then npm i

*repeat removal of folder and file in step 1 + clear the cache with npm cache clear --force

*nvm uninstall 10.13.0, reinstall the version

*uninstall nvm and reinstall nvm

In between, I rebooted my PC several times. Downgrading my Node version is not an option as I am working on a company project.
Here is my NPM log:
3782 silly saveTree `-- websocket@1.0.29 3783 verbose stack TypeError:
 Cannot read property '0' of undefined 3783 verbose stack     at
 rmStuff (C:\tools\nvm\v10.13.0\node_modules\npm\lib\unbuild.js:61:24)
 3783 verbose stack     at tryCatcher
 (C:\tools\nvm\v10.13.0\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
 3783 verbose stack     at ret (eval at makeNodePromisifiedEval
 (C:\tools\nvm\v10.13.0\node_modules\npm\node_modules\bluebird\js\release\promisify.js:184:12),
 <anonymous>:13:39) 3783 verbose stack     at lifecycle.then.then
 (C:\tools\nvm\v10.13.0\node_modules\npm\lib\install\action\unbuild.js:12:12)
 3783 verbose stack     at tryCatcher
 (C:\tools\nvm\v10.13.0\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
 3783 verbose stack     at Promise._settlePromiseFromHandler
 (C:\tools\nvm\v10.13.0\node_modules\npm\node_modules\bluebird\js\release\promise.js:512:31)
 3783 verbose stack     at Promise._settlePromise
 (C:\tools\nvm\v10.13.0\node_modules\npm\node_modules\bluebird\js\release\promise.js:569:18)
 3783 verbose stack     at Promise._settlePromise0
 (C:\tools\nvm\v10.13.0\node_modules\npm\node_modules\bluebird\js\release\promise.js:614:10)
 3783 verbose stack     at Promise._settlePromises
 (C:\tools\nvm\v10.13.0\node_modules\npm\node_modules\bluebird\js\release\promise.js:693:18)
 3783 verbose stack     at Promise._fulfill
 (C:\tools\nvm\v10.13.0\node_modules\npm\node_modules\bluebird\js\release\promise.js:638:18)
 3783 verbose stack     at
 C:\tools\nvm\v10.13.0\node_modules\npm\node_modules\bluebird\js\release\nodeback.js:42:21
 3784 verbose cwd C:\src\agl-bot-alfie\botkit 3785 verbose Windows_NT
10.0.17134 3786 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "i"
 3787 verbose node v10.13.0 3788 verbose npm  v6.4.1 3789 error Cannot
 read property '0' of undefined 3790 verbose exit [ 1, true ]

A: Use the correct version of npm and node. You can use a nvm https://github.com/nvm-sh/nvm
Check the package.json value. For example:
"engines": {
  "node": "~6.17.1",
  "npm": ">=5.0.0"
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make vue-HighChart responsive, but chartOptions from an API I have a little problem when I want to make my vue-highchart responsive. I have an example for it (see image 1)

and its mine (see image 2)

this is my code
<v-tab-item class="tabs__resources">
          <v-card outlined rounded="60">
            <v-container>
              <v-row>
                <v-col>
                  <highcharts :options="chart_cpu"></highcharts>
                </v-col>
                <v-col>
                  <highcharts :options="chart_memory"></highcharts>
                </v-col>
                <v-col class="py-6">
                  <v-card class="card-incoming" :ripple="false">
                    <v-layout class="py-1" align-center justify-center>
                      <v-flex>

Incoming Rate Total

{{network_total.rx}}

                      </v-flex>
                    </v-layout>
                  </v-card>
                  <v-card class="card-outgoing" :ripple="false">
                    <v-layout class="py-1" align-center justify-center>
                      <v-flex>

Incoming Rate Total

{{network_total.tx}}

                      </v-flex>
                    </v-layout>
                  </v-card>
                </v-col>
              </v-row>
            </v-container>
          </v-card>
        </v-tab-item>

A: Chose responsive.rules to fit the charts, manipulate size and center to change position of pie. Plot chart area is reserved for the whole circle, you need to remember this when you setting.
  responsive: {
    rules: [{
      condition: {
        maxWidth: 400
      },
      chartOptions: {
        series: [{
          size: '100%',
          center: ['50%', '50%'],
        }]
      }
    }]
  }

Demo: https://jsfiddle.net/BlackLabel/5kh9ad4w/1/
API: https://api.highcharts.com/highcharts/responsive


text:
Q: Reward someone who edited their answer as obsolete to point to mine I've been active on SO since 2009, and have seen many old questions get new answers as technology changes. Sometimes the accepted answer becomes suboptimal, and the OP is no longer active to mark another answer as the accepted one.
This causes the correct answer(s) to gain few upvotes, while the accepted one keeps piling up votes due to the snowball effect.
However, some rare individuals have edited their own answers to point to the better ones right off the bat. Is there some sort of badge or reward I could award in such instances, to encourage this honorable behavior?
UPDATE: There's a closely related feature request that would solve my ask:
Allow Accepted Answer recipient to give it away
I've added my "outdated answers" use case to it because back when it was requested (2009), this use case didn't exist.

A: Badges are never directly awarded by users. They're only extremely rarely awarded by staff and that's only in special situations (Not a Robot, for example).
The only real way we have to "thank" someone is through bounties. That said, you note that it seems inappropriate to bounty this specific answer as it is outdated and the bounty will only draw attention to it. It also requires that you are willing to give up some of your own reputation to thank this person. If you are, the other option you have would be to find one of their other answers that is currently excellent and worthy of recognition and put a bounty on that question rather than this one. In your search for such an answer, please avoid voting on them all as that may look like targeted voting to our system.
In this way you can grant the user reputation without drawing attention to the outdated answer... that said... eh... you've said thank you already in a comment. While I love that you want to thank them somehow, our current system doesn't really allow for that and that's largely by design. Our system, as much as people accuse us of being a social media site, is designed primarily to recognize the content, not the people who create it. The two are very closely intertwined but not quite the same.
Now, there actually is one badge that this user may get and it's one we've had for a while. That is, the Sportsmanship badge... and the user in question doesn't have it yet. The badge description is:

Up vote 100 answers on questions where an answer of yours has a positive score.

Now, this isn't quite the same as what you're looking for but it does reward that same quality you appreciate from this user - recognizing that answers competing with yours on a question may also be of value. So, if David upvoted your answer and eventually upvotes 99 other competing answers, he'll earn this badge (assuming he's not upvoted others yet).


text:
Q: Tangent, condition How to bypass the angles at which the function tan (x) is not defined, ie x != Pi/2 + k * PI ?
I tried to use the condition:
(x != 0) && (2 * x / M_PI - (int)(2 * x / M_PI ) ) < epsilon,

but it represents a condition
x != Pi/2 + k * PI / 2.
Thanx for your help.

A: The same condition can be used to determine which values of cos(x) will be zero. Thanks to that wonderful fact, you can simply do the following (pseudocode):
SafeTan(x)
{
    if (cos(x) < epsilon) { /* handle the error */ }
    else { return tan(x); }
}

Edit: As In silico points out, this is a result of the trigonometric identity:
tan(x) = sin(x) / cos(x)
In this form, you can see that the undefined values will appear wherever cos(x) = 0 because of the division by zero.

A: How about trying
(x - PI/2) % PI != 0

Will find check for the values of x that cause tan(x) to be undefined.

A: Don't use tangent? It can be more performant than using a (sine, cosine) pair, but usually you can use a (sine, cosine) pair without worrying about discontinuities.
What are you using tangent for?


text:
Q: Syntax error with pgSQL, using functions and if else I'm practicing a little bit with postgreSQL,  i'm creating  a very simple function that inserts a row into a table depending on the value of the variable 'num'. However, when I try to create the function I get the following error in pgAdmin III:
"An error has occured: ERROR: syntax error at or near IF LINE 3: IF num = 1 THEN"
This is my code:
    CREATE FUNCTION "elseIf"(IN num integer) RETURNS void AS
    $BODY$
    IF num = 1 THEN

        INSERT INTO "Accounts"(
         "Email", "Password")
           VALUES ('email1', 'password1');

    ELSE
        INSERT INTO "Accounts"(
         "Email", "Password")
           VALUES ('email2', 'password2');

    END IF;
    $BODY$
    LANGUAGE plpgsql VOLATILE NOT LEAKPROOF;
    ALTER FUNCTION public."elseIf"(IN integer)
    OWNER TO repository;

Any possible solution? thanks in advance!

A: You forgot the BEGIN.
PL/PgSQL must be wrapped in a BEGIN ... END block.
... RETURNS VOID AS
$BODY$
BEGIN
   IF num = 1 THEN
      ...
   END IF;
END;
$BODY$ ....


text:
Q: Swift - How to sort and array by optional property Say I have a Cat class with this property:
var order: Int?

I have an array of these classes that I need to order by this property:
let sortedCats = cats.sorted(by: { $0.order > $1.order })

I get this error:
"Binary operator '>' cannot be applied to two 'Int?' operands"

What's the proper way to do this?

A: Use a default value of .min which is the smallest number you can have on an Int
let sortedCats = cats.sorted(by: { $0.order ?? .min > $1.order ?? .min })


text:
Q: Waiting for observable until API Load all the information Angular2 I have been working in a loading component to make a friendly wait between the content is called and loaded from API. There is no issue when is just text, but when the information has images or more information, the loading component disappear before the content is fully loaded.
I took a look to the lifecycle hooks of Angular2, but any of them look like fit for my requirement.
Mainly my component understand when the isLoading = true have to disappear.
Here is my way I tried to do it.
ngOnInit() {
        // Payload to call the API
        var model: myPayload = {
            AuthorId: this._authorid,
            CountryId: this._countryid

        }
        // Api loading
        Observable.forkJoin(
            this._service.getList(model)
        )
            .subscribe(
            res => {
                this.authorList = res[0];
            },
            null,
            () => {
                this.isLoading = false
                }
            )
}

A: There is no way to make components wait for a Promise or Observable.
The router can be made to wait for Observable to complete with the CanActivate guard.
A simple workaround is to just add *ngIf="data" on the outermost element in the view.

A: For others, this is how you write your canActivate function.
In your router:
// all your imports go here

const APP_ROUTES: Routes = [
    { path: '', component: HomePageComponent, canActivate: [WaitForApiLoad] }
]

export const AppRouter = RouterModule.forRoot(APP_ROUTES);

Create a new service WaitForApiLoad
// all your imports go here

@Injectable()
export class WaitForApiLoad implements CanActivate
{

    private dataFromApi: any;

    canActivate(activatedRouteSnapshot: ActivatedRouteSnapshot,
            routerStateSnapshot: RouterStateSnapshot): Observable<boolean>
    {

        return
            this.myApiService
                .getData()
                .map( data => {
                    this.dataFromApi = data;
                    return true;
                });
    }

}


text:
Q: PREDICT set for a LL(1) parser help me fix it I am trying to build a compiler for a college projec. Currently I am having problems to create a part of my predict set for the LL(1) grammar. This is the part of my grammar that I am having problems with:
<DECLS>  ::- id <DECL> <N_DECL>
<N_DECL> ::- op_, <DECLS> | null
<DECL>   ::- <SOMETHING_MORE>

The first sets for this part of the grammar are:
<DECLS>  = id
<N_DECL> = op_ , null

The follow sets for this part of the grammar are:
<DECLS>  = op_; , op_,
<N_DECL> = op_; , op_,

The predict set for this part of the grammar is (see as a matrix):
                   id                      op_,
<DECLS>    id <DECL> <N_DECL>
<N_DECL>                               op_, <DECLS> / null      <--- here

As you can see the entry for N_DECL and op_ has two entries. As far as I know, a grammar is wrong if the predict set has two or more entries in the same box. So I was wondering if someone can help me changing my grammar to solve this problem.

A: If I understand your notation correctly, then

*

*FIRST(<N_DECL>) = { op_, , null }

*FOLLOW(<N_DECL>) = { op_; , op_, }
I don't see where op_, in <N_DECL>'s FOLLOW set comes from (perhaps it's coming from a different part of your grammar), but if it's really there, your grammar would be ambiguous due to a FIRST/FOLLOW conflict. These occur whenever the FIRST set of a non-terminal contain null (i.e. the non-terminal can produce the empty string), and the FIRST and FOLLOW set of that non-terminal overlap. In this case, they both contain op_,, which causes problems as you have noticed.
From the fact that you list op_, in <DECLS>'s FOLLOW set, I deduce that the actual ambiguity arises from a part of the grammar that you didn't include in your question. If you're parsing a <DECLS> with a lookahead of one token, encountering a comma may mean that you have another op_, id <DECL> <N_DECL> phrase, or that that comma belongs to a structure where the comma is "outside" the <DECLS>.
It might be that your language is LL(1), but without knowing why <DECLS> can be followed by op_,, I wouldn't know how to resolve this conflict. However, if it turns out that your language isn't LL(1) as it is tokenised now, you should consider tricking the tokeniser to do the lookahead for you:

*

*Use substitution to arrive at <N_DECL> ::- op_, id <DECL> <N_DECL> | null.

*Let the lexer parse op_, id as its own token comma_id.

*Correct the production: <N_DECL> ::- comma_id <DECL> <N_DECL> | null.


text:
Q: Vector as Parameter C I have to do the following:
Given a vector with random numbers, separate it in 2 other vectors, odd and even. But in the function, all vectors must be passed via parameter (can't use global).
Here is my code:
#include <stdio.h>
#include <stdlib.h>

void vetores(int *vetor, int *A, int *B)
{
    int i = 0,aux;
    for(i = 0;i < 100; i++)
    {
        if(vetor[i] % 2 == 0)
        {
            aux = vetor[i];
            A[i] = aux;
        }else{
            aux = vetor[i];
            B[i] = aux;
        }
    }
}

int main()
{
    int vetor[101], a[51], b[51],i;

    /*a = (int)malloc(sizeof(int)*51);
    b = (int)malloc(sizeof(int)*51);*/

    for(i = 0; i < 100; i++)
    {
        vetor[i] = i;
    }

    vetores(vetor,a,b);

    for(i = 0; i < 50; i++)
    {
        if(vetor[i] % 2 == 0)
        {
            printf("%d",a[i]);
        }else
        {
            printf("%d",b[i]);
        }
    }

    return 0;
}

If you test that code, the vector is being altered (it is not supposed to) and the A vector is not receiving the even numbers!

A: Your main problem is that you're indexing your outputs based on the position in the input.
For example, if your first even number is at input[3], then you're writing it to even_output[3], where is should (probably) be at even_output[0].
You probably want something like:
if (input[i] %2 == 0)
    *A++ = input[i];
else
    *B++ = input[i];

You probably also need to do something to tell the caller how many odd and even numbers you found (and the caller may have to allocate memory a bit differently unless those counts are equal -- right now, you have 101 inputs, and 51 spots allocated for each output. If you had (for example) 60 even and 40 odd numbers, you'll write beyond end of the space you've allocated for the even numbers. With the inputs you've provided, that problem won't arise, but in almsot any other case, it's not only possible, but in fact likely.

A: You need separate index count for array A and B.
Try this:
void vetores(int *vetor, int *A, int *B)
{
    int i = 0,aux;
    int aIndex = 0, bIndex = 0;
    for(i = 0;i < 100; i++)
    {
        if(vetor[i] % 2 == 0)
        {
            A[aIndex] = vetor[i];
            aIndex++;
        }else{
            B[bIndex] = vetor[i];
            bIndex++;
        }
    }
}

Try using a nice debugger tool, that will help you find this kind of errors in the code.
You also need to check the length of your arrays:
int vetor[101], a[51], b[51]

I think a or b could have more than 51 values if they are random.
Hope it helps.

A: Here are some hints: Beside you nearly always misspelled "vector", you are using classic c arrays not vectors. Your vectors method needs some heavy refactoring as you are unnecessary using extra memory and double assign variables.
#include <stdio.h>
#include <stdlib.h>

void vectores(int *vector, int *A, int *B)
{
    int i = 0, k = 0, l = 0;
    for(;i < 100; i++)
    {
        if(vector[i] % 2 == 0)
        {
            A[k++] = vector[i];
        }else{
            B[l++] = vector[i];
        }
    }
}

int main()
{
    int vector[100], a[51], b[51],i;

    for(i = 0; i < 100; i++)
    {
        vector[i] = i;
    }

    vectores(vector,a,b);
    for(i = 0; i < 51; i++){
        printf("%d          %d",a[i], b[i] );
        printf("\n");
    }
    return 0;
}

A: This is technically not an answer to your question, but if you want to separate the odd and even values, you're better off doing a single pass of QuickSort on the last bit of each value, e.g.
int temp, i = 0, j = N-1;
while ( i < j ) {
    while ( vetor[i] & 1 == 0 )
        i += 1;
    while ( vetor[j] & 1 == 1 )
        j -= 1;
    if ( i < j ) {
        temp = vetor[i];
        vetor[i] = vetor[j];
        vetor[j] = temp;
        }
    }

The above is untested, if you find any bugs, feel free to keep them.


text:
Q: GLFW key input on GNOME 3 desktop I've a problem with GLFW3 on a GNOME 3 desktop.
I've tested this on several Linux machines, including a fresh installed Ubuntu 16.04 LTS machine (with Unity).
The problem occurs in every GLFW3 application.
If i press and hold any key, a normal key GLFW_PRESS, and while holding the GLFW_REPEAT events are emitted.
But if I release the key, one GLFW_RELEASE event is emitted, following by another GLFW_PRESS (and sometimes multiple GLFW_REPEAT) events.
Here a minimal example:
#include <GLFW/glfw3.h>
#include <cstdio>

void glfw_key_callback(GLFWwindow* w, int key, int scancode, int action, int mods) {
    printf("win %p: key %d, scancode %d, action %d, mods %d\n", w, key, scancode, action, mods);
}

int main() {
    if (!glfwInit()) {
        printf("Failed to init glfw!\n");
        return 1;
    }

    GLFWwindow* window = glfwCreateWindow(800, 600, "Key input test", 0, 0);
    glfwMakeContextCurrent(window);

    glfwSetKeyCallback(window, glfw_key_callback);

    while (!glfwWindowShouldClose(window)) {
        glfwWaitEvents();

        glfwSwapBuffers(window);
    }

    return 0;
}

Example output when I press and hold Space and release it after a few seconds:
win 0x104fb20: key 32, scancode 65, action 1, mods 0
win 0x104fb20: key 32, scancode 65, action 2, mods 0
...
win 0x104fb20: key 32, scancode 65, action 2, mods 0
win 0x104fb20: key 32, scancode 65, action 0, mods 0
win 0x104fb20: key 32, scancode 65, action 1, mods 0
win 0x104fb20: key 32, scancode 65, action 2, mods 0
win 0x104fb20: key 32, scancode 65, action 0, mods 0

I also have tried to compile and run this program with the current GLFW3 dev version (from https://github.com/glfw/glfw.git ) but with the same result.
Then i searched in the glfw3 source code where this events came from.
I found the XPending() call in the glfw3 source x11_window.c.
But it looks as that this additions events are emitted from the X11 system,
so I am not sure if this is a GLFW or X11 problem?
On other desktop environments such as Mate Desktop everything works fine for me.


text:
Q: VHDL record fields do not update in Simulation in Vivado 2020.2 I first noticed this issue in this post here. I've now gone ahead and made an MCVE. The DUT:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
use work.top_pkg.all;

entity top is
  Port (
      clk : in std_logic;
      ce : in std_logic;
      input_custom_arr : in custom_record_array(4 downto 0);
      info : in custom_record;
      ctrl : in custom_record;
      output_custom_arr : out custom_record_array(4 downto 0)
  );
end top;

architecture Behavioral of top is

begin
    process(clk)
    begin
      if(ce = '1' and rising_edge(clk)) then
        output_custom_arr <= func_manipulate_custom_record_array(input_custom_arr, info, ctrl);
      end if;
    end process;
end Behavioral;

The package it uses that contains the custom function and types:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

package top_pkg is
    type custom_record is record
        data_1 : std_logic_vector(3 downto 0);
        data_2 : std_logic_vector(3 downto 0);
        sync   : std_logic;
        enable : std_logic;
    end record;

    type custom_record_array is ARRAY (INTEGER RANGE <>) of custom_record;

    FUNCTION func_manipulate_custom_record_array(dp : custom_record_array; info, ctrl : custom_record) RETURN custom_record_array;
    end package;

package body top_pkg is

    FUNCTION func_manipulate_custom_record_array(dp : custom_record_array; info, ctrl : custom_record) RETURN custom_record_array is
        VARIABLE v_dp : custom_record_array(dp'RANGE) := dp;
        begin
            for I IN dp'RANGE LOOP
                v_dp(I).sync := info.sync;
                v_dp(I).enable := ctrl.enable;
            end loop;
        return v_dp;
        END func_manipulate_custom_record_array;
end package body;

And the testbench to simulate:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.all;
use work.top_pkg.all;

entity tb_top is
end tb_top;

architecture Behavioral of tb_top is
constant half_period : time := 10ns;
constant num_of_clocks : integer := 10;

signal input_custom_arr : custom_record_array(4 downto 0);
signal output_custom_arr : custom_record_array(4 downto 0);
signal info : custom_record := ((others=>'0'),(others=>'0'),'1','0');
signal ctrl : custom_record := ((others=>'0'),(others=>'0'),'0','1');
signal clk : std_logic := '0';
signal ce : std_logic := '0';
signal i : integer := 0;

begin
    -- continuous clock
    process
    begin
        clk <= '0';
        wait for half_period;
        clk <= '1';
        wait for half_period;

        if (i = num_of_clocks) then
            wait;
        elsif (i < 5) then
            input_custom_arr(i).data_1 <= std_logic_vector(TO_SIGNED(i,4));
            input_custom_arr(i).data_2 <= std_logic_vector(TO_SIGNED(4-i,4));
            i <= i + 1;
        elsif ( i = 5) then
            ce <= '1';
            i <= i + 1;
        else
            i <= i + 1;
        end if;
    end process;

    --DUT
    u_dut : entity work.top
    port map(
        clk => clk,
        ce => ce,
        input_custom_arr => input_custom_arr,
        output_custom_arr => output_custom_arr,
        info => info,
        ctrl => ctrl
    );
end Behavioral;

If you simulate, you get the following wave window:

After the 7th period, you will note that the sync and enable fields of the output_custom_arr array do not get updated as the function specifies. From the testbench, I'd expect that the sync and enable fields of every element in the output_custom_arr be '1'.
This issue is different to what was occurring here where the untouched fields were being altered. However, unless I've made an error here, does this reaffirm Vivado's struggle to simulate records correctly? At lease for version 2020.2 on Windows 10?
Thank you.
Talon Myburgh.

A: I've found that this appears to be a version issue for both this problem and the one mentioned here.
In Vivado 2020.1 on Windows 10, for the exact same project as above, I get what we would expect in Simulation:

I do not know how far this issue extends in Vivado 2020.2 but I'd recommend avoiding designs with arrays of records in that version for the time being.
Thanks all.


text:
Q: php cron job every 10 minutes I'm trying to run a cron job so that a php script will run every 10 minutes on my server. The script updates a database. Right now my crontab looks like:
* /10 * * * * /usr/bin/php  /home/user/public_html/domain.com/private/update.php

However, the php script never seems to run. I've also tried reloading cron after updating the cron tab with :
  $ /etc/init.d/cron reload

but this didn't work either. Does my current crontab look correctly formatted? Are there specific permissions that need to be specified on a file in order for it to run a script?

A: There should not be a space between "*" and "/10".  It should be:
*/10 * * * * /usr/bin/php  /home/user/public_html/domain.com/private/update.php


text:
Q: How to structure tests in django, for functional vs unit vs other? It seems that
python manage.py test

runs all the tests in myapp/tests.py
But say i want to break those up into myapp/functional_tests.py, myapp/unittests.py, myapp/ajaxtests.py what is the recommended way to do that? My functional tests wouldn't have any sense of coverage, while my unit tests would definitely want to report coverage, my "ajax" tests are just an example of something in between.
I would like it so i could run one command that would run all tests (for continuous integration), while being able to pick and choose tests while developing.

A: You can run separate tests with python manage.py test monkey.test, which will run all of the tests in the monkey.test module. Read here about that. Or use, my favorite test runner py.test which will help you separate tests into folders and make it really easy to run!
Now you might want to have some fancy command and not do the above all the time, then you could use a task automator as fabric!
After doing the normal pip install fabric, you setup a fabfile.py in your root folder.
Inside of this you define your tasks that you want to run.
A crude version of this would look like this
from fabric.api import local

def run_tests(env):
    local('python manage.py test {0}_test.py'.format(env))

And run it from the command line like this
$ > fab run_tests:integration

With this tool, you've also started on the path of getting your tasks automated and you can also start using Fabric to do your deployment for you and also it integrates really well with CI servers.


text:
Q: How to split a vector into other two containing the N random chosen elements and the rest? I want to have a function that chooses N random elements from the input vector and returns as output parameters two vectors: one containing the chosen elements and one containing the remaining elements.
I have created a template that looks like here:
template< class T > void splitVector(const std::vector< T >& vecIn, int nbIn, std::vector< T >& chosenOut, std::vector< T >& remainedOut)
{
    if (nbIn >= vecIn.size())
    {
        chosenOut = vecIn;
        remainedOut.clear();
        return;
    }

    if (nbIn <= 0)
    {
        chosenOut.clear();
        remainedOut = vecIn;
        return;
    }

    cv::RNG randomChooser(cv::getTickCount()); // this is an OpenCV RNG, but it can be any other
    chosenOut.clear();
    remainedOut = vecIn;
//  I have also tried these approaces too, but none works
//  remainedOut.clear();
//  std::copy(vecIn.begin(), vecIn.end(), remainedOut.begin());
//  remainedOut.insert(remainedOut.begin(), vecIn.begin(), vecIn.end());
    int index;
    size_t listSize = vecIn.size();
    fs::path name;

    for (size_t i = 0; i < nbIn; ++i)
    {
        index = randomChooser.next() % listSize;
        name = remainedOut[index];
        remainedOut.erase(remainedOut.begin() + index);
        chosenOut.push_back(name);
        listSize = remainedOut.size();
    }
}

*

*I am getting an error at runtime: bad_alloc when remainedOut = vecIn;.

*If I have tried the insert I am getting the same error when inserting.

*If I use copy it works but I am getting an error when name = remainedOut[index];
I think it is something about the allocation. When I called the function I have created the output vectors like this:
std::vector< boost::filesystem::path > chosen;
std::vector< boost::filesystem::path > remained;
splitVector< boost::filesystem::path >(elements, 12, chosen, remained);

Can anyone help me to make this work? I would like to do all the things in the function (if it is possible). Shall I use assign? Or how would you suggest me to do this in the best way?

EDIT:
Why even If I do
//... the ifs in the function
std::vector< T > tmpVec = vecIn; // here
std::random_shuffle(tmpVec.begin(), tmpVec.end());
chosenOut.insert(chosenOut.begin(), vecIn.begin(), vecIn.begin() + nbIn);
remainedOut.insert(remainedOut.begin(), vecIn.begin() + nbIn, vecIn.end());

I get the std::bad_alloc error at the mentioned line?
Even copy c-tor is throwing that error...

A: You may try, this will return a pair of pointer, not reference though:
template< class T > std::pair<vector<T>* , vector<T>* > splitVector(const std::vector< T >& vecIn, int nbIn)
{
    auto vecC = vecIn;
    std::random_shuffle(vecC.begin(), vecC.end());
    auto vec1 = new vector<T>(vecC.begin(), vecC.begin()+nbIn);
    auto vec2 = new vector<T>(vecC.begin()+nbIn, vecC.end());
    return std::make_pair(vec1, vec2);
}


text:
Q: How to find if a value exists within a VARRAY I've created a VARRAY within a table (below)
I would like to query whether or not a Title has a particular theme, eg. Show 'Action' games.
I'm not to sure how to go about this...
CREATE OR REPLACE TYPE Theme_Game AS OBJECT
(Theme VARCHAR(20));
/
CREATE OR REPLACE TYPE Theme_Type AS VARRAY(3) OF Theme_Game;
/
CREATE OR REPLACE TYPE Game_Type AS OBJECT
(Title VARCHAR2(50),
GameTheme Theme_Type);
/
CREATE TABLE Game_Table of Game_Type
/
INSERT INTO Game_Table
VALUES('Star Wars' ,(Theme_Type(Theme_Game('Action'), Theme_Game('FPS'))))
/

A: You need to expose the nested table in the FROM clause using the table() function. You can then reference attributes of the collection:
SQL> select g.title
  2  from game_table g
  3       , table(g.gametheme) gt
  4  where gt.theme = 'Action';

TITLE
--------------------------------------------------
Star Wars

SQL>

"what if I then needed to retrieve rows with multiple Themes i.e Action, FPS?"

Apologies for the clunky solution but I need to go to work now. I may post a more elegant solution later.
SQL> select * from game_table
  2  /

TITLE
--------------------------------------------------
GAMETHEME(THEME)
--------------------------------------------------------------------------------
Star Wars
THEME_TYPE(THEME_GAME('Action'), THEME_GAME('FPS'))

Uncharted 3
THEME_TYPE(THEME_GAME('Action'), THEME_GAME('Puzzle'))

Commander Cody
THEME_TYPE(THEME_GAME('Fun'), THEME_GAME('Puzzle'))

SQL> select g.title
  2  from game_table g
  3       , table(g.gametheme) gt
  4       , table(g.gametheme) gt1
  5  where gt.theme = 'Action'
  6  and gt1.theme = 'FPS' ;

TITLE
--------------------------------------------------
Star Wars

SQL>

This alternative approach won't work with your current type because VARRAY does not support member of. But it would work if the collection was a Nested Table.
 select g.title
  from game_table g
  where  'Action' member of g.gametheme
  and 'FPS' member of g.gametheme

A: For multiple themes you could do something like
select g.Title
from game_table g, table(g.gameTheme) t
where t.Theme in ('FPS','Action')
group by g.Title having count(0) = 2;

This could also allow you to do things like get titles with exactly n matches, at least n matches, at most n matches...

A: You can use a collection and then compare multiple items using the SUBMULTISET operator:
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE OR REPLACE TYPE Theme_Game AS OBJECT
(Theme VARCHAR(20));
/
CREATE OR REPLACE TYPE Theme_Type AS TABLE OF Theme_Game;
/
CREATE OR REPLACE TYPE Game_Type AS OBJECT(
  Title VARCHAR2(50),
  GameTheme Theme_Type
);
/
CREATE TABLE Game_Table of Game_Type
NESTED TABLE GameTheme STORE AS GameTheme_Tab
/
INSERT INTO Game_Table
VALUES('Star Wars' ,(Theme_Type(Theme_Game('Action'), Theme_Game('FPS'))))
/

Query 1:
SELECT *
FROM   game_table
WHERE  Theme_Type(Theme_Game('Action'), Theme_Game('FPS'))
       SUBMULTISET OF GameTheme

Results:
|     TITLE |                                             GAMETHEME |
|-----------|-------------------------------------------------------|
| Star Wars | oracle.sql.STRUCT@67e8dc0f,oracle.sql.STRUCT@795b6d4c |

However, why are you using the Theme_Game object when it only has a single VARCHAR2 attribute? You can just use a VARRAY(3) OF VARCHAR2(20) or TABLE OF VARCHAR2(20) without the intermediate object:
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE OR REPLACE TYPE Varchar20List AS TABLE OF VARCHAR2(20);
/
CREATE OR REPLACE TYPE Game_Type AS OBJECT(
  Title VARCHAR2(50),
  GameTheme Varchar20List
);
/
CREATE TABLE Game_Table of Game_Type
NESTED TABLE GameTheme STORE AS GameTheme_Tab
/
INSERT INTO Game_Table
VALUES('Star Wars' , Varchar20List('Action', 'FPS'))
/

Query 1:
SELECT *
FROM   game_table
WHERE  Varchar20List('Action','FPS')
       SUBMULTISET OF GameTheme

Results:
|     TITLE |  GAMETHEME |
|-----------|------------|
| Star Wars | Action,FPS |

If you want to do it with VARRAYs then:
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE OR REPLACE TYPE Varchar20List AS VARRAY(3) OF VARCHAR2(20);
/
CREATE OR REPLACE TYPE Game_Type AS OBJECT(
  Title VARCHAR2(50),
  GameTheme Varchar20List
);
/
CREATE TABLE Game_Table of Game_Type
/
INSERT INTO Game_Table
VALUES('Star Wars' , Varchar20List('Action', 'FPS'))
/

Query 1:
SELECT *
FROM   game_table g
WHERE  2 >= ( SELECT COUNT(*)
              FROM   TABLE( g.GameTheme ) a
                     INNER JOIN
                     TABLE( Varchar20List( 'Action', 'FPS' ) ) b
                     ON ( a.COLUMN_VALUE = b.COLUMN_VALUE )
             )

Results:
|     TITLE |  GAMETHEME |
|-----------|------------|
| Star Wars | Action,FPS |

or:
Query 2:
SELECT *
FROM   game_table g
WHERE  2 >= ( SELECT COUNT(*)
              FROM   TABLE( g.GameTheme ) a
              WHERE  a.COLUMN_VALUE IN ( 'Action', 'FPS' )
             )

Results:
|     TITLE |  GAMETHEME |
|-----------|------------|
| Star Wars | Action,FPS |


text:
Q: Find all locations / cities / places in a text If I have a text containing for example an article of a newspaper in Catalan language, how could I find all cities from that text?
I have been looking at the package nltk for python and I have downloaded the corpus for catalan language (nltk.corpus.cess_cat).
What I have at this moment:
I have installed all necessary from nltk.download().  An example of what I have at this moment:
te = nltk.word_tokenize('Tots els gats son de Sant Cugat del Valles.')

nltk.pos_tag(te)

The city is 'Sant Cugat del Valles'. What I get from the output is:
[('Tots', 'NNS'),
 ('els', 'NNS'),
 ('gats', 'NNS'),
 ('son', 'VBP'),
 ('de', 'IN'),
 ('Sant', 'NNP'),
 ('Cugat', 'NNP'),
 ('del', 'NN'),
 ('Valles', 'NNP')]

NNP seems to indicate nouns whose first letter is uppercase. Is there a way of getting places or cities and not all names?
 Thank you

A: You have either to train an named entity recognizer (NER) or you can make your own Gazetteer.
A simple Gazetteer I have made and use for tasks like yours is this one:
# -*- coding: utf-8 -*-
import codecs
from lxml.html.builder import DT
import os
import re

from nltk.chunk.util import conlltags2tree
from nltk.chunk import ChunkParserI
from nltk.tag import pos_tag
from nltk.tokenize import wordpunct_tokenize

def sub_leaves(tree, node):
    return [t.leaves() for t in tree.subtrees(lambda s: s.node == node)]

class Gazetteer(ChunkParserI):
    """
    Find and annotate a list of words that matches patterns.
    Patterns may be regular expressions in the form list of tuples.
    Every tuple has the regular expression and the iob tag for this one.
    Before applying gazetteer words a part of speech tagging should
    be performed. So, you have to pass your tagger as a parameter.
    Example:
        >>> patterns = [(u"Αθήνα[ς]?", "LOC"), (u"Νομική[ς]? [Σσ]χολή[ς]?", "ORG")]
        >>> gazetteer = Gazetteer(patterns, nltk.pos_tag, nltk.wordpunct_tokenize)
        >>> text = u"Η Νομική σχολή της Αθήνας"
        >>> t = gazetteer.parse(text)
        >>> print(unicode(t))
        ... (S Η/DT (ORG Νομική/NN σχολή/NN) της/DT (LOC Αθήνας/NN))
    """

    def __init__(self, patterns, pos_tagger, tokenizer):
        """
        Initialize the class.

        :param patterns:
            The patterns to search in text is a list of tuples with regular
            expression and the tag to apply
        :param pos_tagger:
            The tagger to use for applying part of speech to the text
        :param tokenizer:
            The tokenizer to use for tokenizing the text
        """
        self.patterns = patterns
        self.pos_tag = pos_tagger
        self.tokenize = tokenizer
        self.lookahead = 0  # how many words it is possible to be a gazetteer word
        self.words = []  # Keep the words found by applying the regular expressions
        self.iobtags = []  # For each set of words keep the coresponding tag

    def iob_tags(self, tagged_sent):
        """
        Search the tagged sentences for gazetteer words and apply their iob tags.

        :param tagged_sent:
            A tokenized text with part of speech tags
        :type tagged_sent: list
        :return:
            yields the IOB tag of the word with it's character, eg. B-LOCATION
        :rtype:
        """
        i = 0
        l = len(tagged_sent)
        inside = False  # marks the I- tag
        iobs = []

        while i < l:
            word, pos_tag = tagged_sent[i]
            j = i + 1  # the next word
            k = j + self.lookahead  # how many words in a row we may search
            nextwords, nexttags = [], []  # for now, just the ith word
            add_tag = False  # no tag, this is O

            while j <= k:
                words = ' '.join([word] + nextwords)  # expand our word list
                if words in self.words:  # search for words
                    index = self.words.index(words)  # keep index to use for iob tags
                    if inside:
                        iobs.append((word, pos_tag, 'I-' + self.iobtags[index]))  # use the index tag
                    else:
                        iobs.append((word, pos_tag, 'B-' + self.iobtags[index]))

                    for nword, ntag in zip(nextwords, nexttags):  # there was more than one word
                        iobs.append((nword, ntag, 'I-' + self.iobtags[index]))  # apply I- tag to all of them

                    add_tag, inside = True, True
                    i = j  # skip tagged words
                    break

                if j < l:  # we haven't reach the length of tagged sentences
                    nextword, nexttag = tagged_sent[j]  # get next word and it's tag
                    nextwords.append(nextword)
                    nexttags.append(nexttag)
                    j += 1
                else:
                    break

            if not add_tag:  # unkown words
                inside = False
                i += 1
                iobs.append((word, pos_tag, 'O'))  # it's an Outsider

        return iobs

    def parse(self, text, conlltags=True):
        """
        Given a text, applies tokenization, part of speech tagging and the
        gazetteer words with their tags. Returns an conll tree.

        :param text: The text to parse
        :type text: str
        :param conlltags:
        :type conlltags:
        :return: An conll tree
        :rtype:
        """
        # apply the regular expressions and find all the
        # gazetteer words in text
        for pattern, tag in self.patterns:
            words_found = set(re.findall(pattern, text))  # keep the unique words
            if len(words_found) > 0:
                for word in words_found:  # words_found may be more than one
                    self.words.append(word)  # keep the words
                    self.iobtags.append(tag)  # and their tag

        # find the pattern with the maximum words.
        # this will be the look ahead variable
        for word in self.words:  # don't care about tags now
            nwords = word.count(' ')
            if nwords > self.lookahead:
                self.lookahead = nwords

        # tokenize and apply part of speech tagging
        tagged_sent = self.pos_tag(self.tokenize(text))
        # find the iob tags
        iobs = self.iob_tags(tagged_sent)

        if conlltags:
            return conlltags2tree(iobs)
        else:
            return iobs

if __name__ == "__main__":
    patterns = [(u"Αθήνα[ς]?", "LOC"), (u"Νομική[ς]? [Σσ]χολή[ς]?", "ORG")]
    g = Gazetteer(patterns, pos_tag, wordpunct_tokenize)
    text = u"Η Νομική σχολή της Αθήνας"
    t = g.parse(text)
    print(unicode(t))

    dir_with_lists = "Lists"
    patterns = []
    tags = []
    for root, dirs, files in os.walk(dir_with_lists):
        for f in files:
            lines = codecs.open(os.path.join(root, f), 'r', 'utf-8').readlines()
            tag = os.path.splitext(f)[0]
            for l in lines[1:]:
                patterns.append((l.rstrip(), tag))
                tags.append(tag)

    text = codecs.open("sample.txt", 'r', "utf-8").read()
    #g = Gazetteer(patterns)
    t = g.parse(text.lower())
    print unicode(t)

    for tag in set(tags):
        for gaz_word in sub_leaves(t, tag):
            print gaz_word[0][0], tag

In the if __name__ == "__main__": you can see an example where I make patterns in the code patterns = [(u"Αθήνα[ς]?", "LOC"), (u"Νομική[ς]? [Σσ]χολή[ς]?", "ORG")].
Later in the code I read files from a directory named Lists (put it in the folder where you have the above code). The name of every file becomes the Gazetteer's tag. So, make files like LOC.txt with patterns for locations (LOC tag), PERSON.txt for Persons, etc.

A: You don't need to use NLTK for this. Instead, do the following:

*

*Divide the text in to a list with all the words.

*Divide the cities into a dictionary where {"Sant Cugat del Valles":["Sant","Cugat","del","Valles"]}. It should be easily to find a list with all the cities in the area somewhere online or from sol local government.

*Iterate over the elements in the text in list form.
3.1. Iterate over the cities if the element first element corresponds with the element in the text then check next element.
Here is a code example that is runnable:
text = 'Tots els gats son de Sant Cugat del Valles.'
#Prepare your text. Remove "." (and other unnecessary marks).
#Then split it into a list of words.
text = text.replace('.','').split(' ')

#Insert the cities you want to search for.
cities =  {"Sant Cugat del Valles":["Sant","Cugat","del","Valles"]}

found_match = False
for word in text:
    if found_match:
        cityTest = cityTest
    else:
        cityTest = ''
    found_match = False
    for city in cities.keys():
        if word in cities[city]:
            cityTest += word + ' '
            found_match = True
        if cityTest.split(' ')[0:-1] == city.split(' '):
            print city    #Print if it found a city.

A: You can use the geotext python library for the same.
pip install geotext

is all it takes to install this library. The usage is as simple as:
from geotext import GeoText
places = GeoText("London is a great city")
places.cities

gives the result 'London'
The list of cities covered in this library is not extensive but it has a good list.


text:
Q: Bitbucket: How to create a list of issues from multiple repositories? We have several repositories on BitBucket. For every repository we
have the issue tracker enabled. For our progress reports I would like
to be able to see all issues from all related repositories in one
overview.
Is this possible and how can it be done?
Thanks,
Paul

A: Bitbucket has an API. You could quickly put together a script (or webpage using JSONP) calling:
https://api.bitbucket.org/1.0/repositories/USERNAME/REPOSITORY/issues/
for each repository? (Replacing USERNAME and REPOSITORY with appropriate values)
For something more advanced you could query the USER, get all their repositories, then iterate.

A: I needed the same thing today so I made the following python script available here on github.
The two API call URLs you need are
https://bitbucket.org/api/1.0/user/repositories/
https://bitbucket.org/api/1.0/repositories/{owner}/{slug}/issues/

You'll have to authenticate with your BitBucket credentials which I did using the python requests library:
response = requests.get(url, auth=HTTPBasicAuth(_USERNAME, _PASSWORD))


text:
Q: How to launch a JAR with runtime command from another JAR? This is the code i'm using:
public class CLASSNAME extends JFrame
{

public static String MYAPP = new String(Util.getWorkingDirectory() + File.separator + "MYAPP.jar");
public static File MYJAR = new File(MYAPP); //used in other sections of the code

then when i call the runtime command it won't start, it works on Linux but not on Windows (possibly working on MAC as well):
public static final void launching() throws Exception {
      try {

        Runtime.getRuntime().exec (MYAPP);
        System.exit(0);
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
  }

EDIT: that's how i made the code work (hope will be helpful for someone else):
public class CLASSNAME extends JFrame
{

public static String MYAPP = new String(Util.getWorkingDirectory() + File.separator + "MYAPP.jar");

//THE JFRAME CODE AND THEN:

public static final void launching() throws Exception {
try {
String osName = System.getProperty("os.name");

        if(osName.startsWith("Win")) {
            Runtime.getRuntime().exec (new String[]{"javaw","-jar",MYAPP});
            System.exit(0);
        }
        if(osName.startsWith("Linux")) {
            Runtime.getRuntime().exec (new String[]{"java","-jar",MYAPP});
            System.exit(0);
        }
        if(osName.startsWith("Mac")) {
            Runtime.getRuntime().exec (new String[]{"java","-jar",MYAPP});
            System.exit(0);;
        }

        }catch (IOException e1) {
            e1.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
  }

in this way on linux also runs MYAPP even if has not been marked with a runnable bit

A: Runtime.getRuntime().exec(command)

if you can run the command in terminal or cmd,it will be right.


text:
Q: Cover a disk with thin rectangles Let $D$ be a disc of diameter 20, and suppose you are given 19 rectangles, each of which is $1 \times 20$. Can  $D$ be covered completely by the rectangles? Note that the rectangles can be arranged "any which-way" for the covering.
Note: this was a popular poser in my grad student days; some of us came up with an answer, but had a hard time nailing down the proof. I'd like to hear from anyone with a good approach, or even a good reference, to this question.
Added note: the rectangles are not to be cut up. And the question may be posed differently in terms of 19 width 1 "strips", each infinitely long (i.e. copies of $[0,1] \times R$). In this form the question becomes: Can we cover the diameter-20 disk using 19 of these width 1 strips? [If one could cover via strips, then each strip could be trimmed to a 1X20 rectangle without uncovering any covered points in the disk.]

A: I remember that problem from university! (But I didn't solve it, somebody gave me a big clue)
The answer is that it is impossible, you can't cover the circle of diameter 20 using only 19 strips $1\times 20$.
To see why, suppose you have such cover and imagine a sphere of diameter 20 cut in half by our circle. Find the orthogonal projection of each strip on the sphere, it is a ring, and it is easy to compute it's area $2\pi R x$, where $R$ is the radius of the sphere and $x$ the width of the strip.
But between all the rings, they  cover the whole sphere so the total area must be at least $4\pi R^2$, so
$$ N \times 2 \pi R x \ge 4 \pi R^2 $$
where $N$ is the number of strips. Letting $N=19, R=10$ and $x=1$ we obtain a contradiction.


text:
Q: java.lang.NoClassDefFoundError errors when trying to run client:build I am building an app with Gluon-mobile in InteliJ on Windows and having problems when I add additional dependencies via Maven. On Windows, when I add a new dependency to my pom file and try to run client:build from a command line I start getting getting java.lang.NoClassDefFoundError errors.
In this case I am trying to use the obs-websocket-java module and added the dependency in my pom file. I have tried other ones too and see to have the same problem.
Error Examples
[Tue Mar 09 16:39:58 GMT-08:00 2021][INFO] We will now compile your code for x86_64-microsoft-windows. This may take some time.
[Tue Mar 09 16:39:58 GMT-08:00 2021][INFO] [SUB] Warning: Ignoring server-mode native-image argument --no-server.
[Tue Mar 09 16:40:00 GMT-08:00 2021][INFO] [SUB] [org.jdf.teamdatacollect:20756]    classlist:   1,404.15 ms,  0.96 GB
[Tue Mar 09 16:40:06 GMT-08:00 2021][INFO] [SUB] [org.jdf.teamdatacollect:20756]        (cap):   4,533.88 ms,  0.95 GB
[Tue Mar 09 16:40:06 GMT-08:00 2021][INFO] [SUB] [org.jdf.teamdatacollect:20756]        setup:   5,221.72 ms,  0.95 GB
[Tue Mar 09 16:40:06 GMT-08:00 2021][INFO] [SUB] Error: Error parsing reflection configuration in file:/C:/Users/joshu/IdeaProjects/TeamDataCollect/target/classes/META-INF%5cnative-image%5creflect-config.json:
[Tue Mar 09 16:40:06 GMT-08:00 2021][INFO] [SUB] Could not register net.twasi.obsremotejava.OBSCommunicator: allDeclaredMethods for reflection. Reason: java.lang.NoClassDefFoundError: org/eclipse/jetty/websocket/api/Session. To allow unresolvable reflection configuration, use option -H:+AllowIncompleteClasspath
[Tue Mar 09 16:40:06 GMT-08:00 2021][INFO] [SUB] Verify that the configuration matches the schema described in the -H:PrintFlags=+ output for option ReflectionConfigurationResources.
[Tue Mar 09 16:40:06 GMT-08:00 2021][INFO] [SUB] com.oracle.svm.core.util.UserError$UserException: Error parsing reflection configuration in file:/C:/Users/joshu/IdeaProjects/TeamDataCollect/target/classes/META-INF%5cnative-image%5creflect-config.json:
[Tue Mar 09 16:40:06 GMT-08:00 2021][INFO] [SUB] Could not register net.twasi.obsremotejava.OBSCommunicator: allDeclaredMethods for reflection. Reason: java.lang.NoClassDefFoundError: org/eclipse/jetty/websocket/api/Session. To allow unresolvable reflection configuration, use option -H:+AllowIncompleteClasspath
[Tue Mar 09 16:40:06 GMT-08:00 2021][INFO] [SUB] Verify that the configuration matches the schema described in the -H:PrintFlags=+ output for option ReflectionConfigurationResources.
[

pom file
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.jdf</groupId>
    <artifactId>teamdatacollect</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>TeamDataCollect</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.release>11</maven.compiler.release>
        <javafx.version>15.0.1</javafx.version>
        <attach.version>4.0.10</attach.version>
        <client.plugin.version>0.1.38</client.plugin.version>
        <javafx.plugin.version>0.0.5</javafx.plugin.version>
        <mainClassName>org.jdf.TeamDataCollect</mainClassName>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.hierynomus</groupId>
            <artifactId>sshj</artifactId>
            <version>0.31.0</version>
        </dependency>
        <dependency>
            <groupId>net.twasi</groupId>
            <artifactId>obs-websocket-java</artifactId>
            <version>1.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>${javafx.version}</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>${javafx.version}</version>
        </dependency>
        <dependency>
            <groupId>com.gluonhq</groupId>
            <artifactId>charm-glisten</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>com.gluonhq.attach</groupId>
            <artifactId>display</artifactId>
            <version>${attach.version}</version>
        </dependency>
        <dependency>
            <groupId>com.gluonhq.attach</groupId>
            <artifactId>lifecycle</artifactId>
            <version>${attach.version}</version>
        </dependency>
        <dependency>
            <groupId>com.gluonhq.attach</groupId>
            <artifactId>statusbar</artifactId>
            <version>${attach.version}</version>
        </dependency>
        <dependency>
            <groupId>com.gluonhq.attach</groupId>
            <artifactId>storage</artifactId>
            <version>${attach.version}</version>
        </dependency>
        <dependency>
            <groupId>com.gluonhq.attach</groupId>
            <artifactId>util</artifactId>
            <version>${attach.version}</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>Gluon</id>
            <url>https://nexus.gluonhq.com/nexus/content/repositories/releases</url>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
            </plugin>

            <plugin>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>${javafx.plugin.version}</version>
                <configuration>
                    <mainClass>${mainClassName}</mainClass>
                </configuration>
            </plugin>

            <plugin>
                <groupId>com.gluonhq</groupId>
                <artifactId>client-maven-plugin</artifactId>
                <version>${client.plugin.version}</version>
                <configuration>
                    <target>${client.target}</target>
                    <attachList>
                        <list>display</list>
                        <list>lifecycle</list>
                        <list>statusbar</list>
                        <list>storage</list>
                    </attachList>
                    <reflectionList>
                        <list>org.jdf.views.CollectDataPresenter</list>
                        <list>org.jdf.views.SetupPresenter</list>
                        <list>org.jdf.views.StreamingPresenter</list>
                    </reflectionList>
                    <mainClass>${mainClassName}</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>desktop</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <client.target>host</client.target>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>com.gluonhq.attach</groupId>
                    <artifactId>display</artifactId>
                    <version>${attach.version}</version>
                    <classifier>desktop</classifier>
                </dependency>
                <dependency>
                    <groupId>com.gluonhq.attach</groupId>
                    <artifactId>lifecycle</artifactId>
                    <version>${attach.version}</version>
                    <classifier>desktop</classifier>
                </dependency>
                <dependency>
                    <groupId>com.gluonhq.attach</groupId>
                    <artifactId>storage</artifactId>
                    <version>${attach.version}</version>
                    <classifier>desktop</classifier>
                </dependency>
            </dependencies>
        </profile>
        <profile>
            <id>ios</id>
            <properties>
                <client.target>ios</client.target>
            </properties>
        </profile>
        <profile>
            <id>android</id>
            <properties>
                <client.target>android</client.target>
            </properties>
        </profile>
    </profiles>
</project>

I have tried running the client:runagent but that doesn't seem to help. What I found in looking through the error logs is that the classpath in the classpathJar.jar manifest file which is in target\client\x86_64-windows\gvm\tmp does not contain all the jars that the obs-websocket-java modules depends on. If I run the native-image command by hand substituting a custom classpathJar.jar I am able to make further progress but still haven.t found a magic recipe to make it build
I have also found that the jni-config.json and reflect-config.json that is generated by the client:runagent seem to be missing many of the entries that I get when I run the Graalvm agent to generate these by hand. I don't know if this is related.
Is there a step that I am missing? Any and all help appreciated.
Joshua


text:
Q: Python/Selenium - how to loop through hrefs in
*? Web URL: https://www.ipsos.com/en-us/knowledge/society/covid19-research-in-uncertain-times
I want to parse the HTML as below:

I want to get all hrefs within the < li > elements and the highlighted text. I tried the code
elementList = driver.find_element_by_class_name('block-wysiwyg').find_elements_by_tag_name("li")
for i in range(len(elementList)):
    driver.find_element_by_class_name('blcokwysiwyg').find_elements_by_tag_name("li").get_attribute("href")

But the block returned none.
Can anyone please help me with the above code?

A: I suppose it will fetch you the required content.
import requests
from bs4 import BeautifulSoup

link = 'https://www.ipsos.com/en-us/knowledge/society/covid19-research-in-uncertain-times'

r = requests.get(link)
soup = BeautifulSoup(r.text,"html.parser")
for item in soup.select(".block-wysiwyg li"):
    item_text = item.get_text(strip=True)
    item_link = item.select_one("a[href]").get("href")
    print(item_text,item_link)

A: Try is this way:
coronas = driver.find_element_by_xpath("//div[@class='block-wysiwyg']/ul/li")
hr = coronas.find_element_by_xpath('./a')
print(coronas.text)
print(hr.get_attribute('href'))

Output:
The coronavirus is touching the lives of all Americans, but race, age, and income play a big role in the exact ways the virus — and the stalled economy — are affecting people. Here's what that means.
https://www.ipsos.com/en-us/america-under-coronavirus


text:
Q: Undirected Breadth First Search for calculating distance Trying  to make a Breadth First Search, to create list of distance from one node to another. However i get confused with the for loop and the table.
I keep getting error 'list index out of range'
Expected output = [0,1,2,2,3]
#graph of nodes and vertex
G = {0: [1], 1: [2, 3], 2: [1, 3], 3: [4]}
print(G)
distance = []
for u in range(len(G)):
    distance.append(float('inf')) #filling the table with infinity, just in case theres a disconnected nodes

#In the case looking for distance from point 0
distance[0] = 0
distance.append(0)
print(distance)
while distance!=[]:
    u = distance.pop()
    for v in G[u]: #v as the neighbor for every nodes
        print(v)
        if distance[v] == float('inf'):
            distance[v] = distance[u]+1
            print(distance)
            distance.append(v)


text:
Q: Filter out dataframe based on values being within the 90th percentile Suppose I have this dataframe
d = {'fruit': ['apple', 'apple', 'apple', 'orange'], 'names': ['bob', 'bob', 'bob', 'joe']}

df = pd.DataFrame(data=d)

Now I want to go through each column and filter out the low percentiles keeping only values that are contained in the 90th percentile.
Thus since apple and bob are each within their associated 90th percentiles I would have this dataframe
d = {'fruit': ['apple', 'apple', 'apple'], 'names': ['bob', 'bob', 'bob']}

df = pd.DataFrame(data=d)

How do I achieve this?

A: Hope this helps:

*

*Calculate 90th percentile and keep them in a dictionary:

perc_dic = df.apply(lambda x : np.percentile(x.value_counts().tolist(), 90) , axis= 0).to_dict()

perc_dic
{'fruit': 2.8, 'names': 2.8}

2.Calculate value counts of each value:
value_dic = df.apply(lambda x : x.value_counts() , axis= 0).to_dict()

value_dic
{'fruit': {'apple': 3.0, 'bob': nan, 'joe': nan, 'orange': 1.0},
 'names': {'apple': nan, 'bob': 3.0, 'joe': 1.0, 'orange': nan}}

*Compare value counts and percentile:

df_result =  df.apply(lambda row : row  if value_dic['fruit'][row['fruit']] >= perc_dic['fruit']  and
                                           value_dic['names'][row['names']] >= perc_dic['names']
                                          else np.nan , axis= 1)

df_result.dropna()
    fruit   names
0   apple   bob
1   apple   bob
2   apple   bob

Note:  There are some nan values in value_dic but it won't hurt the performance.


text:
Q: QT Network QObject::connect no matching member function I am new to QT and maybe i just dont see something. but QObject::connect method gives me this error -> no matching member function for call to 'connect'.
I googled and searched but nothing helps. Actually even examples from official documentation give me the same error. All libraries are imported.
QTCreator version is 4.14
Based on Qt5.15
Here is a sample of my code
#include "imagepagehandler.h"
#include <QNetworkAccessManager>
#include <QIODevice>

ImagePageHandler::ImagePageHandler(QObject *parent) : QObject(parent)
{
    networkAccessManager = new QNetworkAccessManager(this);
    networkReply = nullptr;
    dataBuffer = new QByteArray();

    QNetworkRequest request;
    request.setUrl(QUrl("https://www.qt.io"));

    networkReply = networkAccessManager->get(request);

   connect(networkReply, &QIODevice::readyRead, this, &ImagePageHandler::DataReadyToRead);

}

void ImagePageHandler::DataReadyToRead()
{

}

void ImagePageHandler::DataReadFinished()
{

}

And header
#define IMAGEPAGEHANDLER_H

#include <QObject>
#include <QNetworkAccessManager>

class ImagePageHandler : public QObject
{
    Q_OBJECT
public:
    explicit ImagePageHandler(QObject *parent = nullptr);

public slots:
    void DataReadyToRead();
    void DataReadFinished();

private:
    QNetworkAccessManager* networkAccessManager;
    QNetworkReply* networkReply;
    QByteArray* dataBuffer;

signals:

};

#endif // IMAGEPAGEHANDLER_H

Issues screenshot


text:
Q: Override right click in SwiftUI I try to add additional functionality when doing a right click. Unfortunately, this will break the .context modifier and I don't understand why. This is the code I am using:
extension View {
    func onRightClick(handler: @escaping () -> Void) -> some View {
        modifier(RightClickHandler(handler: handler))
    }
}

struct RightClickHandler: ViewModifier {
    let handler: () -> Void
    func body(content: Content) -> some View {
        content.overlay(RightClickListeningViewRepresentable(handler: handler), alignment: .center)
    }
}

struct RightClickListeningViewRepresentable: NSViewRepresentable {
    let handler: () -> Void
    func makeNSView(context: Context) -> RightClickListeningView {
        RightClickListeningView(handler: handler)
    }
    func updateNSView(_ nsView: RightClickListeningView, context: Context) {}
}

class RightClickListeningView: NSView {
    let handler: () -> Void

    init(handler: @escaping () -> Void) {
        self.handler = handler
        super.init(frame: .zero)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func rightMouseDown(with event: NSEvent) {
        handler()
        super.rightMouseDown(with: event)
        if let menu = super.menu(for: event) {
            print(menu)
            let location = event.locationInWindow
            menu.popUp(positioning: nil, at: location, in: self)
        }
    }

}

Later then, I have this:
struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .contextMenu(menuItems: {
                Button("Test") { }
            })
            .onRightClick {
                print("right click detcted")
            }
            .padding()
    }
}

If I remove the onRightClick-modifier, the context menu works again.

A: I know it's 6 months since you've asked this but if you swap around the modifiers it will work as intended (assuming you are trying to detect when context menu is opened). When you right click, the context menu will open and the right click will be detected. Hope this helps!
struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .onRightClick {
                print("right click detcted")
            }
            .contextMenu(menuItems: {
                Button("Test") { }
            })
            .padding()
    }
}


text:
Q: How to connect full calendar v 1.5.3 with MS SQL Server using asp.net C#/VB I have successfully connected FullCalendar v1.4.2 with sql server using asp.net webforms and vb.net. I want to update to v1.5.3, but the original integration code no longer works and I can't see how to fix it.
Secondly, I would like help adding drag and drop features so that I update the database on drag/drop from asp.net, but I'm not sure where to start for that.
The code I had that worked for v 1.4.2 is as follows:
<script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $('#calendar').fullCalendar({
                header: {
                    left: 'prev, next today',
                    center: 'title',
                    right: 'month, basicWeek, basicDay'
                },
                events: "Calendar.asmx/EventList"
            });

        });
</script>

Imports System
Imports System.Data
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Collections.Generic
Imports System.Web.UI.Page

<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class Calendar
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function EventList(ByVal startDate As String, ByVal endDate As String) As String
        ' List to hold events
        Dim events As List(Of CalendarDTO) = New List(Of CalendarDTO)()

        Dim WebConfigConnection As String = ConfigurationManager.ConnectionStrings("FresheyeTimeTrackerConnectionString").ConnectionString
        Dim query As String = "SELECT * FROM CORE_PROJECT"
        Dim conn As New SqlConnection(WebConfigConnection)
        Dim cmd As New SqlCommand(query, conn)
        Dim da As New SqlDataAdapter(cmd)
        Dim ds As New DataSet()
        da.Fill(ds)
        'If startDate > ToUnixTimespan(DateTime.Now) Then
        'GoTo x
        'End If
        Dim starting As DateTime = FromUnixTimespan(startDate)
        ' Loop through events to be added
        For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
            If String.IsNullOrEmpty(ds.Tables(0).Rows(i)("ProjectDeliveryDate").ToString()) Then

            Else

                ' Create a new event and start to populate
                Dim value As CalendarDTO = New CalendarDTO()
                ' Date is required to be in a unix format
                value.StartDate = ToUnixTimespan(DateTime.Parse(ds.Tables(0).Rows(i)("ProjectAddedDate").ToString))
                value.id = ds.Tables(0).Rows(i)("ProjectID").ToString()
                value.title = ds.Tables(0).Rows(i)("ProjectTitle").ToString()
                value.EndDate = ToUnixTimespan(DateTime.Parse(ds.Tables(0).Rows(i)("ProjectDeliveryDate").ToString))
                events.Add(value)

            End If

        Next
        ' Serialize the return value so it can be decoded in java.

x:

        Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
        Return js.Serialize(events)
    End Function

    Private Function ToUnixTimespan(ByVal d As DateTime) As Int64
        Dim time As New TimeSpan()
        time = d.ToUniversalTime().Subtract(New DateTime(1970, 1, 1, 0, 0, 0))

        Return CType(Math.Truncate(time.TotalSeconds), Int64)
    End Function

    Private Function FromUnixTimespan(ByVal s As String) As DateTime
        Dim time As DateTime = New DateTime(1970, 1, 1, 0, 0, 0)
        Return time.AddSeconds(s)
    End Function
End Class

A: I'm also struggling with this... It looks like we have borrowed code from similar places...
In your code above you do not seem to be converting startDate and endDate back to start and end. Were you doing this in FullCalendar.js?
Basically I have much the same as yours except before Returning events I do a replace so that the string sent back contains start and end instead of startDate and EndDate.
My code seems to work OK in Chrome but not in IE.
As for updating Db... I'm looking at a couple of answers posted at....
FullCalendar, how do I allow users to edit/delete events and remove them from the database?


text:
Q: there's a problem when I build my own crosstool with crosstool-4.3 When compiling cross-compiler tool crosstool-0.43 (for arm9) on the CentOS 7.5 64-bit system, I encountered the following error:
cc    -c -o flat_bl.o /home/muhuo/arm-linux-project/transplant-test/build-tools/crosstool-0.43/build/arm-9tdmi-linux/gcc-4.1.0-glibc-2.3.2/binutils-2.16.1/gprof/flat_bl.m
/home/muhuo/arm-linux-project/transplant-test/build-tools/crosstool-0.43/build/arm-9tdmi-linux/gcc-4.1.0-glibc-2.3.2/binutils-2.16.1/gprof/flat_bl.m:2:2: error: expected identifier or ??before ??token
%         the percentage of the total running time of the
^
I don't know what the *. m file in binutils-2.16.1 is. Whether I need to install some other tools before?
From the picture above, Compiling *.m file with GCC should be wrong.
I need some help. Thanks.

A: The problem is that there is a builtin '.m.o' suffix rule which triggers with a higher priority than the '.c.o' suffix rule.  There was an attempt to disable this rule under PR2587 but because it is an old-style suffix rule this doesn't work.
There are two possible solutions, one is to remove all builtin rules by adding the line .MAKEFLAGS: -r to binutils/gprof/Makefile.in somewhere, or else more correctly change the .SUFFIXES: line in the same file so that the '.m' comes after '.c', thus changing the rule priority.


text:
Q: How to centering of div who's display property may change? I am trying to center google ads (doubleclick for publishers, adsense).
First I assumed they are going to use display: block; so I did margin: 0 auto;
It seems they are using display: inline-block; so I just used text-align: center;
Is there a solution that will help me sleep well at night, knowing it my ad centering won't change if they change display to something else one day?
Also that will work with other ad providers if they are using display: block; or other display type?
This is my code for now:
.ad {
  text-align: center;
  // & > div {
  //   display: inline-block;
  // }
}

It works without comments, but not sure if I should uncomment or not.
Ad code looks like this now, but can change.

Again, other ad providers might put anything else inside.

A: Wrap it by an own DIV which is set to display:inline-block always and have it centered.

.ad-wrapper{
    display:inline-block;
    text-align:left;
}

.outer-wrapper{
    display:block;
    text-align:center;
}

A: You can use well known trick left + transform attributes to center both of block and inline-block:

.cont {
  width: 100%;
}
[class^="ad"] {
  width: 200px;
  height: 100px;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}

.ad1 {
  display: block;
  background: tomato;
}

.ad2 {
  display: inline-block;
  background: orange;
}

advert1 display: block

advert2 display: inline-block

UPDATE
divs have not defined width and height

.cont {
  width: 100%;
}
[class^="ad"] {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}

.ad1 {
  display: block;
  background: tomato;
}

.ad2 {
  display: inline-block;
  background: orange;
}

advert1 display: block

advert2 display: inline-block


text:
Q: program flow when ShowDialogue another window consider the flowing scenario
chequeInfo = new Check();
                Messenger.Default.Register<Check>(this, (a) => this.doSomething(a));
                AddNewCheck j = new AddNewCheck();
                _dialogService.showDialoge(j);
                Console.WriteLine("this text doesn't show up");
                SpecialCustomerPayments d = new SpecialCustomerPayments();
                d.chequeId = chequeInfo.Id;
                d.paymentAmount = chequeInfo.value;
                d.userId = 1;
                ....

as you can observe from code above I'm showDialog() another window in the middle of a method , I expected the flow to continue after I done with the new window , but it is not , I think I'm missing something obvious here, any help will be much appreciated
thanks in advance

A: ShowDialog() is a blocking call.
It will only return when the new window is closed.
If you want it to return immediately and leave the window open, call .Show().


text:
Q: Google Maps v3 Fit the Contents of Multiple Info Windows I would like to make the contents of this infowindow to fit. I just fork this code from this post.
So far, I've manage to try the following links as the result of my research

*

*The first answer on this link seems to work in the year 2010, but no longer
works in 2014, or maybe I'm just missing something.

It states that

set the maxWidth options property in the constructor. Yes, even if setting the maximum width was not what you wanted to do.

then one of the comment says that maybe this is working in year 2010 but not anymore in 2014

This may have worked in 2010, but does not help as of 2014. –  Simon Aug 15 at 1:25

*This link replaces the "standard" google maps infowindow with our own style, but this doesn't work also to me.

What you want to do is replace the "standard" Googlemaps infoWindow with your own, and put your content into it. Once you replace the standard GM infoWindow, you have a lot of latitude to work with.

*I've also tried this, but the code doesn't fit my codes.

Below is the code that I've tried
 content: $(this.infocontent)[0]

*Lastly is this, which aims on resizing the infowindow but it doesn't work still.
var infowindow = new google.maps.InfoWindow({
content: ...,
maxWidth: 300
})
Something like this is the result that I want to get, when we click the marker, an infowindow that can autofit will show.

A: This is not the fix, but just a work around. Didn't permanently fixed the problem.
It seems that by changing the code of this
var sites = [
            ['American Range', 34.2737729, -118.4284391, 1, "American Range"],
            ['Gorenje', 46.3446568, 15.0064148, 1, "Gorenje"]
        ];

To this
 var sites = [
        ['American Range', 34.2777032, -118.4238387, 1, '
American Range

'],
        ['Gorenje', 46.4906673, 15.3754774, 1, '
Gorenje

']
];

Specifically this
"American Range"

To this
'
American Range

'

Fixes the problem for certain marker, but not all.


text:
Q: Interpolation in Angular innerHtml I have some HTML templates with interpolation and ng classes are stored in the database. When fetched and used in innerHtml, everything is working except Angular's interpolation, ng classes and ng for.
I tried bypassSecurityTrustHtml and tried lots of things found in Google.
Does anybody know any solution?


text:
Q: How to fix "Gas estimation failed error" when transferring Minter and Owner roles to a new account in one function? I have a simple ERC20 contract which is ERC20Detailed, ERC20Mintable and Ownable. On deployment I want:

*

*Add Minter to a new account, passed in the argument

*Remove deployer from Minter role

*Transfer Ownership to a new account, passed in the argument

Same actions I have declared in another function called transferRights()
The problem is that I am getting "Gas estimation failed error", which isn't because I don't have enough gas, but there might be a bug in the code. If I remove first two (addMinter, renounceMinter) actions, then it's all good (No warning).
I have deployed this contract on Ropsten, where I was getting same error in the beginning, but by commenting first two actions and adding them again transaction went through without any warning and Contract works as it supposed to be.
pragma solidity ^0.5.0;

import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";
import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol";
import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/ownership/Ownable.sol";

contract MyToken is ERC20Detailed, ERC20Mintable, Ownable {

    uint256 private msgCount;
    address constant ETHER = address(0);
    mapping(uint256 => string) private message;

    constructor(string memory name, string memory symbol, uint8 decimals, address _newOwner) ERC20Detailed(name, symbol, decimals) public {
        addMinter(_newOwner);
        renounceMinter();
        transferOwnership(_newOwner);
    }

    function doMint(uint256 _amount, address _beneficiary1, address _beneficiary2, address _beneficiary3) public onlyOwner {
        require (_amount >= 0);
        require(_beneficiary1 != ETHER && _beneficiary2 != ETHER && _beneficiary3 != ETHER);
        require(mint(_beneficiary1, _amount.mul(20).div(100)));
        require(mint(_beneficiary2, _amount.mul(30).div(100)));
        require(mint(_beneficiary3, _amount.mul(50).div(100)));
    }

    function setMessage(string memory _message) public onlyOwner {
        message[msgCount] = _message;
        msgCount = msgCount.add(1);
    }

    function readMessage(uint256 _msgId) public view returns(string memory) {
        return message[_msgId];
    }

    function transferRights(address _newOwner) public onlyOwner {
        addMinter(_newOwner);
        renounceMinter();
        transferOwnership(_newOwner);
    }
}

I can still send a transaction and deploy I guess (as mentioned above I did it on testnet), even though it is saying "The transaction execution will likely fail", but I want to make sure that code is bug free. Any feedback would be greatly appreciated. Thanks!
UPDATE
Problem found! In the constructor I was passing the same account address as I was using for deploying. Thus, it resulted adding the Minter role to myself, which I already had.


text:
Q: Função equivalente a $() em um Objeto Javascript A minha ideia é o seguinte, como possuo muitas tarefas repetidas, criei um objeto JavaScript e acesso as funções referentes a ele por meio do ., por exemplo:
Objeto.funcao(params)

Porém preciso, de algo como o jQuery que utiliza tanto $() como $.().
Como posso atribuir no objeto a seguir, uma função equivalente a $()? Tentei da seguinte maneira>
const $ = {
   $: function(text) { alert(text) }
   f1: function(text) { alert(text) }
   f2: function(text) { alert(text) }
}

$('texto padrao') // erro gerado pelo browser dizendo que precisa acessar como objeto

$.f1('texto f1') // retorna alert dizendo 'texto f1'


text:
Q: How can I maintain my props/states in ReactJS? I'm currently building a React application with the following workflow:

*

*List of application categories, the user will select one

*Once a user has selected an application category, they will select a water type from a list

*A list of products will then be displayed depending on the category and type selected.

*They can then select a product to see the information i.e. product charts, images etc.

The problem:

*

*Once a user selects a product, if they click the back button, the category and type props are lost.

Solution required:

*

*I need to be able to maintain these props/state at all times, allowing them to be updated if the user goes back and changes category/type

I've included my code for reference below.
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter as Router } from "react-router-dom";

ReactDOM.render(
  <React.StrictMode>
    <Router>
      <App />
    </Router>
  </React.StrictMode>,
  document.getElementById("root")
);

App.js
import React from "react";
import { Route, Switch } from "react-router-dom";
import Home from "./components/Home";
import WaterType from "./components/WaterType";
import Products from "./components/Products";
import Product from "./components/Product";

import "./App.css";

function App() {
  return (

      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/waterType" component={WaterType} />
        <Route path="/products/:productName" component={Product} />
        <Route path="/products" component={Products} />
      </Switch>

  );
}

export default App;

Home.js
import React, { Component } from "react";
import { Link } from "react-router-dom";
import CategoryData from "./data/CategoryData";

class Home extends Component {
  render() {
    return (
      <>

Categories

          {CategoryData.map((cat, i) => (

              <Link
                to={{
                  pathname: "/waterType",
                  name: cat.name,
                }}
              >

                {cat.name}
              </Link>

          ))}

      </>
    );
  }
}

export default Home;

WaterType.js
import React from "react";
import { Link } from "react-router-dom";
import WaterTypeData from "./data/WaterTypeData";

const WaterType = ({ location }) => {
  const categorySelected = location.name;
  return (
    <>

Water Types

Current category: {categorySelected}

        {WaterTypeData.map((type, i) => (

            <Link
              to={{
                pathname: "/products",
                categorySelected: categorySelected,
                waterType: type.name,
              }}
            >
              {type.name} - {type.description}
            </Link>

        ))}

    </>
  );
};

export default WaterType;

Products.js
import React from "react";
import { Link } from "react-router-dom";
import ProductData from "./data/ProductData";

const Products = ({ location }) => {
  const categorySelected = location.categorySelected;
  const waterType = location.waterType;

  const ProductsResult = ProductData.filter(x => x.categories.includes(categorySelected) && x.waterTypes.includes(waterType));

  return (
    <>

Products

Current category: {categorySelected && categorySelected}

Water Type: {waterType && waterType}

            {ProductsResult.map((item, i) => (

                <Link
                  to={{
                    pathname: '/products/' + item.slug,
                    name: item.name,
                  }}
                >
                  {item.name}
                </Link>

            ))}

    </>
  );
};

export default Products;

Product.js
import React from "react";

const Product = ({ location }) => {
  const productName = location.name;

  return (
    <>

{productName}

    </>
  );
};

export default Product;

A: The easiest solution that I can think of is to keep your selected choices (category and water type) in a top level context.
Something like this:
// ChoicesProvider.js
import React, { createContext, useState } from "react";

export const ChoicesContext = createContext(null);

export const ChoicesProvider = ({ children }) => {
  const [choices, setChoices] = useState({
    category: null,
    waterType: null,
  });

  return (
    <ChoicesContext.Provider value={{ choices, setChoices }}>
      {children}
    </ChoicesContext.Provider>
  );
};

…and then in your entry point:
// index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter as Router } from "react-router-dom";
import { ChoicesProvider } from "./context/ChoicesProvider";

ReactDOM.render(
  <React.StrictMode>
    <ChoicesProvider>
      <Router>
        <App />
      </Router>
    </ChoicesProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

…and then each time you pick a category / waterType save the selected state in a context using setChoices defined in context. For example:
// Home.js
import React, { Component } from "react";
import { Link } from "react-router-dom";
import CategoryData from "./data/CategoryData";
import { ChoicesContext } from "../../context/ChoicesContext";

const Home = () => {
  const { choices, setChoices } = useContext(ChoicesContext);

  return (
    <>

Categories

        {CategoryData.map((cat, i) => (

            <Link
              onClick={() => setChoices({ ...choices, category: cat.name })}
              to={{
                pathname: "/waterType",
                name: cat.name,
              }}
            >

              {cat.name}
            </Link>

        ))}

    </>
  );
};

export default Home;

Hopefully that gives you an idea.
Have a great day

A: First of all, I am not sure if your Router setup is necessary. React is great for single page applications (SPA), this means, you don't neet new page for every single functionality. You can very comfortably build your application on single Route, changing just the components you currently need.
So the first possible solution is to build the application on single page, using three simple states
[category, setCategory] = useState(null)
[waterType, setWatertype] = useState(null)
[product, setProduct] = useState(null)

Based on this you can simply show or hide the select options

  {!category && (<Categories />)}
    {(category && !watertype) && (<WaterTypes />)}
    {category && watertype) && (<Products />)}

category && <WaterTypes /> means, WaterTypes will be displayed only if category is true.
This if course requires your Link to be replaced with something like
<button type="button" onClick={() => setCategory(cat.name)}>{cat.name}</button>

With this approach you can then handle back and forward button to manipulate your states and URL, so the user has access to desired category with hyperlink like www.youreshop.com?category=first&watertype=second
Another approach is to add context to your app, what would allow you to share states between individual components.

A: I highly recommend Redux (https://redux.js.org/) for application state managemt.
In general it's a good idea to include Redux to modern React applications, and in your case it seems to be exactly what you're looking for.
Hope this helps.
Cheers


text:
Q: Using PageControl? I have an array and lets say I have 5 objects in it. The array just contains a string with an address to a picture. I would like to use the Page Control feature in the iPhone SDK to swipe Left and Right to change the picture. I already have the multitouch gestures in place all I need is to implement the Page Control so if I swipe left and then right it will take me back to the previous image.
Does anyone know of any good Page Control tutorials or sample code online that may be able to help me thought implementing the Page Control.

A: The UIPageControl isn't a control as much as it's just an indication of what "page" your on.
To do what you want, you need to set up a UIScrollView and add subviews for each image. It will require some math to figure out where each "page" starts and ends based on image dimensions and screen sizes.
Apple has some docs on using scroll views with page controls here.

A: Indeed, you need a UIScrollView along with the UIPageControl. You can find a good tutorial on how to make them work together here


text:
Q: catch PDFBox warnings when loading erroneous PDFs when loading a PDF with PDFBox one gets log-level warnings if the PDF is erroneous:
    PDDocument doc = PDDocument.load (new File (filename));

For example, this could lead to the following output on the console:
Dez 08, 2020 9:14:41 AM org.apache.pdfbox.pdfparser.COSParser validateStreamLength
WARNING: The end of the stream doesn't point to the correct offset, using workaround to read the stream, stream start position: 3141, length: 1674, expected end position: 4815

Obviously, the pdf has some errors in the content stream, but it does load into doc. But would it be possible to catch this warnings programmatically with PDFBox? Do some properties exist which tell you about the warnings after the document has been loaded?
I've tried PDFBox-Preflight, but that checks for PDF/A compliance, which leads to much more messages.

A: Try the non-lenient mode of the parser. This code is from the ShowSignature.java example:
RandomAccessBufferedFileInputStream raFile = new RandomAccessBufferedFileInputStream(file);
// If your files are not too large, you can also download the PDF into a byte array
// with IOUtils.toByteArray() and pass a RandomAccessBuffer() object to the
// PDFParser constructor.
PDFParser parser = new PDFParser(raFile);
parser.setLenient(false);
parser.parse();
PDDocument document = parser.getPDDocument();