text:
Q: pivot longer with multiple columns and values I have a data frame of the format
# A tibble: 6 x 8
  type  id    age2000 age2001 age2002 bool2000 bool2001 bool2002
  <chr> <chr> <chr>   <chr>   <chr>   <chr>    <chr>    <chr>
1 1     1     20      21      22      1        1        1
2 1     2     35      36      37      2        2        2
3 1     3     24      25      26      1        1        1
4 2     1     32      33      34      2        2        2
5 2     2     66      67      68      2        2        2
6 2     3     14      15      16      1        1        1

and would like to use pivot_longer from the tidyr universe to generate longitudinal data of the form:
# A tibble: 18 x 5
   type  id    age   bool  year
   <chr> <chr> <chr> <chr> <chr>
 1 1     1     20    1     2000
 2 1     1     21    1     2001
 3 1     1     22    1     2002
 4 1     2     35    2     2000
 5 1     2     36    2     2001
 6 1     2     37    2     2002
 7 1     3     24    1     2000
 8 1     3     25    1     2001
 9 1     3     26    1     2002
10 2     1     32    2     2000
11 2     1     33    2     2001
12 2     1     34    2     2002
13 2     2     66    2     2000
14 2     2     67    2     2001
15 2     2     68    2     2002
16 2     3     14    1     2000
17 2     3     15    1     2001
18 2     3     16    1     2002

Does anybody here know a solution to this problem i am facing?
Thank you very much for any advice!

A: You can use names_pattern here.
tidyr::pivot_longer(df,
                    cols = -c(id, type),
                    names_to = c('.value', 'year'),
                    names_pattern = '([a-z]+)(\\d+)')

# A tibble: 18 x 5
#    type    id year    age  bool
# * <int> <int> <chr> <int> <int>
# 1     1     1 2000     20     1
# 2     1     1 2001     21     1
# 3     1     1 2002     22     1
# 4     1     2 2000     35     2
# 5     1     2 2001     36     2
# 6     1     2 2002     37     2
# 7     1     3 2000     24     1
# 8     1     3 2001     25     1
# 9     1     3 2002     26     1
#10     2     1 2000     32     2
#11     2     1 2001     33     2
#12     2     1 2002     34     2
#13     2     2 2000     66     2
#14     2     2 2001     67     2
#15     2     2 2002     68     2
#16     2     3 2000     14     1
#17     2     3 2001     15     1
#18     2     3 2002     16     1

data
df <- structure(list(type = c(1L, 1L, 1L, 2L, 2L, 2L), id = c(1L, 2L,
3L, 1L, 2L, 3L), age2000 = c(20L, 35L, 24L, 32L, 66L, 14L), age2001 = c(21L,
36L, 25L, 33L, 67L, 15L), age2002 = c(22L, 37L, 26L, 34L, 68L,
16L), bool2000 = c(1L, 2L, 1L, 2L, 2L, 1L), bool2001 = c(1L,
2L, 1L, 2L, 2L, 1L), bool2002 = c(1L, 2L, 1L, 2L, 2L, 1L)),
class = "data.frame", row.names = c(NA, -6L))

A: We can pass a regex lookaround in names_sep
library(dplyr)
library(tidyr)
df %>%
    pivot_longer(cols = -c(id, type), names_to = c('.value', 'year'),
          names_sep= "(?<=[a-z])(?=[0-9])")
# A tibble: 18 x 5
#    type    id year    age  bool
#   <int> <int> <chr> <int> <int>
# 1     1     1 2000     20     1
# 2     1     1 2001     21     1
# 3     1     1 2002     22     1
# 4     1     2 2000     35     2
# 5     1     2 2001     36     2
# 6     1     2 2002     37     2
# 7     1     3 2000     24     1
# 8     1     3 2001     25     1
# 9     1     3 2002     26     1
#10     2     1 2000     32     2
#11     2     1 2001     33     2
#12     2     1 2002     34     2
#13     2     2 2000     66     2
#14     2     2 2001     67     2
#15     2     2 2002     68     2
#16     2     3 2000     14     1
#17     2     3 2001     15     1
#18     2     3 2002     16     1

data
df <- structure(list(type = c(1L, 1L, 1L, 2L, 2L, 2L), id = c(1L, 2L,
3L, 1L, 2L, 3L), age2000 = c(20L, 35L, 24L, 32L, 66L, 14L), age2001 = c(21L,
36L, 25L, 33L, 67L, 15L), age2002 = c(22L, 37L, 26L, 34L, 68L,
16L), bool2000 = c(1L, 2L, 1L, 2L, 2L, 1L), bool2001 = c(1L,
2L, 1L, 2L, 2L, 1L), bool2002 = c(1L, 2L, 1L, 2L, 2L, 1L)),
class = "data.frame", row.names = c(NA, -6L))


text:
Q: Goland: Install package "assert" without leaving Goland? I want to install the well-known "assert" package from https://pkg.go.dev/github.com/stretchr/testify/assert
I can remember "assert", but not the full URL.
I could leave the IDE and use my favorite search engine,
but maybe there is way to install and import the "assert" package
without leaving Goland?
Expected result:
 import (
+   "github.com/stretchr/testify/assert"
    "testing"
 )

And go.mod and go.sum get updated.
With other words: I want to get to this string ("github.com/stretchr/testify/assert") without leaving Goland.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cron job of my custom command in Laravel 4.2 I know there is Laravel 5.* now but for many reasons I'm using Laravel 4.2
I have a custom command, and in the fire() method, I import a file and seed the information in my database, so my class is some like this
class SeedDataFile extends Command {
    protected $name = 'import:file';

    public function fire(){
    $command = 'mongoimport --db things --collection users --type csv --file file.csv --headerline';
    $result = exec($command, $output, $return);
    }
}

I want the file that is seeding data, i.e. every 12 hours (considering the file every 12 hours is changing with new data), but as an user I don't want to type the command in my terminal:
php artisan import:file

..every 12 hours (I just want to upload the new file to my project).
So the cron job is where I do all the work, but I don't want to do this:
crontab -e

and edit the file
I want to setup the schedule of my command in one class o somewhere in the code, and automatically the custom command is running everyday until a determined date.
Is this possible? Or I have to configure the crontab file?

A: You could take a look at this package, description says that it does exactly what you want
https://github.com/Indatus/dispatcher

