text:
Q: iOS 5.1 Core Data Memory Leak I am trying to centralize Core Data calls for each Core Data entity into a Helper Class. Each Helper class contains the entity's fetch, update, and insert methods. For one entity helper class, I am getting a memory leak when I profile the application at this line:
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];

ARC is turned on and the leak appears after the view has been unloaded.
Here are the associated ViewController and Helper Class code:
ViewController.m:
@synthesize location // and other properties...;

- (void)viewDidLoad
{
    [self loadLocation];
    [super viewDidLoad];
}

- (void)viewDidUnload
{
    // Set properties to nil here

    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)loadLocation
{
    if (self.locationID.intValue > 0)
    {
        LocationCoreDataHelper *helper = [[LocationCoreDataHelper alloc] init];
        self.location = [helper selectLocationWithPredicate:[NSString stringWithFormat:@"id = %d", self.locationID.intValue]];

        if(self.location)
        {
            // Create a new coordinate of the user's location
            CLLocationCoordinate2D coord;
            coord.latitude = [self.location.latitude doubleValue];
            coord.longitude =[self.location.longitude doubleValue];

            // Annotate the point with user's information
            MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
            point.coordinate = coord;
            point.title = self.location.title;
            point.subtitle = self.location.subtitle;

            // Add the annotated point
            [mkMap addAnnotation:point];

            // Set the viewable region of the map
            MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(point.coordinate, 5000, 5000);

            [mkMap setRegion:region animated:YES];
        }

        helper = nil;
    }
}

The location property is defined as the entity's managed object class.
LocationCoreDataHelper.m:
@implementation LocationCoreDataHelper

- (id)init
{
    if(self = [super init])
    {
        // Setup the core data manager if needed
        if(managedObjectContext == Nil)
        {
            managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
        }
    }

    return self;
}

- (Location *)selectLocationWithPredicate:(NSString *)predicateString
{
    NSError *error = nil;

    // Build the entity and request
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Location" inManagedObjectContext:managedObjectContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];

    if(predicateString)
    {
        // Set the search criteria
        NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
        [request setPredicate:predicate];
    }

    // Perform the search
    // LEAK HERE
    NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];

    if(results.count >0)
    {
        return (Location *)[results lastObject];
    }
    else
    {
        return nil;
    }
}

// Other methods here
@end

I can't figure out why the memory leak is occurring there. Any ideas?
UPDATE #1:
If I replace this:
point.coordinate = coord;
point.title = self.location.title;
point.subtitle = self.location.subtitle;

with this:
point.coordinate = coord;
point.title = @"Title";
point.subtitle = @"Subtitle";

NSLog(@"%@", self.location.title);

I do not get the memory leak. Why is that?

A: Thanks to Inafziger for pointing me in the right direction. I ended up having to create a custom MKAnnotation class like so:
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface MyAnnotation : NSObject <MKAnnotation>

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy, readonly) NSString *title;
@property (nonatomic, copy, readonly) NSString *subtitle;

- (id) initWithCoordinates:(CLLocationCoordinate2D)paramCoordinates
                     title:(NSString *)paramTitle
                     subTitle:(NSString *)paramSubTitle;

@end

and I updated my View Controller like so:
MyAnnotation *point = [[MyAnnotation alloc] initWithCoordinates:coord
                                                          title:self.location.title
                                                       subTitle:self.location.subtitle];

By implementing the custom annotation class in this manner, it solved the issue of the memory leak. I'm still not a 100% sure why Instruments pointed the leak to the Core Data call. Perhaps because that is where the NSManagedObject originated and that wasn't what was getting released properly?


text:
Q: Xor String Encryption/Decryption Output Error I'm trying out xor encryption for strings in Python but for some reason I'm getting this weird output in terminal. Although the decryption runs just fine, transferring this data seems to be causing an error.
Line 1 is the plaintext string, 2-3 are the encrypted string output, 4 is the encrypted string decrypted, and 5 is the byte string for the encrypted string.
Hello world!
<
    U
Hello world!
\x3c\x0\x1f\x18\x1b\x45\x4\x1b\x6\x9\x17\x55

Here's how the encryption is working in Python.
    def encrypt(self, plaintext: str) -> str:
        ciphertext = ""

        for i in range(len(plaintext)):
            current = plaintext[i]
            current_key = self.key[i%len(self.key)]
            ciphertext += chr(ord(current) ^ ord(current_key))

        return ciphertext

And to actually call the encryption method is as follows.
            tmp2 = tmp2.strip('"')
            encryption = Encryption(self.key)
            encrypted_string = encryption.encrypt(tmp2)
            byte_string = encryption.to_byte_string(
                encrypted_string.encode('utf-8'))

What I'm trying to do with the last line of output (byte string), is decrypt this xor string in a C++ program. However the output for that program is just giving me an H.
#define POLY_ENGINE_KEY "test"

static string Decrypt(string ciphertext)
    {
        string plaintext = ciphertext;

        for (int i = 0; i < ciphertext.size(); i++)
            plaintext[i] = ciphertext[i] ^ POLY_ENGINE_KEY[i % (sizeof(POLY_ENGINE_KEY) / sizeof(char))];

        return plaintext;
    }

Greatly appreciate some help with this.

A: Most likely the length/size of ciphertext is 1 in Decrypt(). It maybe because that encrypted text contains 0x00(NULL) ascii value in second place. So, turning that character array into std::string (I am guessing that what you have done in your code) makes a string with only one character. String constructor that takes only character array expects that the character array is NULL terminated. So, as it encounters NULL in second position, it creates a string with only the first character.You can try to create the string mentioning the length of the array alongside the character array. Like these -
char ciphered_bytes[] = {....};
int size = sizeof(ciphered_bytes)/sizeof(ciphered_bytes[0]);
std::string ciphertext(ciphered_bytes, size); // instead of only ciphertext(ciphered_bytes)

// Then call the Decrypt
std::string plaintext = Decrypt(ciphertext);

Also you might want to change string of Decrypt() to const string& as you are not changing the input string ciphertext.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nextcord send a message to a specific channel (discord.py fork) So, I've been trying to make a suggestion discord bot, so it sends a message to a specific channel when prompted and verified with a button, but I can't seem to make it work.
My code is here:
import nextcord
import os
import requests
import asyncio
import random
import catapi
import json
import nest_asyncio

nest_asyncio.apply()
apicat = catapi.CatApi(api_key=os.environ['CAT_API_KEY'])
loop = asyncio.new_event_loop()
intents = nextcord.Intents.default()
intents.members = True

client = commands.Bot(command_prefix = '$', intents=intents)
colors = [0x00ffee,0x32a852,0x4287f5,0xcc2af5,0xf7e7a6,0xdea4a2]

def run_coro(coroutine):
  return loop.run_until_complete(coroutine)

class YesOrNo(nextcord.ui.View):

  def __init__(self):
    super().__init__()
    self.value = None

  @nextcord.ui.button(emoji="✔", style=nextcord.ButtonStyle.success)
  async def yes(self, button: nextcord.ui.Button, interaction: Interaction):

    channel = client.get_channel(950111018405748746)
    embed = nextcord.Embed(title="Suggestion was sent!", color=0x51ff00)
    await channel.send("test")
    await interaction.edit(embed=embed, view=None)
    self.value = True
    self.stop()

  @nextcord.ui.button(emoji="✖", style=nextcord.ButtonStyle.danger)
  async def no(self, button: nextcord.ui.Button, interaction: Interaction):

    embed = nextcord.Embed(title="Suggestion was discarded!", color=0xff0000)

    await interaction.edit(embed=embed, view=None)
    self.value = False
    self.stop()

But I receive this error:
AttributeError: 'YesOrNo' object has no attribute 'client'
Any ideas how to fix it?
I've tried changing all the clients and stuff to bot, I've tried putting client inside the init, super init, class, ui.button, async def, and I STILL DO NOT KNOW WHAT'S WRONG!

A: Pass client and then define it with self.client, like this:
class YesOrNo(nextcord.ui.View):

#pass `client` here
               ↓
  def __init__(self):
    super().__init__()
    self.value = None
    self.client = client    # ← then define self.client

Your code will look like this:
class YesOrNo(nextcord.ui.View):

  def __init__(client, self):
    super().__init__()
    self.value = None
    self.client = client

  @nextcord.ui.button(emoji="✔", style=nextcord.ButtonStyle.success)
  async def yes(self, button: nextcord.ui.Button, interaction: Interaction):

    channel = client.get_channel(950111018405748746)
    embed = nextcord.Embed(title="Suggestion was sent!", color=0x51ff00)
    await channel.send("test")
    await interaction.edit(embed=embed, view=None)
    self.value = True
    self.stop()

  @nextcord.ui.button(emoji="✖", style=nextcord.ButtonStyle.danger)
  async def no(self, button: nextcord.ui.Button, interaction: Interaction):

    embed = nextcord.Embed(title="Suggestion was discarded!", color=0xff0000)

    await interaction.edit(embed=embed, view=None)
    self.value = False
    self.stop()

This is probably it.

• Sxviaat


