text:
Q: Error mapping tables to nodejs using typescript i need to map multiple entities using sequelize, and i just don't understand where the error lies. I keep getting " Error: Profesor.hasOne called with something that's not a subclass of Sequelize.Model". How do i fix this ?
Professor model class:
import { Association, NonAttribute, CreationOptional, DatabaseError, DataTypes, InferAttributes, InferCreationAttributes, Model, Optional, Sequelize, HasOneGetAssociationMixin, HasOneCreateAssociationMixin, HasOneSetAssociationMixin, BelongsToGetAssociationMixin, BelongsToSetAssociationMixin, BelongsToCreateAssociationMixin } from 'sequelize'
import sequelize from '../config'
import Clasa from './Clasa';

class Profesor extends Model<InferAttributes<Profesor>, InferCreationAttributes<Profesor>>{
  declare id: CreationOptional<number>;
  declare nume: string;
  declare prenume: string;
  declare CNP: string;
  declare password: string;
  declare id_clasa_dirigentie: CreationOptional<number>;

  declare getClasa: HasOneGetAssociationMixin<Clasa>;
  declare setClasa: HasOneSetAssociationMixin<Clasa, 'id'>;
  declare addClasa: HasOneCreateAssociationMixin<Clasa>;

  declare clasa?: NonAttribute<Clasa>;

  declare static associations: {
    clase: Association<Profesor, Clasa>;
  };
}

Profesor.init(
  {
    id: {
      type: DataTypes.BIGINT,
      autoIncrement: true,
      primaryKey: true
    },
    nume: {
        type: new DataTypes.STRING,
        allowNull: false
    },
    prenume: {
        type: new DataTypes.STRING,
        allowNull: false
    },
    CNP: {
        type: new DataTypes.STRING,
        allowNull: false
    },
    password: {
        type: new DataTypes.STRING,
        allowNull: false
    },
    id_clasa_dirigentie: {
        type: new DataTypes.BIGINT,
    }
},
  {
    tableName: 'profesor',
    sequelize
  }
);
Profesor.hasOne(Clasa, { sourceKey: 'id' });

(async () => {
  await sequelize.sync();
})();

export default Profesor;

Clasa model class:
import { BelongsToCreateAssociationMixin, BelongsToGetAssociationMixin, BelongsToManyCreateAssociationMixin, BelongsToManyGetAssociationsMixin, BelongsToManySetAssociationsMixin, BelongsToSetAssociationMixin, CharDataType, CreationOptional, DatabaseError, DataTypes, InferAttributes, InferCreationAttributes, Model, Optional, Sequelize, SmallIntegerDataType } from 'sequelize'
import sequelize from '../config'
import Materie from './Materie';
import Profesor from './Profesor';
import Student from './Student';

class Clasa extends Model<InferAttributes<Clasa>, InferCreationAttributes<Clasa>>{
  declare id: CreationOptional<number>;
  declare idDiriginte: bigint;
  declare an: SmallIntegerDataType;
  declare litera: CharDataType;

  declare getStudent: BelongsToGetAssociationMixin<Student>;
  declare setStudent: BelongsToSetAssociationMixin<Student, 'id'>;
  declare addStudent: BelongsToCreateAssociationMixin<Student>;

  declare getDiriginte: BelongsToGetAssociationMixin<Profesor>;
  declare setDiriginte: BelongsToSetAssociationMixin<Profesor, 'id'>;
  declare addDiriginte: BelongsToCreateAssociationMixin<Profesor>;

  declare getMaterie: BelongsToManyGetAssociationsMixin<Materie>;
  declare setMaterie: BelongsToManySetAssociationsMixin<Materie,'id'>;
  declare addMaterie: BelongsToManyCreateAssociationMixin<Materie>;

  declare get
}

Clasa.init(
  {
    id: {
      type: DataTypes.BIGINT,
      autoIncrement: true,
      primaryKey: true
    },
    idDiriginte: {
        type: new DataTypes.BIGINT
    },
    an: {
        type: new DataTypes.SMALLINT
    },
    litera: {
        type: new DataTypes.CHAR
    }
},
  {
    tableName: 'clasa',
    sequelize
  }
);
Clasa.belongsTo(Student, {foreignKey: 'id_clasa'});
Clasa.belongsTo(Profesor, {foreignKey: 'id_clasa_dirigentie'});
Clasa.belongsToMany(Materie,{through: 'profesor_clasa', foreignKey:'id_clasa'});
Clasa.belongsToMany(Profesor,{through: 'profesor_clasa', foreignKey:'id_profesor'});

export default Clasa;

index file:
import 'dotenv/config'
import express, {Request,Response,Application} from 'express';
import testConnection from './src/db/config';
import { Sequelize } from 'sequelize';
import Student from './src/db/models/Student';
import Materie from './src/db/models/Materie';
import Profesor from './src/db/models/Profesor';
import Clasa from './src/db/models/Clasa';

require('dotenv').config;

const app:Application = express();
const PORT = process.env.PORT || 8000;

app.get("/", (req:Request, res:Response):void => {
   res.send("Hello Typescript with Node.jsx!")
  async () => {
    const project = await Clasa.findByPk(1);
    if (project === null) {
      console.log('Not found!');
    } else {
      console.log(project instanceof Clasa); // true
}
  }
 });

  app.listen(PORT, ():void => {
    console.log(`Server Running here: https://localhost:${PORT}`);
  });

I've looked for solutions online and they said that putting them together would solve the problem, but that didn't seem to work in my case

A: You need to register associations separately after you initialize all models, see my answer to get an idea of how to do it.


text:
Q: Discord.JS V13 client.on messagecreate not firing I've just recently finished upgrading my Discord.js bot to v13 and now the client.on(messageCreate) function doesn't fire? None of my code in it ever runs and I'm really confused as to why.
Before anybody asks, I have already set my intents.
const client = new Discord.Client({
  intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.DIRECT_MESSAGES ],
  partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
});

I have two functions, the client.on fires but the message doesn't
client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('messageCreate', msg => {
  console.log(anything)
}

A: Make sure you include GUILDS in your list of intents. Otherwise, the bot can only see messages that have been sent after the bot itself sent a message.
In my case, I needed to set these:
partials: ['MESSAGE', 'CHANNEL', 'REACTION']
intents: ['DIRECT_MESSAGES', 'DIRECT_MESSAGE_REACTIONS', 'GUILD_MESSAGES', 'GUILD_MESSAGE_REACTIONS', 'GUILDS']

but the particulars will vary by your use case.

A: You could try replacing your messageCreate with an async option, probably won't fix your issue but you can always try.
client.on('messageCreate', async (message) => {
      console.log("DEBUG");
});

See if there are any errors on your console or does it send "DEBUG" message when you sent a message to the channel that the bot can see.
On my own bot, I do not have partials set, so you probably don't need them either.
Make sure you have also included your discord.js properly, here is example:
const { Client, Intents } = require("discord.js");

redpajama_set_name: RedPajamaStackExchange


text:
Q: HASHBYTES() function usage in Sql server2008 i came to know that Sql server2008 introduce HASHBYTES() which use md5 to encrypt any string like this way Select HASHBYTES( 'md5', 'demo' ) and the the code used to decrypt like this way
Select CONVERT(VARCHAR(MAX), HASHBYTES( 'md5', 'demo' ), 2)

but when i try this second select statement it is showing the value in encrypted format. so how to decrypt the demo as text. thanks

A: It's one way hashing; you can't get back original form. It is not possible to decrypt a hash.
What is the purpose though?
if you are just trying to compare this hash value with some other then you can do something like
IF HASHBYTES('md5', 'demo') = HASHBYTES('md5',@param)
    PRINT 'Match!';

EDIT:
Hashing does not encrypt the original value at all.  Hashing instead applies a one-way mathematical algorithm to the original value, resulting in a binary value.
It's mainly used for storing password. so, the password will be stored in hash format. When user provides credential (id/password); it doesn't decrypt the stored password; rather, user provided password will be hashed with the same algorithm and that hash value will be compared with the stored hash value (as shown a code example above).


text:
Q: flexslider not showing all of the pictures I'm using a flexslider as my slideshow, it seems to be working however it is not picking up all of the images.
Here is the code:

        <?php
       foreach ($dataAttachments as $attachment) {
        ?>

              <img src="<?php echo Calling the image directory;  ?>" />

        <?php

            } ?>

That is how I have the code so far. Is there something that I could be missing?


text:
Q: Performance metrics on SQL Server Profiler and sp_trace commands Are there any metrics available that indicate the varying performance of using MS SQL Profiler against the sp_trace commands on SQL Server 2008.  Most articles and writers seem to suggest that using sp_trace commands would be more efficient but is their any empirical evidence for this under varying workloads.

A: I believe the reason you hear this suggestion is because SQL Server Profiler is merely the GUI front end that runs on top of SQL Trace
From Brad McGeHee's Mastering SQL Server Profiler:

What may be a surprise to many DBAs and developers is that SQL Server
  Profiler is only a GUI designed to work with another feature of SQL
  Server called SQL Trace. It is SQL Trace that is actually doing most
  of the work when it comes to capturing SQL Server events and storing
  them for later use. SQL Trace is a feature of SQL Server that can be
  accessed indirectly with the Profiler GUI, system stored procedures,
  or programmatically using Server Management Objects (SMO).
In essence, SQL Trace is a very simple tool. Its job is just to
  capture SQL Server-related communication between a client and SQL
  Server. It acts similarly to a specialized network sniffer that
  captures traffic on the network related to SQL Server and allows you
  to see exactly which events are being sent from the client to SQL
  Server.


text:
Q: Incompatible pointer types assigning to 'UIColor' from NSString Please check the below code portion and help me to solve the warning..
theGraphSubDataObj2.subDataColor = [self hexStringFromColor:[clrDic valueForKey:key]] ;

    - (NSString *)hexStringFromColor:(UIColor *)color {
    const CGFloat *components = CGColorGetComponents(color.CGColor);

    CGFloat r = components[0];
    CGFloat g = components[1];
    CGFloat b = components[2];

    return [NSString stringWithFormat:@"#%02lX%02lX%02lX",
            lroundf(r * 255),
            lroundf(g * 255),
            lroundf(b * 255)];
}

A: Just Change the below line of code
theGraphSubDataObj2.subDataColor = [clrDic objectForKey:key] ;

As [clrDic valueForKey:key] returns UIColor and subDataColor of Object is also UIColor then we can assign.
You are assigning NSString ([self hexStringFromColor:[clrDic valueForKey:key]])to UIColor (subDataColor of Object)


text:
Q: Weird Redirect/rewrite URL causing 404 issue I am having this weird issue where if I go to any page,
e.g. if I go to a category page, http://wonderna.com/all-products/daily-health/sub-health.html
Contact us page or any other non-category page will have this broken URL
http://wonderna.com/all-products/daily-health/contacts
As you can see "all-products/daily-health" being append to the contacts.
Similarly if I go to customer account page
http://wonderna.com/customer/account/
Then contacts page will be rewrite to http://wonderna.com/customer/account/contacts
There is "customer/account" being append to the contacts page.
Anyone has ever experienced this issue? I am using bitnami's out of box 1.9.2.0 installation (LAMP) + mango theme from themeforest.

A: Look at the HTML source:

联系我们

邮寄配送

产品退换

The problem is href="contacts". This probably comes from a static block, then it should be edited as:
href="{{base url='contacts'}}"

Or if it is in a PHTML template file:
href="<?php echo Mage::getBaseUrl() ?>contacts"

To be honest, if this is really an out of the box installation with this theme, this speaks for very low quality of the theme.


text:
Q: SVN - how to apply change made in trunk to all branches I am a beginner in SVN.I have the SVN directory structure like this:
|-trunk
  |-file1.php
  |-file2.php
|-branches
  |-branch_1
    |-file1.php
    |-file2.php
  |-branch_2
    |-file1.php
    |-file2.php

In the trunk I have the main version of my application. I have two branches for different clients which have the modifications only in some files. When I find some core bug I fix it in trunk. For example I modified the file1.php in trunk directory. I want to apply changes to the files named file1.php in all the branches.
I am little confused. In the Version Control with Subversion I have found the following explanation.

Subversion's repository has a special
  design. When you copy a directory, you
  don't need to worry about the
  repository growing huge—Subversion
  doesn't actually duplicate any data.
  Instead, it creates a new directory
  entry that points to an existing tree.

So I though that when I commit a change in the file trunk\file1.php it will be automaticaly aplied to the other file1.php files as I didn't make any changes to that files in branches directory.
How can I apply changes from trunk directory to all the branches? I was trying to use svn merge like this:
svn merge -r 31:32 http://mysvnserver.com/project/branches/branch_1

but I didn't do any changes (svn diff -r 31:32 returns all the changes I made.)

A: cd workingcopy
svn merge -r 31:32 http://mysvnserver.com/project/trunk branches/branch_1
svn merge -r 31:32 http://mysvnserver.com/project/trunk branches/branch_2
svn commit -m "Merged r32 into branches"

A: If you want to apply a change from trunk to branch_1, the merge command needs to specify where to get the diff from, and then specify a target to apply the merge to:
cd branch_1
svn merge -r 31:32 http://mysvnserver.com/project/trunk .
svn diff   # confirm that the only diff is your change to file1.php
svn commit

A: Try:
svn merge -r 31:32 http://mysvnserver.com/project/trunk branch_1

where branch_1 is your local working directory of the branch.  That is, first you have the source address, and then the destination, which must be local.


text:
Q: how to use dispatch_async I implemented a thread with dispatch, but the code works fine, but the progress UI does not work
This is my code
@interface thirdController () {
    float progress;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    progress = 0.0;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self progressDeny];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setProgress];
        });
    });
}