A: As is Laravel 4.2 does not offer this type of functionality. In fact you'll need to set up 1 cron job for this functionality no matter the version you're using.
Newer versions of Laravel do indeed provide this functionality, but they still require you to set up 1 cron job (scheduler on Windows) at highest frequency available for Laravel's command php artisan schedule:run.
If you want to have scheduling of your commands in your code (rather than cron file) you could replicate what newer versions of Laravel do.
1. you would create a "master" command, let's call it TaskSchedulerCommand and let's say it's signature is php artisan schedule.
2. you would create a cronjob at highest frequency on the TaskSchedulerCommand like this: * * * * * php /path/to/artisan schedule`
3. you would write all the scheduling logic of other commands within the TaskSchedulerCommmand


text:
Q: Test xml messages I want to test my "engine" for a game, the engine generates xml messages for each run of the game , bellow there is a simplistic form of it.
My method now is to take the xml each time, "parse" it, check the values i want with java(the game engine which generates the ticket is also in java), first i make an object almost with the same structure as the xml message and after for each message i do the checks, when i want to take statistics from all messages (millions per test) i have some public static variables to keep everything i want.
My question now is , is out there any faster or ready solution for this kind of testing ??
<?xml version='1.0' encoding='UTF-8' ?>
    < myCar="4" track="4" level="8"/>
    <params opponents="18,7,3,21,1,2,9" levels="5,7,4,8,6,5,6" startpo="8"/>
    <games>
    <game>
    <counter i="1" crash="3" turn="4"/>
    <counter i="2" crash="0" turn="12"/>
    .
    .
    <counter i="9" crash="3" turn="10"/>
    <counter i="10" crash="0" turn="3"  miniGame="2" win="0" r="5.5" p="99" />
    .
    .
    <counter i="50" crash="18" turn="2"/>
    </game>
    <aftergame>
    <counter="b1" ball="4" wins="0" />
    <counter="b2" ball="5" wins="0" />
    <counter="b3" ball="3" wins="0" />
    <counter="b4" ball="5" wins="0" />
    <counter="b5" ball="5" wins="1" />
    <counter="b6" ball="2" wins="0" />
    </aftergame>
    </games>

The checks i do is no duplicates at the cars, or that a win is indeed a win, ratio of when an after game is shown , or statistics pere level that the average turn is "this" and stuff like that
Thanks

A: It sounds like you want to Validate the XML to see if a Value=Value or an Element only occurs X-Number-Of-Times. It also sounds like you may want to perform other complex checks.
You might want to consider validating the XML against one or more custom XSD Schemas. It is still work, but It could be easier than coding an Object each time! Maybe someone in your project already even made XSD for this?
If the XML shape and content should always follow certain rules, XML Schema Validation may be what you are looking for. Consider using an XSD Validator.
You can read more about XML Validtion. Search for "Cardinality" and "Simple Types"
LOOK HERE


text:
Q: How to create parameterised jenkins pipeline using jenkinsfile only and trigger it remotely using curl I was trying to create parameterised jenkins pipeline. I checked online we have to select "this project is parameterised" in configuration and add parameters there, but is it possible to add those parameters configuration in jenkinsfile instead?
I know we can use this in jenkinsfile:
parameters {
        string(name: 'name')
        string(name: 'env')
}

but using this, when i'm trying to trigger job remotely using curl, the parameters are null. On the other hand if i add parameters configuration using "this project is parameterised", it works fine.
Is it possible to have those configurations in jenkinsfile only?

A: Let's take the example of String parameter.
Below pipeline snippet will help you to include the Straing parameter in jenkinsfile.
    properties([
    parameters([
    string(name: 'DEPLOY_ENV', defaultValue: 'TESTING', description: 'The target environment')
     ])
    ])

So, your jenkinsfile will be like:
properties([
    parameters([
    string(name: 'DEPLOY_ENV', defaultValue: 'TESTING', description: 'The target environment', )
     ])
    ])

pipeline {
  agent any
  stages {
      stage ("Example") {
        steps {
         script{

       echo "Hello World"
       echo "${params.DEPLOY_ENV}"
       }
      }
    }
  }
}

Edit:
Using the below command, I triggered the jenkins job.
curl -vvv -u "xxx:xxxx" -X POST "http://xx.xxx.xxx.xxx:8080/job/test-param/buildWithParameters?DEPLOY_ENV=SOURAV"

Output:

A: The answer by souravatta is correct but i use a different approach and will like to share with an example.
//define the variable globally so that can be used by a fuction as well as pipeline
somevalue1=""; somevalue2=""; somevalue3=""; somevalue4="";

pipeline{
    environment{
    releasevalue = "r5"
    depenv = "dev"
    servicename = "Myservice"
    setecsvalues = settingvalues(releasevalue,depenv,servicename)
    }
agent any
    stages{
        stage(testing){
            steps{
                echo "${releasevalue}"
                echo "${depenv}"
                echo "${servicename}"
                echo "${somevalue1}"
                echo "${somevalue2}"
                echo "${somevalue3}"
                echo "${somevalue4}"
            }
        }
    }
}

//Setting Values from this function, you can write any program here to dynamically set values or maybe read from an external file

def settingvalues(releasevalue,depenv,servicename){
//some code to set values dynamically
somevalue1 = value1
somevalue2 = value2
somevalue3 = value3
somevalue4 = value4
}

It contains some more things from what you have asked for so bear with me :)
In environment block I have written 3 values and one function. You can simply write the values and use it inside any stage.
You can write a function and return a value by setting it dynamically. Here I am not returning anything because I wanted to set 4 values instead of returning a single one.
On top I have defined 4 values, that can be used by the function as well as inside the pipeline.
TIP
If you hardcode the values of variables inside the Jenkinsfile, that is not a good solution. Instead what you need to do is create a file, JSON or Yaml. Put it in a common location and use readJSON or readYaml to read those files and extract values dynamically. this way if you have to manage a lot of applications with many values then you can simply use one file to place all the values. This can come in handy and saves a lot of time as you do not want to edit your Jenkisnfile very often.


text:
Q: Oracle- GRANT ALL PRIVILEGES? Whenever I give a user "all privileges" in ORACLE (example below), what does this actually do?
My understanding is that it gives a user any privilege, e.g inserting, deleting etc within that schema but not to any schema in the DB?
grant all privileges to my_user;

A: You can grant all [privileges] on <some object>, but you aren't specifying an object; so you are granting system privileges:

The documentation for system privileges says:

Oracle Database provides the ALL PRIVILEGES shortcut for granting all the system privileges listed in Table 18-1, except the SELECT ANY DICTIONARY, ALTER DATABASE LINK, and ALTER PUBLIC DATABASE LINK privileges.

System privileges are not always restricted to a schema. That table includes a lot of ANY privileges, which are specifically not restricted to a schema. If you grant all privileges to a user they will be able to create or alter a table in any schema, for example. That probably isn't what you want.
There is no shortcut to grant only schema-restricted privileges. You'll need to grant CREATE TABLE, CREATE INDEX, etc. explicitly.
It's common practice to create a role to which you grant the necessary privileges, and then you just have to grant that role to your users. (Although you sometimes still need to grant privileges directly to users, e.g. if they are required in a stored procedure).


text:
Q: cant select and echo array within foreach the db has one row with 4 columns. i have selected 2 columns, first_name and last_name. i passed it through a select function in a db class, hows one result but it wont echo out
db class
<?php
  /* this script is for creating a class to connect to the database */

  include "includes/config.php";

  class database {
    protected static $connection; // variable to hold the mysqli connection

  protected function connect(){
      if (!isset(self::$connection)){ // if the connection variable is not set
          self::$connection = new mysqli(SERVER_NAME, USERNAME, PASSWORD, DB_NAME); // set the connection
      }
      if (self::$connection === false){ //in case connection failed return false
        return false;
      }
      else {
        return self::$connection; // returns the connection
      }
    }

    protected function query($query){ // public function to take a sql query
      $connection = $this->connect(); // calls the connect function to create a connection to the database
      $result = $connection->query($query); // puts the query into the result variable
      return $result; //returns the result
    }

    public function select($query){
      $rows = array();
      $result = $this->query($query);
      if($result === false){
        return false;
      }
      while($row = $result->fetch_assoc()){
            $rows[] = $row;
            }
        return $rows;
    }

    public function error(){
      $connection = $this->connect();
      return $connection->error;
    }
  }
?>

and the script with the foreach loop
<?php

  include 'view/header.php';
  include 'includes/connect.php';

  $db = new database();

  $sql = "SELECT `first_name`, `last_name` FROM `pratts_db`
          WHERE `first_name` = `clive`;";

  $result = $db->select($sql);

  if (sizeof($result) >= 1){
    echo "query successful";
    foreach($result as $result){
      echo "<p>{$result[0]['first_name']}</p>"
    }
  }

  include 'view/footer.php';

?>

the error says 'expecting semicolon on line 17 but i put that in and still got the same error
Parse error: syntax error, unexpected '}', expecting ',' or ';' in C:\wamp64\www\final\index.php on line 17


text:
Q: How to transfer all repos and commits (activity) from one github account to another? I have a github account account_A to which I had lost access in 2018. Since, I've been working on a separate account acount_B.
Recently, I regained access of account_A and would like to fill in its beautiful activity graph with everything I've ever commited to acount_B. How can I do this?
edit: this answer suggests 'adding a new email' to the account to which I'd like to merge my commit history. However, it shows 'email already in use', because it is being used in my other account (from which I'd like to transfer).


text:
Q: ways to reduce noise + smooth the image to create a mask for the largest object I need your advice, guys! So I am trying to create a mask for a football (i.e. soccer) pitch, and if I only use filtering by the most common hue/saturation/value values, I get the following image

As you can see, the desired part is inside the grey boundary I drawn and there is a lot of noise here - trees, lines, external objects, and of course I would like to get rid of it. The desired outcome is something similar to this:

I thought about an algorithm that would transform the first image into another by analyzing each pixel's surrounding and color it white if more than threshold% of pixels into a (x, x) square is white, otherwise black.
Do you know if there is an implementation on openCV or similar libraries for this or I should build it from scratch?
Also, maybe you can propose other way to deal with the noise and external objects? I already tried the morphological transform and blurring techniques, but either I don't do it right or it doesn't work well for my problem.
Thank you in advance for your advice!

A: I actually found an easy implementation of the algo I proposed - I simply use cv2.blur on the image and then filter with cv2.inRange, so it does exactly what I wanted it to do.


text:
Q: Mutate a column in a tsibble dataframe, applying a Box-Cox transformation I am a big fan of Hyndman's packages, but stumbled with Box-Cox transformation.
I have a dataframe
class(chicago_sales)
[1] "tbl_ts"     "tbl_df"     "tbl"        "data.frame"

I am trying to mutate an extra column, where the Mean_price variable will be transformed.
foo <- chicago_sales %>%
mutate(bc = BoxCox(x = chicago_sales$Median_price, lambda =
BoxCox.lambda(chicago_sales$Median_price)))

gives me some result (probably wrong too) and cannot apply autoplot.
I also tried to apply the code from Hyndman's book, but failed.
What am I doing wrong? Thanks!
UPDATED:

A: Issue, inside tsibbles, when using dplyr, you do not call chicago_sales$Median_price, but just Median_price. When using tsibbles I would advice using fable and fabletools, but if you are using forecast, it should work like this:
library(tsibble)
library(dplyr)
library(forecast)

pedestrian %>%
  mutate(bc = BoxCox(Count, BoxCox.lambda(Count)))
# A tsibble: 66,037 x 6 [1h] <Australia/Melbourne>
# Key:       Sensor [4]
   Sensor         Date_Time           Date        Time Count    bc
   <chr>          <dttm>              <date>     <int> <int> <dbl>
 1 Birrarung Marr 2015-01-01 00:00:00 2015-01-01     0  1630 11.3
 2 Birrarung Marr 2015-01-01 01:00:00 2015-01-01     1   826  9.87
 3 Birrarung Marr 2015-01-01 02:00:00 2015-01-01     2   567  9.10
 4 Birrarung Marr 2015-01-01 03:00:00 2015-01-01     3   264  7.65
 5 Birrarung Marr 2015-01-01 04:00:00 2015-01-01     4   139  6.52
 6 Birrarung Marr 2015-01-01 05:00:00 2015-01-01     5    77  5.54
 7 Birrarung Marr 2015-01-01 06:00:00 2015-01-01     6    44  4.67
 8 Birrarung Marr 2015-01-01 07:00:00 2015-01-01     7    56  5.04
 9 Birrarung Marr 2015-01-01 08:00:00 2015-01-01     8   113  6.17
10 Birrarung Marr 2015-01-01 09:00:00 2015-01-01     9   166  6.82
# ... with 66,027 more rows

I used a built in dataset from the tsibble package as you did not provide a dput of chicago_sales.


text:
Q: How to make a copy button to copy input text from another field? I want to make a copy button that copies another textfield to the current one.
Here is my code of the field I want to copy

  <textarea class="form-control" row="5" col="10"
           id="alamat_tempat_tinggal"
            name="alamat_tempat_tinggal"
            onchange="update_data()" >
           <?=@$registration->address?>
   </textarea>

here is the code of the filed i want to copy to

  Alamat Surat Menyurat*
    <input type=button id="copy_asm_address" onclick="copy_alamat_asm_address()" value = "Sama Dengan Alamat Tinggal">

       <textarea class="form-control" row="5" col="10"  name="asm_address" id="asm_address" onchange="update_data()"><?=@$registration->ASM_address?></textarea>

Here is the function
function copy_alamat_asm_address(){
    var alamat = document.getElementById("alamat_tempat_tinggal").val();
    document.getElementById("asm_address").value = alamat;
}

A: getElementsByName "Returns a nodelist collection with a given name in the (X)HTML document." (source)
This is not what you're after: you want to select one element to copy the value.
Use getElementById instead, and make sure you only use each ID once in your page.
function copy_alamat_asm_address(){
var alamat = document.getElementById("copy_asm_address").value();
document.getElementById("copy_to_field").value = alamat;
}

Next to that, to get the value of an input field, you need .value()

  Alamat Surat Menyurat*
    <input type=button id="copy_asm_address" onclick="copy_alamat_asm_address()" value = "Sama Dengan Alamat Tinggal">

       <textarea class="form-control" row="5" col="10" name="asm_address" onchange="update_data()" id="copy_to_field"><?=@$registration->ASM_address?></textarea>

A: .val() is jQuery.  You need to use .value().


text:
Q: Hash Table Not Working Because of Segmentation Fault I just learned about hash tables today and I tried to make one in C. I get a segmentation fault at line 90. It seems to store the data and retrieve the data fine. It's just when I try to use strcpy to copy the value in the data to a string in the calling function that I get a segmentation fault. I'm not really sure why this is happening since the data is printing out fine.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define size 100

//creates the lsit where the hash table will be stored

float round(int conver){
  conver = conver*10.0f;
  conver = (conver > (floor(conver)+0.5f)) ? ceil(conver) : floor(conver);
  conver = conver/10.0f;

  //If you're using C99 or better, rather than ANSI C/C89/C90, the following will also work.
  //conver = roundf(conver*10.0f)/10.0f;

  return conver;
}

int hash(char input[]){
    //decides where a string should be stored
    float number = 0;
    for(int i = 0; i < strlen(input); i++){
        int toAdd = input[i];
        printf("to add: %d", toAdd);
        number = number + toAdd;
        printf("number: %f", number);
    }
    printf("number again: %f", number);
    number /= strlen(input);
    number = round(number);
    printf("number divided: %f \n", number);
    return number;
}

struct Node{
    //blueprint for linked list node
    struct Node *Next;
    char data[];

};

struct Node *hashTable[];

struct Node *createNode(char *data){
    //utility function to create a node in the linked list
    struct Node *newNode = malloc(sizeof(struct Node));
    newNode->Next = NULL;
    strcpy(newNode->data, data);

    return newNode;
};

void createHashTable(){
    //creates the hash table before anything can be inserted
    for(int i = 0; i < size; i++){
        hashTable[i] = NULL;
    }
}

void addToHashTable(char *input){
    //adds to the hash table
    int hashed = hash(input);
    if(hashTable[hashed] == NULL){
        hashTable[hashed] = createNode(input);
    }
    else{
        struct Node *newNode = createNode(input);
        newNode->Next = hashTable[hashed];
        hashTable[hashed] = newNode;
    }
}

char *search(char input[], char *writeTo){
    //searches the hash table for a value
    int hashed = hash(input);
    printf("\nhashed: %d", hashed);
    printf("\ndata: %s", hashTable[hashed]->data);
    if(hashTable[hashed] == NULL){
        strcpy(writeTo, "not found");
        return;
    }
    else if(hashTable[hashed]->Next == NULL){
        printf("\nit is: %s", hashTable[hashed]->data);
        strcpy(writeTo, hashTable[hashed]->data);
        return;
    }
    else{
        struct Node *newNode = hashTable[hashed];
        while(newNode != NULL){
            if(newNode->data == input){
                strcpy(writeTo, hashTable[hashed]->data);
                return;
            }
            newNode = newNode->Next;
        }
    }
}

int main()
{
    //main function
    createHashTable();
    addToHashTable("124");
    char *writeTo;
    search("124", writeTo);
    printf("%s", writeTo);

    return 0;
}

A: First of all, when I run your code I don't get a segfault. Did you remove the use case where the segfault occured? If not, it could be a difference in our environments.
More importantly, your code seems to be riddled in small problems. If you get to fixing those one by one, then the important logical errors will have nowhere to hide.
Here is a (n unordered and incomplete) list of such problems:
In your round function, you are using floor and ceil, but you never include the math library.
In your search function, you are not returning a char*, you are returning nothing. The function header should reflect that.
In your search function, in the final else statement, in the while loop, the condition of the if statement compares two char* values, whereas I assume you mean to compare two strings.
In some of your print statements, you are not printing a new line or any other whitespace, making the results hard to read.

A: There were some bugs in it.
This code should work. I tried to change your code as minimal as possible.
Dont forget that you have to free() pointerstructures.
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "math.h"

#define size 100

int _round(float conver){

  conver = (conver > (floorf(conver)+0.5f)) ? ceilf(conver) : floorf(conver);
  return (int) conver;
}

int hash(char input[]){
    float number = 0;
    for(int i = 0; i < strlen(input); i++)
    {
        int toAdd = (int) input[i];
        number = number + toAdd;
    }
    number /= strlen(input);
    number = _round(number);
    return number;
}

struct Node{
    struct Node *Prev;
    struct Node *Next;
    char *data;
};

struct Node *hashTable[size];

struct Node *createNode(char data[]){
    struct Node *newNode = malloc(sizeof(struct Node));
    newNode->Prev = NULL;
    newNode->Next = NULL;
    newNode->data = malloc( sizeof(char) * (strlen(data)));
    strcpy(newNode->data, &data[0]);

    return newNode;
};

void createHashTable(){
    for(int i = 0; i < size; i++){
        hashTable[i] = NULL;
    }
}

void addToHashTable(char input[]){
    int hashed = hash(input);
    if(hashTable[hashed] == NULL){
        hashTable[hashed] = createNode(input);
    }
    else{
        struct Node *newNode = createNode(input);
        newNode->Next = hashTable[hashed];
        hashTable[hashed]->Prev = newNode;
        hashTable[hashed] = newNode;
    }
}

char *search(char input[]){

    int hashed = hash(input);
    printf("hashed: %d\n", hashed );
    if(hashTable[hashed] == NULL){
        char *writeTo = malloc( sizeof( char ) * 9);
        strcpy(writeTo, "not found");
        return writeTo;
    }
    else if(hashTable[hashed]->Next == NULL){
        char *writeTo = malloc( sizeof(char) * (strlen(input)));
        strcpy(writeTo, hashTable[hashed]->data);
        return writeTo;
    }
    else{
        struct Node *newNode = hashTable[hashed];
        char *data = malloc( sizeof( char) * (strlen(input)));
        strcpy( data, &input[0] );
        data[strlen(input)] = '\0';
        while(newNode != NULL){
            if(strcmp(newNode->data, data) == 0 ){
                char *writeTo = malloc( sizeof(char) * (strlen(input)));
                strcpy(writeTo, newNode->data);
                return writeTo;
            }
            newNode = newNode->Next;
        }
        free( data );
    }

    char *writeTo = malloc( sizeof( char ) * 9);
    strcpy(writeTo, "not found");
    return writeTo;
}

void freeHashTable()
{
  struct Node * node;
  for( int i = 0; i < size; ++i )
  {
    node = hashTable[i];

    if( node != NULL )
    {
      while( node->Next != NULL )
      {
        node = node->Next;
      }

      while( node->Prev != NULL )
      {
        node = node->Prev;
        free( (void*) node->Next->data );
        free( (void*) node->Next );
      }
      free( (void*) node->data );
      free( (void*) node );
    }
  }
}

int main()
{

    createHashTable();
    addToHashTable("142");
    addToHashTable("124");
    char *writeTo;
    writeTo= search("142");
    printf("%s\n", writeTo );
    free( (void*) writeTo);
    writeTo = search( "124" );
    printf("%s\n", writeTo);
    free( (void*) writeTo);
    freeHashTable();

    return 0;
}


text:
Q: Configure LAME MP3 encoder in DirectShow application using IAudioEncoderProperties I'm writting a .NET DirectShow application which captures audio stream from any capture device, encodes it in mp3 using the LAME directshow filter and finally writes the stream into a file.
This is my directshow graph:
capture source -> LAME AUDIO ENCODER (Audio compressor) -> WAV DEST (Wave muxer, compiled from SDK sourcres) -> File writer.
The problem is that I'd like to configure the encoder (bitrate, channels, VBR/CBR, etc) programmatically and not using the properties pages (ISpecifyPropertyPages) available on the LAME encoder.
After retrieving LAME sources, it appears that the configuration must be done using the specific IAudioEncoderProperties interface.
I tried to marshal this COM interface in my .NET application using this declaration:

 [ComImport]
 [SuppressUnmanagedCodeSecurity]
 [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
 [Guid("ca7e9ef0-1cbe-11d3-8d29-00a0c94bbfee")]
 public interface IAudioEncoderProperties
 {
   // Get target compression bitrate in Kbits/s
   int get_Bitrate(out int dwBitrate);

   // Set target compression bitrate in Kbits/s
   // Not all numbers available! See spec for details!
   int set_Bitrate(int dwBitrate);
 }

Note that not all methods are redefined.
I can successfully cast my audio compressor filter (the LAME encoder) using:
IAudioEncoderProperties prop = mp3Filter as AudioEncoderProperties;
But when I call get_Bitrate method the returned value is 0 and calling the set_Bitrate method seems to have no incidence on the output file.
I tried configuring my filter using the properties pages and it works.
So, I'd like to know if anybody has already used the LAME encoder into a DirectShow application (.NET or not) and could bring me some help?
Regards.
--
Sypher

A: Maybe I am late, but I ran in the same problem. The solution is to declare methods in your interface in exactly same order as they are declared in LAME sources.
[ComImport]
[SuppressUnmanagedCodeSecurity]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("ca7e9ef0-1cbe-11d3-8d29-00a0c94bbfee")]
public interface IAudioEncoderProperties
{
    /// <summary>
    /// Is PES output enabled? Return TRUE or FALSE
    /// </summary>
    int get_PESOutputEnabled([Out] out int dwEnabled);

    /// <summary>
    /// Enable/disable PES output
    /// </summary>
    int set_PESOutputEnabled([In] int dwEnabled);

    /// <summary>
    /// Get target compression bitrate in Kbits/s
    /// </summary>
    int get_Bitrate([Out] out int dwBitrate);

    /// <summary>
    /// Set target compression bitrate in Kbits/s
    /// Not all numbers available! See spec for details!
    /// </summary>
    int set_Bitrate([In] int dwBitrate);

    ///... the rest of interface
}


text:
Q: Spring context indexer not working for dependency jar I have some library jar lib.jar (made using spring boot but packaged as normal jar without spring boot plugin) which is made of spring boot and contains spring.components file generated by spring-context-indexer.
Now, I'm using this jar in my application which also has spring-context-indexer and its own spring.components file and uses some of the bean defined in lib.jar.
When I start my application, spring should register all beans defined in spring.components of lib.jar and spring.components of application. But spring isn't registering any of bean of lib.jar.
I tried using basePackages property of @SpringBootApplication but no results.
I even copied all entries of spring.components of lib.jar into spring.components of my application but no result.
Can anyone please help me?

A: TL;DR
If you're using Spring Data, @SpringBootApplication.scanBasePackages is not enough, you also need @EnableJdbcRepositories (or *Jpa* or whatsoever).
package application;

// without this annotation all Repository classes
// from library will be missing
@EnableJdbcRepositories({
        "application",
        "library"
})
@SpringBootApplication(
        scanBasePackages = {
                "application",
                "library"
        }
)
public class Application {

    public static void main(final String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

Some more info
Okay, maybe I'm a bit late, but I decided to investigate this case a bit.
That's what I've found as of 2 Feb 2022:

*

*All META-INF/spring.components files are loaded in CandidateComponentsIndexLoader.doLoadIndex. You can use debug to check whether it sees file from lib or not

*CandidateComponentsIndexLoader then creates CandidateComponentsIndex, which is then stored in the component scanner, for me it is AnnotationConfigServletWebServerApplicationContext.scanner.componentsIndex

*Then in ClassPathScanningCandidateComponentProvider findCandidateComponents is called, which, if componentsIndex is not null, just gets components from that index by provided basePackage.
That's why missing basePackage is crucial.
I haven't dug into the Spring Data algorithms, but in my case Spring hadn't been generating library Repositories until I added the @EnableJdbcRepositories with packages.
P.S. All links represent files at the 5.3.15 tag, latest atm.


text:
Q: How can I tell if someone else is logged into my Windows 10 PC? Three or four times recently, I've tried shutting down my Windows 10 PC, only for it (mysteriously) to instead go back to the normal Windows login screen. And when I then try to shut the PC down from there, it (again mysteriously) warns me that this will shut down any connected users' sessions (but without giving any useful details).
All of which makes suspect (in a slightly paranoid, but probably justified way) that someone else might possibly now be logging in to my PC from time to time.
So: is there anything (i.e. application / trick / hack / whatever) I can use to find out / track who (or what) is currently (remotely) logged in to my Windows 10 PC?
Because I work from home, I guess it's conceivable that a client company's firewall / antivirus bot is doing something nasty (but legit) that I'm unaware of. But... I'd just like to know. Thanks!

A: Type query user in a command prompt. No need for elevation.


text:
Q: How to make the read-only port 10255 only available in the vpc in Google Cloud with GKE? I noticed I have the read only port 10255 opened to the wide web. We want to make it available only from inside the VPC, like this answer is suggesting. I'm not sure how to specify such rule. I've tried something like that:
gcloud compute firewall-rules create "testcloseport" --action=DENY --rules tcp:10255  --source-tags=public --source-ranges=0.0.0.0/0 --description="Close port 10255 from outside the vpc"

I unfortunately got this error:
ERROR: (gcloud.compute.firewall-rules.create) Could not fetch resource:
 - The resource 'projects/myproject-prod/global/networks/default' was not found

I tried to set the region and zone like this:
gcloud config set compute/region us-east1
gcloud config set compute/zone us-east1-d

I still got the error. I simply want to close this port for the outside of the VPC. Is there a way I can change the firewall-rules create command so it works?

A: The reason you are getting this error:

The resource 'projects/myproject-prod/global/networks/default' was not
found

is because the gcloud command you are attempting to run defaults to the VPC named "default" which is the one that comes by default.
In order to create the firewall rule to a custom network (VPC) you have to pass the parameter --network for example (replace the <MY_VPC_NAME>):
gcloud compute firewall-rules create testcloseport --network <MY_VPC_NAME> --action=DENY --rules tcp:10255  --source-tags=public --source-ranges=0.0.0.0/0 --description="Close port 10255 from outside the vpc"

One more thing, with the rule above you will deny any IP source on port 10255 so you might need a second rule with a higher priority allowing port 10255 only to the private subnet you would like to allow that connection through.


text:
Q: magento connect manager extension not visible Magento extensions installed by another team and they are not reachable now. When we checked files, we identify there are few extensions installed. But we couldn't see any extensions in Magento connect and also clicked 'check for upgrades' but its not showing any result.

A: The extensions might be installed directly via ftp/shell and not via MagentoConnect. In that case, the extension is not mentioned in MagentoConnect.
Probably, in the config file of the module, the version number is added, so you can check if this is the most recent release.
If you want to upgrade to a newer version, you can simply copy and override these files to your shell to upgrade the module.


text:
Q: Const variable still being reassigned in chess challenge I'm trying to do a challenge on code wars and I can't seem to figure out why const variable is being changed. I thought this was the place to use a constant like this. I just want to reset the piece location to what it was when checkDiagonal() is called but it always stays to what it was after the first while loop finishes.
function checkDiagonal(piece){
const store = piece;
var current = piece;

// northwest
while(current[0] && current[1] > 0){
  current[0] -= 1;
  current[1] -= 1;
  if(spaceCheck(current)){
    return true;
  }
  if(spaceCheck(current) == "break"){
    break;
  }
}

current = store;
console.log("piece1: " + piece + " current :" + current + "store: " + store);

//northeast
while(current[0] > 0 && current[1] < 7){
  current[0] -= 1;
  current[1] += 1;
  if(spaceCheck(current)){
    return true;
  }
  if(spaceCheck(current) == "break"){
    break;
  }
}

current = store;
console.log("piece2: " + piece + " current :" + current + "store: " + store);

//southwest
while(current[0] < 7 && current[1] > 0){
  current[0] += 1;
  current[1] -= 1;
  if(spaceCheck(current)){
    return true;
  }
  if(spaceCheck(current) == "break"){
    break;
  }
}

current = store;
console.log("piece3: " + piece + " current :" + current + "store: " + store);

//southeast
while(current[0] && current[1] < 7){
  current[0] += 1;
  current[1] += 1;
  if(spaceCheck(current)){
    return true;
  }
  if(spaceCheck(current) == "break"){

    break;
  }
}

return false;

};
function spaceCheck(location){
  if(chessboard[location[0]][location[1]] == '♔'){
    console.log("Check detected " + location);
    return true;
  }
  if(chessboard[location[0]][location[1]] != ' '){
    console.log("Piece blocking check" + location);
    return "break";
  }
  else{
    console.log("False" + location);
    return false;
  }

};
/// Bolded the part thats getting me, how can I just "reset the piece" back to what it was at the function call?
piece1: 3,0 current :3,0store: 3,0
False 2,1
False 2,1
False 1,2
False 1,2
False 0,3
False 0,3
piece2: 0,3 current :0,3store: 0,3
False 1,2
False 1,2
False 2,1
False 2,1
Piece blocking check3,0
Check by Queen(Diag)
False 2,0
False 2,0
False 1,0
False 1,0
False 0,0
False 0,0
False 1,0
False 1,0
False 2,0
False 2,0
Piece blocking check3,0
Check by Queen(Linear)

A: Your problem here is scope. Basically you are declaring the const inside a function so the const only lives for the duration of that specific function call and once the call is done the variable will be destroyed (which is why you would also be unable to access it outside the function).
So when you call your checkDiagonal function the second time the const is being re-declared from scratch.
There is an explanation of this here: https://wsvincent.com/javascript-scope-closures/
Hope this makes sense.
Edit:
After some digging it turns out the problem seems to be that piece is an object and is therefore being passed by reference rather than by value. This means that when current was updated it kinda updated all three (technically all three are the same object in memory)
There is a good article on these two here: https://hackernoon.com/grasp-by-value-and-by-reference-in-javascript-7ed75efa1293


text:
Q: How to debug Visual Studio in 64-bit OK, after creating an application I want it to be compatible for 64 and 32 bit systems. By default Visual Studio debugs applications in x86 (which is 32-bit). So how can I make Visual Studio debug in x64, for 64-bit systems.
Thanks.

A: Not sure what language but if it's C# ...
The default build setting for C# projects is an x86 build in debug mode in Visual Studio 2010.  To debug in 64 bit you simple need to change the build setting to 64 bit.

*

*Right click on the project and select properties

*Switch to the build tab

*Change "Platform Target" to x64


text:
Q: Raspberry Service permissions not working i have trouble with permissions in my service.
[Unit]
Description=TwinHubClient

[Service]
WorkingDirectory=/home/pi/TwinHubClient
ExecStart=/home/pi/TwinHubClient/TwinHubClient
Restart=always
# Restart service after 60 seconds if the dotnet service crashes:
RestartSec=60
KillSignal=SIGINT
SyslogIdentifier=dotnet-TwinHubClient
User=pi
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target

after starting service, i've got a failure in log:
SQLite Error 8: 'attempt to write a readonly database'.

if I execute with same user manually, everything is working fine.
I tryed different permissionsettings 775, 644 without succeed. Any ideas whats going wrong here?

A: Problem description
After starting my bash script, i downloading files and extracting them to my defined folder. After extracting succeed, I copied my service to /etc/systemd/system/xxxx.service, enabled it and starting it. After few seconds, service is crashed. In journalctl you can see the following exception:
SQLite Error 8: 'attempt to write a readonly database'.

If i starting my programm manually, everything is working fine! So, tryed to change permissions to my executing folder where database exists. 644 and 775 doesn't work! After changing to 777 and restarting service, everything is working like expected!
Solution
I found out, that I changed the permissions but never changed the owner and group of my folder! Both are as root/root. After changing to pi:pi with command
sudo chown pi:pi <folder>

and also
sudo chmod 644 <folder>

My Service is working with user 'pi' like expected! So my mistake was the wrong ownership of directory where database exists.
Thanks!


text:
Q: Spark ElasticSearch Configuration - Reading Elastic Search from Spark I am trying to read data from ElasticSearch via Spark Scala. I see lot of post addressing this question, i have tried all the options they have mentioned in various posts but seems nothing is working for me
JAR Used - elasticsearch-hadoop-5.6.8.jar (Used elasticsearch-spark-5.6.8.jar too without any success)
Elastic Search Version - 5.6.8
Spark - 2.3.0
Scala - 2.11

Code:
import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._

import org.elasticsearch.spark._

val spark = SparkSession.builder.appName("elasticSpark").master("local[*]").getOrCreate()

val reader = spark.read.format("org.elasticsearch.spark.sql").option("es.index.auto.create", "true").option("spark.serializer", "org.apache.spark.serializer.KryoSerializer").option("es.port", "9200").option("es.nodes", "xxxxxxxxx").option("es.nodes.wan.only", "true").option("es.net.http.auth.user","xxxxxx").option("es.net.http.auth.pass", "xxxxxxxx")

val read = reader.load("index/type")

Error:
ERROR rest.NetworkClient: Node [xxxxxxxxx:9200] failed (The server xxxxxxxxxxxxx failed to respond); no other nodes left - aborting...
org.elasticsearch.hadoop.EsHadoopIllegalArgumentException: Cannot detect ES version - typically this happens if the network/Elasticsearch cluster is not accessible or when targeting a WAN/Cloud instance without the proper setting 'es.nodes.wan.only'
  at org.elasticsearch.hadoop.rest.InitializationUtils.discoverEsVersion(InitializationUtils.java:294)
  at org.elasticsearch.spark.sql.SchemaUtils$.discoverMappingAndGeoFields(SchemaUtils.scala:98)
  at org.elasticsearch.spark.sql.SchemaUtils$.discoverMapping(SchemaUtils.scala:91)
  at org.elasticsearch.spark.sql.ElasticsearchRelation.lazySchema$lzycompute(DefaultSource.scala:129)
  at org.elasticsearch.spark.sql.ElasticsearchRelation.lazySchema(DefaultSource.scala:129)
  at org.elasticsearch.spark.sql.ElasticsearchRelation$$anonfun$schema$1.apply(DefaultSource.scala:133)
  at org.elasticsearch.spark.sql.ElasticsearchRelation$$anonfun$schema$1.apply(DefaultSource.scala:133)
  at scala.Option.getOrElse(Option.scala:121)
  at org.elasticsearch.spark.sql.ElasticsearchRelation.schema(DefaultSource.scala:133)
  at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:432)
  at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:239)
  at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:227)
  at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:174)
  ... 53 elided
Caused by: org.elasticsearch.hadoop.rest.EsHadoopNoNodesLeftException: Connection error (check network and/or proxy settings)- all nodes failed; tried [[xxxxxxxxxxx:9200]]
  at org.elasticsearch.hadoop.rest.NetworkClient.execute(NetworkClient.java:149)
  at org.elasticsearch.hadoop.rest.RestClient.execute(RestClient.java:461)
  at org.elasticsearch.hadoop.rest.RestClient.execute(RestClient.java:425)
  at org.elasticsearch.hadoop.rest.RestClient.execute(RestClient.java:429)
  at org.elasticsearch.hadoop.rest.RestClient.get(RestClient.java:155)
  at org.elasticsearch.hadoop.rest.RestClient.remoteEsVersion(RestClient.java:655)
  at org.elasticsearch.hadoop.rest.InitializationUtils.discoverEsVersion(InitializationUtils.java:287)
  ... 65 more

Apart from this I have also tried below properties without any success:
option("es.net.ssl.cert.allow.self.signed", "true")
option("es.net.ssl.truststore.location", "<path for elasticsearch cert file>")
option("es.net.ssl.truststore.pass", "xxxxxx")

Please note elasticsearch node is within Unix edge node and is http://xxxxxx:9200 (mentioning it just in case if that makes any difference with the code)
What I am missing here? Any other properties? Please Help

A: Use below Jar which support spark 2+ version instead  of Elastic-Hadoop or Elastic-Spark jar.
https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch-spark-20_2.11/5.6.8


text:
Q: How to select expo release-channel in the mobile app? I can't find my newly published "QA" release channel in the expo mobile client app.
I've been using the default channel to publish my expo app while developing, and that works great.  Now I want to test the same code in a QA environment.  I published it successfully with expo publish --release-channel qa.  I can even see it was published when I run expo publish:history.
But I can't see it in the expo mobile app so I'm not sure how to load it up and test it..

A: This isn't so much a solution as a workaround, but if I create an expo url like this in my mobile browser address bar, android will open it in the expo app:
https://expo.io/@myaccount/My-Project-Name?release-channel=qa


text:
Q: How to implement failover with MQTT brokers? I'm implementing a few devices and services with a fair bit of data running around my local network, with all publishers and most subscribers within the firewall.  Because it's easy, I'm starting with a CloudMQTT subscription, but ideally, I'd like that to be the primary (to service a couple of external clients), but if the internet goes down, I'd like an internal server to be a hot back up, with all publishing and, for internal clients, subscribe service.  I'm not sure if Bridging can help?
Is there anyway to implement this?  In my head, it's something like the way DNS works - you can have a local server, and to the extent it knows your answer, it can service it, but it has a place to go for further answers.

A: Run a broker on each site and bridge it to the CloudMQTT instance. This way things can always communicate locally even if the internet is down


text:
Q: Can Apache BeanUtils be used to REMOVE items from a list instead of setting them to null? I am considering using Apache BeanUtils to manage some data structures in my project. The task is for an arbitrary path, known only at runtime, to remove items from a list.
I think I can use BeanUtils to set an item to null with a call like this:
PropertyUtils.setProperty(myObject, "subitem.aList[3]", null);

However in other areas of my project there are loops which iterate over these lists. Having a null item in the list is currently unhandled. There are many (dozens, possibly hundreds) places where the code expects these items to not be null so it is unfortunately impractical to add a null check to all of the code that might iterate over these lists.
Is it possible to use BeanUtils to remove an item from a collection instead of setting it to null?
I think I can implement this myself by parsing the path passed to setProperty and determining if its a List by looking for paths ending with [<number>] then parsing out the number, getting the List with the path to the list and calling remove(number). I would like to use existing solutions before rolling my own.

A: I guess you can achieve your results with two steps process as below:
    List aList = (List)PropertyUtils.getProperty(myObject, "subitem.aList");
    aList.remove(3); // remove the fourth element

    //set the modified list back
    PropertyUtils.setProperty(myObject, "subitem.aList", aList);


text: Q: Ubuntu 16.04 LTS update problem i have dual boot with Windows 10 Pro and Ubuntu Linux 16.04 LTS, I'd like to update to 18.04 but it doesn't work with the updater assistant, neither with the console; so, what can I do?


text:
Q: Получение списка подъездов у дома Получаю список домов в заданном полигоне, и задался вопросом: "как получить подъезды у дома?".
Пробовал логировать объект дома и смотреть свойства - там ничего связаного с entrances нету.
В API Yandex Maps про entrances упоминаний вообще нет.
Возможно, я что-то упускаю?

A: Можно, например, получить координаты подъезда через Геокодер:
https://geocode-maps.yandex.ru/1.x/?apikey=7d414129-bdb5-4dbf-9f93-0d0aa59d2fba&geocode=Россия,%20Москва,Мичуринский%20проспект,%2017,%20подъезд%202&kind=locality


text:
Q: What exactly did Hermann Weyl mean? "The introduction of numbers as coordinates is an act of violence." - Hermann Weyl.
A lot of people like this quote, apparently. They also seem to associate it to the manifold context in the obvious way: they interpret the quote as saying that focusing on coordinate charts is insightless, or at least dry. Although I aggree with this, I feel like the way the quote is phrased is not inclined to that interpretation. If not by the fact that Weyl is connected to geometry (and that this quote is in Bredon), I would interpret this phrase as saying that "Representing numbers by a given basis is insightless and can lead to mistakes, like thinking that divisibility is dependent of the number basis you are using." I think the words numbers and coordinates are strangely placed.
Therefore, my question is: What was the precise context on which this quote arose and, if possible, can we pinpoint exactly what did Weyl mean?

A: From a Google search, it appears the quote is from Hermann Weyl's Philosophy of Mathematics and Natural Science. I found a copy online here; the relevant passage is on page 90 (search "act of violence"):

The introduction of numbers as coordinates by reference to the particular division scheme of the open one dimensional continuum is an act of violence whose only practical vindication is the special calculatory manageability of the ordinary number continuum with its four basic operations. The topological
  skeleton determines the connectivity of the manifold in the large.

His meaning appears to turn on the idea of a "division scheme." In a preceding paragraph, he wrote:

In general a coordinate assignment covers only part of a given continuous manifold. The 'coordinate' $(x_1, \ldots, x_n)$ is a symbol consisting of real numbers. The continuum of real numbers can be thought of as created by iterated bipartition. In order to account for the nature of a manifold as a whole, topology had to develop combinatorial schemes of a more general nature.

To paraphrase, I believe he's saying that the topological structure of both the real number line and manifolds more generally is determined by how it breaks into smaller pieces, and how those pieces fit together (in modern terminology, we might look at a space's locale of open sets). To add a coordinate system rooted in arithmetic operations, either to the real line or to a manifold, in his view, is to add too much structure (although it does help with calculations).


text:
Q: Why is my javascript onchange function not getting called? I have a dynamically generated html which has multiple input elements , that have an onchange function like this : onchange=adStGroup();. In my html I have created a javascript function like so :
function adStGroup(jsObj){
    console.log(jsObj.name);
}

If I go to developer tools change the function to : onchange=adStGroup(this); and make some changes in the input element , the name of the element is logged .
But since the dynamically html does not contain the this argument , hence , on window onload , I am removing the default onchange and adding another onchange , like so :
for(var i=0;i<document.getElementById("f5erz").getElementsByTagName('input').length;i++){
        document.getElementById("f5erz").getElementsByTagName('input')[i].removeAttribute('onchange');
        document.getElementById("f5erz").getElementsByTagName('input')[i].setAttribute('onchange','javascript:adStGroup(this);');
}

Now the dynamically generated html input elements contain the this argument, but If I make any change to the input element , the corresponding method is not getting called . Why So ?
How can I still pass the this reference to such dynamically generated input elements ?
Note : I am using IE document mode emulated as 5 , since the app works only in this version .


text:
Q: PSO Package in R always end with an error in while TRUE/FALSE needed Trying to perform ANN optimization but I always get the same error which I cannot resolve.
I put some trackback() in my code but nothing was returned except the error below:
Error in while (stats.iter < p.maxit && stats.feval < p.maxf && error >  :
  missing value where TRUE/FALSE needed

Do you have already seen this error and where i can coming from?

A: The error tells you that a condition was to be tested, but it evaluated to NA. In optimisation problems, this often happens when your objective function evaluates to NA for some parameter values.  (But without a reproducible example, it is hard to tell what exactly went wrong.)


text:
Q: PHP preg_match() PCRE logic issue? Consider the following:
$lat = '89° 5'; // works
if(preg_match('/^(([0-8]\d|\d)°?(\s?([0-5]\d|\d))?)(N|S)?$/', $lat, $la)){
  $ck = 'DD° MM format --> ';
}
else{
  $test = 'invalid $lat format';
}
if(isset($ck)){
  $test = $ck.$la[0];
}
echo $test;

When $lat = '89°5' everything works fine too. What I'm trying to understand is why $lat = '89 5' fails? Maybe my brain isn't working, but it seems that last one should not be an invalid format because of °?. Thanks for helping me understand.

A: Use /(*UTF8)^(([0-8]\d|\d)°?(\s?([0-5]\d|\d))?)(N|S)?$/
From http://www.pcre.org/pcre.txt:

In  order  process  UTF-8  strings, you must build PCRE's 8-bit library with UTF support, and, in addition, you must call  pcre_compile()  with the  PCRE_UTF8 option flag, or the pattern must start with the sequence (*UTF8) or (*UTF). When either of these is the case, both  the  pattern and  any  subject  strings  that  are matched against it are treated as
  UTF-8 strings instead of strings of individual 1-byte characters.

So the PCRE engine was still seeing ° as two separate characters, and only making the second half optional.
Note: Interestingly, I was able to get the expected results only using the (lowercase) u modifer on my install. http://php.net/manual/en/reference.pcre.pattern.modifiers.php.
Note 2: My original comment had two options, don't use the other one as it breaks the test that currently works for you.


text:
Q: query has no destination for result data in POSTGRESQL for stored procedure having a slight issue here, trying to call this function, but getting this error:
ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM instead.

used perform but that is not what I need. I don't understand the error message, do i need to return a table or something?
create or replace procedure myProc(colkey varchar, colvalue varchar)
language plpgsql
as $$
declare
old varchar(250);
keyId bigint;

begin

select @keyid= id
from conkey
where conkey.key like colkey
limit 1;

if not exists (select * from ConValu where conkeyId= @keyid and appId is null) THEN

else

select @old_value_for_update = value
from ConValu
where conkeyId= @conkeyId and appId is null
limit 1;

update ConValu  set Value = colvalue where ConkeyId= @conkeyID and appId is null;

end if;

end; $$

A: You seem to try to use T-SQL syntax in PL/pgSQL. But in PL/pgSQL variables aren't and cannot be prefixed with @. But you can and should prefix them with an underscore (_) (or some other valid prefix) to avoid name clashes with column names which can result in pretty hard to find errors.
Either way they need to be declared in the DECLARE block. You also missed that for that variables now beginning with @.
And they cannot be filled in a query with the <variable name> = <column expression> syntax.
You need to either use SELECT ... INTO ... or a subquery and an assignment.
Like
SELECT value
       INTO _old_value_for_update
       FROM convalu
       WHERE conkeyid = _conkeyid
             AND appid IS NULL
       LIMIT 1;

or:
_old_value_for_update := (SELECT value
                                 FROM convalu
                                 WHERE conkeyid = _conkeyid
                                       AND appid IS NULL
                                 LIMIT 1);

Oh and one thing I already forgot: If you use LIMIT without an ORDER BY the rows chosen are expected to be random. I couldn't introduce an ORDER BY because I don't know what could make sense in your case.


text:
Q: Ionic Framework - HTML rel import works on emulator but NOT on device I am trying to import the contents (import the reference of the CSS and JavaScript files) of a particular html page, named "helper.html" to another html page,named "navigation.html". It works on the emulator (the reference of the CSS and JavaScript files of the "helper.html" can be imported) but NOT on the device (the device I am using is Android tablet).
My project directory looks like this:
www
-templates

*

*navigation.html (inside templates folder)

-helper.html (inside www)
In my "navigation.html", I have the following code snippet:
<!DOCTYPE html>

<link rel="import" href="helper.html">

 <ion-view view-title="Navigation">
    <ion-content>
  // SOME CODES
 </ion-content>
    </ion-view>

In my "helper.html", I have the following code snippet:
<!DOCTYPE html>

 <title></title>
<link rel="stylesheet" href="css/pathFindingstyle.css" />

Can someone tell me a way how I could make this work on the android device? Thanks!

A: Old versions of Cordova for Android (<= 4.4.4) don't use Blink, the Chromium / Chrome web engine, or use an old version of Blink (< 36) that doesn't implement Web Components -including HTML Imports- for HTML rendering.
Therefore you'll need to upgrade Android to version 5+, or to use a more recent device to get a native implementation.
As a workaround, you can try to use the webcomponentsjs polyfill, with the HTMLImports.js file which emulates HTML Imports (though I don't know if it will work on your Android version).


text:
Q: How do i vertically center align div with dynamic multiple line text Below is the CSS i am using:
        .flip-container
           {
        -webkit-perspective: 1000;
        -moz-perspective: 1000;
        perspective: 1000;

    }

    .flip-container:hover .flipper, .flip-container.hover .flipper {
             -webkit-transform: rotateY(180deg);
             -moz-transform: rotateY(180deg);
              transform: rotateY(180deg);
    }

    .flip-container, .front, .back {
                  width: 150px;
                  height: 150px;

    }

    .flipper {
        -webkit-transition: 0.6s;
        -webkit-transform-style: preserve-3d;
        -moz-transition: 0.6s;
        -moz-transform-style: preserve-3d;
         transition: 0.6s;
         transform-style: preserve-3d;
         position: relative;
    }

    .front, .back {
        -webkit-backface-visibility: hidden;
        -moz-backface-visibility: hidden;
        backface-visibility: hidden;
        display: table-cell;
        vertical-align:middle;

        position: absolute;
        top: 0;
        left: 0;

    }

    .front {
         z-index: 2;
         text-align: center;
    }

    .back {

        -webkit-transform: rotateY(180deg);
        -moz-transform: rotateY(180deg);
        transform: rotateY(180deg);

    }

    .front .name {
        font-size: 2em;
        display: inline-block;
        background: rgba(33, 33, 33, 0.9);
        color: #f8f8f8;
        font-family: Courier;
        padding: 5px 10px;
        border-radius: 5px;
        bottom: 60px;
        left: 25%;
        position: absolute;
        text-shadow: 0.1em 0.1em 0.05em #333;

        -webkit-transform: rotate(-20deg);
        -moz-transform: rotate(-20deg);
        transform: rotate(-20deg);
    }

    .back-logo {
        position: absolute;
        top: 40px;
        left: 90px;
        width: 160px;
        height: 117px;
        background: url(logo.png) 0 0 no-repeat;

    }

    .back-title {
        font-weight: bold;
        color: #00304a;
        position: absolute;
        top: 180px;
        left: 0;
        right: 0;
        text-align: center;
        text-shadow: 0.1em 0.1em 0.05em #acd7e5;
        font-family: Courier;
        font-size: 2em;

    }

    .back p {
        position: absolute;
        bottom: 40px;
        left: 0;
        right: 0;
        text-align: center;
        padding: 0 20px;

    }

The HTML that i am using looks like this :

The CSS of the article class is:
#article {
margin: 5px;
float: left;
height: 150px;
width: 150px;}

I am unable to make the fext in the FRONT div center vertically centered. Also it would be dynamic and multiline. Any Ideas?
I tried using 'vertical-align:middle' along with 'display:table-cell' but that didn't help or maybe i just applied them to the wrong CSS Blocks.
The Code is on jsFiddle: here

A: You can use display: table for your parent container and display: table-cell for your child container:
#article {
    display:table;
    height: 150px;
    width: 150px;
    float: left;
    text-align: center;
}

.front {
    display: table-cell;
    vertical-align:middle;
}

Fiddle Demo: http://jsfiddle.net/uVSN6/1/


text:
Q: Run a python script from another python script using IF __name__ == "__main__" statement I have a script LCP_02.py with the if statement:
if __name__ == "__testcase__" or __name__ == "__main__":

    ask_costsurfacepath_path()
    ask_outputpath_path()
    CostSurfacefn = config.costsurfacepath
    startCoord = (config.startX,config.startY)
    stopCoord = (config.stopX,config.stopY)
    outputPathfn = config.outputpath
    main(CostSurfacefn,outputPathfn,startCoord,stopCoord)

when I run testcase.py (below) in the shell, it doesn't run the LCP_02 script:
import config
import LCP_02

if __name__ == "__main__":
    config.startX = 356254.432
    config.startY = 5325191.299
    config.stopX = 346200.101
    config.stopY = 5301688.499
    LCP_02

All the functions in LCP_02 have print statements (as a visual). But when running testcase.py, they are not printed. The program starts, waits around 2 seconds, and then shows the >>> in the shell.

A: There are two reasons it doesn't work:

*

*You imported LCP_02, so the __name__ value in that module is set to 'LCP_02', not '__main__' or '__testcase__'. The name is never based on whatever imported the module.

*Just referencing LCP_02 on a line won't 'invoke' that module; if the guarded code was going to run, it would have done so when importing.
Use a function in LCP_02 instead:
def run_test():
    ask_costsurfacepath_path()
    ask_outputpath_path()
    CostSurfacefn = config.costsurfacepath
    startCoord = (config.startX,config.startY)
    stopCoord = (config.stopX,config.stopY)
    outputPathfn = config.outputpath
    main(CostSurfacefn,outputPathfn,startCoord,stopCoord)

if __name__ == "__main__":
    run_test()

and call that function from your testcase.py module:
LCP_02.run_test()


text:
Q: How to change function of bigPlayButton in video js? I'm showing the bigPlayButton when my video is playing. I want video stop when bigPlayButton is clicked and video play when bigPlayButton is clicked again.
At first, I used $( ".video-js" ).hasClass('vjs-playing') to detect video is playing but it don't work well in mobile.
 var myPlayer = videojs("vod");
 myPlayer.bigPlayButton.on('click', function(){
   if($( ".video-js" ).hasClass('vjs-playing')) {
     myPlayer.pause();
   }
});

Is there any way to change function of bigPlayButton to PlayToggle?


text:
Q: How to eliminate specific brew doctor errors? When I am running brew doctor I am getting the following list of errors.
Is there any way I can eliminate these error reports?
Thank you.
    Please note that these warnings are just used to help the Homebrew maintainers
with debugging if you file an issue. If everything you use Homebrew for is
working fine: please don't worry and just ignore them. Thanks!

Warning: Unbrewed header files were found in /usr/local/include.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected header files:
    /usr/local/include/c-client.h
    /usr/local/include/dummy.h
    /usr/local/include/env.h
    /usr/local/include/env_unix.h
    /usr/local/include/fdstring.h
    /usr/local/include/flockcyg.h
    /usr/local/include/flocksim.h
    /usr/local/include/flstring.h
    /usr/local/include/fs.h
    /usr/local/include/ftl.h
    /usr/local/include/imap4r1.h
    /usr/local/include/layout/LayoutEngine.h
    /usr/local/include/layout/LEFontInstance.h
    /usr/local/include/layout/LEGlyphFilter.h
    /usr/local/include/layout/LEGlyphStorage.h
    /usr/local/include/layout/LEInsertionList.h
    /usr/local/include/layout/LELanguages.h
    /usr/local/include/layout/LEScripts.h
    /usr/local/include/layout/LESwaps.h
    /usr/local/include/layout/LETypes.h
    /usr/local/include/layout/loengine.h
    /usr/local/include/layout/ParagraphLayout.h
    /usr/local/include/layout/playout.h
    /usr/local/include/layout/plruns.h
    /usr/local/include/layout/RunArrays.h
    /usr/local/include/linkage.h
    /usr/local/include/mail.h
    /usr/local/include/mcrypt.h
    /usr/local/include/misc.h
    /usr/local/include/netmsg.h
    /usr/local/include/newsrc.h
    /usr/local/include/nl.h
    /usr/local/include/nntp.h
    /usr/local/include/node/eio-emul.h
    /usr/local/include/node/ev-emul.h
    /usr/local/include/node/uv-private/eio.h
    /usr/local/include/node/uv-private/ev.h
    /usr/local/include/os_a32.h
    /usr/local/include/os_a41.h
    /usr/local/include/os_a52.h
    /usr/local/include/os_aix.h
    /usr/local/include/os_aos.h
    /usr/local/include/os_art.h
    /usr/local/include/os_asv.h
    /usr/local/include/os_aux.h
    /usr/local/include/os_bsd.h
    /usr/local/include/os_bsf.h
    /usr/local/include/os_bsi.h
    /usr/local/include/os_cvx.h
    /usr/local/include/os_cyg.h
    /usr/local/include/os_d-g.h
    /usr/local/include/os_do4.h
    /usr/local/include/os_drs.h
    /usr/local/include/os_dyn.h
    /usr/local/include/os_hpp.h
    /usr/local/include/os_isc.h
    /usr/local/include/os_lnx.h
    /usr/local/include/os_lyn.h
    /usr/local/include/os_mct.h
    /usr/local/include/os_mnt.h
    /usr/local/include/os_nto.h
    /usr/local/include/os_nxt.h
    /usr/local/include/os_os4.h
    /usr/local/include/os_osf.h
    /usr/local/include/os_osx.h
    /usr/local/include/os_ptx.h
    /usr/local/include/os_pyr.h
    /usr/local/include/os_qnx.h
    /usr/local/include/os_s40.h
    /usr/local/include/os_sc5.h
    /usr/local/include/os_sco.h
    /usr/local/include/os_sgi.h
    /usr/local/include/os_shp.h
    /usr/local/include/os_slx.h
    /usr/local/include/os_soln.h
    /usr/local/include/os_solo.h
    /usr/local/include/os_sos.h
    /usr/local/include/os_sua.h
    /usr/local/include/os_sun.h
    /usr/local/include/os_sv2.h
    /usr/local/include/os_sv4.h
    /usr/local/include/os_ult.h
    /usr/local/include/os_vu2.h
    /usr/local/include/osdep.h
    /usr/local/include/php/ext/hash/php_hash_types.h
    /usr/local/include/php/main/logos.h
    /usr/local/include/php/main/php_logos.h
    /usr/local/include/php/TSRM/tsrm_virtual_cwd.h
    /usr/local/include/pseudo.h
    /usr/local/include/rfc822.h
    /usr/local/include/smtp.h
    /usr/local/include/sslio.h
    /usr/local/include/tcp.h
    /usr/local/include/tcp_unix.h
    /usr/local/include/unicode/alphaindex.h
    /usr/local/include/unicode/appendable.h
    /usr/local/include/unicode/basictz.h
    /usr/local/include/unicode/bms.h
    /usr/local/include/unicode/bmsearch.h
    /usr/local/include/unicode/brkiter.h
    /usr/local/include/unicode/bytestream.h
    /usr/local/include/unicode/bytestrie.h
    /usr/local/include/unicode/bytestriebuilder.h
    /usr/local/include/unicode/calendar.h
    /usr/local/include/unicode/caniter.h
    /usr/local/include/unicode/chariter.h
    /usr/local/include/unicode/choicfmt.h
    /usr/local/include/unicode/coleitr.h
    /usr/local/include/unicode/coll.h
    /usr/local/include/unicode/colldata.h
    /usr/local/include/unicode/curramt.h
    /usr/local/include/unicode/currpinf.h
    /usr/local/include/unicode/currunit.h
    /usr/local/include/unicode/datefmt.h
    /usr/local/include/unicode/dbbi.h
    /usr/local/include/unicode/dcfmtsym.h
    /usr/local/include/unicode/decimfmt.h
    /usr/local/include/unicode/docmain.h
    /usr/local/include/unicode/dtfmtsym.h
    /usr/local/include/unicode/dtintrv.h
    /usr/local/include/unicode/dtitvfmt.h
    /usr/local/include/unicode/dtitvinf.h
    /usr/local/include/unicode/dtptngen.h
    /usr/local/include/unicode/dtrule.h
    /usr/local/include/unicode/errorcode.h
    /usr/local/include/unicode/fieldpos.h
    /usr/local/include/unicode/fmtable.h
    /usr/local/include/unicode/format.h
    /usr/local/include/unicode/fpositer.h
    /usr/local/include/unicode/gregocal.h
    /usr/local/include/unicode/icudataver.h
    /usr/local/include/unicode/icuplug.h
    /usr/local/include/unicode/idna.h
    /usr/local/include/unicode/localpointer.h
    /usr/local/include/unicode/locdspnm.h
    /usr/local/include/unicode/locid.h
    /usr/local/include/unicode/measfmt.h
    /usr/local/include/unicode/measunit.h
    /usr/local/include/unicode/measure.h
    /usr/local/include/unicode/messagepattern.h
    /usr/local/include/unicode/msgfmt.h
    /usr/local/include/unicode/normalizer2.h
    /usr/local/include/unicode/normlzr.h
    /usr/local/include/unicode/numfmt.h
    /usr/local/include/unicode/numsys.h
    /usr/local/include/unicode/parseerr.h
    /usr/local/include/unicode/parsepos.h
    /usr/local/include/unicode/platform.h
    /usr/local/include/unicode/plurfmt.h
    /usr/local/include/unicode/plurrule.h
    /usr/local/include/unicode/ptypes.h
    /usr/local/include/unicode/putil.h
    /usr/local/include/unicode/rbbi.h
    /usr/local/include/unicode/rbnf.h
    /usr/local/include/unicode/rbtz.h
    /usr/local/include/unicode/regex.h
    /usr/local/include/unicode/rep.h
    /usr/local/include/unicode/resbund.h
    /usr/local/include/unicode/schriter.h
    /usr/local/include/unicode/search.h
    /usr/local/include/unicode/selfmt.h
    /usr/local/include/unicode/simpletz.h
    /usr/local/include/unicode/smpdtfmt.h
    /usr/local/include/unicode/sortkey.h
    /usr/local/include/unicode/std_string.h
    /usr/local/include/unicode/strenum.h
    /usr/local/include/unicode/stringpiece.h
    /usr/local/include/unicode/stringtriebuilder.h
    /usr/local/include/unicode/stsearch.h
    /usr/local/include/unicode/symtable.h
    /usr/local/include/unicode/tblcoll.h
    /usr/local/include/unicode/timezone.h
    /usr/local/include/unicode/tmunit.h
    /usr/local/include/unicode/tmutamt.h
    /usr/local/include/unicode/tmutfmt.h
    /usr/local/include/unicode/translit.h
    /usr/local/include/unicode/tzfmt.h
    /usr/local/include/unicode/tznames.h
    /usr/local/include/unicode/tzrule.h
    /usr/local/include/unicode/tztrans.h
    /usr/local/include/unicode/ubidi.h
    /usr/local/include/unicode/ubrk.h
    /usr/local/include/unicode/ucal.h
    /usr/local/include/unicode/ucasemap.h
    /usr/local/include/unicode/ucat.h
    /usr/local/include/unicode/uchar.h
    /usr/local/include/unicode/ucharstrie.h
    /usr/local/include/unicode/ucharstriebuilder.h
    /usr/local/include/unicode/uchriter.h
    /usr/local/include/unicode/uclean.h
    /usr/local/include/unicode/ucnv.h
    /usr/local/include/unicode/ucnv_cb.h
    /usr/local/include/unicode/ucnv_err.h
    /usr/local/include/unicode/ucnvsel.h
    /usr/local/include/unicode/ucol.h
    /usr/local/include/unicode/ucoleitr.h
    /usr/local/include/unicode/uconfig.h
    /usr/local/include/unicode/ucsdet.h
    /usr/local/include/unicode/ucurr.h
    /usr/local/include/unicode/udat.h
    /usr/local/include/unicode/udata.h
    /usr/local/include/unicode/udateintervalformat.h
    /usr/local/include/unicode/udatpg.h
    /usr/local/include/unicode/uenum.h
    /usr/local/include/unicode/uidna.h
    /usr/local/include/unicode/uiter.h
    /usr/local/include/unicode/uldnames.h
    /usr/local/include/unicode/uloc.h
    /usr/local/include/unicode/ulocdata.h
    /usr/local/include/unicode/umachine.h
    /usr/local/include/unicode/umisc.h
    /usr/local/include/unicode/umsg.h
    /usr/local/include/unicode/unifilt.h
    /usr/local/include/unicode/unifunct.h
    /usr/local/include/unicode/unimatch.h
    /usr/local/include/unicode/unirepl.h
    /usr/local/include/unicode/uniset.h
    /usr/local/include/unicode/unistr.h
    /usr/local/include/unicode/unorm.h
    /usr/local/include/unicode/unorm2.h
    /usr/local/include/unicode/unum.h
    /usr/local/include/unicode/uobject.h
    /usr/local/include/unicode/upluralrules.h
    /usr/local/include/unicode/uregex.h
    /usr/local/include/unicode/urename.h
    /usr/local/include/unicode/urep.h
    /usr/local/include/unicode/ures.h
    /usr/local/include/unicode/uscript.h
    /usr/local/include/unicode/usearch.h
    /usr/local/include/unicode/uset.h
    /usr/local/include/unicode/usetiter.h
    /usr/local/include/unicode/ushape.h
    /usr/local/include/unicode/uspoof.h
    /usr/local/include/unicode/usprep.h
    /usr/local/include/unicode/ustdio.h
    /usr/local/include/unicode/ustream.h
    /usr/local/include/unicode/ustring.h
    /usr/local/include/unicode/ustringtrie.h
    /usr/local/include/unicode/utext.h
    /usr/local/include/unicode/utf.h
    /usr/local/include/unicode/utf16.h
    /usr/local/include/unicode/utf32.h
    /usr/local/include/unicode/utf8.h
    /usr/local/include/unicode/utf_old.h
    /usr/local/include/unicode/utmscale.h
    /usr/local/include/unicode/utrace.h
    /usr/local/include/unicode/utrans.h
    /usr/local/include/unicode/utypes.h
    /usr/local/include/unicode/uvernum.h
    /usr/local/include/unicode/uversion.h
    /usr/local/include/unicode/vtzone.h
    /usr/local/include/unix.h
    /usr/local/include/utf8.h
    /usr/local/include/utf8aux.h

A: It looks like you've manually downloaded and compiled something that has dropped files in /usr/local (I'm guessing a mail server). If you don't need it you could remove the files it has deposited in /usr/local.
At the same time, as the message says this is only a warning, not an error message. The only time you really need to worry about this is if you are having trouble compiling software with brew. If everything is compiling okay then don't worry about it.

A: I guess you installed node.js before. Try this, search in Terminal /usr/local/include and delete all stuffs.

A: For these types of warnings specifically, you could probably use a custom installation prefix. The homebrew installation instructions (2016 Apr 3 permalink) say you can do that, but warn against it. In practice I've heard that issues are quite rarely encountered.


text:
Q: Check file size before uploading I have a problem when I upload a file in ASP.NET MVC. My code is below:
public class RegisterForm
    {

        #region Ctor
        public RegisterForm()
        {

        }

        #endregion Ctor

        #region Properties

        [Key]
        [Required]
         public int ID { get; set; }

        [StringLength(50, ErrorMessage = " error")]
        [TypeConverter("NVarchar(121)")]
        public string FullName { get; set; }

        [RegularExpression(@"^[0-9]*$", ErrorMessage = "enter number")]
        [Remote("IsUserExists", "RegisterForms", ErrorMessage = "  ")]
        [StringLength(10, MinimumLength = 10, ErrorMessage = " length:10")]
        public String Mellicode { get; set; }

        [AllowFileSize(FileSize = 100 * 1024, ErrorMessage = "size:100kb")]
         //upload
        public string FilePathName { get; set; }

}

AllowFileSize  Notapply for FilePathName :
code AllowFileSize
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class AllowFileSizeAttribute: ValidationAttribute
    {
        public int FileSize { get; set; } = 100 * 1024 ;

        public override bool IsValid(object value)
        {
            // Initialization
            HttpPostedFileBase file = value as HttpPostedFileBase;
            bool isValid = true;

            // Settings.
            int allowedFileSize = this.FileSize;

            // Verification.
            if (file != null)
            {
                // Initialization.
                var fileSize = file.ContentLength;

                // Settings.
                isValid = fileSize <= allowedFileSize;
            }

            // Info
            return isValid;
        }

    }

I used to uploadhelper:
public static class UploadHelper
{
    public static MvcHtmlString Upload(this HtmlHelper helper, string name, object htmlAttributes = null)
    {
        //helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression))
        TagBuilder input = new TagBuilder("input");
        input.Attributes.Add("type", "file");
        input.Attributes.Add("id", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(name));
        input.Attributes.Add("name", helper.ViewData.TemplateInfo.GetFullHtmlFieldName(name));
    if (htmlAttributes != null)
    {
        var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
        input.MergeAttributes(attributes);
    }

    return new MvcHtmlString(input.ToString());
}

}
controller:
public ActionResult Create([Bind(Include = "ID,FullName,Mellicode,FilePathName")] RegisterForm registerForm, HttpPostedFileBase UploadFile)
        {
            var myUniqueFileName = string.Format(@"{0}.txt", Guid.NewGuid());
        if (ModelState.IsValid)
        {

           string strFileExtension = System.IO.Path.GetExtension(UploadFile.FileName).ToUpper();

            string strContentType = UploadFile.ContentType.ToUpper();

            if ((UploadFile == null
            || (UploadFile.ContentLength == 0)
            || (UploadFile.ContentLength > 100 * 1024)))

            {
                                 return View("Error");
            }

            else
            {
                registerForm.FilePathName = myUniqueFileName + UploadFile.FileName;

                string strPath = Server.MapPath("~") + "App_Data\\";

                if (System.IO.Directory.Exists(strPath) == false)
                {
                    System.IO.Directory.CreateDirectory(strPath);
                }

                string strPathName =
                    string.Format("{0}\\{1}", strPath, registerForm.FilePathName);

                UploadFile.SaveAs(strPathName);
            }

            db.Registers.Add(registerForm);
            db.SaveChanges();
            return RedirectToAction("Back");
        }
        return View(registerForm);
    }

Create.cshtml:
@using (Html.BeginForm("Create", "RegisterForms", FormMethod.Post, new { enctype = "multipart/form-data", id = "UploadForm" }))
        {
            @Html.AntiForgeryToken()
        <form>
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                    @Html.LabelFor(model => model.FullName, htmlAttributes: new { @class = "control-label col-md-10" })

                        @Html.EditorFor(model => model.FullName, new { htmlAttributes = new { @class = "form-control"
                    }
                })
                        @Html.ValidationMessageFor(model => model.FullName, "", new { @class = "text-danger" })

                    @Html.LabelFor(model => model.Mellicode, htmlAttributes: new { @class = "control-label col-md-10" })

                        @Html.EditorFor(model => model.Mellicode, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Mellicode, "", new { @class = "text-danger" })

                    @Html.LabelFor(model => model.FilePathName, htmlAttributes: new { @class = "control-label col-md-10" })

                        @Html.Upload("UploadFile", new { htmlAttributes = new { @class = "form-control ", type = "file", id = "upload-id" } })

@Html.ValidationMessageFor(model => model.FilePathName, "", new { @class = "text-danger" })

                <input type="submit" style="   margin-right:25%" OnClientClick="return checkfile();" class="btn btn-info btn-lg   btn-responsive" id="search" value="send"   />

        </form>

}


text:
Q: Another 'NSUInteger *' (aka 'unsigned int *') vs 'NSUInteger' (aka 'unsigned int') I have the following instance method which should be returning a NSUInteger:
    - (NSUInteger)getCurAnsPos {

    NSUInteger CAP = 999;
    NSArray *curCAS = [[GameData gameData].curData valueForKey:@"clueAnsState"];
    for (NSInteger idx = 0; idx < 8; idx++) {
        NSString *temp = [curCAS objectAtIndex:idx];
        if ([temp isEqualToString:@"2"]) {
            CAP = [curCAS indexOfObject:temp];
            NSLog(@"CAP = ");
            NSLog(@"%i", CAP);
        } // only one curCAS should be = 2
    }
    return CAP;
}

I get the error in the question title.  The value of CAP computed is correct, but the return type is apparently wrong.  I don't see why.  I know this has to do with pointers vs primitives, but after reading the SO archives I thought this should work.  It may be that CAP = [curCAS indexOfObject:temp]; returns CAP as a pointer (really, it must be), but I still don't see how to change it.  What I need back is something I can use in an objectAtIndex:CAP statement.  Thanks.

A: This code doesn't make a lot of sense to me:
    NSString *temp = [curCAS objectAtIndex:idx];
    if ([temp isEqualToString:@"2"]) {
        CAP = [curCAS indexOfObject:temp];
        NSLog(@"CAP = ");
        NSLog(@"%i", CAP);
    } // only one curCAS should be = 2

temp is the object at index idx
if temp == "2" then CAP is the index of the object temp (which must be idx, so that operation is unnecessary)
And that method does return a number, not a pointer to a number: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/doc/uid/20000137-BABDHGFB


text:
Q: How to round to the nearest fourth I'm looking for a way to round a number to nearest number that can be divided by 4 without remainder

A: num = std::round(num / 4.0) * 4.0;

A: Here is some pseudo code.  Probably not the most efficient way, but...
if num mod 4 == 0 then you are good
if num mod 4 == 1 then subtract 1
if num mod 4 == 2 then you decide (subtract/add 2)
if num mod 4 == 3 then add 1

A: Use the following MACRO:
#define ALIGN4(len) (((len) + 3) & ~3) // round up to 4 items


text:
Q: Embedding HTML code in Power Automate table I have a Power Automate flow that uses the "Create HTML Table" function as one of its steps. One of the fields in the table is a URL address. The latter can be quite long and makes the display of the table in the email to which it is sent quite crowded. The link appears as the full address. I would prefer to have a label displayed so that when it's clicked the reader gets sent to the underlying link. I know how to create a labeled link in a regular HTML page. However, I'm trying various ways to embed the labeled URL into the table created by Create HTML Table. For example, I've something like this: Click for Google. The table that is generated shows the link but ignores the label section.
Any advice?

A: Assuming you want to use the table in the email, it should be all done with HTML tags.

*

*You need to built that HTML code for link, expression inside "Create HTML table" might look like this:

concat('Short Name for link')

Concat function connect multiple strings together. In the example it
connects first part of HTML tag, inserting dynamic content body()?['{Link}'], and rest of the HTML tag.

HTML table will not allow you to add another HTML tags as it could break the table. It will end up as a plain text in the email body + It will replace < with <  ||  > with >  ||  " with "

*You must replace those characters back. - In Email body insert this Expression:

replace(replace(replace(body('Create_HTML_table'),'<','<'),'>','>'),'"','"')

now the table will display correct short URL links in the email as desired.


text:
Q: Como armazenar valores a cada interação durante a repetição de uma estrutura - Python lista= ["2,55","3,4","3,83","5,1","6,8"]

for i in range(len(lista)):

    lista[i] = lista[i]

    #PREEENCHER VALOR

    navegador.find_element_by_xpath('...').send_keys(lista[i])
    time.sleep(3)
    #obter valor #
    valor = navegador.find_element_by_xpath('...')
    valor = valor.text[:-3].replace(',', '.')

Gostaria de armazenar cada valor gerado para cada interação feita.

A: Se eu entendi bem a pergunta, você deve criar uma nova lista para armazenar os valores gerados.
Crie uma nova variável de valor lista vazia.
Exemplo:
valores = []
...
valor = valor.text[:-3].replace(',', '.')
valores.append(valor)

Infelizmente, não consigo entender seu código exatamente, as variáveis não estão no escopo desse código, não sei de onde vem usinas, por exemplo.


text:
Q: How to override the hostname that DHCP configures on a CentOS7 box in AWS? The title nearly says it all.  I have a VM in EC2 running CentOS 7. It uses DHCP, which seems to be a EC2 requirement.  DHCP keeps overwriting the hostname on reboot, no matter what I try.  I won't enumerate it, but I've tried pretty much every suggestion here: Override DHCP hostname on RHEL5/CentOS/Amazon Linux as well as those found on several other sites that google searches turned up.  I don't understand if it's the particular OS version or AWS/EC2 environment, but I can't change the hostname and make it stick across reboots.  Even brute forcing it via /etc/rc.d/rc.local (adding "/bin/hostnamectl set-hotname foo.bar.baz" did not work.  I can't believe other AWS/EC2 users haven't figured this out.  Please help.
Update:
This also does not work: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-hostname.html I.e., adding a DNS A record for the box in AWS's Route53 (and verifying it works), and setting HOSTNAME=foo.bar.baz in /etc/sysconfig/network (checking after a reboot) is also futile.
Update 2:
A similar question was answered for Fedora 20. The accepted solution there also involved reconfiguring cloud-init, though in a different manner. Also, it wasn't clear that that question/solution applies to other distros. Thus, I feel my question should probably remain for others running CentOS and searching for it that way (yes, I know Fedora and CentOS are siblings, but not everyone googles for all synonyms when searching for solutions).

A: Alright. I spent probably a total of five hours on this problem before arriving at an answer. @Sirex's suggestion to uninstall cloud-init was the clue.  Essentially, cloud-init is a service built into most EC2 images (AMIs), including AMI Linux and CentOS.  The system does lots of things (google it), and is probably useful for certain provisioning and maintenance foo. Thus, I am hesitant to simply disable it. But, it also appears to be setting the EC2 hostname.  So, to override that with your preferred hostname, simply do this:
(1) create a file called something like 99_...cfg (I named mine 99_hostname.cfg), and write the following contents into it:
#cloud-config
hostname: foo
fqdn: foo.bar.baz

replacing "foo" and "foo.bar.baz" with your host name and fully-qualified domain name, of course.
(2) Place this file in /etc/cloud/cloud.cfg.d/99_hostname.cfg
(3) Make sure the file permissions/owner/selinux context (if you have SELinux enforcing) are set properly via these commands:
sudo su -
cd /etc/cloud/cloud.cfg.d/
chown root: 99_hostname.cfg
chmod 644 99_hostname.cfg
chcon system_u:object_r:etc_t:s0 99_hostname.cfg

(4) Reboot your VM, and the new hostname should be set. If you don't trust your bash prompt, you can check this, by, for example, executing either of the following:
hostnamectl

or
cat /etc/hostname

A: uninstall cloud-init.
This drove me mental the first time :-)
Still looking to find time to work out how to make cloud-init set the hostname as expected (from a tag or such) - not got that far myself yet.


text:
Q: Read a memory stream I have serialize class with 7 variable which are being written to a memory stream and then inserted into a database field. The 7 variable are all four bytes and there may be hundreds of records combined together before being written to the database. This works successfully.
However when I get the data back from the database and deserialize it:
    rdr = cmd.ExecuteReader
    While rdr.Read()
        arr = rdr("BINPROFILE")
        ms.Write(arr, 0, arr.Length)
        ms.Position = 0
        SER = bf.Deserialize(ms)
    End While

My variable 'SER' which an implementation of the class containing the 7 variables, only reads the first 7 variables.
How do I loop through an entire memory stream and read all the data it contains?

A: SER is overwritten in every iteration of the loop leaving you with just the value from the last record.  You need to save these in a array or list or work with then within the loop.
SER = bf.Deserialize(ms)

This line will replace whatever was in the SER variable with a new value, in your case, the 7 variables.


text:
Q: Why 'tf.python_io.TFRecordWriter' is so SLOW and STORAGE-CONSUMING in TensorFlow? I'm going to write to TFRecord file using this code:
  writer = tf.python_io.TFRecordWriter(output_filename)
  print("Creating TFRecords file at {}...".format(output_filename))
  for i, row in enumerate(create_csv_iter(input_filename)):
    x = example_fn(row)
    writer.write(x.SerializeToString())
writer.close()

The problem is that this process is very slow, such that it's not feasible to write a large dataset even in days!
It's just a writer that serialize to disk. Why it's so slow?! Another problem is that the size of the output file is 10 times greater than the original file!
Do you know any way to speed up the process of TFRecordWriter and compress the result?

A: I don't know about the speed issue, but you can compress after the fact - TFRecordReader supports GZIP and ZLIB compression, e.g.
    reader = tf.TFRecordReader(
        options=tf.python_io.TFRecordOptions(
            compression_type=tf.python_io.TFRecordCompressionType.ZLIB
        )
    )
    _, tfrecord = reader.read(file_queue)
    # etc.

See more here. Decompression takes a bit of time, but you only really notice it at the start if you're using the TF batching system (so a CPU core can be decompressing and filling your queue while the GPU works away, etc.).

A: I had a similar problem when the dataset I wanted to use was expensive to create and preprocess.
Using TFRecordWriter was incredibly slow, so instead I used the caching option available on Dataset objects.
ds.cache('./cache/train.cache').repeat().batch(32).prefetch(1)

The files created are about the same size as those created by TFRRecordWriter, but they're created at the sort of speed you'd expect.
Plus, when you relaunch your notebook, for example, if the files are still available, they're used automatically.


text:
Q: Consultar em todas as tabelas do banco de dados É possível fazer uma consulta em todas as tabelas que contenham a mesma coluna os seus respectivos valores?
Por exemplo, eu tenho o Banco chamado SGE, nele possuo 230 tabelas, sendo que todas essas tabelas possuem a coluna CodPRF e eu quero que a Query me retorne todos o resultados em que as tabelas possuam a coluna com o valor do CodPRF sendo igual a 101.
Pensei em algo parecido com isso (apenas um exemplo pra ver se ajuda melhor no entendimento do problema por parte de vocês):
SELECT TOP (1000) [ALL_Collums]
FROM   [SGE_TESTE].[dbo].[ALL_Tables]
WHERE  CODPRF = '101'

A: Isto aqui resolveu o meu problema.
DECLARE @TabNome VARCHAR(256)
DECLARE @ColNome VARCHAR(256)
DECLARE @Resultado TABLE(TabNome VARCHAR(MAX), ColNome VARCHAR(MAX))
DECLARE Colunas CURSOR FOR

--Busca todas as colunas de todas as tabelas

SELECT COL.Name, TAB.Name
FROM SYS.Columns COL
  INNER JOIN SYS.Tables TAB ON TAB.Object_Id = COL.Object_Id
  INNER JOIN SYS.Types TYP ON COL.System_Type_Id = TYP.System_Type_Id
WHERE TYP.Name = 'uniqueidentifier'
                        /*-–filtra o tipo de dado que você procura para
                        --evitar a procura de uma string em um inteiro*/

ORDER BY TAB.Name
OPEN Colunas

FETCH NEXT FROM Colunas INTO @ColNome, @TabNome

WHILE @@FETCH_STATUS = 0

BEGIN

      EXEC('Select * From ' + @TabNome + ' Where ' + @ColNome + ' Like ''%e5459567-54f6-4792-a3dc-51d5c29a48a0%''') /*–- caso encontre, salva a tabela e a coluna*/

    IF @@RowCount > 0 /*–- caso encontre, salva a tabela e a coluna*/

      BEGIN

            INSERT INTO @Resultado VALUES(@TabNome,@ColNome)

    END

      FETCH NEXT FROM Colunas INTO @ColNome, @TabNome

END

CLOSE Colunas

DEALLOCATE Colunas

SELECT * FROM @Resultado /*–- lista todas as tabelas e suas colunas que*/

Fonte: https://social.msdn.microsoft.com/Forums/pt-BR/3ce127cd-c153-4457-93a7-f32506dfcaf7/preciso-encontrar-um-registro-sem-saber-a-qual-tabela-pertence?forum=520

A: Diretamente não tem, até porque quando isto é necessário é porque tem algo errado na modelagem do banco de dados.
É possível criar um script que leia os metadados do banco de dados (information_schema) pegue as tabelas que tem esta coluna e gere a query que faça em todas tabelas. Só vale a pena se for muitas tabelas. E pode dar um falso positivo dependendo da (in)consistência de nomes usados.
Falo um pouco sobre isto em Colunas "inteligentes" no MySQL.