text:
Q: undefined:1625 throw new JS_Parse_Error(message, filename, line, col, pos); I am using usemin and I have this error with the bootstrap file, if I make the reference from the page if it works
no fun:
It works well:
error:
undefined:1625
throw new JS_Parse_Error(message, filename, line, col, pos);
^
JS_Parse_Error [SyntaxError]: Invalid assignment
at JS_Parse_Error.get (eval at  (C:\Users\NIXON\Documents\mi_pagina_web\node_modules\usemin\node_modules\uglify-js\tools\node.js:27:1), :86:23)
at formatError (internal/util/inspect.js:1140:38)
at formatRaw (internal/util/inspect.js:910:14)
at formatValue (internal/util/inspect.js:765:10)
at inspect (internal/util/inspect.js:310:10)
at afterInspector (internal/errors.js:718:14) {
filename: 'node_modules\bootstrap\dist\js\bootstrap.min.js',
line: 6,
col: 629,
pos: 866
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! mi_pagina_web@1.0.0 usemin: usemin index.html -d dist --htmlmin -o dist/index.html  && usemin about.html -d dist --htmlmin -o dist/about.html  && usemin productos.html -d dist --htmlmin -o dist/productos.html && usemin contacto.html -d dist --htmlmin -o dist/contacto.html
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the mi_pagina_web@1.0.0 usemin script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\NIXON\AppData\Roaming\npm-cache_logs\2021-07-31T18_30_28_567Z-debug.log

A: You have problem with an incompatibility between bootstrap file and uglify using es6, you can try exclude this file because is already minified and for custom files maybe modify them to complies es5 standards.
Also you can change uglify and configure in order to use es6 check this other question maybe gives you more answers


text:
Q: Count elements in a org-mode table NOI have an org-mode table with forth column containing only the words YES or NO
I would like to count how many Nos  I have.
I have little experience with calc, so from googling I got the following try:
#+TBLFM: @>$4=vcount(map(<if(eq($4,'NO'), 1, [])>, @I..@II))

which does not work. Thank for any help!

A: I have no experience with calc, so I will use lisp instead (I am not skilled either though). I think this should work:
#+TBLFM: @>$4='(apply '+ (mapcar (lambda (x) (if (string= "YES" x) 1 0)) '(@I$4..@II$4)))

Regarding your function, try to quote "$4" and use the string function eq("$4",string("NO") cf orgmode manual
Hope it helps.


text:
Q: replace values with NA in several columns I have a huge dataset and wish to replace values in certain columns (VAR1, VAR2) with NA if they do not start with AA or DD.
Data:
DF<-tibble::tribble(
  ~ID,  ~VAR1,    ~VAR1DATE,  ~VAR2,    ~VAR2DATE,
   1L, "AABB", "2001-01-01", "BBAA", "2001-01-01",
   2L, "AACC", "2001-01-02", "AACC", "2001-01-02",
   3L, "CCDD", "2001-01-03", "DDCC", "2001-01-03",
   4L, "DDAA", "2001-01-04", "CCBB", "2001-01-04",
   5L, "CCBB", "2001-01-05", "CCBB", "2001-01-05"
  )

Desired output:
A tibble: 5 × 5
     ID VAR1  VAR1DATE   VAR2  VAR2DATE
  <int> <chr> <chr>      <chr> <chr>
1     1 AABB  2001-01-01 NA    NA
2     2 AACC  2001-01-02 AACC  2001-01-02
3     3 NA    NA         DDCC  2001-01-03
4     4 DDAA  2001-01-04 NA    NA
5     5 NA    NA         NA    NA

Is there an elegant and smart way to this? mutate_all?

A: We may do this in two steps - loop across the columns that have 'VAR' followed by digits (\\d+) in column names, replace the values where the first two characters are not AA or DD to NA, then replace the corresponding DATE column to NA based on the NA in the 'VAR1', 'VAR2' columns
library(dplyr)
library(stringr)
DF %>%
    mutate(across(matches("^VAR\\d+$"),
        ~ replace(., !substr(., 1, 2)  %in% c("AA", "DD"), NA)),
      across(ends_with("DATE"),
     ~ replace(., is.na(get(str_remove(cur_column(), "DATE"))), NA)))

-output
# A tibble: 5 × 5
     ID VAR1  VAR1DATE   VAR2  VAR2DATE
  <int> <chr> <chr>      <chr> <chr>
1     1 AABB  2001-01-01 <NA>  <NA>
2     2 AACC  2001-01-02 AACC  2001-01-02
3     3 <NA>  <NA>       DDCC  2001-01-03
4     4 DDAA  2001-01-04 <NA>  <NA>
5     5 <NA>  <NA>       <NA>  <NA>

A: Here is a tidyverse solution. Using across with str_replace_all and appending two ifelse statements.
library(dplyr)
library(stringr)

DF %>%
  mutate(across(c(VAR1, VAR2), ~str_replace_all(., "^[^AA|DD]", NA_character_))) %>%
  mutate(VAR1DATE = ifelse(is.na(VAR1), NA_character_, VAR1DATE),
         VAR2DATE = ifelse(is.na(VAR2), NA_character_, VAR2DATE))

     ID VAR1  VAR1DATE   VAR2  VAR2DATE
  <int> <chr> <chr>      <chr> <chr>
1     1 AABB  2001-01-01 NA    NA
2     2 AACC  2001-01-02 AACC  2001-01-02
3     3 NA    NA         DDCC  2001-01-03
4     4 DDAA  2001-01-04 NA    NA
5     5 NA    NA         NA    NA

A: Use mutate/across with the assignment function is.na<-.
DF %>%
  mutate(across(starts_with("VAR"), \(x) `is.na<-`(x, !grepl("^AA|^DD", x))))
## A tibble: 5 x 5
#     ID VAR1  VAR1DATE VAR2  VAR2DATE
#  <int> <chr> <chr>    <chr> <chr>
#1     1 AABB  NA       NA    NA
#2     2 AACC  NA       AACC  NA
#3     3 NA    NA       DDCC  NA
#4     4 DDAA  NA       NA    NA
#5     5 NA    NA       NA    NA

Or simpler:
DF %>%
  mutate(across(starts_with("VAR"), ~`is.na<-`(., !grepl("^AA|^DD", .))))

A: Another possibility, using tidyr::unite and tiydr::separate:
library(tidyverse)

DF<-tibble::tribble(
  ~ID,  ~VAR1,    ~VAR1DATE,  ~VAR2,    ~VAR2DATE,
  1L, "AABB", "2001-01-01", "BBAA", "2001-01-01",
  2L, "AACC", "2001-01-02", "AACC", "2001-01-02",
  3L, "CCDD", "2001-01-03", "DDCC", "2001-01-03",
  4L, "DDAA", "2001-01-04", "CCBB", "2001-01-04",
  5L, "CCBB", "2001-01-05", "CCBB", "2001-01-05"
)

DF %>%
  unite(VAR1,VAR1,VAR1DATE) %>% unite(VAR2,VAR2,VAR2DATE) %>%
  mutate(across(starts_with("VAR"),~if_else(str_detect(.x, "^AA|^DD"), .x, NA_character_))) %>%
  separate(VAR1,into = c("VAR1", "VAR1DATE"), sep = "_") %>%
  separate(VAR2,into = c("VAR2", "VAR2DATE"), sep = "_")

#> # A tibble: 5 × 5
#>      ID VAR1  VAR1DATE   VAR2  VAR2DATE
#>   <int> <chr> <chr>      <chr> <chr>
#> 1     1 AABB  2001-01-01 <NA>  <NA>
#> 2     2 AACC  2001-01-02 AACC  2001-01-02
#> 3     3 <NA>  <NA>       DDCC  2001-01-03
#> 4     4 DDAA  2001-01-04 <NA>  <NA>
#> 5     5 <NA>  <NA>       <NA>  <NA>

A: Here is another tidyverse solution with using str_detect to determine where to convert to NA for the date columns. Then, we can use the same type of function on VAR1 and VAR2.
library(tidyverse)

DF %>%
  rowwise %>%
  mutate(
    VAR1DATE = ifelse(str_detect(VAR1, '^BB|^CC') == TRUE, NA, VAR1DATE),
    VAR2DATE = ifelse(str_detect(VAR2, '^BB|^CC') == TRUE, NA, VAR2DATE)
  ) %>%
  mutate(across(c(VAR1, VAR2), function(x)
    ifelse(str_detect(x, '^BB|^CC') == TRUE, NA, x)))

Output
# A tibble: 5 × 5
# Rowwise:
     ID VAR1  VAR1DATE   VAR2  VAR2DATE
  <int> <chr> <chr>      <chr> <chr>
1     1 AABB  2001-01-01 NA    NA
2     2 AACC  2001-01-02 AACC  2001-01-02
3     3 NA    NA         DDCC  2001-01-03
4     4 DDAA  2001-01-04 NA    NA
5     5 NA    NA         NA    NA


text:
Q: SQL Query fails with no error message I use CodeIgniter 3 and I'm trying to change a SQL Query from

SELECT id, shelfmark from documents  where collection_id='ubb'

to

SELECT document_id, shelfmark from documents_revisions
       where collection_id='ubb' and latest='1'

The first SQL Query is generated with:
 public function getDocumentsForCollection($sCollectionId) {
    $this->db->select('id, shelfmark');
    $this->db->where('collection_id', $sCollectionId);
    $query = $this->db->get('documents');
    if($query->num_rows() > 0) {
      return $query->result();
    }
    else {
      return '';
    }
  }

In order to match the second SQL Query I updated this method to
  public function getDocumentsForCollection($sCollectionId) {
    $this->db->select('document_id, shelfmark');
    $where = "collection_id=" . $sCollectionId . " AND latest=1";
    $this->db->where($where);
    $query = $this->db->get('documents_revisions');
    if($query->num_rows() > 0) {
      return $query->result();
    }
    else {
      return '';
    }
  }

When I open the page where the function is executed I just see a blank page.
How can I debug in CodeIgniter to see the generated SQL query of my PHP function?
What's wrong with my updated PHP function?

I updated the method to:
  public function getDocumentsForCollection($sCollectionId) {
    $this->db->select('document_id, shelfmark');
    $where = array("collection_id"=>$sCollectionId,"latest"=>1);
    $this->db->where($where);
    $query = $this->db->get('documents_revisions');
    var_dump($query); exit;
    if($query->num_rows() > 0) {
      return $query->result();
    }
    else {
      return 'foo';
    }
  }

With var_dump($query) right before the if conditional I get:

object(CI_DB_mysqli_result)#65 (8) { ["conn_id"]=> object(mysqli)#16
  (19) { ["affected_rows"]=> int(160) ["client_info"]=> string(79)
  "mysqlnd 5.0.12-dev - 20150407 - $Id:
  b5c5906d452ec590732a93b051f3827e02749b83 $" ["client_version"]=>
  int(50012) ["connect_errno"]=> int(0) ["connect_error"]=> NULL
  ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0)
  { } ["field_count"]=> int(2) ["host_info"]=> string(25) "Localhost via
  UNIX socket" ["info"]=> NULL ["insert_id"]=> int(0) ["server_info"]=>
  string(23) "5.7.18-0ubuntu0.16.04.1" ["server_version"]=> int(50718)
  ["stat"]=> string(139) "Uptime: 252001 Threads: 3 Questions: 36434
  Slow queries: 0 Opens: 501 Flush tables: 1 Open tables: 313 Queries
  per second avg: 0.144" ["sqlstate"]=> string(5) "00000"
  ["protocol_version"]=> int(10) ["thread_id"]=> int(2507)
  ["warning_count"]=> int(0) } ["result_id"]=> object(mysqli_result)#38
  (5) { ["current_field"]=> int(0) ["field_count"]=> int(2)
  ["lengths"]=> NULL ["num_rows"]=> int(160) ["type"]=> int(0) }
  ["result_array"]=> array(0) { } ["result_object"]=> array(0) { }
  ["custom_result_object"]=> array(0) { } ["current_row"]=> int(0)
  ["num_rows"]=> NULL ["row_data"]=> NULL }

The affected_rows represents the amount of documents I get if I run the SQL query directly in MySQL: ["affected_rows"]=> int(160)

A: You must pass an array in case of multiple conditions in db->where() clause
$where = array("collection_id"=>$sCollectionId,"latest"=>1);

FULL CODE:
public function getDocumentsForCollection($sCollectionId) {
$this->db->select('document_id, shelfmark');
$where = array("collection_id"=>$sCollectionId,"latest"=>1);
$this->db->where($where);
$query = $this->db->get('documents_revisions');
if($query->num_rows() > 0) {
  return $query->result();
}
else {
  return 'foo';
}

}
will generate the result as follows:
SELECT `document_id`, `shelfmark` FROM (`documents_revisions`) WHERE `collection_id` = 'ubb' AND `latest` = 1

Using Where Clause Complete Guide: https://www.codeigniter.com/userguide3/database/query_builder.html#looking-for-specific-data


text: Q: How to set up Sql Server reporting services 2016 with Auth0 I am trying to set up my SQL Server Reporting Server 2016 to accept Auth0 authentication. I can not find any links with this information. Could anyone point me in the right direction for finding information on how this is done.


text:
Q: Difference between C: and C:/ I was just reading some java book and making some small programs for practice, I created a small code to get information about the path I entered, and the code is:
String path = JOptionPane.showInputDialog("Enter Path to analyze");

File file =  new File(path);