progressDeny
- (void)progressDeny {
    while (1) {
        if (progress >= 0 && progress <= 1.0) {
            NSLog(@"progress - 0.005!");
            progress -= 0.005;
            usleep(100000);
        }
    }
}

setProgress
- (void)setProgress {
    NSLog(@"%f", progress);
    [clickedProgress setProgress:progress animated:YES];
}

I saw this
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Thread
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
    });
});

Why is the ui update part not working?

A: First, the sleep time in your progressDeny method is a bit long, so you can make it smaller. Second, the while (1){} in your progressDeny method is a endless loop   and the method never returns, you can try to change it like this, for example:
- (void)progressDeny {
        if (progress >= 0 && progress <= 1.0) {
            NSLog(@"progress - 0.005!");
            progress -= 0.005;
            usleep(10);
        }
}

A: The code is not working fine if the purpose of it is present progress view & update its value. You made at least 2 bugs to make progress view work.
Let take a look into your code:
First, you init progress with 0.0
progress = 0.0;

Then, inside progressDeny, you subtracted it if it is equal to 0 & did not provide any way to exit the loop. This will ended up being run once then stuck in doing-nothing infinite loop.
- (void)progressDeny {
    while(1) {
        if (progress >= 0 && progress <= 1.0) {
            // Did you mean: progress += 0.005 ?
            progress -= 0.005;
            // ...
        }
    }
}

Now, let refactor your code to make it work:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    while (progress <= 1.0) {
        progress += 0.005;
        dispatch_async(dispatch_get_main_queue(), ^{
            [clickedProgress setProgress:progress];
        });
        usleep(100000);
    }
});

Or you can make it with NSTimer instead of GCD:
[NSTimer scheduledTimerWithTimeInterval:0.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
    if (progress <= 1.0) {
        progress += 0.005;
        [clickedProgress setProgress:progress];
    } else {
        [timer invalidate];
        timer = nil;
    }
}];


text:
Q: NIntegrate outputs huge value compared to expected I'm trying to replicate something that my professor has done. He's done this on the software MATHCAD but I'm more familiar with Mathematica.
p=0.03

Rxxn[a_, b_, t_] := (p^2 (a - b))/(Sqrt[(a - b)^2 + t^2 + p^2] ((a - b)^2 + t^2)) + (a - b)/Sqrt[(a - b)^2 + t^2 + p^2]  + (a - b)/Sqrt[(a - b)^2 + t^2]
Rxxnavg[a_, t_, k_?NumericQ] := (Rxxn[a, 0.5, t] - Rxxn[a, -0.5, t]) *Cos[k t]
Rxx[a_?NumericQ] := NIntegrate[Rxxnavg[a, t, 0], {t, 0, \[Infinity]}]
Rxx[0]

I get the following error:
During evaluation of In[23]:= NIntegrate::ncvb: NIntegrate failed to converge to prescribed accuracy after 9 recursive bisections in t near {t} = {6.13224*10^28}. NIntegrate obtained -47117.7 and 39303.336387089155` for the integral and error estimates.
Out[26]= -47117.7
According to what he's done we are expected to find that Rxx[0] is close to -1. However I get this answer. I'm not sure how to remedy this.

A: MMA says the integral diverges for real $p$, like this:
r1 = (p^2 (a - b))/(Sqrt[(a - b)^2 + t^2 + p^2] ((a - b)^2 +
        t^2)) + (a - b)/Sqrt[(a - b)^2 + t^2 + p^2] + (a - b)/
    Sqrt[(a - b)^2 + t^2];

r2 = ( (r1 /. b -> 1/2) - (r1 /. b -> -1/2) )*Cos[k t];

r3 = r2 /. k -> 0 /. a -> 0;

s = Integrate[r3, {t, 0, τ}, Assumptions -> {τ > 0, Im[p] == 0}];
s // TeXForm

$$-\frac{1}{2} \log \left(\frac{4
   \tau  \left(\sqrt{4 p^2+4 \tau
   ^2+1}+2 \tau \right)+4 p^2+1}{4
   p^2+1}\right)-\\2 p \tan
   ^{-1}\left(\frac{2 p \tau
   }{\sqrt{p^2+\tau
   ^2+\frac{1}{4}}}\right)-\sinh
   ^{-1}(2 \tau )$$
And then, Limit[s, τ -> ∞] evaluates to $-\infty$.


text:
Q: Trying to get value from hash table in C returns some random value instead of value I am using a hash table library in C, but it seems that whenever I retrieve the value of some key in a different function than where I entered the key-value pair, I get some random value instead of the actual value.
If I get a value from the hash table using a key within the same function that I placed it, everything works fine. But, when I place the key-value pair into the hashtable in one function and then try to retrieve it in another function, it spits out a random new value each time instead of the expected value. I have tried 3 different libraries (GNU Hash table, UTHash, and Ben Hoyt's Implementation, all of which I link below) and none of them work across functions. I assume this is not a problem with the libraries, then, and something wrong with how I am retrieving the values. I have included a screenshot below of what the code and output looks like, and the current code I am using for the hash table.

ht.c:
#include "ht.h"

#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

// Hash table entry (slot may be filled or empty).
typedef struct {
    const char* key;  // key is NULL if this slot is empty
    void* value;
} ht_entry;

#define INITIAL_CAPACITY 16  // must not be zero

// Hash table structure: create with ht_create, free with ht_destroy.
typedef struct ht {
    ht_entry* entries;  // hash slots
    size_t capacity;    // size of _entries array
    size_t length;      // number of items in hash table
};

ht* ht_create(void) {
    // Allocate space for hash table struct.
    ht* table = malloc(sizeof(ht));
    if (table == NULL) {
        return NULL;
    }
    table->length = 0;
    table->capacity = INITIAL_CAPACITY;

    // Allocate (zero'd) space for entry buckets.
    table->entries = calloc(table->capacity, sizeof(ht_entry));
    if (table->entries == NULL) {
        free(table); // error, free table before we return!
        return NULL;
    }
    return table;
}

void ht_destroy(ht* table) {
    // First free allocated keys.
    for (size_t i = 0; i < table->capacity; i++) {
        if (table->entries[i].key != NULL) {
            free((void*)table->entries[i].key);
        }
    }

    // Then free entries array and table itself.
    free(table->entries);
    free(table);
}

#define FNV_OFFSET 14695981039346656037UL
#define FNV_PRIME 1099511628211UL

// Return 64-bit FNV-1a hash for key (NUL-terminated). See description:
// https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function
static uint64_t hash_key(const char* key) {
    uint64_t hash = FNV_OFFSET;
    for (const char* p = key; *p; p++) {
        hash ^= (uint64_t)(unsigned char)(*p);
        hash *= FNV_PRIME;
    }
    return hash;
}

void* ht_get(ht* table, const char* key) {
    // AND hash with capacity-1 to ensure it's within entries array.
    uint64_t hash = hash_key(key);
    size_t index = (size_t)(hash & (uint64_t)(table->capacity - 1));

    // Loop till we find an empty entry.
    while (table->entries[index].key != NULL) {
        if (strcmp(key, table->entries[index].key) == 0) {
            // Found key, return value.
            return table->entries[index].value;
        }
        // Key wasn't in this slot, move to next (linear probing).
        index++;
        if (index >= table->capacity) {
            // At end of entries array, wrap around.
            index = 0;
        }
    }
    return NULL;
}

// Internal function to set an entry (without expanding table).
static const char* ht_set_entry(ht_entry* entries, size_t capacity,
        const char* key, void* value, size_t* plength) {
    // AND hash with capacity-1 to ensure it's within entries array.
    uint64_t hash = hash_key(key);
    size_t index = (size_t)(hash & (uint64_t)(capacity - 1));

    // Loop till we find an empty entry.
    while (entries[index].key != NULL) {
        if (strcmp(key, entries[index].key) == 0) {
            // Found key (it already exists), update value.
            entries[index].value = value;
            return entries[index].key;
        }
        // Key wasn't in this slot, move to next (linear probing).
        index++;
        if (index >= capacity) {
            // At end of entries array, wrap around.
            index = 0;
        }
    }

    // Didn't find key, allocate+copy if needed, then insert it.
    if (plength != NULL) {
        key = strdup(key);
        if (key == NULL) {
            return NULL;
        }
        (*plength)++;
    }
    entries[index].key = (char*)key;
    entries[index].value = value;
    return key;
}

// Expand hash table to twice its current size. Return true on success,
// false if out of memory.
static bool ht_expand(ht* table) {
    // Allocate new entries array.
    size_t new_capacity = table->capacity * 2;
    if (new_capacity < table->capacity) {
        return false;  // overflow (capacity would be too big)
    }
    ht_entry* new_entries = calloc(new_capacity, sizeof(ht_entry));
    if (new_entries == NULL) {
        return false;
    }

    // Iterate entries, move all non-empty ones to new table's entries.
    for (size_t i = 0; i < table->capacity; i++) {
        ht_entry entry = table->entries[i];
        if (entry.key != NULL) {
            ht_set_entry(new_entries, new_capacity, entry.key,
                         entry.value, NULL);
        }
    }

    // Free old entries array and update this table's details.
    free(table->entries);
    table->entries = new_entries;
    table->capacity = new_capacity;
    return true;
}

const char* ht_set(ht* table, const char* key, void* value) {
    assert(value != NULL);
    if (value == NULL) {
        return NULL;
    }

    // If length will exceed half of current capacity, expand it.
    if (table->length >= table->capacity / 2) {
        if (!ht_expand(table)) {
            return NULL;
        }
    }

    // Set entry and update length.
    return ht_set_entry(table->entries, table->capacity, key, value,
                        &table->length);
}

size_t ht_length(ht* table) {
    return table->length;
}

hti ht_iterator(ht* table) {
    hti it;
    it._table = table;
    it._index = 0;
    return it;
}

bool ht_next(hti* it) {
    // Loop till we've hit end of entries array.
    ht* table = it->_table;
    while (it->_index < table->capacity) {
        size_t i = it->_index;
        it->_index++;
        if (table->entries[i].key != NULL) {
            // Found next non-empty item, update iterator key and value.
            ht_entry entry = table->entries[i];
            it->key = entry.key;
            it->value = entry.value;
            return true;
        }
    }
    return false;
}

ht.h:
// Simple hash table implemented in C.

#ifndef _HT_H
#define _HT_H

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

// Hash table structure: create with ht_create, free with ht_destroy.
typedef struct ht ht;

// Create hash table and return pointer to it, or NULL if out of memory.
ht* ht_create(void);

// Free memory allocated for hash table, including allocated keys.
void ht_destroy(ht* table);

// Get item with given key (NUL-terminated) from hash table. Return
// value (which was set with ht_set), or NULL if key not found.
void* ht_get(ht* table, const char* key);

// Set item with given key (NUL-terminated) to value (which must not
// be NULL). If not already present in table, key is copied to newly
// allocated memory (keys are freed automatically when ht_destroy is
// called). Return address of copied key, or NULL if out of memory.
const char* ht_set(ht* table, const char* key, void* value);

// Return number of items in hash table.
size_t ht_length(ht* table);

// Hash table iterator: create with ht_iterator, iterate with ht_next.
typedef struct {
    const char* key;  // current key
    void* value;      // current value

    // Don't use these fields directly.
    ht* _table;       // reference to hash table being iterated
    size_t _index;    // current index into ht._entries
} hti;

// Return new hash table iterator (for use with ht_next).
hti ht_iterator(ht* table);

// Move iterator to next item in hash table, update iterator's key
// and value to current item, and return true. If there are no more
// items, return false. Don't call ht_set during iteration.
bool ht_next(hti* it);

#endif // _HT_H

GNU C: https://www.gnu.org/software/libc/manual/html_node/Hash-Search-Function.html
UTHash: https://troydhanson.github.io/uthash/
Ben Hoyt: https://benhoyt.com/writings/hash-table-in-c/
Thank you for any help.

A: Looking at your screenshot, I see:
void *data = &i;

This is storing the address of a variable that exists on the stack inside your test_hashtable function.  When you store that pointer in your hash table and then the function exits, you cannot rely on the data it points at.  The data is gone, and the memory may be used for something else.
So what you've encountered is undefined behavior.  If you wish to store an int value then you'll need to either allocate memory for it or actually jam it into the pointer (which is a fairly common practice for any data types that fit inside a pointer).
Here is an example of storing the integer inside the actual pointer:
// store
const char *key = "Gate";
int i = 10;
void *data;
memcpy(&data, &i, sizeof(i));
ht_set(hashtable, key, data);

// retrieve
void *result = ht_get(hashtable, key);
int value;
memcpy(&value, &result, sizeof(value));

However, you'll notice one problem here, which is that you cannot store the integer 0 in your table due to the calling semantics of ht_get which uses a NULL value to indicate no data.  So, unless you want to change your interface to return a "found" indicator along with the data, then your only option is to actually allocate:
// store
const char *key = "Gate";
int i = 10;
int *data = malloc(sizeof(i));
if (data) {
    *data = i;
    ht_set(hashtable, key, data);
}

// retrieve
void *result = ht_get(hashtable, key);
if (result) {
    int value = *(int*)result;
}

// note: you'll need to `free` the data when you remove the key from your hash table.


text:
Q: Is a set A a subset of B if all of the elements of A are within sets within B? How "deep" does the subset operator go?
If I have a set A = {1, 1, 2} and a set B = {1, {2}, {1}, {1, 2}, {2, 2, 1}}, is A a subset of B?
Thanks

A: $A$ is a subset of $B$ if and only if $a\in B$ for all $a\in A$, by definition. This does not involve any depth at all: $2\notin B$ and $2\in A$, therefore $A\nsubseteq B$.


text:
Q: Question about .apply() and passing entire columns through functions I have a dataframe with tickers as the headers and rows with the daily adjusted close through this past year and I want to calculate the annualized volatility, but I'm not sure how to pass through the columns. When I run this code I get an exception: TypeError: 'Series' object is not callable
import pandas as pd
import datetime as datetime
from datetime import timedelta
import yfinance as yf

df = pd.read_excel('C:/Users/Jacob/Downloads/Benchmark Tickers.xlsx', sheet_name='Sheet1')

tickers_list = df['Ticker'].tolist()

data = pd.DataFrame(columns=tickers_list)

for ticker in tickers_list:
    data[ticker] = yf.download(ticker, start=datetime.datetime.now()-datetime.timedelta(days=365), end=datetime.date.today()) ["Adj Close"]

def volatility(ticker):
    return data[ticker].pct_change().rolling(252).std()*(252**0.5)

data[ticker].apply(volatility(ticker))

export_excel = data.to_excel(r'C:/Users/User/Downloads/testvol.xlsx', sheet_name='Sheet1', index= True)

How I would apply this volatility function to each column?
Here is a link to the data that gets pulled when you do the yfinance pull:
https://docs.google.com/spreadsheets/d/11-kS1ah1lP8v6xv2JQZt_0i7YmynQxIw6q0stEvS_nM/edit?usp=sharing

A: When you call apply on a Series, you don't specify the argument like you normally would when calling a function, rather pass it through as a key-word argument:
data[ticker] = data[ticker].apply(volatility, ticker=ticker)

That should take care of that.
The pandas documentation has some good examples too. See here.

A: *

*When using .apply on a dataframe, with axis=0, the default, calculations are performed column-wise for each column, so there's no need to specify each ticker name.

import pandas as pd
import yfinance as yf
from datetime import datetime, timedelta, date

# given a list of tickers
tickers = ['EFT', 'PPR', 'SRLN']

# create empty dataframe with columns
data = pd.DataFrame(columns=tickers)

# get data
for ticker in tickers:
    data[ticker] = yf.download(ticker, start=datetime.now()-timedelta(days=365), end=date.today()) ["Adj Close"]

# perform calculation for each ticker and add it to the calcs dataframe
# 252 is to many for rolling; that means it needs 252 rows to perform the calculation.
# to will be used to show that it's working
calcs = data.apply(lambda x: x.pct_change().rolling(10).std()*(10**0.5))

# display(calcs.head(20))
                 EFT       PPR      SRLN
Date
2019-08-20       NaN       NaN       NaN
2019-08-21       NaN       NaN       NaN
2019-08-22       NaN       NaN       NaN
2019-08-23       NaN       NaN       NaN
2019-08-26       NaN       NaN       NaN
2019-08-27       NaN       NaN       NaN
2019-08-28       NaN       NaN       NaN
2019-08-29       NaN       NaN       NaN
2019-08-30       NaN       NaN       NaN
2019-09-03       NaN       NaN       NaN
2019-09-04  0.009594  0.012125  0.004690
2019-09-05  0.009483  0.012122  0.004691
2019-09-06  0.009870  0.009697  0.004736
2019-09-09  0.009037  0.010020  0.004191
2019-09-10  0.009205  0.009544  0.003981
2019-09-11  0.006672  0.009543  0.004084
2019-09-12  0.006492  0.010054  0.003925
2019-09-13  0.005592  0.010049  0.003992
2019-09-16  0.005428  0.012274  0.003367
2019-09-17  0.004926  0.010776  0.002505


text:
Q: Where to set Window flags in android I want to add the following flag to my activity:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

I'm not sure if this line should be before super.onCreate(..) method or after. Is the order important, and is there any difference at all?


text:
Q: Phpstorm gist кракозябры Подскажите, как в phpstorm настроить правильную кодировку в плагине gist, так как сейчас кракозябры. Если description гиста написано на русском, то вместо этого лезут эти некрасивые символы, как это исправить?
Только начал пользоваться phpstorm.

A: Настроить 'encoding' можно попробовать в 'Settings' выполнив поиск по соответствующему параметру:


text:
Q: BlackBerry MapField problem using  BlackBerry MapField
This is the code i use for displaying a map:
class MapScreen extends FullScreen
{
    public MapScreen()
    {
        super( FullScreen.DEFAULT_CLOSE | FullScreen.DEFAULT_MENU );
        MapField map = new MapField();
        MapAction action = map.getAction();
        action.setCentreAndZoom(new MapPoint(40, -40), 3);
        add(map);
    }
}

But only map tiles appear in the screen. Please help.

A: Try This -
MapField mMapField;
Coordinates mCoordinates;
mCoordinates = new Coordinates( -25.900461, 28.135085, 0);
mMapField = new MapField();
mMapField.moveTo(mCoordinates);
add(mMapField);


text:
Q: Express the equation as a first order System in the $(p,q)$ state-plane. Express the equation as a first order System in the $(p,q)$ state-plane.
$$p'' + 5p' + \sin(p) = 2\sin(2t)$$
Thanks for your help.

A: Let $p'=q$.
Then the system becomes
$p' =q$
$q'+q + \sin(p) = 2\sin(2t)$


text:
Q: PHP not writing a Base64 image to html file I have this string of data with some chords and their names:

$html="< img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAA4AQMAAAB31mwxAAAABlBMVEX///8AAABVwtN+AAAAAXRSTlMAQObYZgAAAEVJREFUeF5jIApwgDCIEAFhEKEEwkoIEYQaLID/PxD8AMmDARpDBsaww8JAqMHUTsBkGRkow84Ok4FQQ5zJZDAG0GTCAADwOiM87WVzggAAAABJRU5ErkJggg==" alt="E" /> E

When I try to put this into a file

file_put_contents("data2.html",$html);

I just creates an empty file.

A: Change your $html variable to this:
$html = '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAA4AQMAAAB31mwxAAAABlBMVEX///8AAABVwtN+AAAAAXRSTlMAQObYZgAAAEVJREFUeF5jIApwgDCIEAFhEKEEwkoIEYQaLID/PxD8AMmDARpDBsaww8JAqMHUTsBkGRkow84Ok4FQQ5zJZDAG0GTCAADwOiM87WVzggAAAABJRU5ErkJggg==" alt="E" /> E';

And then do the file_put_contents('data2.html', $html); part.
What we did here was replace the double quotes with single quotes so you wouldn't need to escape the double quotes inside the string. I also put an end with a semicolon to your string, which was missing. Always remember to end a statement when you start it.


text:
Q: VBA get the last invoice number and save the new invoice I have an invoice template sheet in invoice workbook that i want to save some of its fields in an other workbook "Excel data only", sheet "invoices". When creating an invoice i want to get the last invoice number from the "Excel data only", "Invoices" sheet column A and then add 1 to it.
Note that the invoice number has the format ST00001.
After that i want to save the invoice  number in the workbook excel data only with its details: C10,C11 and C12 which represent the total.
I don't know how to do it since i am new in vba this is what i tried to do but not working.
Dim v As Workbook
Set v = Workbooks("Excel data only")

Range("I12").Value = v.Sheets("INVOICES").Cells(v.Sheets("INVOICES").Rows.Count, "A").End(xlUp).Row.Value + 1

A: Sounds like
Dim v As Workbook, cellValue As String
Set v = Workbooks("Excel data only")
With v.Worksheets("INVOICES")
    cellValue = .Range("A" & .Cells(.Rows.Count, "A").End(xlUp).Row).Value
End With

ActiveSheet.Range("I12").Value = "ST" & Format$((Right$(cellValue, 5) + 1), "00000")

A:
Sub test_1()
Dim v As Workbook, cellValue As String
With Worksheets("sheet2")
    cellValue = .Range("A" & .Cells(.Rows.Count, "A").End(xlUp).Row).Value
End With
    ActiveSheet.Range("B13").Value = "" & Format$((Right$(cellValue, 2) + 1), "")
End Sub

these codes increment by going to last row number, with increment can you write these codes that can search if any number missing in between invoice it should show that also. for example invooice from 1 to 10 and 7 number is missing so instead of last row number increment it should give me missing number.
thnx


text:
Q: Use tag as attibute in crfsuite I'm very new in CRF and I want to use CRFsuite to tag words. I read CRFsuite's manual and understand the format of the training data, but if I want to add some features which have some tags of "near words", what's the training data file look like?
I have google around but I found nothing about this problem.

A: The short answer is that you supply attributes of the word coffee (like w[-1]=drank to indicate the previous word) and its label (NOUN), and CRFsuite generates the actual indicator functions that compose the CRF model (including a feature that indicates that the label of the previous word is VERB).  It knows to do this because it uses a "1st-order Markov CRF with dyad features," as described on the manual page you linked to.
One distinction that's important to make (and that the documentation could be more precise about) is the difference between "features" and "attributes" where features are links in the model that represent either (attribute, label) or (label, label) pairs.
So in your example, w[-1]=drank is an attribute that you supply. The combination of w[-1]=drank, NOUN is a state feature and the transition between labels VERB --> NOUN is a transition feature, both of which are generated by CRFsuite.
I recommend the tutorial, which discusses this in more detail.


text:
Q: Filter to scala springboot app I have simple webapp built using springboot and scala. I am able to create a simple rest API in my app. I am now trying to add a filter to support etags. However, I am unsuccessful in doing that. This is how my main app looks. Am I missing something in setting up the filter here?
object SampleApplication {
  def main(args: Array[String]) {
    println("SA:>>>>hello inside main");
    SpringApplication.run(classOf[Launcher]);
  }
}

@Configuration
@EnableAutoConfiguration
@ComponentScan
class Launcher extends SpringBootServletInitializer {
  println("SA:>>>>>>inside Launcher beg")

  override def onStartup(servletContext: ServletContext): Unit = {
    println("SA:>>>>inside Launcher onStartup")
    servletContext.addFilter("etagFilter","org.springframework.web.filter.ShallowEtagHeaderFilter").addMappingForServletNames(null,false,"/*");
    //super.onStartup(servletContext)
  }

  override def configure(app: SpringApplicationBuilder): SpringApplicationBuilder = {
    println("SA:>>>>> inside Launcher")
    app.sources(classOf[Launcher])
    //super.configure(app)
  }
}

A: Thanks to @M. Deinum, got this working within few minutes. The filter gets hooked up fine with my app.
object SampleApplication {
  def main(args: Array[String]) {
    SpringApplication.run(classOf[SampleConfig]);
  }
}

@EnableAutoConfiguration
@Bean
@ComponentScan
@Configuration
class MyFilter extends ShallowEtagHeaderFilter{
}


text:
Q: Which of the following three sets are closed under addition? I am not sure about my solution to the following problem:
Which of the following sets are closed under addition?
(i) The set of all vectors in $R^2$ of the form (a, b) where b = $a^2$.
(ii) The set of all 3 × 3 matrices that have the vector $\begin{bmatrix}2&-3&3\end{bmatrix}^T$ as an eigenvector.
(iii) The set of all polynomials in $P_2$ of the form $a_0 + a_1x + a_2x^2$ where $a_0 = a_2$.

Solution:
i) $(c, c^2) + (d, d^2) = (c + d, c^2 + d^2)$
This set is not closed, since $c^2 + d^2 \neq (c + d)^2$
ii) Assume $A_1$ and $A_2$ have the eigenvector.
$A_1 \cdot v + A_2 \cdot v = \lambda_1 \cdot v + \lambda_2 \cdot v$
$(A_1 + A_2) \cdot v = (\lambda_1 + \lambda_2) \cdot v$
The set is closed.
iii) $(a_0 + a_1x + a_2x^2)$ + $(b_0 + b_1x + b_2x^2)$
$(a_0 + b_0) + (a_1 + b_1) \cdot x + (a_2 + b_2) \cdot x^2$
With assumption $a_0 = a_2$:
$(a_2 + b_2) + (a_1 + b_1) \cdot x + (a_2 + b_2) \cdot x^2$
The set is closed.
I assume the answer is ii) and iii) only. Anything wrong with my assumptions?

A: In (i), $c^2+d^2\not = (c+d)^2$.  This is the so called "freshman's binomial"...
In (ii) and (iii) you are alright...


text:
Q: Can I grant multiple remote LocalService accounts access to a SQL Server database? I am designing a multi-environment Windows-based software product that will extensively employ Windows services running as LocalService to perform data access operations. All of the data access endpoints are .NET applications that use Entity Framework to access the databases.
I don't want to use SQL Server authentication if I can avoid it; I want to use Windows authentication everywhere. Currently there are no roles or users at the database level for any of the system's databases. My current plan is to grant SELECT/INSERT/UPDATE/EXECUTE privileges to the LocalService accounts associated with each of the service host environments.
First, is that approach even possible? After a dizzying amount of research, I can't make sense of how SQL Server will distinguish between the LocalService account on two remote environments.
Second, am I missing a serious security implication? I understand the principle that a role should be limited and narrow in scope. I also understand that any other applications on the servers running as LocalService -- including malware -- will have database access using the current plan. The challenge that I'm facing is that the product is licensed and will be deployed on customer site, and I'm not sure how to tell our customers that our software needs to commission its own domain accounts or, even worse, that they need to commission them.
If it makes the most sense, I will just abandon the idea of using LocalService to access databases and plan on creating purpose-specific service accounts. My expertise is stretched beyond its limit for this particular problem. Thanks in advance for sharing your thoughts.

A: Machine accounts such as LocalService cannot be trusted over the network.
There is essentially no way to authenticate the remote machine without domain authentication of some kind.
Use SQL Server authentication; that's what it is meant for.
Alternately, you could provide a setup procedure that allows your clients to provide a domain account for each service to access the SQL Server database.  You'd need to provide a mechanism where they can enter domain credentials for each service when they are setting up the server end.


text:
Q: Random variable vs Statistic? What's the difference between a random variable and a statistic?
It seems that formally, a random variable is simply any real-valued function (and its domain is a set that we call a "sample space").
But isn't the exact same also true of a statistic? That is, isn't a statistic also simply any real-valued function (whose domain is a set called a "sample space")?

Example. We roll a die. The sample space is $\Omega=\{1,2,3,4,5,6\}$.
Let $T$ be double the value of the die roll: Formally, $T:\Omega\rightarrow \mathbb R$ is the function defined by $T(x)=2x$.
Is $T$ a random variable, a statistic, or both?

In your answer, please give:

*

*A precise definition of a random variable

*A precise definition of a statistic

*An answer to the question in my example: "Is $T$ a random variable, a statistic, or both?"

A: A statistic is a function defined over one or more random variables.
So yes, a statistic is a random variable, and follows a distribution.
Another answer gave the example of the mean of a bunch of iid normal random variables.
$X_1,...,X_n\sim N(\mu,\sigma^2)$
The mean is a statistic because it is a function defined over random variables
$$\bar{X}= g(X_1, X_2 ... X_n) = \frac{1}{n} \sum_{i=1}^n X_i $$
There is one condition however, which is that a statistic cannot explicitly depend on unknown parameters. Take the following definition of $g$ :
$$ g(X_1) = \frac{X_1 - \mu}{\sigma}$$
While $g$ here is a function of a random variable, and it follows a standard normal distribution, it's not a statistic (unless $\mu$ and $\sigma$ are known).
For a more detailed explanation see pg. 122 of this.

A: The definition of a random variable depends on the context because how precise you need the definition to be depends on what kind of math you are doing. In the simplest definition, a random variable $X: \Omega\rightarrow \mathbb{R}$ is a function from a set of possible outcomes $\Omega$ onto the real numbers $\mathbb{R}$. For example, in the case of a coin, $\Omega = \lbrace H,T\rbrace$, you might have $H=1$ and $T=0$. The probability distribution carries all the info about the probabilities.
A statistic is a quantity computed from a sample. In statistical theories, usually these samples are themselves random variables. So the statistic itself is a random variable. For instance, if
$$X_1,...,X_n\sim N(\mu,\sigma^2)$$
then the sample mean is also a random variable
$$\bar{X}=\frac{1}{n} \sum_{i=1}^n X_i $$
$$\bar{X}\sim N\left(\mu,\frac{\sigma^2}{n}\right)$$
However, in practice, people may differ whether they consider a statistic to refer to a random variable.

A: The key thing is that a statistic is not a function of unknown parameters; so not all random variables are statistics. See Examples of a statistic that is not independent of sample's distribution?. And note that the distribution of a statistic may depend on unknown parameters; cf. a pivot, a random variable whose distribution does not depend on unknown parameters, though it may be a function of unknown parameters.
That something is a statistic doesn't mean you have to call it one: in applications the term tends to be reserved for random variables that play a special rôle in inference or description, & typically reduce the dimensionality of the sample space. Your T is a random variable; & also a statistic, even though no such motivation for using the latter term is evident.


text:
Q: Gridview column freeze not working in Mozilla I am trying to freeze the first column of a gridview in asp.net. My css code is
.CellLocked {
background-color:Gray;
position:relative;
left:expression(this.parentNode.parentNode.parentNode.parentNode.parentNode.scrollLeft-1);
}

It is fine in IE but not working in mozilla. Plz help. Thanks...

A: Set this in your css:
position:absolute;


text:
Q: Reuse a complex query result in other queries without redoing the complex query I have a complex query in PostgreSQL and I want to use the result of it in other operations like UPDATEs and DELETEs, something like:
<COMPLEX QUERY>;
UPDATE WHERE <COMPLEX QUERY RESULT> = ?;
DELETE WHERE <COMPLEX QUERY RESULT> = ?;
UPDATE WHERE <COMPLEX QUERY RESULT> = ?;

I don't want to have to do the complex query one time for each operations. One way to avoid this is store the result in a table and use it for the WHERE and JOINS and after finishing, drop the temporary table.
I want to know if there is another way without storing the results to database, but already using the results in memory.
I already use loops for this, but I think doing only one operation for each thing will be faster than doing the operations per row.

A: You can loop through the query results like @phatfingers demonstrates (probably with a generic record variable or scalar variables instead of a rowtype, if the result type of the query doesn't match any existing rowtype). This is a good idea for few resulting rows or when sequential processing is necessary.
For big result sets your original approach will perform faster by an order of magnitude. It is much cheaper to do a mass INSERT / UPDATE / DELETE with one SQL command
than to write / delete incrementally, one row at a time.
A temporary table is the right thing for reusing such results. It gets dropped automatically at the end of the session. You only have to delete explicitly if you want to get rid of it right away or at the end of a transaction. I quote the manual here:

Temporary tables are automatically dropped at the end of a session, or
  optionally at the end of the current transaction.

For big temporary tables it might be a good idea to run ANALYZE after they are populated.
Writeable CTE
Here is a demo for what Pavel added in his comment:
CREATE TEMP TABLE t1(id serial, txt text);
INSERT INTO t1(txt)
VALUES ('foo'), ('bar'), ('baz'), ('bax');

CREATE TEMP TABLE t2(id serial, txt text);
INSERT INTO t2(txt)
VALUES ('foo2'),('bar2'),('baz2');

CREATE TEMP TABLE t3 (id serial, txt text);

WITH x AS (
    UPDATE t1
    SET    txt = txt || '2'
    WHERE  txt ~~ 'ba%'
    RETURNING txt
    )
, y AS (
    DELETE FROM t2
    USING  x
    WHERE  t2.txt = x.txt
    RETURNING *
    )
INSERT INTO t3
SELECT *
FROM   y
RETURNING *;

Read more in the chapter Data-Modifying Statements in WITH in the manual.

A: DECLARE
    r foo%rowtype;
BEGIN
    FOR r IN [COMPLEX QUERY]
    LOOP
    -- process r
    END LOOP;
    RETURN;
END


text:
Q: Linux pci_map_single working My question is regarding the use of the pci_map_single function. I know that a DMA address is generated which the device can use for data transfer but does any change happen to the memory(virtual address pointer) that is passed as an argument to this function?

A: No, virtual address is not going to change. Virtual address is passed by value not passed be reference.
On successful completion, DMA address is retured.


text:
Q: How to store values of loop in matrix when 'i' is not a number, but a character? To put some context to my question, I have a large data set. I would like to analyze the dataset in subsets based on a column variable (which is a character vector). I would then like to store parts of this result in a matrix. I have used loops before to store values calculated from each cycle in a loop into a matrix, but only when 'i' is numeric and not character.
What I have so far is below:
The main issue is that I use 'i' to identify the position of the matrix I would like to store the values in, but it doesn't work when 'i' is a character.
list <- c("xyz","usd","lki","josdl","olid"......"kadl")
output= matrix(ncol=5, nrow=length(unique(c))

for(i in list){
    x <- filter(df, colvar == "i")
    if(nrow(x) <=1) next
    y <- metagen(RR, SE, data=x) #meta-analysis results

  ###### Inputting values from metagen into dataframe ####
      meta.analysis[i,1] = "i" #colvar
      meta.analysis[i,2] = y$TE.fixed #fixed effect model
      meta.analysis[i,3] = y$seTE.fixed #seTE.fixed
      meta.analysis[i,4] = y$lower.fixed #95%CI-lower bound, fixed.effect
      meta.analysis[i,5] = y$upper.fixed #95%CI-upper bound, fixed effect
      meta.analysis[i,6] = y$zval.fixed #Z-value, fixed effect
      meta.analysis[i,7] = y$pval.fixed #P-value of Z-value, fixed effect

      meta.analysis[i,8] = y$TE.random #random effect model
      meta.analysis[i,9] = y$seTE.random #seTE.random
      meta.analysis[i,10] = y$lower.random #95%CI-lower bound, random.effect
      meta.analysis[i,11] = y$upper.random #95%CI-upperbound, random effect
      meta.analysis[i,12] = y$zval.random #Z-value, random effect
      meta.analysis[i,13] = y$pval.random #P-value of Z-value, random effect

      meta.analysis[i,14] = y$k #Number of studies
}

Any help/input would be appreciated! =)

A: Consider a vectorized approach with sapply() as the metagen object returns a list of various components:
list <- c("xyz","usd","lki","josdl","olid"......"kadl")

meta.analysis <- sapply(list, function(i){
         x <- filter(df, colvar == i)
         y <- metagen(RR, SEE, data = x)[c("TE.fixed", "seTE.fixed", "lower.fixed",
                                           "upper.fixed", "zval.fixed", "pval.fixed",
                                           "TE.random", "seTE.random", "lower.random",
                                           "upper.random", "zval.random", "pval.random")]
         y <- c(i, y)   # colvar
         return(y)
     }
)

To ensure a matrix return, consider vapply() -however, leave out the colvar since it is a character and not numeric and elements in a matrix must be of one type:
meta.analysis <- vapply(list, function(i) { ...same as above...},
                        FUN.VALUE = numeric(12))


text:
Q: Successful payment with PayPal but no activity on buyers account I am developing an application which needs an access to PayPal. I use the php-rest-paypal sdk. In my Sandbox account you can see green-checked api calls and after I complete the payment with the sandbox account not activity is shown in my "buyers" or "facilitator"-account?
I tried to Google it but it seems like I am the only one who has this issue.
Here is my code:
$apiContext = new ApiContext(
    new OAuthTokenCredential(
        $this->clientID,
        $this->clientSecret)
);

$payer = new Payer();
$payer->setPaymentMethod('paypal');

$amount = new Amount();
$amount->setCurrency('EUR');
$amount->setTotal($order->getSum());

$transaction = new Transaction();
$transaction->setAmount($amount);

$redirectUrls = new \PayPal\Api\RedirectUrls();
$redirectUrls->setReturnUrl("http://localhost:8080/checkout/confirm");
$redirectUrls->setCancelUrl("http://localhost:8080/checkout/summary");

$payment = new Payment();
$payment->setIntent('sale')
    ->setPayer($payer)
    ->setTransactions(array($transaction))
    ->setRedirectUrls($redirectUrls);

try {
    $payment->create($apiContext);

    echo "\n\nRedirect user to approval_url: " . $payment->getApprovalLink() . "\n";
}
catch (\PayPal\Exception\PayPalConnectionException $ex) {
    file_get_contents(CURRENT_PROJECT_DIRECTORY.'/tmp/paypal-log.log', $ex->getData());
}

Can someone give me some hints? Am I doing something wrong?


text:
Q: How to retrieve a request scoped variable using JSTL on Struts 1 I'm refactoring some legacy code that uses Struts 1 (No flames please), and I am having a difficult time retrieving a parameter I set in my Action class. Here is the code that I'm using in my jsp:
I set the variable submissionFailure in the Action Class, but when I try
<c:out value="${requestScope[cardHolderZipCode]}" />
or
<c:out value="${requestScope.property[submissionFailure]}" />
However nothing is ever output.
I put the following code in my JSP, and I can see the value in the requestScope Map:
Request Scope

<c:forEach items="${requestScope}"  varStatus="status" var="parameter">
    <c:out value="${parameter}"/>

</c:forEach>
But I still can't get the variable out. Can anyone help me or am I just having an I-D-10-T moment?

A: It could be that your Action class is not a JavaBean (i.e. no getter on the submissionFailure field). From the Struts1 reference:

First, your ActionForm bean must have
  a zero-arguments constructor. This is
  required because the framework must be
  able to dynamically create new
  instances of your form bean class,
  while knowing only the class name.
  This is not an onerous restriction,
  however, because the framework will
  also populate your form bean's
  properties (from the request
  parameters) for you.
Second, the fields of your form bean
  are made available to the framework by
  supplying public getter and setter
  methods that follow the naming design
  patterns described in the JavaBeans
  Specification. For most users, that
  means using the following idiom for
  each of your form bean's properties:

private {type} fieldName;

public {type} getFieldName() {
  return (this.fieldName);
}
public void setFieldName({type} fieldName) {
  this.fieldName = fieldName;
}

If this doesn't help, then you should consider posting the relevant parts of your Action class into your question to enable better debugging.

A: It was an I-D-10-T moment on my part. I was trying too hard. Here is the code I ended up using:
<c:choose>
    <c:when test="${submissionFailure}">
         <%-- Do something --%>
    </c:when>
    <c:otherwise>
         <%-- Do something else --%>
    </c:otherwise>
</c:choose>


text:
Q: Replicated cache system to each http servers I have setup recently memcached for a PHP site with lot of traffic. Before we used APC but this lacks the possibility to have a unique cache system (invalidating one key on one server doesn't invalidate through the others).
I noticed a big difference when comes to memcached being on same machine as http server or on separated server.

http+memcached on same server -> 0.06 average time spent to deliver a page
http and memcache on diff servers (but under NAT) -> 0.15 - 0.20 to the deliver a page

So it's a huge difference and I am wondering if won't be better to have the cache system on same machine as http. The additional complexity is the fact the website is served by couple http servers (through a load balancer). So I actually need a cache system with replication, each http server having a cache "copy" and writing the changes only to the "master" (or other approach doing similar things).
There are couple of such systems (couchbase, redis, aso). I think couchbase is not good for this as won't allow connecting to local cache server but rather to the "gate". Redis may work, I am still checking on others.
The main this is: has someone tried this approach to speed up the website? By having on each machine a cache "copy" (kept in synch with the others)?

A: You can use GigaSpaces XAP solution which is a distributed in memory data grid, but also has an integration with jetty allowing you to deploy your web app and manage it from a single management system. The central distributed data grid (which can be a used as simple cache) can have a local cache on each web container which is kept in sync with the main cache, you don't have to use the jetty integration for it, you can still use your own web container and just create a proxy to the distributed cache with an embedded local cache via code. Or you can also have a fully replicated topology between the web containers without having a main distributed cache and each web container will contain a full copy of the entire cache which will be in sync with the other instances of the web container.
You can read more in:
http://wiki.gigaspaces.com/wiki/display/SBP/Web+Service+PU
http://wiki.gigaspaces.com/wiki/display/XAP9/Web+Jetty+Processing+Unit+Container
http://wiki.gigaspaces.com/wiki/display/XAP9/Client+Side+Caching
Disclaimer: I am a developer working for GigaSpaces.


text:
Q: Copying and Pasting data from one workbook to another resulting in random cells getting data/empty rows not getting pasted data UPDATE
Half of my issue is resolved now but I am still having issues. The majority of the data I am pasting to the new workbook is working fine. If you press the button several times, the data gets pasted to the next available row. However, three rows in particular are not working. The data will be pasted in the right place the first time you press the macro button but then the data will be pasted 31 rows down from the appropriate row. I am completely confused by this. Is it some sort of formatting issues with the cells in that part of the worksheet? Any help would be appreciated.
Original Problem
Let me explain whats going on. I am trying to make it so that once a form has been filled out in one workbook, the user presses a button and the data from that form is copied and pasted to another workbook that acts like a master file for all the data. The data from the form is supposed to be pasted in specific columns in the second workbook.
So far I have been successful in creating crude but working code that accomplishes this but now I am running into some issues. When I press the button on the first workbook, everything gets pasted as intended but a cell (G163 specifically) will get pasted with data. I checked and nothing in the code is making the macro paste to that cell specifically. Also, if I press the button a second time, some cells will not paste in the next available empty cell but instead will be pushed down the column and get pasted in a different cell than intended.
I am very new to excel vba so any help would be greatly appreciated. I will post my code below and some pictures of the odd pasting as well.
Sub Button1099_Click()

If IsEmpty(Workbooks("2018Monthly.xls").Worksheets("7").Range("A42")) = True Then
Workbooks("Formtest.xlsm").Worksheets("Form").Range("A4").Copy
Workbooks("2018Monthly.xls").Worksheets("7").Range("A42").PasteSpecial Paste:=xlPasteValuesAndNumberFormats

Else
Workbooks("Formtest.xlsm").Worksheets("Form").Range("A4").Copy
Range("A" & Rows.count).End(xlUp).Offset(1).Select
Workbooks("2018Monthly.xls").Worksheets("7").Range("A" & Rows.count).End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If

If IsEmpty(Workbooks("2018Monthly.xls").Worksheets("7").Range("B42")) = True Then
Workbooks("Formtest.xlsm").Worksheets("Form").Range("P2").Copy
Workbooks("2018Monthly.xls").Worksheets("7").Range("B42").PasteSpecial Paste:=xlPasteValuesAndNumberFormats

Else
Workbooks("Formtest.xlsm").Worksheets("Form").Range("P2").Copy
Range("B" & Rows.count).End(xlUp).Offset(1).Select
Workbooks("2018Monthly.xls").Worksheets("7").Range("B" & Rows.count).End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If

If IsEmpty(Workbooks("2018Monthly.xls").Worksheets("7").Range("C42")) = True Then
Workbooks("Formtest.xlsm").Worksheets("Form").Range("P3").Copy
Workbooks("2018Monthly.xls").Worksheets("7").Range("C42").PasteSpecial Paste:=xlPasteValuesAndNumberFormats

Else
Workbooks("Formtest.xlsm").Worksheets("Form").Range("P3").Copy
Range("C" & Rows.count).End(xlUp).Offset(1).Select
Workbooks("2018Monthly.xls").Worksheets("7").Range("C" & Rows.count).End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If

If IsEmpty(Workbooks("2018Monthly.xls").Worksheets("7").Range("D42")) = True Then
Workbooks("Formtest.xlsm").Worksheets("Form").Range("C10").Copy
Workbooks("2018Monthly.xls").Worksheets("7").Range("D42").PasteSpecial Paste:=xlPasteValuesAndNumberFormats

Else
Workbooks("Formtest.xlsm").Worksheets("Form").Range("C10").Copy
Range("D" & Rows.count).End(xlUp).Offset(1).Select
Workbooks("2018Monthly.xls").Worksheets("7").Range("D" & Rows.count).End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If

If IsEmpty(Workbooks("2018Monthly.xls").Worksheets("7").Range("E42")) = True Then
Workbooks("Formtest.xlsm").Worksheets("Form").Range("C9").Copy
Workbooks("2018Monthly.xls").Worksheets("7").Range("E42").PasteSpecial Paste:=xlPasteValuesAndNumberFormats

Else
Workbooks("Formtest.xlsm").Worksheets("Form").Range("C9").Copy
Range("E" & Rows.count).End(xlUp).Offset(1).Select
Workbooks("2018Monthly.xls").Worksheets("7").Range("E" & Rows.count).End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If

If IsEmpty(Workbooks("2018Monthly.xls").Worksheets("7").Range("F42")) = True Then
Workbooks("Formtest.xlsm").Worksheets("Form").Range("C11").Copy
Workbooks("2018Monthly.xls").Worksheets("7").Range("F42").PasteSpecial Paste:=xlPasteValuesAndNumberFormats

Else
Workbooks("Formtest.xlsm").Worksheets("Form").Range("C11").Copy
Range("F" & Rows.count).End(xlUp).Offset(1).Select
Workbooks("2018Monthly.xls").Worksheets("7").Range("F" & Rows.count).End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If

If IsEmpty(Workbooks("2018Monthly.xls").Worksheets("7").Range("G42")) = True Then
Workbooks("Formtest.xlsm").Worksheets("Form").Range("B17").Copy
Workbooks("2018Monthly.xls").Worksheets("7").Range("G42").PasteSpecial Paste:=xlPasteValuesAndNumberFormats

Else
Workbooks("Formtest.xlsm").Worksheets("Form").Range("B17").Copy
Range("G" & Rows.count).End(xlUp).Offset(1).Select
Workbooks("2018Monthly.xls").Worksheets("7").Range("G" & Rows.count).End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If

If IsEmpty(Workbooks("2018Monthly.xls").Worksheets("7").Range("H42")) = True Then
Workbooks("Formtest.xlsm").Worksheets("Form").Range("C12").Copy
Workbooks("2018Monthly.xls").Worksheets("7").Range("H42").PasteSpecial Paste:=xlPasteValuesAndNumberFormats

Else
Workbooks("Formtest.xlsm").Worksheets("Form").Range("C12").Copy
Range("H" & Rows.count).End(xlUp).Offset(1).Select
Workbooks("2018Monthly.xls").Worksheets("7").Range("H" & Rows.count).End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If

If IsEmpty(Workbooks("2018Monthly.xls").Worksheets("7").Range("I42")) = True Then
Workbooks("Formtest.xlsm").Worksheets("Form").Range("J10").Copy
Workbooks("2018Monthly.xls").Worksheets("7").Range("I42").PasteSpecial Paste:=xlPasteValuesAndNumberFormats

Else
Workbooks("Formtest.xlsm").Worksheets("Form").Range("J10").Copy
Range("I" & Rows.count).End(xlUp).Offset(1).Select
Workbooks("2018Monthly.xls").Worksheets("7").Range("I" & Rows.count).End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If

If IsEmpty(Workbooks("2018Monthly.xls").Worksheets("7").Range("J42")) = True Then
Workbooks("Formtest.xlsm").Worksheets("Form").Range("J11").Copy
Workbooks("2018Monthly.xls").Worksheets("7").Range("J42").PasteSpecial Paste:=xlPasteValuesAndNumberFormats

Else
Workbooks("Formtest.xlsm").Worksheets("Form").Range("J11").Copy
Range("J" & Rows.count).End(xlUp).Offset(1).Select
Workbooks("2018Monthly.xls").Worksheets("7").Range("J" & Rows.count).End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End If

 Application.CutCopyMode = False
 Workbooks("2018Monthly.xls").Save

End Sub

This is what the second workbook looks like once you click the button once:
Pasted workbook after one button press
Pasted workbook after one button press
This is what the workbook looks like if you press the button again:
Pasted workbook after two button presses
Pasted workbook after two button presses

A: Since you are copying cell to cell, try this;
Dim ws1 As Worksheet
Dim ws2 As Worksheet

Set ws1 = Workbooks("Formtest.xlsm").Worksheets("Form")
Set ws2 = Workbooks("2018Monthly.xls").Worksheets("7")

Dim lRow As Long
lRow = ws2.Range("A" & Rows.Count).End(xlUp).Row

If ws2.Range("A42").Value = "" Then
    ws2.Range("A42").Value = ws1.Range("A4").Value
Else: ws2.Range("A" & lRow).Offset(1).Value = ws1.Range("A4").Value
End If


text:
Q: ¿Como pasar de los binarios del ascii 8-bit a los binarios del ascii 6-bit? ¿Como pasar de los binarios del ascii 8-bit a los binarios del ascii 6-bit?
Por ejemplo, ¿existe o no un vinculo entre H en 8-bit ASCII 0100 1000 y H en 6-bit ASCII 011000?
Me refiero al articulo de Eric S. Raymond que fue editado dos veces recientemente sobre las tablas de conversion entre el ASCII y el binario.Aqui esta como recobrar los 6-bits.pero no el binario:

To recover the six bits, subtract 48 from the ASCII character value; if the result is greater than 40 subtract 8.

si eso es muy claro para los decimales
Char ASCII Decimal Bits

"0"  48    0       000000
"1"  49    1       000001
"2"  50    2       000010
"3"  51    3       000011
 ...

No lo esta para las letras
"H"  72    24      011000

He hecho el siguiente codigo para recupererar los binaries asociados con los simbolos ascii. Pero si me da 000001 por 1 en ASCII, que esta acertado, me da 1000101 por la letra u en lugar de 111101
Module Module1

    Public Function traduction_ASCII(trames As String)

        Dim binario_en_8 As Integer = 0
        Dim dec As Integer = 0
        Dim Remainder As Integer
        Dim result As String = ""
        Dim j As Integer = 0
        Dim tabular_binario(40) As String

        'Modificamos los elementos ASCII en binarios'
        For i = 0 To trames.Length - 1
            'Recuperamos el valor numerica del ASCII leido en 8 bits'
            binario_en_8 = Asc(trames.ElementAt(i))

            'est esta necesario pero no se porque'
            dec = Val(binaire_en_8)

            'la modificamos en su valor ASCII en 6 bits'
            dec = dec - 48
            If dec > 40 Then
                dec = dec - 8
            End If

            While dec > 0
                remainder = dec Mod 2
                dec /= 2
                result = Remainder.ToString & result
                j = j + 1
            End While

            While j < 6
                result = "0" & result
                j = j + 1
            End While

            tableau_binario(i) = result
            result = ""
            j = 0
        Next

        Return traduction_binaire_de_ASCII
    End Function
End Module

El error es que para el programa, 1F / 2 = 8 en lugar de 7
pero no sé porque divide por esta manera

A: Se puede hacer manipulación de bits o usar la clase BitArray. Usando esta última, se deben reacomodar los bits en formato MSF.
También se puede aprovechar la implementación nativa para Base 64 que viene con la clase Convert de .Net. Para este caso lo único que se debe tener en cuenta es reemplazar las tablas de codificación y verificar los símbolos de relleno.
' Tabla Base 64 '
Const TABLA_BASE64 As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

' Tabla AIVD tomada de "Table 2. ASCII payload armoring" del artículo "AIVDM/AIVDO protocol decoding" de Eric S. Raymond '
Const TABLA_AIVD As String = "0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVW`abcdefghijklmnopqrstuvw"