if (file.exists())
{
    String result = "";
    if (file.isDirectory())
    {
        result += "Path is directory\n ";
        String [] resList = file.list();

        for (String s : resList)
        {
            result += s + ", ";
        }
    }
    if (file.isFile())
    {
        result += "Path is a file\n";
    }

    JOptionPane.showMessageDialog(null, result);

Now in the input dialogue, when I enter C:, the result is build, build.xml, manifest.mf, nbproject, src, but when I enter C:/, it shows the complete list of directories and files in C.
And strangely it does not happen with the D drive and other drives (i.e. the result is same for D:/ and D:), what is happening please explain?
Update
Same happens in WPF using C#!

A: This is not really a java question, but a windows/dos question.
The explanation comes down to the old dos command for switching drives.
Typing a drive letter followed by a colon is a command to change drives in dos, therefore the 'command' C: does nothing since your working dir is already on the C drive. The 'directory' returned by the native interface to the JRE is the same as if you used the path "", ie your working directory.
On the other hand, add a slash and it is a proper path, to the root of your C drive, therefore your JRE is given this directory by the native interface.
If you go to a dos command (windows>run>cmd) and type in C: you will see that it accepts the command but does not change directory, unless of course you are currently on a different drive at the time.
hope that helps.

A: C: means "whatever directory is currently selected on drive C:". In your case, it's probably the directory that your application is running from.
D: is the same as D:/ in your case because the root directory is the current working directory in D:.


text:
Q: wordpress auto login after registration I have this code under my registration form, it doesn't redirect to the profile page, Note: redux_demo['profile'] contains the link to the profile page.
if ($_POST['answer'] == $_POST['answer-hidden']) {
  $user_name = $wpdb->escape($_POST['username']);
  $user_email = $wpdb->escape($_POST['email']);
  $password = $wpdb->escape($_POST['pwd']);
  $confirm_password = $wpdb->escape($_POST['confirm']);
  $user_id = username_exists( $user_name );

  if (!$user_id and email_exists($user_email) == false and !empty($user_email) and !empty($user_name) and is_email($user_email)) {
    $user_id = wp_create_user( $user_name, $password, $user_email );
    $from = get_option('admin_email');
    $headers = 'From: '.$from . "\r\n";
    $subject = "Registration successful";
    $msg = "Registration successful \n Your login details \n Username: $user_name \n Password: $password \n $login";
    $headers2 = 'From: '.$user_email . "\r\n";
    $subject2 = "New user register on your website.";
    $msg2 = "New user register on your website \n User details are \n Username: $user_name \n Email: $user_email";
    wp_mail( $user_email, $subject, $msg,  $headers);
    wp_mail( $from, $subject2, $msg2,  $headers2);
    $login_data = array();
    $login_data['user_login'] = $user_name;
    $login_data['user_password'] = $password;
    $user_verify = wp_signon( $login_data, false );

    // wp_signon is a wordpress function which authenticates a user. It accepts user info parameters as an array.
    if (isset($_POST['op-register'])) {
      if ($_POST['submit'] == 'Register') {
        if (is_wp_error($user_verify)) {
            $UserError = __('Invalid username or password. Please try again!','agrg');
        } else {
            echo $profile;
            global $redux_demo;
            $profile = $redux_demo['profile'];
            wp_redirect( $profile );

        }
      }
    }
  }
}

A: remove
    echo $profile;
before
    wp_redirect( $profile );


text:
Q: Winforms semi-transparent PNG over semi-transparent PNG I think I must be missing something obvious, but I'm unable to find this after several hours of searching.  Is there no way to use a PictureBox or other control to contain an image with partial transparent/alpha-blended pixels, and place that over another image and have the blending be based on the image under it?
For example, this produces the results I want:

*

*Place a panel on a form.

*Add an OnPaint handler.

*In the OnPaint handler draw 1 PNG, then draw another PNG over it, using Graphics.DrawImage for both.

This does not:

*

*Place a PictureBox on a form and set it to a PNG.

*Place another PictureBox on the form and set it to a PNG.

*Place the 2nd picture box over the first.
...even if the 2nd picture box is just empty and has a background color of Transparent, it still covers the picture below it.
I've read this stems from all winform controls being windows, so by nature they aren't transparent.
...but even the 15 year old platform I'm migrating from, Borland's VCL, had several windowless controls, so it's hard to imaging winforms doesn't at least have some easy solution?
My first example above is one answer, true, but that adds a lot of work when you can only use one big panel and draw all of your "controls" inside of it.  Much nicer if you can have separate controls with separate mouse events/etc.  Even if not an image control, and a control I have to draw myself, that would be fine, as long as I can just put one image in each control.  In VCL they called this a "paint box", just a rectangle area you could place on a form and draw whatever you want on it.  Has it's own mouse events, Bounds, etc.  If you don't draw anything in it, it is like it's not even there (100% transparent) other than the fact it still gets mouse events, so can be used as a "hot spot" or "target" as well.

A: The PictureBox control supports transparency well, just set its BackColor property to Transparent.  Which will make the pixels of its Parent visible as the background.
The rub is that the designer won't let you make the 2nd picture box a child of the 1st one.  All you need is a wee bit of code in the constructor to re-parent it.  And give it a new Location since that is relative from the parent.  Like this:
    public Form1() {
        InitializeComponent();
        pictureBox1.Controls.Add(pictureBox2);
        pictureBox2.Location = new Point(0, 0);
        pictureBox2.BackColor = Color.Transparent;
    }

Don't hesitate to use OnPaint() btw.

A: Sorry, I just found this... once I decided to Google for "winforms transparent panel" instead of the searches I was doing before, the TransPictureBox example show seems to do exactly what I need:
Transparency Problem by Overlapped PictureBox's at C#
Looks like there are 2 parts to it:

*

*Set WS_EX_TRANSPARENT for the window style

*Override the "draw background" method (or optionally could probably make the control style Opaque).


text:
Q: How to set data inside a QAbstractTableModel I need to implement a table with Qt.
I believe I'll be suing a QAbstractTableModel, with a QTableView using this model.
I understand I'll have to edit the rowCount(), columnCount(), and data() functions of the model.
However, I don't understand how to exactly set the data inside the model, so that data() function can retrieve it..
Is the setData() function provided for this purpose? I have seen it takes EditRole as its parameter, which I don't want, as I don't want my table to be editable.
So, how do I "set" data inside the model, or have data for the model to get at, using data() function?
Also, how is the data() function called, i.e., who calls it and where would it need to be called?
Please help me with this.
Thanks.

A: You don't need to use setData(...). Instead, you need to subclass QAbstractTableModel in such a way that its methods rowCount(), columnCount(), data(index) and potentially headerData(section, horizontalOrVertical) return the data you wish to display. Here's an example based on PyQt5:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

headers = ["Scientist name", "Birthdate", "Contribution"]
rows =    [("Newton", "1643-01-04", "Classical mechanics"),
           ("Einstein", "1879-03-14", "Relativity"),
           ("Darwin", "1809-02-12", "Evolution")]

class TableModel(QAbstractTableModel):
    def rowCount(self, parent):
        # How many rows are there?
        return len(rows)
    def columnCount(self, parent):
        # How many columns?
        return len(headers)
    def data(self, index, role):
        if role != Qt.DisplayRole:
            return QVariant()
        # What's the value of the cell at the given index?
        return rows[index.row()][index.column()]
    def headerData(self, section, orientation, role):
        if role != Qt.DisplayRole or orientation != Qt.Horizontal:
            return QVariant()
        # What's the header for the given column?
        return headers[section]

app = QApplication([])
model = TableModel()
view = QTableView()
view.setModel(model)
view.show()
app.exec_()

It's taken from this GitHub repository and displays the following table:

A: How the actual data is kept in memory, generated or queried from a data store is completely up to you. If it's static data, you can use the Qt container classes or custom data structures.
You only need to reimplement the setData() method for editable models.
There are 4 methods you need to implement in a non-editable QAbstractTableModel subclass:

*

*int rowCount()

*int columnCount()

*QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole )

*QVariant data(const QModelIndex & index, int role = Qt::DisplayRole)
These methods are called from the view, usually a QTableView instance. The first two methods should return the dimensions of the table. For example, if rowCount() returns 10 and columnCount() returns 4, the view will invoke the data() method 40 times (once for each cell) asking for the actual data in your model's internal data structures.
As an example suppose you have implemented a custom slot retrieveDataFromMarsCuriosity() in your model. This slot populates a data structure and is connected to a QPushButton instance, so you get fresh data by clicking a button.
Now, you need to let the view know when the data is being changed so it can update properly. That's why you need to emit the beginRemoveRows(), endRemoveRows(), beginInsertRows(), endInsertRows() and its column counterparts.
The Qt Documentation has everything you need to know about this.


text:
Q: Finding the local extrema of $f(x, y) = \sin(x) + \sin(y) + \sin(x+y)$ on the domain $(0, 2 \pi) \times (0, 2 \pi)$ I am trying to find the relative extrema of
$$f(x, y) = \sin(x) + \sin(y) + \sin(x+y), \text{  where  } (x, y) \in (0, 2 \pi) \times (0, 2 \pi)$$
Setting the partial derivatives equal to zero gives
$$\frac{\partial f}{\partial x}(x, y) = \cos(x) + \cos(x+ y) = 0$$
$$\frac{\partial f}{\partial y}(x, y) = \cos(y) + \cos(x+ y) = 0$$
Subtracting the equations gives $\cos(x) = \cos (y)$, and since $0 < x, y < 2 \pi,$ we can see from the unit circle that this equation holds $\iff y = 2\pi - x \iff x+y = 2\pi$. Now using this information in the two equations above, we get
$$\cos(x) + \cos(2 \pi) = 0 \implies x = \pi$$
$$\cos(y) + \cos(2 \pi) = 0 \implies y = \pi$$
However, I graphed $f$, and this seems incorrect. In the pictures, we can see that there appears to be a local maximum around $(1, 1)$ and around $(5.5, 5.5)$. Could someone please tell me my mistake?

A: We have that
$$\cos(x) = \cos (y) \implies x=y \:\lor\: x=2\pi-y$$
it seems you only have considered the second condition.

A: hint
The equation
$$\cos(x)=\cos(y)$$ has a solution, other than the one you gave,  which is simply $ x=y$.
after replacing this in the two equations, one gets
$$\cos(x)+\cos(2x)=0$$
or
$$2\cos^2(x)+\cos(x)-1=0$$
thus
$$\cos(x)=\frac{-1\pm \sqrt{9}}{4}$$
$$=\frac 12 \text{ or } -1$$


text:
Q: Noscript form fallback for no javascript browser I am coding a landingpage for one of our future products and I have a little trouble with that

    <form novalidate method="POST" class="subscribe-form">

      </form>
      <form method="POST" action="/" class="subscribe-form">

      <input type="email" placeholder="{subscribe-status}" class="input-lg" name="email">
      <input type="text" value="general" class="hidden" name="interest" class="interest-field">
      <input type="submit" value="Let me know!" class="btn btn-blue btn-lg" data-location="header">
    </form>
    *Prepare to be amazed. We promise we won't spam you.

The idea is to have defined form for js supporting browser and be ready for client side validation, but in case of noscript browser to have a fallback ready. But chrome renders it like that
Any

A: The HTML is not valid; different browsers are likely to render it differently.  The W3C validator is your friend: http://validator.w3.org/
If JS is turned off, your validation won't run, and you don't really need to do anything about that; just write one form and use it for both cases.  If you need/want to know server-side whether the client side validation has been run, include <input type="hidden" name="clientvalidated" value="false"> in your form and change the value attribute to true with JS.
Note that you must validate at the server anyway because the client is untrusted.