Codificación:
Dim Texto as String = "Texto a codificar"

' Codifica en base 64 '
Dim cod as String = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(Texto))

' Elimina los símbolos de relleno finales '
If cod.EndsWith("==") Then
    cod = cod.Substring(0, cod.Length - 2)
ElseIf cod.EndsWith("=") Then
    cod = cod.Substring(0, cod.Length - 1)
End If

' Reemplaza los símbolos de Base 64 por los de AIVD'
dim sb as system.text.stringbuilder = new system.text.stringbuilder
dim pos as integer
For Each ch As Char In cod
    pos = TABLA_BASE64.IndexOf(ch)
    sb.Append(TABLA_AIVD(pos))
Next

' Texto codificado en AIVD '
cod = sb.tostring

Decodificación:
' Reemplaza los símbolos de AIVD por los de Base 64 '
dim sb as system.text.stringbuilder = new system.text.stringbuilder
dim pos as integer
For Each ch As Char In cod
    pos = TABLA_AIVD.IndexOf(ch)
    sb.Append(TABLA_BASE64(pos))
Next

' Agrega los símbolos de relleno para Base 64 '
Dim m as integer = sb.Length Mod 4

If m Then
    sb.Append("="c, 4 - m)
End If

' Texto decodificado '
dim Texto as string = System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(sb.ToString))