A: Browsers have different behavior how to render the DOM
one option is to turn on/off the noValidate with javascript
<form id="myForm" novalidate method="POST" class="subscribe-form">

    <input type="email" placeholder="{subscribe-status}" class="input-lg" name="email">
    <input type="text" value="general" class="hidden" name="interest" class="interest-field">
    <input type="submit" value="Let me know!" class="btn btn-blue btn-lg" data-location="header">
</form>
*Prepare to be amazed. We promise we won't spam you.

Another is to to toggle the visibility of js/no-js elements with css

A: This wont work because incase you have javascript disabled it will generate 3 tags ( and

Merging 2 forms in one which is not very clean and can have unwanted sideeffects.
I would suggest you do it otherwise, create 2 complete forms mark them with an ID. The JavaScript version should be hidden by default. Then JavaScript should perform the changes that are nesessary only if JavaScript works.
<form id="this_is_for_javascript_mode" method="post" style="display: none;">
    -put form content here...-
</form>

<form id="this_is_for_non_javascript_mode" method="post">
    -put form content here...-
</form>

And then simply control visiblity by JavaScript.
This will work because a script-tag will not be executed if JavaScript id disabled in the browser!


text:
Q: Setting Thread.CurrentPrincipal in MVC Application so that it can be used in service layer I am confused as to whether or not it is safe to set the Thread.CurrentPrincipal equal to the signed in user in an MVC application i.e. so that I can perform authorization checks in my service layer?
This stackoverflow post recommends doing this.... but in this post the author suggests that there are issues with setting Thread.CurrentPrincipal. What exactly are these issues?
Also would I need to set the Thread.CurrentPrincipal for every request made by a logged in user?


text:
Q: How to combine values based on condition of two different keys in key-value map? I am struggling with basic operations on key value maps in pyspark. Below is problem description:
data = {(1, [2, 3, 4]), (2, [a, b, 3]), (3, [x, y]) }

I want to get all the values of the keys that are not contained in the current value list. The result should be like this:
data = {(1, [a, b, x, y]), (2, [x, y]), (3, []) }

Before even filtering the results I was just trying to combine values, with several approaches:

*

*Send data to a function and create nested loops to transform the data: failed as I couldn't get my RDDs to iterate properly

*Iterate through data using map: data.map(lambda x: (x[0], x[1].map(lambda a,b: (x[a] + x[b])))): failed as the list doesn't have map or flatMap attributes

*Using valuemap method: data.flatMapValues(lambda a, b: (data.lookup(a) + data.lookup(b))).
Btw, I am completely new to pyspark so my approaches might be naive, but is there a way to make any of these work or is there different approach that I should use?

A: I think you want to do something like the following:
1) Collect all the values (Assuming they'll fit in memory. If not, I'd have to think more):
values = (data.mapValues(lambda x: set(x))
              .values()
              .reduce(lambda x, y: x.union(y))
              .collect())

2) (Probably after broadcasting the values) Map over the values to end up with your final lists
data.mapValues(lambda x: [y for y in values if y not in x])

Iterate through data using map: data.map(lambda x: (x[0], x[1].map(lambda a,b: (x[a] + x[b])))): failed as the list doesn't have map or flatMap attributes

A quick note on this. You want the Python bultin map. The syntax is map(function, sequence).


text:
Q: GNU time(1) reports wrong I/O count on fedora 16, running time(1) on a small program that just does 10 writes of 1024 bytes to a file, reports "24 outputs". I was expecting the I/O count to be 10. Note that if i run strace on the program I can see the 10 write() calls.
So what is the I/O count as reported by time(1)?
thanks a lot
#!/usr/bin/python

import os
import pdb

SIZE_IO=1024
IONB=10

def test1(file):
    #pdb.set_trace()
    buffer= '\x01' * SIZE_IO
    fd = os.open(file, os.O_CREAT|os.O_RDWR, 0777)
    for ix in range(IONB):
        len = os.write(fd, buffer)
        print len
    os.close(fd)
    return 1

if name__== "__main":
    test1("ttt.txt")
    print 'ok'

A: Isn't each print going to cause a write as well?

A: excerpt from the ACCURACY section in time(1) manpage :

The  '%I' and '%O' values are allegedly only 'real' input and output
  and do not include those supplied by caching devices.  The meaning
  of 'real' I/O reported by '%I' and '%O' may be muddled for workstations,
  especially diskless ones.


text:
Q: Haskell -- mapping function to permutation I defined function listToNumber as below:
listToNumber = foldl1 (\acc xs -> acc*10 + xs)

It works fine when only supplied with one numeric list, for example:
listToNumber [1,2,3,4] = 1234
map listToNumber [[1,2,3,4], [5,4,3,2]] = [1234,5432]

However, the following returns error message:
map listToNumber permutations[1..3]

can someone explain please?
P.S. the error msg is as below:
Couldn't match expected type `[t1] -> t0' with actual type `[b0]'
The function `map' is applied to three arguments,
but its type `([b0] -> b0) -> [[b0]] -> [b0]' has only two
In the expression: map listToNumber permutations [1 .. 3]
In an equation for `it':
    it = map listToNumber permutations [1 .. 3]

A: try map listToNumber (permutations [1 .. 3])
in ghci you can check the type of a function or an expression with :t
> :t map
> map :: (a -> b) -> [a] -> [b]

im means map requires a function and  a list and returns a list, but in map listToNumber permutations [1 .. 3] you try to pass two functions and a list to map
(since function application associates to the left).

A: Another variant: map listToNumber $ permutations [1..3].


text:
Q: javascript trying to drop the decimal I'm trying to format 65.32 to become 6532
65.32 * 100 gets me 6531.999999999999.
Why does it do that? Is it a bug? Should I change it to a string and use string manipulation instead?

A: Generally speaking, if you're dealing with numbers it's usually better to stick with numbers.  It makes your code more readable and easier to follow. The Math library provides what you need.

var x = 62.29933;
console.log(x*100);
x = Math.floor(62.29933*100);
console.log(x);
x = Math.ceil(62.29933*100);
console.log(x);
x = Math.round(62.29933*100);
console.log(x);


text:
Q: Serving media files in Chunks I have huge video files (size: 200mb average) stored in my media folder.
I fetch those files using os.listdir and then store them in dictionary, with respect to storing filename, date (fetch from file) and time (fetched from file) against each file in the dir '../media/videos/'. Refer to code below:
file_names = [os.path.join('../media/videos/',fn) for fn in os.listdir(path) if fn.startswith(example_20_Apr_20)]
    file_names_final=[]
    for item in file_names:
            tmp=item.split("-")
            file_names_final.append({'file_name':item,'date':"-".join(tmp[-6:-3]),'time':"-".join(tmp[-3:-1])})
    print(file_names_final) #for debugging

Then i place those files in the template. Refer to code section below:
{% for i in files %}

                                <video class="video-container" preload="auto">
                                    <source src="{{ i.file_name }}#t=0.5" type="video/mp4">
                                </video>

                                Location : {{location}}

                                Date : {{i.date}}

                                Time (24h): {{i.time}}

                {% endfor %}

FYI, im passing file_names_final in context as files
The problem that I'm running into is, when I try to stream the files from external network, I just can't load the huge files that may size around 200mb, however i'm able to stream the files that are roughly within the 10mb to 50mb ballpark.
This may primarily be due to the internet connectivity, and it is bound to happen, but this issue kept me wondering, does the django development server have an issue with large files being streamed? Just a wild thought!
But what i would like to achieve is, to break this video files in suitable chunks, and then server them in the html5 video player, through django/python


text:
Q: Trying to dynamically create a div and append it to body element but not working? I browsed a few questions here regarding dynamically injecting a div to the body element. It seems pretty simple, but for some reason, this is not working:
var div = document.createElement("div");
div.id = "uniqueID";
document.body.appendChild( div );

The specific error is returned in Google Chrome's developer console: Uncaught TypeError: Cannot call method 'appendChild' of null.

A: Are you running this script after the DOM has been loaded? For example,
window.onload = function() {
    // your code
};


text:
Q: How to add newline to textarea after label I'm trying to get the following pattern which is from Microsoft Word:

and in HTML I'm getting:

How do i code it in the way where the textarea is after the label like the visualization in word above?

<!DOCTYPE html>

    <meta charset = "UTF-8">
    <title>testform</title>
    <link rel = "stylesheet" href = "test2.css">

        Enter your address
        <textarea id = "addr_out"></textarea>

A: *

*Make the entity a flexbox container and use
margin-bottom for the entity label.

*Use rows attribute to enlarge the text area
according to your desired layout.

.entity {
  display: flex;
  flex-direction: column; /* Vertical alignment of the flexbox container */
  width: 300px;
}

label {
  margin-bottom: 10px; /* Go down you Textarea! */
}