Este método se puede usar en cualquier sistema de codificación de 8 bits en 6, con la tabla de símbolos correspondiente.


text:
Q: Copy certain value to varying position in defined worksheet I am working on a macro that takes the value in H2 in the 3rd sheet of the workbook and copies it to the column behind the last used column in row 5 in the row that contains the word "page" in column A in a worksheet called "Overview", but only if the value in H2 is not 0. After that, i need to add a string in row 4 in the same column that the value was posted to. Can somebody help me get my code to work? I specifically have issues with copying the value. THis is what i have so far:
'
' example Macro
'

'

Dim cRange As Range
Dim valuessendmemore As Range
Dim Cell As Range
Dim wsDestination As Worksheet, wsSource As Worksheet

    'set worksheets
With ThisWorkbook
        Set wsSource = .Worksheets(3)
        Set wsDestination = .Worksheets("Overview")
End With

LastColumn1 = wsDestination.Cells(5, wsDestination.Columns.Count).End(xlToLeft).Column
Set cRange = wsSource.Range("H2")

    For Each Cell In cRange
    If Cell.Value > 0 Then
        Cell.Value.Copy

        'Set the value you want to search
        strSearch = "*Page*"

        'Set the column you want to seach
        ColumnNo = 1

        'Create a with statement to point Sheet1.
        With wsDestination

            'Search for strSearch in column number ColumnNo
            Set rngFound = .Columns(ColumnNo).Find(strSearch, LookIn:=xlValues, lookat:=xlWhole)

            If Not rngFound Is Nothing Then

                'Paste row
                wsDestination.Range(LastColumn1 & rngFound.Row).PasteSpecial Paste:=xlPasteValues
                'Delete row

            End If

        End With

    End If

    Next Cell

    Application.CutCopyMode = False