textarea {
  border: 2px solid #70AD47;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>testform</title>
  <link rel="stylesheet" href="test2.css">

    Enter your address
    <textarea id="addr_out" rows="10"></textarea>

A: This can be done in a couple of ways:
(old hack) would be adding
 after the label but I don't recommend this:
Enter your address

Or you can also make it so the label and the textarea is wrapped on a different div considering that div is full width:

   Enter your address

   <textarea id = "addr_out"></textarea>

OR you can do it on css, either make the label width 100%:
textarea {
  width: 100%;
}

OR make the .entity use flex:
.entity {
  display: flex;
}

A: Just add display: block.

#addr_out {
  border: 2px solid green;
  width: 200px;
  height: 100px;
  display: block;
  resize: none;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>testform</title>
  <link rel="stylesheet" href="test2.css">

    Enter your address
    <textarea id="addr_out"></textarea>

A: *

*Simply, add
 tag between  and <textarea> selectors.

*You can change the style of  with display: block.

<!DOCTYPE html>

    <meta charset = "UTF-8">
    <title>testform</title>
    <link rel = "stylesheet" href = "test2.css">

        Enter your address

        <textarea id = "addr_out"></textarea>

A: What about something like this
I added some css code to make your label & textarea according to your need.

.entity label::after{
      content: "\a";
      white-space: pre;
}
.entity textarea{
      border: 2px solid green;
      width: 200px;
      height: 100px;
      margin-top: 5px;
      resize: none;
}
<!DOCTYPE html>

    <meta charset = "UTF-8">
    <title>testform</title>
    <link rel = "stylesheet" href = "test2.css">

        Enter your address
        <textarea id = "addr_out"></textarea>

Explaination:
Css Line 2:-  Set the content property to "\a" (this character for new-line) after label using ::after pseudo-class.
Css Line 3:-  Set white-space property to pre. because the browser will read every white-space, in your given class, as a white-space.
Css Line 6:-   Set the border of textarea thick and green.
Css Line 7 & 8:-   Set the height and width to 200px and 100px respectively, to make it enlarge.
Css Line 9:-   Set top margin to 5px, to add more space.
Css Line 10:-  Set the resize property to none to tell the browser to do not make the textarea resizable.
Hope this will helpful for you, thank you .

A: I recommend to use display: block for all labels inside a specific div, in this case ".entity" for example or a parent div used to contain your form. With this approach all the labels you add inside this div will follow the same layout automatically. See example below.
I don't recommend using
 after a label as some of the other answers suggest here. The reason is because any additional label you add will require you to manually do the same. Not only this approach relies on human action but it will also flood your code with unnecessary html tags.

.entity label {
display: block;
}
<!DOCTYPE html>

    <meta charset = "UTF-8">
    <title>testform</title>
    <link rel = "stylesheet" href = "test2.css">

        Enter your address
        <textarea id = "addr_out"></textarea>


text:
Q: Can't import: PyCharm "Unsolved Reference", Python "No module named ..." A file named Item defines class Fists:
class Fists(Weapon):
    def __init__(self):
        super().__init__(name="Fists",
                         desc="Just fists",
                         value=0,
                         usable=1,
                         damage=1)

A file named Enemy in the same directory defines class Slime:
import Item

class Slime(Enemy):
    def __init__(self):
        super().__init__(enemyhealth=23,
                         enemyweapon=Item.Fists,
                         enemyshield=None)

As you see, I'm trying to give instances of Slime the ability to instantiate Fists, but PyCharm gives the warning: Unsolved Reference 'Item'. When run, Python gives an ImportError No module named 'Item'. How can make it work? I searched everywhere and nothing helped me.

A: Make sure your IDE is in the current directory (use a shortcut or os.chdir). If you are using IDLE, in some versions it will not work if you right click and press 'Edit with IDLE'.


text:
Q: Low RAM for application in Linux I install software in Linux called Spades, but I can't run it because of a RAM problem.
When I tap the "spades.py --test" command, I get this error:

When I tap the "free" command to check the swap memory, I have this result:

When I contacted support, Spades sent me this mail, but I still can't solve the problem:

here is the result of the command free -h and as you can see the memory swap is totally shared that's why it is no longer free!4


text:
Q: Kafka Streams add name to a block of steps in topology I am creating a kafka streams  library. I am trying to make the topology generic by having a fixed base topology and let the client modify on top of it.
Here is what it looks like:
@Override
public void configureTopology(final Topology topology) {
    KafkaStreamsInfrastructureCustomizer.super.configureTopology(topology);
    modifyTopology(topology);
}

@Override
public void configureBuilder(final StreamsBuilder builder) {

    final Consumed<A, B> consumed = config.getConsumed();
    final KStream<A, B> source = builder.stream(config.getSourceTopic(), consumed);
    final KStream<C, D> preProcessedStream = preProcess(builder, source);

    // Skipping the other topology steps which contain transformers.
    preProcessedStream.process(processorSupplier,
            Named.as("terminal-processor"));
}

public void modifyTopology(final Topology topology) {}

protected abstract KStream<C, D> preProcess(StreamsBuilder builder, KStream<A, B> stream);

*

*The preProcessStream is a function which the client will implement if they want to perform some preprocessing.

*They will use the modifyTopology to add new processors to the existing topology.

Questions:

*

*How can I add a name to the preProcess step so that if someone wants to add a processor in modifyTopology to consume after preProcess step, they can do so like below:

public void modifyTopology(final Topology topology) {
  topology.addProcessor("processor-name", OtherProcessor::new, "name-of-preprocess-step");
}

I am aware I can do so by adding a always true filter step with name. But is there any other way?

*

*Is it fine to use both configureBuilder and configureTopology like this?
I want to use configureBuilder because I am using a Transformer in my fixed topology.

I am aware that I can use a processor with context.forward in place of transformer but I want to make the library easy to implement for clients.


text:
Q: Why do I have to specify !important to a hover pseudo-class for it take effect? I had to use the !important property for a hover style to take effect. The code below would not work without me including the !important property. Why is that?
Non-working code
#sbw a.content_copy:link {
    color: #F12B63;
    padding: 10px;
}

#sbw a.content_copy:visited {
    color: #F12B63;
    padding: 10px;
}

#sbw a.content_copy:hover {
    color: #ffffff;
    background-color: #F12B63;
    padding: 10px;

}

Working code
#sbw a.content_copy:link {
    color: #F12B63;
    padding: 10px;
}

#sbw a.content_copy:visited {
    color: #F12B63;
    padding: 10px;
}

#sbw a.content_copy:hover {
    color: #ffffff !important;
    background-color: #F12B63;
    padding: 10px;

}

A: The rules with :visited and :link may appear to be more specific.
You may do this :
#sbw a.content_copy:hover, #sbw a.content_copy:visited:hover, #sbw a.content_copy:link:hover {
    color: #ffffff;
    background-color: #F12B63;
    padding: 10px;
}

A: color: #ffffff !important;

this only ensures that on Hover color #ffffff will always be applied.
for Example :-
p { color: red !important; }
 p { color: blue; }

For the paragraph color will always be red, irrespective of second line CSS.
Why to use !important
Suppose you are writing css for your page in which you added a style  p { color: red ;}
on the first line but later on you again added  p { color: blue;} for same element, So
your first style will be gone and always second style will applied by browser.
So if you add !important with your style it enforce browser to stick with that only.


text:
Q: Select and Deselect the checkboxs using JQuery I am using JQuery and I have below HTML with checkboxes in it.

                        <asp:CheckBox ID="chkSelectAll" CssClass="selectall-txt" runat="server" />

                            <asp:CheckBox ID="chkItemLists" CssClass="selectall-txt-1" runat="server" />

                            <asp:CheckBox ID="chkComponentLinks" CssClass="selectall-txt-1" runat="server" />

                            <asp:CheckBox ID="chkResourceKeyData" CssClass="selectall-txt-1" runat="server" />

Now I want whenever user selects "chkSelectAll" then it should select all other checkboxes and whenever user deselect any of them it should deselect the "chkSelectAll".
Please suggest!!

A: You would basically do something like this:
$('#myCheckAllCheckbox').click(function()
{
     // Other jQuery versions:
     if(this.checked)
        $('input[@type=checkbox]').attr('checked', 'checked');
     else
        $('input[@type=checkbox]').removeAttr('checked');

     // jQuery 1.6
     $('input[@type=checkbox]').prop('checked', this.checked);
});


text:
Q: How to use multiple conditions to validate form with react final form I have form inside my react app,
And i would like to use this condition to validate the form before send the data to backend.

 Diseño ChatBot

          <Form
            onSubmit={onSubmit}
            validate={values => {
             const errors = {};
             if (!values.text || !values.link ||!values.image) {
               errors.error = 'Es necesario cumplimentar uno de estos tres campo: Texto, Imagen, Link';
             } else {errors.error = undefined;}
             return errors;
           }}
            initialValues={{ title: title, text: text, link: link, link_title: link_title, image: image, image_title: image_title }}
            render={({ handleSubmit, values, errors }) => (
              <form id='editForm' className="row mt-4" onSubmit={handleSubmit} >

 Título

                  <Field
                    type="text"
                    className="form-control"
                    name='title'
                    component="input"
                    />

 Texto

                  <Field
                    className="form-control"
                    type="textarea"
                    name='text'
                    component="input"

                  />

 Link

                  <Field
                    className="form-control"
                    type="link"
                    name="link"
                    component="input"

                  />

 Title Link

                  <Field
                    className="form-control"
                    type="text"
                    name='link_title'
                    component="input"
                  />

 Image

                  <Field
                    name="image"
                    type="file"
                    component={UploadImage}
                  />

 Title Image

                  <Field
                    className="form-control"
                    type="text"
                    name='image_title'
                    component="input"
                  />

                  {(isCreated && !isVariationsError) &&

                      Respuesta EDITADA Correctamente

                  }

                  <Volver className={"btn btn-outline-danger me-5 mb-3"} prevStep={prevStep} step={2}/>
                  <button className="btn btn-outline-warning me-5 mb-3" onClick={(e) => (e.preventDefault(), openPreview(values))} >Preview</button>
                  <SaveAndEdit className={"btn btn-outline-success me-5 mb-3"} idForm={'editForm'} text={'Guardar Cambios'}/>
                  <Cancelar className={"btn btn-outline-dark  me-5 mb-3"} />

                {errors.error && <Error meta={errors.error} /> }

{JSON.stringify(values, undefined, 2)}

{JSON.stringify(errors, undefined, 2)}

              </form>
            )}
          />

I have outside the form this Component Error with this:
const Error = (meta) => (

{meta.meta}

  );

If i use just with one condition like
validate={values => {
             const errors = {};
             if (!values.text) {
               errors.error = 'Es necesario cumplimentar uno de estos tres campo: Texto, Imagen, Link';
             } else {errors.error = undefined;}
             return errors;
           }}

works Fine, but if i try to use more conditions inside the conditional, not works.
Any idea to guide me?
Thanks


text:
Q: Operator-> transistency and shared_ptr I recall reading somewhere, can't recall where though, that operator-> is transient. That it will look through objects with operator-> until it find something that isn't a pointer and then running a normal operator. on that. I have however run into a problem with this,
Consider this code:
#include <boost/shared_ptr.hpp>
#include <vector>
#include <iostream>

struct Foo {
    Foo(int val) : i(val) {}
    typedef boost::shared_ptr<Foo> ptr;
    int i;
};

int main(int argc, char** argv) {
    typedef std::vector<Foo::ptr> FooVec;
    FooVec v;
    for(FooVec::iterator it = v.begin(); it != v.end(); ++it) {
        std::cout <<it->i <<std::endl;
    }
    return 0;
}

I get this error:
ptr.cpp: In function 'int main(int, char**)':
ptr.cpp:15:19: error: 'class boost::shared_ptr<Foo>' has no member named 'i'
   std::cout <<it->i <<std::endl;

Since a boost::shared_ptr isn't a pointer. I could solve this by instead writing
std::cout <<(*it)->i <<std::endl

But I think that looks a lot worse, I tried std::shared_ptr as well but that got the same problem. Is there a nice way of solving this or am I stuck with (*it)->i?

A:
I recall reading somewhere, can't recall where though, that operator->
  is transient.

Not in C++.  You'll need to double-dereference as you already discovered.


text:
Q: How much memory does a union need I have the following union
typedef union rem{
    int addr;
    char addrbuf[32];
} foo;

A sizeof on the union provides the following output
foo addr;
printf("size is: %d\n",sizeof addr);

size is: 32
Does it mean that a union allocates or needs the memory equal to biggest element in the union at definition ?

A:
Does it mean that a union allocates or needs the memory equal to biggest element in the union at definition ?

Yes. Memory for the largest member is allocated. That's why the members of a union are stored at the same location.
Assuming int requires 4 bytes, for union
union{
    char c;
    int i;
} U;

memory will be allocated as:

Note that how c and i overlap. In fact c is first byte of i.

A: Memory occupied by union unlike structure will be memory for the largest member of the union. But depending on the implementation there might be extra padding at the end so there is no guarantee that the size of a union = size of the largest member. So you can say size of union will be atleast the size of the largest member in the union.
Side note: Since the memory is shared between all the members of the union only one member is active at a time.