End Sub

A: Your problem no doubt lies in this statement Range(LastColumn1 & rngFound.Row).  Say your LastColumn1 evaluated to 25 and rngFound.Row evaluated to 1000.  Now your statement says Range(251000) which doesn't exist.  The proper rewrite would be:
wsDestination.Cells(rngFound.Row, LastColumn1)...


text:
Q: What is the difference between an Array, ArrayList and a List? I am wondering what the exact difference is between a Array, ArrayList and a List (as they all have similar concepts) and where you would use one over the other.
Example:
Array
For the Array we can only add types that we declare for this example an int.
int[] Array = new Int[5]; //Instansiation of an array
for(int i = 0; i < Array.Length; i++)
{
   Array[i] = i + 5; //Add values to each array index
}

ArrayList
We can add values just like a Array
ArrayList arrayList = new ArrayList();
arrayList.Add(6);
arrayList.Add(8);

List
Again we can add values like we do in an Array
List<int> list = new List<int>();
list.Add(6);
List.Add(8);

I know that in a List you can have the generic type  so you can pass in any type that you cannot do in an Array but my exact questions are:

*

*Where would you use one over the other?

*The exact difference functionality wise between the three?

A: They are different object types.  They have different capabilities and store their data in different ways.
An Array (System.Array) is fixed in size once it is allocated.  You can't add items to it or remove items from it.  Also, all the elements must be the same type.  As a result, it is type safe, and is also the most efficient of the three, both in terms of memory and performance.  Also, System.Array supports multiple dimensions (i.e. it has a Rank property) while List and ArrayList do not (although you can create a List of Lists or an ArrayList of ArrayLists, if you want to).
An ArrayList is a flexible array which contains a list of objects.  You can add and remove items from it and it automatically deals with allocating space.  If you store value types in it, they are boxed and unboxed, which can be a bit inefficient.  Also, it is not type-safe.
A List<> leverages generics; it is essentially a type-safe version of ArrayList.   This means there is no boxing or unboxing (which improves performance) and if you attempt to add an item of the wrong type it'll generate a compile-time error.


text:
Q: Using HTML 5 / Javascript template to send contact e-mail form I recently created a simple site for a friend's business using an HTML 5 template. It contained some cutesy Javascript elements too. The website URL is www.michianamemories.com
One of the elements is a Contact Form at the bottom of the page. It looks like the "Send Message" button is coded to do absolutely nothing. How simple is it to have this form forward the user-entered values (ie: their name, e-mail, and their message) to a dedicated e-mail inbox?
If it's not that simple, what other options are available to make the form functional but also integrated with the site's general theme?
I'm assuming the answer is very simple, but I'm a novice at HTML 5 and am totally clueless about Javascript. Your help is appreciated in advance.

A: It's not possible in pure Javascript. Sending email requires server-side processing.
There are several websites that will let you generate simple email forms, check out: http://www.google.com/search?hl=en&safe=off&q=email+form+generator&aq=5&aqi=g10&aql=&oq=email+form

A: HTML doesn't allow you to submit a form to an email.
You could use mailto but it's not the friendliest piece of functionality. It will open up Outlook and dump the form data into the email content. Has a lot of issues though.
More info on mailto
My recommendation is to use a "form mail script". This is only done on server side though so you'll need to have a web server. You'll need to google and read up on them.
Reference about form submit options

A: In my opinion the best thing you can do is to create a simple Back-End App in PHP.

*

*Create file mail.php in your root directory.