text:
Q: Is there a way to reverse the order of a macro? Hello (I apologise in advance if I'm wrong in the tittle),
I'm writing a program and all, I created a macro but I want to use it in a reverse order like:
#define MAGIC "\x34\x19\x23\x4C"

Would become something like :
"\x4C\x23\x19\x34"

Is there a way to do it or I need to write a new one?
Thanks in advance.

A: Preprocessor is responsible for macros (so they are interpreted before your program executes).
If you would like to use both "\x34\x19\x23\x4C" and "\x4C\x23\x19\x34" in your code it would be much better to declare a static global variable and then modify it by simple reverse function. Or, in fact, declare two macros.


text:
Q: OPENGLES 2.0 PUSHMATRIX POP MATRIX implementation I am implementing an application in opengl es2.0. I need to use pushmatrix() and popmatrix(). We all know that this function is no more available in opengl es 2.0. I have tried to follow and implement the method given here. However I ddnt find too much success. Also we need to implement some huge number of header files for the same. Has anybody implemented this as a part of their project? If possible, can someone post some code snippet which will guide me to save and restore states of current matrices?

A: Say you have a simple linmath library, like this:
typedef GLfloat vec4[4];
inline void vec4_add(vec4 a, vec4 b)
{
    int i;
    for(i=0; i<4; ++i)
        a[i] += b[i];
}
inline void vec4_sub(vec4 a, vec4 b)
{
    int i;
    for(i=0; i<4; ++i)
        a[i] -= b[i];
}
inline void vec4_scale(vec4 v, GLfloat s)
{
    int i;
    for(i=0; i<4; ++i)
        v[i] *= s;
}
inline GLfloat vec4_inner_product(vec4 a, vec4 b)
{
    GLfloat p = 0.;
    int i;
    for(i=0; i<4; ++i)
        p += b[i]*a[i];
    return p;
}
inline GLfloat vec4_length(vec4 v)
{
    return sqrtf(vec4_inner_product(v,v));
}
inline void vec4_normalize(vec4 v)
{
    GLfloat k = 1.0 / vec4_length(v);
    vec4_scale(v, k);
}
inline void vec4_cross(vec4 a, vec4 b)
{
    vec4 c;
    c[0] = a[1]*b[2] - a[2]*b[1];
    c[1] = a[2]*b[0] - a[0]*b[2];
    c[2] = a[0]*b[1] - a[1]*b[0];
    c[3] = 0.;
    memcpy(a, c, sizeof(a));
}

typedef vec4 mat4x4[4];
inline void mat4x4_identity(mat4x4 M)
{
    int i, j;
    M[0][0] = 1; M[1][0] = 0; M[2][0] = 0; M[3][0] = 0;
    M[0][1] = 0; M[1][1] = 1; M[2][1] = 0; M[3][1] = 0;
    M[0][2] = 0; M[1][2] = 0; M[2][2] = 1; M[3][2] = 0;
    M[0][3] = 0; M[1][3] = 0; M[2][3] = 0; M[3][3] = 1;
    /*for(j=0; j<4; ++j)
        for(i=0; i<4; ++i) {
            M[i][j] = i==j ? 1 : 0;
    }*/
}
inline void mat4x4_cpy(mat4x4 M, mat4x4 N)
{
    int i, j;
    for(j=0; j<4; ++j) {
        for(i=0; i<4; ++i) {
            M[i][j] = N[i][j];
        }
    }
}
inline void mat4x4_mul(mat4x4 M, mat4x4 b)
{
    mat4x4 a;
    int i, j, k;
    memcpy(a, M, sizeof(a));
    for(j=0; j<4; ++j) {
        for(i=0; i<4; ++i) {
            M[i][j] = 0;
            for(k=0; k<4; ++k) {
                M[i][j] += a[i][k]*b[k][j];
            }
        }
    }
}
inline void mat4x4_trans(mat4x4 M, GLfloat x, GLfloat y, GLfloat z)
{
    mat4x4 T; mat4x4_identity(T);
    T[3][0] = x;
    T[3][1] = y;
    T[3][2] = z;
    mat4x4_mul(M, T);
}
inline void mat4x4_rot_X(mat4x4 M, GLfloat angle)
{
    GLfloat s = sinf(angle);
    GLfloat c = cosf(angle);
    mat4x4 R = {
        {1, 0, 0, 0},
        {0, c, s, 0},
        {0,-s, c, 0},
        {0, 0, 0, 1}
    };
    mat4x4_mul(M, R);
}
inline void mat4x4_rot_Y(mat4x4 M, GLfloat angle)
{
    GLfloat s = sinf(angle);
    GLfloat c = cosf(angle);
    mat4x4 R = {
        {c, 0, s, 0},
        {0, 1, 0, 0},
        {-s, 0, c, 0},
        {0, 0, 0, 1}
    };
    mat4x4_mul(M, R);
}
inline void mat4x4_rot_Z(mat4x4 M, GLfloat angle)
{
    GLfloat s = sinf(angle);
    GLfloat c = cosf(angle);
    mat4x4 R = {
        {c, s, 0, 0},
        {-s, c, 0, 0},
        {0, 0, 1, 0},
        {0, 0, 0, 1}
    };
    mat4x4_mul(M, R);
}
inline void mat4x4_row(vec4 r, mat4x4 M, int i)
{
    int k;
    for(k=0; k<4; ++k)
        r[k] = M[k][i];
}
inline void mat4x4_col(vec4 r, mat4x4 M, int i)
{
    int k;
    for(k=0; k<4; ++k)
        r[k] = M[i][k];
}
inline void mat4x4_cpy_T(mat4x4 M, mat4x4 N)
{
    int i, j;
    for(j=0; j<4; ++j) {
        for(i=0; i<4; ++i) {
            M[i][j] = N[j][i];
        }
    }
}

Instead of pushing a matrix, you simply create a copy and continue work on and use that one.  Poping then turns into deallocating the copy and switch back to the matrix you made the copy of.


text:
Q: Creating a script to send calendar invite after submitting Google Form but keep getting TypeError: Cannot read property 'push' of undefined message We have a script that we connect to the Google Sheets responses table of a form that allows us to send an invitation to a calendar entry.
It seems to be really hit and miss, some people are able to get it working first time and I'm now trying to run it but keep getting the error message in the execution log:
TypeError: Cannot read property 'push' of undefined
     at addGuestAndSendEmail(Code:47:13)
     at addGuest(Code:39:3)

This is the code (with placeholders - which I've double and triple checked) and I've also made sure to turn on access and grant permission for the Calendar API service. Any help would be really appreciated - I've just hit a total block on where to go!
// Add a trigger - add guest on form submit
function Initialize() {

  var triggers = ScriptApp.getProjectTriggers();

  for(var i in triggers) {
    ScriptApp.deleteTrigger(triggers[i]);
  }

  ScriptApp.newTrigger("addGuest")
  .forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
  .onFormSubmit()
  .create();

}

function addGuest(e) {
  // Find your calendar ID in "Settings and sharing" > "Integrate Calendar". Mine was my email address.
  var calendarId = "EMAIL ADDRESS GOES HERE";

  var email = e.namedValues['Email'].toString();

  // This will only work for standalone events, or the first in an event series (recurring event).
  // To find eventId: https://stackoverflow.com/a/46428456
  var eventId = "EID GOES HERE";

  addGuestAndSendEmail(calendarId, eventId, email);
}

// Note: requires advanced API https://stackoverflow.com/a/55509409
// If an Event Series, this will only work for the the first event
function addGuestAndSendEmail(calendarId, eventId, newGuest) {
  var event = Calendar.Events.get(calendarId, eventId);
  var attendees = event.attendees;
  attendees.push({email: newGuest});

  var resource = { attendees: attendees };
  var args = { sendUpdates: "all" };

  Calendar.Events.patch(resource, calendarId, eventId, args);
}

A: Assuming that you have already enabled calendar API in GCP console and use project number from GCP in AppScript settings, here's the code of working function:
// If it's your primary google calendar, use your email as ID
const calendarId = 'john.smith@gmail.com'
// How to get event ID:
// 1. Open event editor in Calendar Web UI
// 2. Base64 decode part or URL after "...eventedit/"
// 3. Use first string from the output as the eventId below
const eventId = 'xxxxxxxxxxxxx'
// Email column number in the form responses Google Sheet, 0-based
const emailColumnId = 2

function addEventGuests() {
  var sheet = SpreadsheetApp.getActiveSheet()
  var email = sheet.getDataRange().getCell(sheet.getLastRow(), emailColumnId).getValue();

  var event = Calendar.Events.get(calendarId, eventId);
  if(event.attendees) {
    event.attendees.push({
      email: email
    });
  } else {
    event.attendees = new Array({email: email});
  }
  event = Calendar.Events.patch(event, calendarId, eventId, {
    sendNotifications: true
  });
}


text:
Q: Rehosting Windows Workflow Foundation Usage I need to create an application to auto generate C code. ie. User can design the logic from the G-UI using basic blocks from C. This is similar to Matlab Code Generation. I need to do this using .net framework. When I search for the samples, I've seen about rehosting workflow foundation. I don't have any idea about WF4. Can you please anybody tell me is it possible to do the designer(Design is like flowchart) using WF4? And also I have seen some samples using MFC? I'm not sure which one can be applicable for my situation..

A: I think you are confusing the Flowchart and Rehosted Workflow designer in WF  as some kind of UI to draw  the flowcharts.
Workflows are meant for executing business process and the different blocks like If-Else
While etc help to implement a business logic.
Workflow Designer just provides a visual way of representing those if else / whiles etc so that developers and possible super users of the application can modify the business logic in a more visual manner instead of writing them using code.


text:
Q: How does getaddrinfo() do DNS lookup? getaddrinfo() is a function we need to use before creating a socket() or connect()ing, right? Then how does getaddrinfo communicate with DNS server in the first place?
PS: Where can I see the complete source of getaddrinfo?

A: getaddrinfo() likely does make a connect() call behind the scenes, however it already knows the IP address of the DNS server it needs to connect to in order to query for the address of the host you are asking it to query for.
getaddrinfo() is only needed if you want to map "www.somehost.com" to an IP address, it's not needed as a primer to call connect().
You can probably find the complete source code for getaddrinfo() in glibc sources which you'd be able to find here (among other places).
Hope that clarifies things for you.

A: The short answer is "it asks the system", which in turn knows how to do DNS lookups and which servers to use.
getaddrinfo() is documented by the getaddrinfo(3) manual page, which means it's a C library function. It is also a POSIX function, so there is no canonical "source"; each standard C library of an operating system that conforms to POSIX will implement its own version. Either way the source to just that function is probably not too enlightening, since it would just call other functions and OS APIs, and you'd have to drill down pretty far to get to the actual DNS mechanism. You'd be better off reading documentation of the DNS protocol itself if you're interested in how that works.

A: It is not necessary to call getaddrinfo() before creating a socket or connecting.  It is used to translate a domain name, like stackoverflow.com, to an IP address like 69.59.196.211.  If you know the IP address then you can connect directly to that address and there is no need to use getaddrinfo().  getaddrinfo() uses the DNS protocol to talk to your name servers, which are configured using their IP address.
The glibc source code is here.

A: Does your Unix system have the file /etc/nsswitch.conf?  If so, then the "hosts" entry gives the search order for resolving hostnames into IP addresses.  Does your system have the file /etc/resolv.conf?  If so, then it specifies what DNS servers to use.
As you can see, getaddrinfo() can do quite a bit (and can take a while)!

A: It is using DNS protocol (UDP)
http://www.freesoft.org/CIE/Topics/77.htm


text:
Q: onclick slide to page down not working In this website
www.homepreneurawards.com
when navbar menu is clicked it wont slide to the specific div content what could be the issue

ABOUT

HOMEPRENEUR ?

CATEGORIES

JURY MEMBERS

PROCESS FLOW

ORGANIZERS

SPONSORS

PARTNERS

CONTACT US

            <button class="cmn-toggle-switch"></button>

A: The problem is in your function in anchors.navigation.js
function setImmediateAnchor(anchorObject, time) {
    scrollFlag = 1;
    if (currentAnchor) {  -- THIS LINE
        $('html,body').stop().animate({
            'scrollTop': contentTop[anchorObject.attr('href')].top
        }, time, function() {
            $(scrollLinkSelector).parent().removeClass('active');
            anchorObject.parent().addClass('active');
            window.location.hash = '#/' + anchorObject.attr('href').substr(1);
            currentAnchor = anchorObject.attr('href');
            scrollFlag = 0;
        });
    }
}

The condition if (currentAnchor) is failing because currentAnchor is empty. You have set it to  currentAnchor = window.location.hash.replace('/', '') which will be empty when your page is loaded because you does not have anything in url after http://www.homepreneurawards.com
There are 2 solution for it which ever you find feasible.

*

*Add a condition below your initialization code to check if currentAnchor is empty then set it to some value say "#initialized" like below.
    var contentTop = {},
    contentOffset = 87,
    currentAnchor = window.location.hash.replace('/', ''),
    scrollFlag = 0,
    scrollLinkSelector = '.anchor-scroll';

    -- add this condition.
    if(currentAnchor =='')
    {
     currentAnchor = '#initialized';
    }

*You can simply check for empty values in you function setImmediateAnchor like below notice 3rd line and handle empty values.
   function setImmediateAnchor(anchorObject, time) {
    scrollFlag = 1;
    if (currentAnchor == '' || currentAnchor) {  -- THIS LINE
        $('html,body').stop().animate({
            'scrollTop': contentTop[anchorObject.attr('href')].top
        }, time, function() {
            $(scrollLinkSelector).parent().removeClass('active');
            anchorObject.parent().addClass('active');
            window.location.hash = '#/' + anchorObject.attr('href').substr(1);
            currentAnchor = anchorObject.attr('href');
            scrollFlag = 0;
        });
    }
}

Or you can use any other feasible way, the core problem lies in that condition that does not allow you to scroll since your variable is empty. You can fix either way which you find feasible.

A: presuming it is all on one page,

ABOUT

  scrolls to here once navbar is clicked

you can also try

  My div

A: It looks as though you may be preventing the default click action of the link? If you manually go to the link URL e.g. http://www.homepreneurawards.com/#/aboutbrandavatar you will see that the scroll works as expected and further clicks work without an issue.
The URL structure does not look the same as a standard anchor link either and this could be causing you some issues?
Instead of /#/aboutbrandavatar I would expect to see #aboutbrandavatar


text:
Q: Change font within Chapter Title - e.g. first part black, second red Since I often use one document in two forms, lets say in form 1 and form 2, I would like to label that accordingly in the chapter headings and have parts in a different color. So the questions is, how can one change Colors within a chapter heading (I know of sectsty, but this seems to affect the whole and all chapter headings?)?
The following example gives an idea of what I want to achieve, but it does not work since simple text colours in headings seem to be not supported.
\documentclass{book}
\usepackage[english]{babel}
\usepackage{xcolor}

\begin{document}
\chapter{Lions and Birds \textcolor{red}{(Document Form 1)}}
%
\newpage
%
\chapter{Alligators and Storks \textcolor{red}{(Document Form 1)}}
\end{document}

Thanks in advance and best regards, Manuel

A:
The same cause why \ref or \gls in a chapter etc. title is problematic occurs with \textcolor: The macro \MakeUppercase for the chapter marks at the heading transforms \textcolor{ref}{...} into \textcolor{RED}{...} first, which is expanded to its final meaning, trying to apply an undefined (most likely) color named RED.
In order to prevent this, the color change must be hidden in a robust macro (or some macro prepended with \protect, but that might get tedious:
E.g.
\newrobustcmd{\redtext}[1]{%
  \textcolor{red}{#1}%
}

defines a macro meant for red text.
Another possibility is using the optional argument of \chapter and omitting the color change there, but this will not colorize the text in the ToC.
Please be aware, that mixing too much colors in text may worsen readability.
\documentclass{book}
\usepackage{xcolor}
\usepackage{etoolbox}
\usepackage{blindtext}
\usepackage[english]{babel}

\newrobustcmd{\redtext}[1]{%
  \textcolor{red}{#1}%
}

\newrobustcmd{\bluetext}[1]{%
  \textcolor{blue}{#1}%
}

\begin{document}
\tableofcontents

\chapter{Lions and Birds \redtext{(Document Form 1)}}

\chapter{Cats and mice \bluetext{(Document Form 2)}}

\chapter[Cows and goats]{Cows and goats \textcolor{brown}{(Document Form 3)}}

\blindtext[5]

\end{document}

A: May be I have missed something! I have just add \usepackage{xcolor} to the OP MWE preamble and I get this output:

\documentclass{book}
\usepackage[english]{babel}
\usepackage{xcolor} % I add this line

\begin{document}
\chapter{Lions and Birds \textcolor{red}{(Document Form 1)}}

\end{document}


text:
Q: Filter Foreign Key Drop Down Field Django I have 3 tables Student, K8Points, and TeacherClass . The table students tracks all student data information and you can assign them to a classroom, points tracks the points they earned for the day, classroom table is where you create the classroom names. What i want to accomplish is when you are logged in to /k8_points_classroom/1? page, there is a drop down field of students. 1 at the end of the classroom is the classroom id. The field student_name should only show the kids in that particular class, how do i filter that field ? Right now it just pulls up every student in the database. Thanks for the help .
Model

class TeacherClass(models.Model):
    class_name = models.CharField(max_length = 50, default= "")
    teacher_name = models.ManyToManyField(User)
    grade = models.CharField(max_length = 2, default= "")

    class Meta:
       verbose_name = "Teacher Class Room"

    def __str__(self):
        return self.class_name

class Student(models.Model):
    studentpsid= models.CharField(primary_key = True , default = "", max_length = 50, unique = True)
    student_name = models.CharField(max_length = 50)
    student_grade = models.CharField(max_length = 2, default = "")
    home_room = models.CharField(max_length = 3, default = "")
    counseling_goal = models.TextField(max_length = 255)
    class_name = models.ManyToManyField(TeacherClass)
    image =models.ImageField(default ="default.png", upload_to='student_pics')

class K8Points(models.Model):
    date = models.DateField(default=datetime.date.today)
    class_name = models.ForeignKey(TeacherClass, on_delete = models.PROTECT, default = "",)
    student_name = models.ForeignKey(Student,on_delete = models.CASCADE, default ="" ,)
    week_of = models.IntegerField(default=weeknumber)
    day = models.CharField(max_length= 10, default = dayofweek)
    TIME_FRAME_CHOICES = [
        (None, 'PLEASE SELECT TIME FRAME'),
        (1, '(1.) 8:45AM - 9:00AM'),
        (2, '(2.) 9:00AM - 9:30AM'),
        (3, '(3.) 9:30AM - 10:00AM'),
        (4, '(4.) REC. I 10:00AM -10:10AM'),
        (5, '(5.) 10:10AM-10:40AM'),
        (6, '(6.) 10:40AM-11:10AM'),
        (7, '(7.) 11:10AM-11:40AM'),
        (8, '(8.) LUNCH 11:40AM-12:00PM'),
        (9, '(9.) REC. II 12:00PM-12:20PM'),
        (10, '(10.) 12:20PM-12:50PM'),
        (11,'(11.) 12:50PM-1:20PM'),
        (12,'(12.) 1:20PM-1:50PM'),
        (13,'(13.) 1:50PM-2:20PM'),
        (14,'(14.) REC. III 2:20PM-2:30PM'),
    ]
    time_frame = models.PositiveSmallIntegerField(choices=TIME_FRAME_CHOICES,)
    behavior = models.IntegerField(default="", validators=[
            MaxValueValidator(5),
            MinValueValidator(1)
        ])
    academic = models.IntegerField(default="", validators=[
            MaxValueValidator(5),
            MinValueValidator(0)
        ] )

    created_at = models.DateTimeField(default = timezone.now)

    class Meta:
        verbose_name = "K8-Points"

    def __str__(self):
        return self.student_name

Form

    def __init__(self, *args, **kwargs):
          self.classid = kwargs.pop('classid', None)
          super(K8Points_ClassroomForm,self).__init__(*args,**kwargs)
          self.fields['date'].disabled = True
          self.fields['day'].disabled = True
          self.fields['week_of'].disabled = True
          self.fields['class_name'].widget.attrs['readonly'] = True
          getstudents = Student.objects.filter(class_name = self.classid).order_by('student_name')
          self.fields['student_name'].queryset= getstudents.all().order_by('student_name')

View
@login_required
def K8_Points_Classroom(request, classid):

    if request.method == "GET":

        date = datetime.date.today()
        students = Student.objects.filter(class_name=classid).order_by('student_name')
        class_name = TeacherClass.objects.get(id=classid)
        form = K8Points_ClassroomForm(classid = class_name.id)
        request.session['my_class_id'] = classid
        return render(request, 'points/k8_points_classroom.html', {'form': form, 'students': students, 'class_name': class_name, 'date': date , 'classid': classid})

A: You need to pass the class in as a parameter to the form in the view, then adjust the student_name field's queryset to filter down to that class' students.
class K8PointsClassroomForm(forms.ModelForm):
    def __init__(self, *args, class_=None, **kwargs):
          super (K8Points_ClassroomForm,self).__init__(*args,**kwargs )
          self.fields['date'].disabled = True
          self.fields['day'].disabled = True
          self.fields['week_of'].disabled = True
          # Limit the fields queryset to that of the class's students.
          self.fields['student_name'].queryset = class_.student_set.all()

Edit:
Here's the view I was trying to explain:
@login_required
def K8_Points_Classroom(request, classid):
    class_name = TeacherClass.objects.get(id=classid)
    form = K8Points_ClassroomForm(class_=class_name)


text:
Q: How to get current element in order to select with javascript? I've got the follwoing HTML structure (I do not have the IDs of the following elements because they are dynamically created):
<fieldset>

    <select onchange="updateInputBox()">
      <option>a</option>
      <option>b</option>
      <option>c</option>
      <option>d</option>
    </selects>

    <input data-myAttribute="case1">

      x

</fieldset>

The filedset and it's children is dynamically created. I want to change the attribute in the inputBox depending on what the user selected in the selectBox.
Here is an example how I would have done if the element fieldset would not have been dynamic (the following contains elements have IDs, but only because I want to demonstrate what I want; in reality I don't have IDs because they are dynamically created by clicking a button, that I do not show here):
https://jsfiddle.net/thadeuszlay/6bsgazvv/4/
But unfortunately I don't have the id of the fieldset, because it is dynamically created. Is there a way how you can get the position of the current element?
I tried to pass itself in the updateInputBox-function:
<select id="selectBox" onchange="updateInputBox('+ this +')">

I also tried with jQuery:
$(this).parent().parent()

but in both cases the console would say

"Unexpected identifier"

Update:
Inside the function doing something like this (currentElement is the selectBox/DropDownBox):
currentElement.parent().parent().setAttribute("data-myAttribute", "hello");

Uncaught TypeError: selectBox.parent is not a function

A: You can use jquery 'closest' for this as below.
HTML
<select id="selectBox" onchange="updateInputBox(this)">

JS
function updateInputBox(selectElm) {
   var inputElm = $(selectElm).closest('fieldset').find('input');

inputElm.attr('data-myAttribute', $(selectElm).val());

}

// instead of inline onchange event and the above code, you can use the below to trigger the event
$(document).on('change', 'fieldset select', function () {
       var inputElm = $(this).closest('fieldset').find('input');

    inputElm.attr('data-myAttribute', $(this).val());

    });

A: In updateInputBox, simply look at the selectedIndex of #selectBox

A: <select id="selectBox" onchange="updateInputBox(this)">

function
function updateInputBox(dropdowntBox) {
    var inputBoxField = document.getElementById("inputBox").setAttribute("data-myAttribute", dropdowntBox.value);
}

A: Here is jquery version:solution
You need to trigger change() event for select with ID selectBox
$(document).on('change','select',function(){
    var value=$(this).val();
    $(this).parents('fieldset').find('input').attr('data-myAttribute',value);
});


text:
Q: Apply form CSS to all input using Bootstrap 3 without class How can I apply the same style to all form elements (input, select, textarea) using Bootstrap 3 and without the class form-control?
"That I want" using the form-control class.
Red arrow no CSS = =

A: If you use less or sass you can just extend
form-control on all inputs.
For plain CSS you can copy styles from form-control and paste to input {}

A: input:-moz-placeholder, select:-moz-placeholder, textarea:-moz-placeholder {
    color: #999999;
}

input::-moz-placeholder, select::-moz-placeholder, textarea::-moz-placeholder {
    color: #999999;
}

input:-ms-input-placeholder ,select:-ms-input-placeholder, textarea:-ms-input-placeholder {
    color: #999999;
}

input::-webkit-input-placeholder, select::-webkit-input-placeholder, textarea::-webkit-input-placeholder {
    color: #999999;
}

input, select, textarea {
  display: block;
  width: 100%;
  height: 34px;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.428571429;
  color: #555555;
  vertical-align: middle;
  background-color: #ffffff;
  border: 1px solid #cccccc;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  -webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}

input:focus, select:focus, textarea:focus {
  border-color: #66afe9;
  outline: 0;
  -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
  box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}

.input[disabled],
input[readonly] {
  cursor: not-allowed;
  background-color: #eeeeee;
}

textarea {
  height: auto;
}

A: input[type = "any"]{background-color: #FFFFFF;background-image: none;border: 1px solid #CCCCCC;border-radius: 4px;box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;color: #555555;display: block;font-size: 14px;height: 34px;line-height: 1.42857;padding: 6px 12px;transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;width: 100%;}input, button, select, textarea {font-family: inherit;font-size: inherit;line-height: inherit;}input {line-height: normal;}button,input, optgroup, select, textarea {color: inherit;font: inherit;margin: 0;}


text:
Q: Error when executing VBA code when wrong Excel tab is open My VBA code utilizes two Excel spreadsheets. It gets data from one (Tab1) and writes results to the other tab (Tab2). However, when I launch the code while Tab2 is open, VBA is giving me "Application defined or Object Defined error". Code works find when I am on Tab1.  Below is the line of code where it chokes:
Set YE_last = Forecast.Range(Cells(YE_forecast.Row + 1, YE_forecast.Column + i - 1), Cells(YE_forecast.Row + 1, YE_forecast.Column + i - 1))

Can you help please!

A: Cells without a worksheet object qualifier, implicitly refers to whatever the ActiveSheet is (if you're in a standard code module). If you're in a worksheet's code-behind module, then unqualified Cells calls are basically doing Me.Cells, i.e. they're referring to that worksheet.
Solution is to qualify everything with the sheet object you're working with:
Set YE_last = Forecast.Range(Forecast.Cells(YE_forecast.Row + 1, YE_forecast.Column + i - 1), Forecast.Cells(YE_forecast.Row + 1, YE_forecast.Column + i - 1))

A With block can simplify this:
With Forecast
    Set YE_last = .Range(.Cells(YE_forecast.Row + 1, YE_forecast.Column + i - 1), .Cells(YE_forecast.Row + 1, YE_forecast.Column + i - 1))
End With


text:
Q: Windows notepad as log If I save a notepad as .LOG, it acts as a log file.
My question is when I change an entry in the middle of an existing file - it does not append today's date to that.
Is there any way to get that working ?

A: Try this:
Open Notepad and in a new file type .LOG on the first line.
Save it as a .TXT file or .LOG file or whatever filename you want.
The next time you open the file with Notepad, the current date and time will auto-magically be appended to the file.

A: As you already know, when you open a text file that begins with .LOG, Notepad will scroll to the bottom of the file and insert the time and date.
To manually insert the time and date somewhere else, you can use Edit → Time/Date or press F5.

A: I don't think so. Notepad only adds current date & time at the end of the file, not anywhere else.
If you're looking for an alternative, use a tool like PhraseExpress which substitutes #date with current date and #now with current time


text:
Q: Cant update multi picklist on a workflow? Cant update multi picklist on a workflow?  I'm assuming you cant?  And why?

A: This is workflow limitation of Salesforce, You can not update multiple picklist values through workflow. There is already IDEA posted on salesforce community, you can vote for it. Other alternative you can use trigger to update the multi picklist values.


text:
Q: Problem executing a PostgreSQL SQL script on Ubuntu Linux I would like to execute a SQL script that will create a database in Postgres. It produces the message:
bash: syntax error near unexpected token 'newline'

The script is:
 postgres@tom: /home/tom$ psql -1q test test <script.sql 2>

A: If you want to redirect standard error to standard output, you should run
psql -1q -d test -U test -f script.sql 2>&1


text:
Q: Does it make sense to use sklearn GridSearchCV together with CalibratedClassifierCV? What I want to do is to derive a classifier which is optimal in its parameters with respect to a given metric (for example the recall score) but also calibrated (in the sense that the output of the predict_proba method can be directly interpreted as a confidence level, see https://scikit-learn.org/stable/modules/calibration.html). Does it make sense to use sklearn GridSearchCV together with CalibratedClassifierCV, that is, to fit a classifier via GridSearchCV, and then pass the GridSearchCV output to the CalibratedClassifierCV object? If I'm correct, the CalibratedClassifierCV object would fit a given estimator cv times, and the probabilities for each of the folds are then averaged for prediction. However, the results of the GridSearchCV could be different for each of the folds.

A: Yes you can do this and it would work.  I don't know if it makes sense to do this, but the least I can do is explain what I believe would happen.
We can compare doing this to the alternative which is getting the best estimator from the grid search and feeding that to the calibration.

*

*Simply getting the best estimator and feeding it to calibrationcv

from sklearn.model_selection import GridSearchCV
from sklearn import svm, datasets
from sklearn.calibration import CalibratedClassifierCV

iris = datasets.load_iris()
parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
svc = svm.SVC()
clf = GridSearchCV(svc, parameters)
clf.fit(iris.data, iris.target)
calibration_clf = CalibratedClassifierCV(clf.best_estimator_)
calibration_clf.fit(iris.data, iris.target)
calibration_clf.predict_proba(iris.data[0:10])

array([[0.91887427, 0.07441489, 0.00671085],
       [0.91907451, 0.07417992, 0.00674558],
       [0.91914982, 0.07412815, 0.00672202],
       [0.91939591, 0.0738401 , 0.00676399],
       [0.91894279, 0.07434967, 0.00670754],
       [0.91910347, 0.07414268, 0.00675385],
       [0.91944594, 0.07381277, 0.0067413 ],
       [0.91903299, 0.0742324 , 0.00673461],
       [0.91951618, 0.07371877, 0.00676505],
       [0.91899007, 0.07426733, 0.00674259]])

*Feeding grid search in the Calibration cv

from sklearn.model_selection import GridSearchCV
from sklearn import svm, datasets
from sklearn.calibration import CalibratedClassifierCV

iris = datasets.load_iris()
parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
svc = svm.SVC()
clf = GridSearchCV(svc, parameters)
cal_clf = CalibratedClassifierCV(clf)
cal_clf.fit(iris.data, iris.target)
cal_clf.predict_proba(iris.data[0:10])

array([[0.900434  , 0.0906832 , 0.0088828 ],
       [0.90021418, 0.09086583, 0.00891999],
       [0.90206035, 0.08900572, 0.00893393],
       [0.9009212 , 0.09012478, 0.00895402],
       [0.90101953, 0.0900889 , 0.00889158],
       [0.89868497, 0.09242412, 0.00889091],
       [0.90214948, 0.08889812, 0.0089524 ],
       [0.8999936 , 0.09110965, 0.00889675],
       [0.90204193, 0.08896843, 0.00898964],
       [0.89985101, 0.09124147, 0.00890752]])

Notice that the output of the probabilities are slightly different between the two.
The difference between each method is:

*

*Using the best estimator is only doing the calibration across 5 splits (the default cv).  It uses the same estimator in all 5 splits.

*Using grid search, is doing going to fit a grid search on each of the 5 CV splits from calibration 5 times.  You are essentially doing cross validation on 4/5 of the data each time choosing the best estimator for the 4/5 of the data and then doing the calibration with that best estimator on the last 5th.  You could have slightly different models running on each set of test data depending on what the grid search chooses.
I think the grid search and calibration are different goals so in my opinion I would probably work on each separately and go with the first way specified above get a model that works the best and then feed that in the calibration curve.
However, I don't know your specific goals so I can't say that the 2nd way described here is the WRONG way.  You can always try both ways and see what gives you better performance and go with the one that works best.

A: I think that your approach is a little different with your objective. What you objective says is "Find a model with best recall, which confidence should be unbiased", but what you do is "Find a model with best recall, then make the confidence unbiased". So a better (but slower) way to do that is:

*

*Wrap your model with CalibratedClassifierCV, treat this model as the final model you should be optimized on;

*Modify your param grid, make sure that you are tuning the model inside CalibratedClassifierCV (change param to something like base_estimator__param, which is the property CalibratedClassifierCV to hold the base estimator)

*Feed CalibratedClassifierCV model into your final GridSearchCV, then fit

*get best_estimator_, which is your unbiased model with best recall.

A: I would advise that you do calibrate on a separate set not to bias the estimate.
I see two options. Either you cross validate within a fraction of the folds generated for calibrating, as suggested above, or you set apart an ad-hoc evaluation set that you would use only for calibration, after performing cross validation on training set.
In any case, I would recommend that you finally evaluate on a test set.


text:
Q: Referencing an environment before it is labelled Using the package hyperref I'm noticing that I can't reference things properly. It seems that \autoref actually references the latest section, table, equation or figure (in short environment) before a label. Is this right? and what am I doing wrong?
\subsection{One one}

I want to write: `\autoref{tab:one}' shows such and such:

\begin{table}
    \caption{some bumpf}
    \label{tab:one}
\end{table}

Gives me: I want to write subsection 1.1 shows such and such.
EDIT
I have caption I forgot it in this instance. The question I'm asking is why my reference is to something that is not labelled? Eg, why do I get a reference to a subsection if the label is clearly in the figure environment or table environment?  Is it really always because I may have forgotten the order of label after caption somewhere?

A: You need to add a \caption{...} before the \label:
\subsection{One one}

I want to write: `\autoref{tab:one}' shows such and such:

\begin{table}
    \caption{Some Table}
    \label{tab:one}
\end{table}