*In your HTML form tag you need to add  the action attribute with the path to mail.php file and the method attribute, so that the form knows which HTTP Request Method use to send the data <form action="mail.php" method ="post">. This will add the action to trigger for the 'Send Message' button, that you said is not working.
This happens because now the button knows what to do if you click it. It takes all of your data from the form input fields and send them to the mail.php file. This file needs to fetch them and validate them. (You should at least create the validation for the required fields in your form, to check if they're not null. You can make some extra validations in your build-in html attributes or with some help of the JavaScript)

*The most important thing now, is to create the Mail function in your mail.php. Here is all the documentation you need to do this: PHP Mail Documentation.
Here is the code (your site is not working so I'm just improvising with the input fields):
HTML:
<form action="mail.php" method="post">

    Name:
    <input id="name-field" name="name" type="text" required>

    Surname:
    <input id="surname-field" name="surname" type="text" required>

    Message:
    <textarea id="message-field" name="message" required></textarea>

    Your e-mail:
    <input id="mail-field" name="mail" type="mail" required>

    <button type="submit">Send Message</button>

</form>

PHP:
// Validating if everything is filled
if(isset($_POST['name']) && isset($_POST['surname']) && isset($_POST['message']) && isset($_POST['mail'])
{
    $to = "example@mysite.com";
    $subject = "Automatically generated messege from" . $_POST['name'] . ' ' . $_POST['surname'];
    $body = $_POST['message'];
    $headers = 'To: ' . $to . "\r\n";
    $headers .= 'From: ' . $_POST['mail'];

    // Send mail function
    if(mail($to, $subject, $body, $headers))
    {
        echo 'Mail sent successfuly!';
    } else {
        echo 'Error occurred while sending the message';
    }
}

A: As mentioned in the other answers, you can't use HTML5 to send e-mail. This needs to be done on your server.
One easy and free solution is to use Google Apps Script though. You can publish your Apps Script as a Web App and have a doPost method like this:
function doPost(e){
    var email = e.parameter.email;
    var subject = 'E-mail from website';
    var message = e.parameter.message;
    MailApp.sendEmail(emailAddress, subject, message);

    return ContentService.createTextOutput('E-mail sent!');
}

And in your HTML, you would have a form like this:
<form action="url to your deployed app script" method="post">
    <input type="email" name="email"></input>
    <textarea name="message"></textarea>
    <input type="submit" value="Submit"></input>
</form>

The URL to put in the action attribute will be shown when you deploy your Apps Script as a Web App:


text:
Q: Spring Dependency Injection into JPA entity listener I need to have a Spring dependency injected into a JPA entity listener. I know I can solve this using @Configurable and Spring's AspectJ weaver as javaagent, but this seems like a hacky solution. Is there any other way to accomplish what I'm trying to do?

A: Another trick is to implement an utility class with static method that helps you to use Spring beans everywhere, not only in managed classes:
@Component
public final class BeanUtil {

    private static ApplicationContext context;

    private BeanUtil(ApplicationContext context) {
        BeanUtil.context = context;
    }

    public static <T> T getBean(Class<T> clazz) throws BeansException {

        Assert.state(context != null, "Spring context in the BeanUtil is not been initialized yet!");
        return context.getBean(clazz);
    }
}

A: Here's a solution in Kotlin (Spring Boot 2.3.9, Hibernate 5.4.29.Final). First part is similar to Matthias' answer. However, the second part was needed even though it's a Spring Boot application.
Bean declaration
@Component
class EntityXyzListener(val mySpringBean: MySpringBean) {

    @PostLoad
    fun afterLoad(entityXyz: EntityXyz) {
        // Injected bean is available here. (In my case the bean is a
        // domain service that I make available to the entity.)
        entityXyz.mySpringBean= mySpringBean
    }

}

Datasource configuration
I already had this datasource @Configuration in my spring boot app. I only had to add the line of code that puts the BEAN_CONTAINER property in the jpaPropertyMap.
@Resource
lateinit var context: AbstractApplicationContext

@Primary
@Bean
@Qualifier("appDatasource")
@ConfigurationProperties(prefix = "spring.datasource")
fun myAppDatasource(): DataSource {
    return DataSourceBuilder.create().build()
}

@Primary
@Bean(name = ["myAppEntityManagerFactory"])
fun entityManagerFactoryBean(builder: EntityManagerFactoryBuilder): LocalContainerEntityManagerFactoryBean {
    val localContainerEntityManagerFactoryBean =
            builder
                    .dataSource(myAppDatasource())
                    .packages("com.mydomain.myapp")
                    .persistenceUnit("myAppPersistenceUnit")
                    .build()
    // the line below was the long-sought solution :^)
    localContainerEntityManagerFactoryBean.jpaPropertyMap.put(
            AvailableSettings.BEAN_CONTAINER, SpringBeanContainer(context.beanFactory))
    return localContainerEntityManagerFactoryBean
}

A: Since Hibernate 5.3 org.hibernate.resource.beans.container.spi.BeanContainer and Spring 5.1 org.springframework.orm.hibernate5.SpringBeanContainer you do not need to extra autowiring effort any more. See details of this feature in https://github.com/spring-projects/spring-framework/issues/20852
Simply annotate your EntityListener class with @Component, and do any autowiring like so:
@Component
public class MyEntityListener{

  private MySpringBean bean;

  @Autowired
  public MyEntityListener(MySpringBean bean){
    this.bean = bean;
  }

  @PrePersist
  public void prePersist(final Object entity) {
    ...
  }

}

In Spring Boot the configuration of LocalContainerEntityManagerFactoryBean is done automatically in org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration.
Outside of Spring Boot, you have to register SpringBeanContainer to Hibernate:
LocalContainerEntityManagerFactoryBean emfb = ...
 emfb.getJpaPropertyMap().put(AvailableSettings.BEAN_CONTAINER, new SpringBeanContainer(beanFactory));

A: You can try this solution
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public final class AutowireHelper implements ApplicationContextAware {

private static final AutowireHelper INSTANCE = new AutowireHelper();
private static ApplicationContext applicationContext;

private AutowireHelper() {
}

/**
 * Tries to autowire the specified instance of the class if one of the specified beans which need to be autowired
 * are null.
 *
 * @param classToAutowire        the instance of the class which holds @Autowire annotations
 * @param beansToAutowireInClass the beans which have the @Autowire annotation in the specified {#classToAutowire}
 */
public static void autowire(Object classToAutowire, Object... beansToAutowireInClass) {
    for (Object bean : beansToAutowireInClass) {
        if (bean == null) {
            applicationContext.getAutowireCapableBeanFactory().autowireBean(classToAutowire);
            return;
        }
    }
}

/**
 * @return the singleton instance.
 */
public static AutowireHelper getInstance() {
    return INSTANCE;
}

@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
    AutowireHelper.applicationContext = applicationContext;
}

}
and then
 @Autowired
SomeService thatToAutowire;

  AutowireHelper.autowire(this, this.thatToAutowire);//this in the method

A: Extending a bit the above responses:
Since Hibernate 5.3 org.hibernate.resource.beans.container.spi.BeanContainer and Spring 5.1. You can use this to post process loaded domain entities for instance. Instead of using the aspect.
See:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/orm/hibernate5/SpringBeanContainer.html
In your config:
@Bean
    LocalContainerEntityManagerFactoryBean customCartEntityManagerFactory(DataSource customCartDataSource, EntityManagerFactoryBuilder builder, ConfigurableListableBeanFactory beanFactory) {
        var mf = builder
                .dataSource(customCartDataSource)
                .packages("com.my.domain")
                .build();
        mf.getJpaPropertyMap().put(AvailableSettings.BEAN_CONTAINER, new SpringBeanContainer(beanFactory));
        return mf;
    }

In your entity bean:
@EntityListeners(MyEntityListener.class)

The listener, notice no @Component decoration.
@Slf4j
public class MyEntityListener implements BeanFactoryAware, InitializingBean {

    private final BeanConfigurerSupport beanConfigurerSupport = new BeanConfigurerSupport();

    public CustomCartEntityListener() {
        log.info("MyEntityListener created");
    }

    @PostLoad
    public void postLoad(MyEntity entity) {
        beanConfigurerSupport.configureBean(entity);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanConfigurerSupport.setBeanWiringInfoResolver(new AnnotationBeanWiringInfoResolver());
        this.beanConfigurerSupport.setBeanFactory(beanFactory);
    }

    @Override
    public void afterPropertiesSet() {
        this.beanConfigurerSupport.afterPropertiesSet();
        log.info("MyEntityListener initialized");
    }

}


text:
Q: How do I list a url to a list that has multiple content types (Sharepoint Online) I have a jquery data table that displays sharepoint list data I currently have a column in the table that displays a link to the record.
I need to update that URL to add a variable based on the content type:
An example of this is....
http://www.domain/"+ var1 +"/editifs.aspx?ID="+ id +"
The "var1" is just a variable for the content type of the record

A: You can add a field to each content type, perhaps 'CT', with the default value set as the corresponding content type name. This should then allow you to build to url via a calculated column


text:
Q: pulling data from multiple tables on the same page I'm stuck on this code and can't figure out where I need to go. I'm trying to pull name, phone number and email from table "contacts" which is dispayed on page and on the same page post notes to table "contactnotes" and then display them under the textbox. I can't figure out how to do it all on the same page. Here is what I have thus far.
 <?php
 mysql_connect ("link","db","pw") or die ('Error: ' .mysql_error());
 mysql_select_db ("db");

 $ID = $_GET['ID'];
 $notes = $_POST['notes'];

 $query="INSERT INTO contactnotes (id, notes)VALUES ('NULL', '".$notes."')";

 mysql_query($query) or die ('Error Updating Database');

 $sql = "SELECT * FROM contacts WHERE ID='$ID' limit 1" or die ('Error: ' .mysql_error());
 $result = mysql_query($sql) or die ('Error: ' .mysql_error());

 while ($row = mysql_fetch_array($result);

 ?>

<?php include("contact-info.php"); ?>

 <form method="post" action="/db/notes.php?ID=<? echo $row['ID']; ?>"/>
 <input type="hidden" value="<? echo $row['id']; ?>" name = "id" id="id"/>

 <input type="submit" value="Edit Contact">
 <input type="submit" value="Delete Contact">

 Notes

 <textarea name="notes" id="notes" rows="5" cols="100"></textarea>

<? echo $row['user']; ?> on <? echo date("F d Y @ h:i:s", strtotime($row['timestamp'])); ?> wrote:

 <? echo $row['notes']; ?>

 <input type="submit" value="Edit Contact">
 <input type="submit" value="Delete Contact">
 </form>
 <?
 mysql_close();
 ?>

A: Check out MySQL JOIN.


text:
Q: SVN Repository - can checkout but commit gives a timeout I have configured a svn server and I can the checkout with no issue. But when I try commit, it takes long time and gives a "connection time out" error in Tortoise svn client. Does anyone have an idea how to resolve or where to check. seems this is a permission issue and I believe the user that I used has required write permission to the server.
Error

A:
seems this is a permission issue and I believe the user that I used
  has required write permission to the server.

This is not a permission issue. You have to check firewalls and your server configuration.

Does anyone have an idea how to resolve or where to check.

No. This is just a timeout error. You should revise your server configuration and check firewalls. There is a chance that your firewall rejects certain HTTP requests.


text:
Q: Magento Soap API Service Unavailable I have to connect to a shipping company for my online store using Magento Soap API. I cannot get the two to connect. I get The
request failed with HTTP status 503: Service Unavailable.
I have tried to turn off WS-I Compliance as well as WSDL and still nothing. It seems like the API service is not working. I have SOAP enabled on my server. If I try to visit the API service in my browser it redirects to my index page and never loads any SOAP XML. If I turn both WS-I and WSDL I get an error of
Procedure 'login' not present.
I cannot seem to get this figured out and running out of options.


text:
Q: ideal of an non-nuclear $C^*$ algebra If $A$ is a nuclear $C^*$-algebra,$I$ is a closed ideal of $A$,then $A/I$ is nuclear.
My question :Does there exist an non-nuclear $C^*$-algebra whose quotient is nuclear?

A: Of course. Take $A$ nuclear, $B$ non-nuclear, and consider $A\oplus B$. With $I=0\oplus B$, you have $(A\oplus B)/I\simeq A$.


text:
Q: FileNotFoundException when using an Interop assembly (even if the file exists) I am trying to automate actions against some in house ActiveX browser control.
I added a reference to the COM type in my C# code, which automagically generates the Interop.AssemblyName.dll
2 Weeks ago when i tested this, it worked like a charm, however trying the same code now fails with a FileNotFoundException when trying to get a reference to some type found in the interop assembly.
How can i trace back exactly what is the source of error? the Interop file exists right next to my test application's exe.
What else should i be looking for?
Is there any good tutorial on interoperability and problems of this kind?

A: It's looking in the wrong location...a location other than the one you expect. Simplest way to track this down is to look at the detail of the Exception, but if that's unrevealing I would use Process Monitor from Sysinternals to track down exactly what's going on.

A: I had this problem with a WMI class I created that hooked into a COM object to pull back information. WMI wrote to the event log that the Interop file for the COM object could not be found.
I resolved it just as Chris B. Behrens said: capture all disk IO while generating the exception and see where it is looking for, and failing to find, the interop file.
...And yes, my interop file was alongside my main application the entire time, however that directory was not one of the locations searched when the system tried to find it. Bizarre.
I copied my interop file to C:\Windows\System32\wbem and it magically started working (Windows XP x86).


text:
Q: How to query formula field and related object field values by Schema class I have this below method when I am passing fields dynamically to get passed object records.
relatedObjectName ==> Planner__c
recId ==> RecordId of Planner__c
fields = AccountPlanner__r.Email (Lookup to contact), Role__c (formula field of Planner__c object)

When I pass these values to below method, I am getting attempt to dereference null object at below line
string.valueOf(objectResult.fields.getMap().get(field).getDescribe().getType()) == 'REFERENCE'

What is the way I can include related object fields and formula fields in Schema class.
public static List<sObject> getRecords(String recId, String fields, String relatedObjectName,
                                           String conditions, String sortOrder, String relationship, String recordLimit, String offset) {

        List<sObject> relatedRecords = new List<sObject>();

        Id recordId = Id.valueOf(recId);
        Schema.SObjectType objectType = recordId.getSObjectType();
        String sObjectName = objectType.getDescribe().getName();
        DescribeSObjectResult objectResult = Schema.getGlobalDescribe().get(relatedObjectName).getDescribe();
        String finalFields = '';

        for (String field : fields.split(',')){
            system.debug('field ' + field);
            if (string.valueOf(objectResult.fields.getMap().get(field).getDescribe().getType()) == 'REFERENCE' ){
                finalFields = finalFields + ', ' + objectResult.fields.getMap().get(field).getDescribe().getRelationshipName() + '.Name' ;
            } else {
                finalFields = finalFields + ', ' + field;
            }
        }

        try{
            relatedRecords = Database.query(queryGenerator(finalFields.substring(1), relatedObjectName,recordLimit,offset, recordId,conditions,sortOrder));
            System.debug('RelatedRecords: ' + relatedRecords);

        }catch(Exception e){
            System.debug('Exception: '+ e);
        }

        return relatedRecords;
    }