text:
Q: Handle Google C2DM intents in a service? If I set up my Android Manifest XML file correctly, can I handle C2DM intents (REGISTRATION and RECEIVE) in a regular service, rather than a broadcast receiver?
Clearly, the application would need to be designed for this, but I'm just curious if it's possible or if something is limiting the C2DM intents to a broadcast receiver, as every example I've read online uses a broadcast receiver, but it seems to me one could use a service as well.

A: No, but you can receive the broadcast in a broadcast receiver and then start a service from that.

A: Quote from Google: An application on an Android device doesn't need to be running to receive messages. The system will wake up the application via Intent broadcast when the the message arrives, as long as the application is set up with the proper broadcast receiver and permissions.
So, no. The only way to receive the messages is within a broadcast receiver. This is no big deal. Normally you receive the message and then you call a service. Google even provides you with an standard implementation. The Google IO session Android + App Engine: A Developer's Dream Combination uses a wizard (see below for the installation) to generate the code.
Search for C2DMBaseReceiver, C2DMBroadcastReceiver and C2DMessaging for example in the ChromeToPhone code: all you have to do with these 3 classes is to provide a class C2DMReceiver which inherits from C2DMBaseReceiver and set up the manifest.
Update
Google bloggt about Client Login key expiration. Therefore I expected that the plugin gets updated to include source which deals with that. Compared to the session video above some things changed. First you have to install the android wizard extra (it is not part of the Google plugin):

Then as described in the video you have to use this wizard:
In the generated project you can find c2dm.jar and  c2dm-sources.jar. These files are spreaded all over the internet, but don't have a home location to download the latest version. So you have to generate them via the wizard. The source doesn't include a version comment and doesn't deal with the key expiration issues.


text:
Q: Python ConfigParser elements into CSV arguments I have a script that parses a csv file and produces an XML file. One of the arguments I have to give the parser is the delimiter, which in my case is not a comma but a tab.
This information is stored in a configuration file which I extract and then pass to the csv parser.
ident = parser.get('CSV', 'delimiter') #delimiter taken from config file

csv.register_dialect('custom',
                    delimiter= ident, #passed to csv parser
                    doublequote=False,
                    escapechar=None,
                    quotechar='"',
                    quoting=csv.QUOTE_MINIMAL,
                    skipinitialspace=False)

However I get a type error saying that the "delimiter" must be an 1-character string. I checked the type of ident and it's a string but it doesn't seem to be recognising the \t as a tab. When I put ident = '\t' or delimiter = '\t' it works. How do I get the value correctly from the config file.

A: Maybe a bit too late, but I have a small workaround: setting the parameter as the hex code value and then decoding it
from ConfigParser import ConfigParser
cp = ConfigParser()
cp.add_section('a')
cp.set('a', 'b', '09') #hex code for tab (please note that there is no \x
cp.write(open('foo.ini', 'w'))

from ConfigParser import ConfigParser
cp_in = ConfigParser()
cp_in.read('foo.ini')
print(repr(bytearray.fromhex(cp_in.get('a', 'b')).decode())) #where the magic happens

A: This doesn't appear to be possible using ConfigParser.
While the docs don't explicitly mention this case, they do say that leading whitespace will be stripped from values.
Having tried to round-trip the value, it just gets back an empty string:
from ConfigParser import ConfigParser
cp = ConfigParser()
cp.add_section('a')
cp.set('a', 'b', '\t')
cp.write(open('foo.ini', 'w'))

cp_in = ConfigParser()
cp_in.read('foo.ini')
print(repr(cp_in.get('a', 'b'))) # prints ''

A: I'm adding what I think is the obvious answer that everyone apparently missed.  Judging from the comments, the config file looks something like this:
[CSV]
delimiter=\t
quoting=QUOTE_ALL

The value for 'delimiter' is two characters, a backslash and a 't'.  Here's how to read it and convert the value into a tab.
>>> import configparser, codecs, csv
>>> parser = configparser.ConfigParser()
>>> parser.read('foo.cfg')
['foo.cfg']

>>> ident = parser.get('CSV', 'delimiter')
>>> csv.register_dialect('custom', delimiter=ident)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: "delimiter" must be a 1-character string
>>> ident, len(ident)
('\\t', 2)

>>> decoded = codecs.decode(ident, encoding='unicode_escape')
>>> csv.register_dialect('custom', delimiter=decoded)
>>> decoded, len(decoded)
('\t', 1)

And here's a bonus:
>>> quoting = parser.get('CSV', 'quoting')
>>> csv.register_dialect('custom', quoting=quoting)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: "quoting" must be an integer
>>> quoting
'QUOTE_ALL'

>>> try:
...   quoting = parser.getint('CSV', 'quoting')
... except ValueError:
...   quoting = getattr(csv, parser.get('CSV', 'quoting'))
>>> csv.register_dialect('custom', quoting=quoting)
>>> quoting
1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using variables in regular expressions Python amateur here:
I'm just playing around with regular expressions, and I've come across this:
import re

while True:
    userInput = input('Type in your string here: ')
    regexInput = input('Enter Regex pattern here:')

    testRegex = re.compile([^regexInput])
    testMO = testRegex.search(userInput)
    print(testMO.group())

Basically, I want my regex to match everything except the pattern I've specified through regexInput. However, I am getting syntax errors from this code. I thought that putting a carrot right after the opening bracket of a character class, it means that Python will search for everything other than what's in the bracket?
I'm doing the last project of Chapter 7 in Automate the Boring Things.
How can I get my code to match everything other than what is typed in regexInput?
Someone told me this:

regex expects string so you have to create string:

"[^" + regexInput +"]" or "[^{}]".format(regexInput)
I don't really fully understand this reply, especially the second part of the answer. Just to test out what he said, I used this code:
import re

while True:
    userInput = input('Type in your string here: ')
    regexInput = input('Enter Regex pattern here:')

    testRegex = re.compile(regexInput)
    testMO = testRegex.search(userInput).group()
    print(testMO)

Which gave me an output of:
Type in your string here: Here lies Batman.
Enter Regex pattern here:Batman
Batman
Type in your string here:

Doesn't this mean that the regex also took a variable, and made it work? So I'm kind of confused as to what this other person said, as it seems to contradict his statement of 'regex expects a string'.

A: [^regexInput] is not a syntactically valid Python expression.  It looks like you are trying to create the string consisting of the characters [^, followed by the value of the variable regexInput, followed by the character ].  One way to write this in Python is: '[^' + regexInput + ']'.


text:
Q: Could not fetch elements from a list in R. As one element contains multiple elements My list (sector_region) contains 2 elements. In those 2 elements there are multiple elements. How can I fetch these elements?
Following is my piece of code.
sector_region = unique(universe_database[, c("Region", "Sector")])

A: I quote your comment below:

Let's say : employee <- c('John Doe','Peter Gynn','Jolie Hope','John Doe','Peter Gynn','Jolie Hope','John Doe','Peter Gynn','Jolie Hope','John Doe','Peter Gynn','Jolie Hope') salary <- c(21000, 23400, 26800,21000, 23400, 26800,21000, 23400, 26800,21000, 23400, 26800) universe_database <- data.frame(employee, salary,stringsAsFactors=FALSE) sector_region = unique(universe_database[,c("employee","salary")]) Now sector_region is a list. If I do sector_region[1] I will get a list of elements. How can I get single element like 'John Doe'?

First of all, sector_region is a data frame, not a list. You can confirm that with class(sector_region). By the way, your code is equivalent to sector_region = unique(universe_database) since you only have two columns for universe_database.
To retrieve "John Doe" here, simply execute sector_region$employee[1] or sector_region[1, 1].
A more general solution would be sector_region$employee[sector_region$employee %in% "John Doe"]. Or, if you want to keep the returned values in a data frame, do subset(sector_region, employee %in% "John Doe", select = employee).


text:
Q: How to array objects reload in DataBase Table by CoreData I have one array list like this:
(
"08-12-2016, Thursday, Greg",
"15-12-2016, Thursday, Greg",
"22-12-2016, Thursday, Greg",
"08-12-2016, Thursday, tug"
)

This array list how to reload in DataBase Table with coredata
I want to like this data reload in DB Table

How can i do this. I am so tried many times but do not insert array data in DataBase Table. Please help

A: Perfect work
long int counts=[resultss count];// resultss is a array list
for(int i=0;i<counts;i++)
{
    NSArray*foos = [[resultss objectAtIndex:i] componentsSeparatedByString:@","];
    NSString*date_name = [foos objectAtIndex:0];
    NSString*day_name = [foos objectAtIndex:1];
    NSString*name_name = [foos objectAtIndex:2];
     NSLog(@"date_name %@",date_name);
     NSLog(@"day_name %@",day_name);
     NSLog(@"name_name %@",name_name);
    //new device
    NSManagedObjectContext *context = [self managedObjectContext];
    NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Cal" inManagedObjectContext:context];

    [newDevice setValue:date_name forKey:@"date"];
    [newDevice setValue:day_name  forKey:@"day"];
    [newDevice setValue:name_name forKey:@"pillname"];

    NSError *error = nil;
    // Save the object to persistent store

    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }

}


text:
Q: How to use ng-show and ng-hide in an angularjs custom directive's template? I have searched all day for an answer and cannot seem to get this right.
I have a scope value profile_edit_mode being set to either true or false by clicking an edit button. This value then activates the ng-hide and ng-show on the form.
when I move this into a custom directive the ng-hide or ng-show won't work.
I have the following.
HTML Code
<bos-input fieldname="firstname" title="First Name" place-holder="First Name" ng-model="user_profile_details.firstname" edit-mode="{{profile_edit_mode}}"></bos-input>

Custom directive.
enter code hereangular.module('aesthetics')
.directive('bosInput', function(){
    return {
        restrict: 'E',
        require: 'ngModel',
        template: '
' +
                    '{{title}}' +
                        '
' +
                        '<input ng-show="editMode" class="form-control" id="{{fieldname}}" ng-model="ngModel" placeholder="{{placeHolder}}">' +
                        '
{{ngModel}}
' +
                    '
' +
                  '
{{editMode}}',
        scope: {
            fieldname: '@',
            placeHolder: '@',
            title: '@',
            editMode: '@',
            ngModel: '='
        }
    }

})

The form input is rendering correctly and everything else is working except the ng-show or ng-hide.
I have outputted the value of the editMode to check it is getting updated correctly and it is.
Any help will be greatly appreciated.
Many thanks
Brent

A: Instead of using @, which passes profile_edit_mode as a string, use =, which will two way bind the actual value.
<bos-input ... edit-mode="profile_edit_mode"></bos-input>

Directive
.directive('bosInput', function(){
    return {
        // Previous code...
        scope: {
            fieldname: '@',
            placeHolder: '@',
            title: '@',
            editMode: '=',
            ngModel: '='
        }
    }

})

This works because when you use @ and pass a string, 'false' still evaluates as truthy.


text:
Q: Unable to write a squarefree algorithm I'm trying to write a function that returns true, if an integer is Square-Free - this is what I've tried:
def squarefree(n):
    for i in range (2,n-1):
        if n%(i**2)==0:
            return False
        else:
            return True

In mathematics, a square-free, or quadratfrei (from German language) integer, is an integer which is divisible by no other perfect square than 1. For example, 10 is square-free but 18 is not, as 18 is divisible by 9 = 32. The smallest positive square-free numbers are

A: The main problem here is your returning whenever your if statement fails. Move the return out of the for loop. Also a quick time save you only need to go up to the 4th root of n.
import math

def squarefree(n):
    for i in range (2,math.ceil(math.sqrt(math.sqrt(n)))):
        if n%(i**2)==0:
            return False
    return True

you could probably optimise more by only checking prime numbers up to the 4th root of n.


text:
Q: POST http://localhost:5000/users/signin 500 (Internal Server Error) trying to make auth works When I post the data for my Auth the console throws this error ** 500 (Internal Server Error) ** I think the problem is with my server, first check the database and the data is in the cluster
but the data does not work in my client. I know that this type of problem is often on the server. I've been searching for several hours and I can't figure it out.
This is the index

import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';

import postRoutes from './routes/posts.js';
import userRoutes from './routes/users.js';

const app = express();

app.use(bodyParser.json({ limit: '30mb', extended: true }))
app.use(bodyParser.urlencoded({ limit: '30mb', extended: true }))
app.use(cors());

app.use('/posts', postRoutes);
app.use('/users', userRoutes);

const CONNECTION_URL = '**THIS_IS_MY_MONGO_DB;
const PORT = process.env.PORT|| 5000;

mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`)))
  .catch((error) => console.log(`${error} did not connect`));

mongoose.set('useFindAndModify', false);

The users.js route

import express from 'express';

import { signin, signup } from '../controllers/user.js';

const router = express.Router();

router.post('/signin', signin);
router.post('/signup', signup);

export default router;

The user controller

import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";

import User from "../models/user.js";

export const signin = async (req, res) => {
    const { email, password} = req.body;

    try {
        const existingUser = await User.findOne({ email });

        if(!existingUser) return res.status(404).json({ message: "El usuaruio no existe."});

        const isPasswordCorrect = await bcrypt.compare(password, existingUser.password);

        if(!isPasswordCorrect) return res.status(400).json({ message: "Credenciales invalidas."});

        const token = jwt.sing({ email: existingUser.email, id: existingUser._id }, 'test', { expiresIn: "1h" });

        res.status(200).json({ result: existingUser, token});
    } catch (error) {
        res.status(500).json({ message: 'Algo salio mal.' });
    }
}

export const signup = async (req, res) => {
    const { email, password, confirmPassword, firstName, lastName } = req.body;

    try {
        const existingUser = await User.findOne({ email });

        if(existingUser) return res.status(400).json({ message: "El usuaruio ya existe."});

        if(password !== confirmPassword) return res.status(400).json({ message: "Las contraseñas no coinciden."});

        const hashedPassword = await bcrypt.hash(password, 12);

        const result = await User.create({ email, password: hashedPassword, name: `${firstName} ${lastName}` })

        const token = jwt.sing({ email: result.email, id: result._id }, 'test', { expiresIn: "1h" });

        res.status(200).json({ result, token});
    } catch (error) {
        res.status(500).json({ message: 'Algo salio mal.' });
    }
}

The index api

import axios from 'axios';

const API = axios.create({ baseURL: 'http://localhost:5000' })

export const fetchPosts = () => API.get('/posts');
export const createPost = (newPost) => API.post('/posts', newPost);
export const likePost = (id) => API.patch(`/posts/${id}/likePost`);
export const updatePost = (id, updatedPost) => API.patch(`/posts/${id}`, updatedPost);
export const deletePost = (id) => API.delete(`/posts/${id}`);

export const signIn = (formData) => API.post('/users/signin', formData);
export const signUp = (formData) => API.post('/users/signup', formData);

A:

export const signup = async (req, res) => {
    const { email, password, confirmPassword, firstName, lastName } = req.body;

    try {
        const existingUser = await User.findOne({ email });

        if(existingUser) return res.status(400).json({ message: "El usuaruio ya existe."});

        if(password !== confirmPassword) return res.status(400).json({ message: "Las contraseñas no coinciden."});

        const hashedPassword = await bcrypt.hash(password, 12);

        const result = await User.create({ email, password: hashedPassword, name: `${firstName} ${lastName}` })

        // you have typo in next line
        const token = jwt.sing({ email: result.email, id: result._id }, 'test', { expiresIn: "1h" });
        // replace it by:
        const token = jwt.sign({ email: result.email, id: result._id }, 'test', { expiresIn: "1h" });

        res.status(200).json({ result, token});
    } catch (error) {
        res.status(500).json({ message: 'Algo salio mal.' });
    }
}


text:
Q: Plotting two graphs side by side (seaborn and subplots) I need to plot two graphs side by side. Here the column in my dataset which I am interested in.
X
1
53
12
513
135
125
21
54
1231

I did
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
mean = df['X'].mean()

fig, ax =plt.subplots(1,2)
sns.displot(df, x="X", kind="kde", ax=ax[0]) # 1st plot
plt.axvline(mean, color='r', linestyle='--') # this add just a line on the previous plot, corresponding to the mean of X data
sns.boxplot(y="X", data=df, ax=ax[2]) # 2nd plot

but I have this error: IndexError: index 2 is out of bounds for axis 0 with size 2, so the use of subplots is wrong.

A: sns.boxplot(..., ax=ax[2]) should use ax=ax[1] as there doesn't exist an ax[2].
sns.displot is a figure-level function, which creates its own figure, and doesn't accept an ax= parameter. If only one subplot is needed, it can be replaced by sns.histplot or sns.kdeplot.
plt.axvline() draws on the "current" ax. You can use ax[0].axvline() to draw on a specific subplot.  See What is the difference between drawing plots using plot, axes or figure in matplotlib?
The following code has been tested with Seaborn 0.11.1:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

sns.set()
df = pd.DataFrame({'X': [1, 53, 12, 513, 135, 125, 21, 54, 1231]})
mean = df['X'].mean()

fig, ax = plt.subplots(1, 2)
sns.kdeplot(data=df, x="X", ax=ax[0])
ax[0].axvline(mean, color='r', linestyle='--')
sns.boxplot(y="X", data=df, ax=ax[1])
plt.show()


text:
Q: Getting "BLInitializeLibrary failed 0xc0000017" on Windows 8 and Fedora 25 dual boot re-installation On a Toshiba Satellite running Windows 8.1 I installed Fedora 22 as a dual boot setup. It worked fine. The hard drive died, so I bought a new 500GB ssd drive and ordered a recovery usb from Toshiba. I can install Windows fine on it, boot into it, shrink the volume, boot from a LiveCD Fedora USB, and install Fedora 25 into the new space. However, once I do that last step I can no longer boot into Windows from the boot menu, although I can still boot into Fedora. The error I keep getting is:
BLInitializeLibrary failed 0xc0000017
Nothing I have found helps. The Fedora 25 usb was created using Gnome Disk Utility, which from what I understand means that it would be UEFI bootable. Not booting the usb in UEFI mode is one of the possible sources of this issue, but I do not know how to check whether or not grub is in UEFI or not. Is there a way to diagnose or fix this issue? I am fine with starting over, as I have restarted this whole process at least 3 times so far.
Edit: I just verified that the Fedora installation was in UEFI mode.
Edit #2: I was able to do a dual boot installation with a Fedora 22 usb stick, with the thought that if that worked I could just upgrade Fedora afterwards. However, the upgrade did not work, I am assuming because F22 is too old. I will try again with 24, and if that does not work 23. I was able to boot into both F22 and Windows after the installation though, so hopefully this is a Fedora 25 LiveCD image issue only.

A: Ok, so through much trial and error and reading, I finally stumbled on this solution. I edited the Windows menu in grub, and changed the last line from:
chainloader /EFI/Microsoft/Boot/bootmgfw.efi
to be
chainloader (hd0,2)/EFI/Microsoft/Boot/bootmgfw.efi
And Windows loaded. This is on the Fedora 24 installation, which gave the identical error as the 25 did, so I am guessing the fix will work for both.


text:
Q: c# serialization xmlwriter stringwriter out of memory for large objecthelp I am managing a large project and need to serialize and send an object in xml format.  The object is ~130 mb.
(NOTE: I did not write this project, so making edits outside of this method, or drastically changing the architecture is not an option.  It works great normally, but when the object is this large, it throws out of memory exception.  I need to do it another way to handle large objects.)
The current code is this:
public static string Serialize(object obj)
{
    string returnValue = null;

    if (null != obj)
    {
        System.Runtime.Serialization.DataContractSerializer formatter = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());

        XDocument document = new XDocument();

        System.IO.StringWriter writer = new System.IO.StringWriter();
        System.Xml.XmlTextWriter xmlWriter = new XmlTextWriter(writer);

        formatter.WriteObject(xmlWriter, obj);
        xmlWriter.Close();

        returnValue = writer.ToString();
    }

    return returnValue;
}

It is throwing an out of memory exception right at returnValue = writer.ToString().
I rewrote it to use "using" blocks which I prefer:
public static string Serialize(object obj)
    {
        string returnValue = null;
        if (null != obj)
        {
            System.Runtime.Serialization.DataContractSerializer formatter = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
            using (System.IO.StringWriter writer = new System.IO.StringWriter())
            {
                using (System.Xml.XmlTextWriter xmlWriter = new XmlTextWriter(writer))
                {
                    formatter.WriteObject(xmlWriter, obj);
                    returnValue = writer.ToString();
                }
            }
        }
        return returnValue;
    }

researching this, it appears the ToString method on StringWriter actually uses double the RAM. (I actually have plenty of RAM free, over 4 gb, so not really sure why I am getting an out of memory error).

A: Well, I found the best solution was to serialize to a file directly, then instead of passing a string along, I pass the file:
public static void Serialize(object obj, FileInfo destination)
{
    if (null != obj)
    {
        using (TextWriter writer = new StreamWriter(destination.FullName, false))
        {
            XmlTextWriter xmlWriter = null;
            try
            {
                xmlWriter = new XmlTextWriter(writer);
                DataContractSerializer formatter = new DataContractSerializer(obj.GetType());
                formatter.WriteObject(xmlWriter, obj);
            }
            finally
            {
                if (xmlWriter != null)
                {
                    xmlWriter.Flush();
                    xmlWriter.Close();
                }
            }
        }
    }
}

Of course, now I have another problem which I will post ... and that is deserializing the file!


text:
Q: uWSGI libxml2 headers unavailable Every now and again a problem comes up that just seems it shouldn't have to be this exasperating. Or else I'm missing something simple (perhaps more likely).
I'm on a CentOS box trying to get uWSGI installed & configured to host a django site. I'm using python2.7 installed @ /opt/python2.7/lib/python2.7.
Ran: pip install http://projects.unbit.it/downloads/uwsgi-latest.tar.gz
Got:* libxml2 headers unavailable. uWSGI build is interrupted. You have to install libxml2 development package or use libexpat or disable XML
So I thought this would be easy.
Ran: yum install libxml2
Got: Package libxml2 - 2.6.26-2.1.2.8.el5_5.1.i386 is already installed.
Sure enough, I can import libxml2 in python2.4. But not python2.7.  Since then I've been googling ad infinitum for an answer. Seems 10,000 people have similar difficulties getting uWSGI installed because of the XML library issue, but I need to install it twice.
So I tried to compile from source:
wget ftp://xmlsoft.org/libxml2/libxml2-2.7.3.tar.gz
tar xzvf libxml2-2.7.3.tar.gz
cd libxml2-2.7.3
./configure  --prefix=/usr/local
make
make install
(run python2.7)
import libxml2
ImportError: No module named libxml2
What did I do to deserve this? Can't win, it seems. What should I try next?

A: yum install libxml2-devel
libxml2 is a c library there is no way to load it from python without a binding.


text:
Q: Linked-list with unsafe rust leaks memory My linked list has this memory layout:
[dummy] -> (prev, ?DUMMY?, next) <-> (prev, A, next) <-> (prev, B, next)
            ^                                                         ^
            +---------------------------------------------------------+

The dummy node is lazily initialized upon insertion, with prev and next pointer pointing towards itself. After insertion, the prev and next pointer will act as the tail and head pointer.
use std::marker::PhantomData;

use self::node::NodePtr;

mod node;

#[derive(Debug)]
pub struct LinkedList<T> {
    dummy: Option<NodePtr<T>>,
    len: usize,
    _phantom: PhantomData<T>,
}

impl<T> Default for LinkedList<T> {
    fn default() -> Self {
        Self {
            dummy: None,
            len: 0,
            _phantom: PhantomData,
        }
    }
}

impl<T> LinkedList<T> {
    pub fn new() -> Self {
        Default::default()
    }

    pub(crate) fn inner(&mut self) -> NodePtr<T> {
        *self.dummy.get_or_insert(NodePtr::dummy())
    }

    pub fn len(&self) -> usize {
        self.len
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn push_front(&mut self, elem: T) {
        let dummy = self.inner();
        let head = dummy.next();
        let new_head = NodePtr::alloc(dummy, elem, head);
        head.set_prev(new_head);
        dummy.set_next(new_head);

        self.len += 1;
    }

    pub fn pop_front(&mut self) -> Option<T> {
        let dummy = self.inner();
        unsafe { dummy.next().dealloc() }.map(|(_, elem, new_head)| {
            dummy.set_next(new_head);
            new_head.set_prev(dummy);

            self.len -= 1;
            elem
        })
    }
}

impl<T> Drop for LinkedList<T> {
    fn drop(&mut self) {
        while self.pop_front().is_some() {}
        let dummy = self.dummy.take().unwrap();
        unsafe {
            let _ = Box::from_raw(dummy.as_ptr());
        }
    }
}

node.rs
use std::{
    fmt::Debug,
    mem::MaybeUninit,
    ops::Not,
    ptr::{self, NonNull},
};

#[derive(Debug)]
pub struct Node<T> {
    prev: NodePtr<T>,
    next: NodePtr<T>,
    elem: MaybeUninit<T>,
}

pub struct NodePtr<T> {
    ptr: NonNull<Node<T>>,
}

impl<T> Debug for NodePtr<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NodePtr").field("ptr", &self.ptr).finish()
    }
}

impl<T> Clone for NodePtr<T> {
    fn clone(&self) -> Self {
        Self { ptr: self.ptr }
    }
}

impl<T> Copy for NodePtr<T> {}

impl<T> PartialEq for NodePtr<T> {
    fn eq(&self, other: &Self) -> bool {
        ptr::eq(self.as_ptr(), other.as_ptr())
    }
}

impl<T> Eq for NodePtr<T> {}

impl<T> NodePtr<T> {
    pub unsafe fn dangling() -> Self {
        Self {
            ptr: NonNull::dangling(),
        }
    }

    pub unsafe fn raw_alloc(prev: Self, elem: MaybeUninit<T>, next: Self) -> Self {
        let ptr = Box::into_raw(Box::new(Node { prev, next, elem }));
        let ptr = NonNull::new_unchecked(ptr);
        Self { ptr }
    }

    pub fn alloc(prev: Self, elem: T, next: Self) -> Self {
        unsafe { Self::raw_alloc(prev, MaybeUninit::new(elem), next) }
    }

    pub fn dummy() -> Self {
        unsafe {
            let dangling = Self::dangling();

            let dummy = Self::raw_alloc(dangling, MaybeUninit::uninit(), dangling);
            dummy.set_prev(dummy);
            dummy.set_next(dummy);

            dummy
        }
    }

    pub fn prev(self) -> Self {
        unsafe { (*self.as_ptr()).prev }
    }

    pub fn set_prev(self, ptr: Self) {
        unsafe {
            (*self.as_ptr()).prev = ptr;
        }
    }

    pub fn next(self) -> Self {
        unsafe { (*self.as_ptr()).next }
    }

    pub fn set_next(self, ptr: Self) {
        unsafe {
            (*self.as_ptr()).next = ptr;
        }
    }

    pub fn is_dummy(self) -> bool {
        self.prev() == self.next() && self.prev() == self
    }

    pub fn as_ptr(self) -> *mut Node<T> {
        self.ptr.as_ptr()
    }

    pub unsafe fn as_ref<'a>(self) -> &'a Node<T> {
        self.ptr.as_ref()
    }

    pub unsafe fn as_mut<'a>(mut self) -> &'a mut Node<T> {
        self.ptr.as_mut()
    }

    pub fn get_raw(self) -> Option<NonNull<T>> {
        self.is_dummy()
            .not()
            .then(|| unsafe { NonNull::new_unchecked((*self.as_ptr()).elem.as_mut_ptr()) })
    }

    pub unsafe fn get<'a>(self) -> Option<&'a T> {
        self.get_raw().map(|ptr| ptr.as_ref())
    }

    pub unsafe fn get_mut<'a>(self) -> Option<&'a mut T> {
        self.get_raw().map(|mut ptr| ptr.as_mut())
    }

    pub unsafe fn dealloc(self) -> Option<(Self, T, Self)> {
        self.is_dummy().not().then(|| {
            // println!("Deallocating...");
            let Node { prev, next, elem } = *Box::from_raw(self.as_ptr());
            (prev, elem.assume_init(), next)
        })
    }
}

Running the test cases with miri:
#[cfg(test)]
mod test {
    use super::{node::NodePtr, LinkedList};

    #[test]
    fn test_node() {
        let dummy = NodePtr::dummy();
        let node = NodePtr::alloc(dummy, 100, dummy);

        dummy.set_next(node);
        dummy.set_prev(node);

        let (_, elem, _) = unsafe { node.dealloc() }.unwrap();
        unsafe {
            Box::from_raw(dummy.as_ptr());
        }
        assert_eq!(elem, 100);
    }

    #[test]
    fn test_basic_front() {
        let mut list = LinkedList::new();

        // Try to break an empty list
        assert_eq!(list.len(), 0);
        assert_eq!(list.pop_front(), None);
        assert_eq!(list.len(), 0);

        // Try to break a one item list
        list.push_front(10);
        assert_eq!(list.len(), 1);
        assert_eq!(list.pop_front(), Some(10));
        assert_eq!(list.len(), 0);
        assert_eq!(list.pop_front(), None);
        assert_eq!(list.len(), 0);

        // Mess around
        list.push_front(10);
        assert_eq!(list.len(), 1);
        list.push_front(20);
        assert_eq!(list.len(), 2);
        list.push_front(30);
        assert_eq!(list.len(), 3);
        assert_eq!(list.pop_front(), Some(30));
        assert_eq!(list.len(), 2);
        list.push_front(40);
        assert_eq!(list.len(), 3);
        assert_eq!(list.pop_front(), Some(40));
        assert_eq!(list.len(), 2);
        assert_eq!(list.pop_front(), Some(20));
        assert_eq!(list.len(), 1);
        assert_eq!(list.pop_front(), Some(10));
        assert_eq!(list.len(), 0);
        assert_eq!(list.pop_front(), None);
        assert_eq!(list.len(), 0);
        assert_eq!(list.pop_front(), None);
        assert_eq!(list.len(), 0);
    }
}

miri output:
The following memory was leaked: alloc86121 (Rust heap, size: 24, align: 8) {
    0x00 │ ╾0x1f2da8[a86121]<205762> (8 ptr bytes)╼ ╾0x1f2da8[a86121]<205762> (8 ptr bytes)╼ │ ╾──────╼╾──────╼
    0x10 │ __ __ __ __ __ __ __ __                         │ ░░░░░░░░
}
alloc86346 (Rust heap, size: 24, align: 8) {
    0x00 │ ╾0x1f3ef0[a86346]<206225> (8 ptr bytes)╼ ╾0x1f3ef0[a86346]<206225> (8 ptr bytes)╼ │ ╾──────╼╾──────╼
    0x10 │ __ __ __ __ __ __ __ __                         │ ░░░░░░░░
}
alloc86565 (Rust heap, size: 24, align: 8) {
    0x00 │ ╾0x1f4ff8[a86565]<206712> (8 ptr bytes)╼ ╾0x1f4ff8[a86565]<206712> (8 ptr bytes)╼ │ ╾──────╼╾──────╼
    0x10 │ __ __ __ __ __ __ __ __                         │ ░░░░░░░░
}
alloc86723 (Rust heap, size: 24, align: 8) {
    0x00 │ ╾0x1f5c58[a86723]<207063> (8 ptr bytes)╼ ╾0x1f5c58[a86723]<207063> (8 ptr bytes)╼ │ ╾──────╼╾──────╼
    0x10 │ __ __ __ __ __ __ __ __                         │ ░░░░░░░░
}
alloc86946 (Rust heap, size: 24, align: 8) {
    0x00 │ ╾0x1f6da8[a86946]<207524> (8 ptr bytes)╼ ╾0x1f6da8[a86946]<207524> (8 ptr bytes)╼ │ ╾──────╼╾──────╼
    0x10 │ __ __ __ __ __ __ __ __                         │ ░░░░░░░░
}
alloc87169 (Rust heap, size: 24, align: 8) {
    0x00 │ ╾0x1f7f60[a87169]<207985> (8 ptr bytes)╼ ╾0x1f7f60[a87169]<207985> (8 ptr bytes)╼ │ ╾──────╼╾──────╼
    0x10 │ __ __ __ __ __ __ __ __                         │ ░░░░░░░░
}
alloc87393 (Rust heap, size: 24, align: 8) {
    0x00 │ ╾0x1f9100[a87393]<208448> (8 ptr bytes)╼ ╾0x1f9100[a87393]<208448> (8 ptr bytes)╼ │ ╾──────╼╾──────╼
    0x10 │ __ __ __ __ __ __ __ __                         │ ░░░░░░░░
}
alloc87599 (Rust heap, size: 24, align: 8) {
    0x00 │ ╾0x1fa1b0[a87599]<208910> (8 ptr bytes)╼ ╾0x1fa1b0[a87599]<208910> (8 ptr bytes)╼ │ ╾──────╼╾──────╼
    0x10 │ __ __ __ __ __ __ __ __                         │ ░░░░░░░░
}
alloc87823 (Rust heap, size: 24, align: 8) {
    0x00 │ ╾0x1fb2f8[a87823]<209373> (8 ptr bytes)╼ ╾0x1fb2f8[a87823]<209373> (8 ptr bytes)╼ │ ╾──────╼╾──────╼
    0x10 │ __ __ __ __ __ __ __ __                         │ ░░░░░░░░
}
alloc88030 (Rust heap, size: 24, align: 8) {
    0x00 │ ╾0x1fc3a8[a88030]<209837> (8 ptr bytes)╼ ╾0x1fc3a8[a88030]<209837> (8 ptr bytes)╼ │ ╾──────╼╾──────╼
    0x10 │ __ __ __ __ __ __ __ __                         │ ░░░░░░░░
}
alloc88237 (Rust heap, size: 24, align: 8) {
    0x00 │ ╾0x1fd3a8[a88237]<210301> (8 ptr bytes)╼ ╾0x1fd3a8[a88237]<210301> (8 ptr bytes)╼ │ ╾──────╼╾──────╼
    0x10 │ __ __ __ __ __ __ __ __                         │ ░░░░░░░░
}
alloc88454 (Rust heap, size: 24, align: 8) {
    0x00 │ ╾0x1fe4e8[a88454]<210788> (8 ptr bytes)╼ ╾0x1fe4e8[a88454]<210788> (8 ptr bytes)╼ │ ╾──────╼╾──────╼
    0x10 │ __ __ __ __ __ __ __ __                         │ ░░░░░░░░
}
alloc88613 (Rust heap, size: 24, align: 8) {
    0x00 │ ╾0x1ff160[a88613]<211141> (8 ptr bytes)╼ ╾0x1ff160[a88613]<211141> (8 ptr bytes)╼ │ ╾──────╼╾──────╼
    0x10 │ __ __ __ __ __ __ __ __                         │ ░░░░░░░░
}
alloc88773 (Rust heap, size: 24, align: 8) {
    0x00 │ ╾0x1ffe18[a88773]<211496> (8 ptr bytes)╼ ╾0x1ffe18[a88773]<211496> (8 ptr bytes)╼ │ ╾──────╼╾──────╼
    0x10 │ __ __ __ __ __ __ __ __                         │ ░░░░░░░░
}

I got 14 memory leaks but running the test_node case alone doesn't leak any memory. With some further debugging, I can assure that NodePtr::dealloc does run properly ("Deallocating" got printed for 5 times as expected. Note that this method won't be deallocating the dummy node, and I would deallocate the dummy node manually in the Drop impl). The code logic seems to work correctly. Could it be some kind of subtle undefined behavior?

A: Here is your memory leak:
pub(crate) fn inner(&mut self) -> NodePtr<T> {
    *self.dummy.get_or_insert(NodePtr::dummy())
}

NodePtr::dummy() allocates a node, returns the raw pointer and never destroys it. The problem here is that the way it is written it always runs dummy() unconditionally.
This is the fix:
pub(crate) fn inner(&mut self) -> NodePtr<T> {
    *self.dummy.get_or_insert_with(|| NodePtr::dummy())
}

How I found it
When looking at the output of RUSTFLAGS=-Zsanitizer=address cargo +nightly test I realized that the leaked memory always gets initialized in NodePtr::raw_alloc():
Direct leak of 24 byte(s) in 1 object(s) allocated from:
    #0 0x55c80616ed8e in malloc /rustc/llvm/src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:69:3
    #1 0x55c8061a27f9 in alloc::alloc::alloc::ha05f706f7dab9e22 /rustc/06754d8852bea286a3a76d373ccd17e66afb5a8b/library/alloc/src/alloc.rs:171:73
    #2 0x55c8061a27f9 in alloc::alloc::Global::alloc_impl::h5cfa6b00beb3203a /rustc/06754d8852bea286a3a76d373ccd17e66afb5a8b/library/alloc/src/alloc.rs:171:73
    #3 0x55c8061a1e3d in _$LT$alloc..alloc..Global$u20$as$u20$core..alloc..Allocator$GT$::allocate::h6ea44ef9df335707 /rustc/06754d8852bea286a3a76d373ccd17e66afb5a8b/library/alloc/src/alloc.rs:320:11
    #4 0x55c8061a1e3d in alloc::alloc::exchange_malloc::h91c76b5bf53597fd /rustc/06754d8852bea286a3a76d373ccd17e66afb5a8b/library/alloc/src/alloc.rs:320:11
    #5 0x55c80619d43f in alloc::boxed::Box$LT$T$GT$::new::hba6cd0555301746a /rustc/06754d8852bea286a3a76d373ccd17e66afb5a8b/library/alloc/src/boxed.rs:215:9
    #6 0x55c80619d43f in rust_tmp::node::NodePtr$LT$T$GT$::raw_alloc::hc476ac99ddaa5b56 /home/martin/work/rust-tmp/src/node.rs:49:33
    #7 0x55c80619d72b in rust_tmp::node::NodePtr$LT$T$GT$::dummy::h8b4ac6a33651e5fd /home/martin/work/rust-tmp/src/node.rs:62:25
    #8 0x55c806199a04 in rust_tmp::test::test_basic_front::hbb4f6a4888143b15 /home/martin/work/rust-tmp/src/lib.rs:104:20
    #9 0x55c80619fbe9 in rust_tmp::test::test_basic_front::_$u7b$$u7b$closure$u7d$$u7d$::h970eafca0aaa30ba /home/martin/work/rust-tmp/src/lib.rs:93:5
    #10 0x55c8061d94b2 in core::ops::function::FnOnce::call_once::ha04ab83b16462938 /rustc/06754d8852bea286a3a76d373ccd17e66afb5a8b/library/core/src/ops/function.rs:248:5
    #11 0x55c8061d94b2 in test::__rust_begin_short_backtrace::h994ad9d2e6435f98 /rustc/06754d8852bea286a3a76d373ccd17e66afb5a8b/library/test/src/lib.rs:572:5

Then, I reduced the usage down to a minimum. I realized it already happens with a single push_front():
fn main() {
    let mut list = LinkedList::new();
    list.push_front(10);
    dbg!(list.pop_front());
    dbg!(list.pop_front());
}

I then added println()s to all allocations and deallocations:
    pub unsafe fn raw_alloc(prev: Self, elem: MaybeUninit<T>, next: Self) -> Self {
        let ptr = Box::into_raw(Box::new(Node { prev, next, elem }));
        println!("raw_alloc: {:p}", ptr);
        let ptr = NonNull::new_unchecked(ptr);
        Self { ptr }
    }

    // ...

    pub unsafe fn dealloc(self) -> Option<(Self, T, Self)> {
        self.is_dummy().not().then(|| {
            let ptr = self.as_ptr();
            println!("dealloc: {:p}", ptr);
            let Node { prev, next, elem } = *Box::from_raw(ptr);
            (prev, elem.assume_init(), next)
        })
    }

impl<T> Drop for LinkedList<T> {
    fn drop(&mut self) {
        while self.pop_front().is_some() {}
        let dummy = self.dummy.take().unwrap();
        unsafe {
            let ptr = dummy.as_ptr();
            println!("drop: {:p}", ptr);
            let _ = Box::from_raw(ptr);
        }
    }
}

I saw the following output, when running the main() shown earlier:
raw_alloc: 0x603000000070
raw_alloc: 0x6030000000a0
raw_alloc: 0x6030000000d0
dealloc: 0x6030000000a0
[src/main.rs:78] list.pop_front() = Some(
    10,
)
raw_alloc: 0x603000000100
[src/main.rs:79] list.pop_front() = None
raw_alloc: 0x603000000130
drop: 0x603000000070

The allocations 0x603000000070 and 0x6030000000a0 seem fine, that's the dummy element and the first node. The respective deallocations also seem to match, dealloc: 0x6030000000a0 and drop: 0x603000000070. But there are three more allocations that shouldn't be there, 0x6030000000d0, 0x603000000100 and 0x603000000130.
So what I did next is to set a breakpoint in raw_alloc() using VSCode and the amazing rust-analyzer plugin. I ran in debug, hit the first raw_alloc() for the dummy element, then the second for the first node element, and then the third. I looked at the callstack of the third, and saw:

*

*rust_tmp::node::NodePtr<T>::raw_alloc

*rust_tmp::node::NodePtr<T>::dummy

*rust_tmp::LinkedList<T>::inner

*rust_tmp::LinkedList<T>::pop_front

*rust_tmp::main
I then thought, 'why does dummy() get called again in inner()?'; and that's when I noticed the get_or_insert().
I hope this analysis helps to improve your own debugging skills :)


text:
Q: gdb does not stop when piping the command When running the usual way, gdb stops as expected:
(gdb) break main
(gdb) run
Starting program ...
Breakpoint 1, main ...

when running while piping, gdb never stops:
(gdb) run | cat
Starting program: /home/sds/z | cat
...
During startup program exited normally.
(gdb)

How do I debug program behavior when piping?
my setup:
$ gdb --version
GNU gdb (GDB) Amazon Linux (7.6.1-64.33.amzn1)
$ uname -a
Linux datasci-1 4.4.19-29.55.amzn1.x86_64 #1 SMP Mon Aug 29 23:29:40 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
$ gcc --version
gcc (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9)

same problem on the most recent fully updated ubuntu (16.10).

A: While input and output redirection work, you cannot use pipes to pass the output of the program you are debugging to another program; if you attempt this, GDB is likely to wind up debugging the wrong program.
https://www.sourceware.org/gdb/onlinedocs/gdb.html

A: Based on another answer:
(gdb) run > >(cat)

See Process Substitution.


text:
Q: Cancellation properties of matrix multiplication
*

*$AB=AC$ implies $B=C$

*$BA=CA$ implies $B=C$
These statements are true if $A$ is invertible. That is proved easily by multiplication of the inverse on both sides.
However, shouldn't it be the case that the two statements hold whenever $A$ is one to one, that is, its null space is $\{0\}$ which will be satisfied by non singular square matrices as well as nonsquare matrices which have a greater dimension in the output space, whose columns are linearly independent.
If not please provide counter examples and if yes, provide a logical explanation or, much less preferably, a rigorous proof.

A: Counter example to point $2$ where $A$ is injective:
$\begin{pmatrix} 1 & 1  \end{pmatrix} \begin{pmatrix} 1 \\ 0  \end{pmatrix} = 1$
and
$\begin{pmatrix} 1 & 0  \end{pmatrix} \begin{pmatrix} 1 \\ 0  \end{pmatrix} = 1$
where $A = \begin{pmatrix} 1 \\ 0  \end{pmatrix}$ has LI columns and so is injective.
A straightforward way to understand your question is to note the following:
$A$ LI columns $\iff$ $A$ injective $\iff$ A has a left inverse
and
$A$ LI rows $\iff$ $A$ surjective $\iff$ A has a right inverse

A: Well, in a ring $R$, the cancellation law ''$ab=ac$ implies $b=c$'' holds more generally if $a$ is not a zero divisor, since $ab=ac$ gives $a(b-c)=0$ by distributivity. If $a$ is not a zero divisor, then $b-c=0$, i.e., $b=c$. So there is no need for $a$ to be a unit.

A: AB=AC
AB-AC=O
A(B-C)=O
Similarly,
BA=CA
BA-CA=O
(B-C)A=O
So, in both cases, either

*

*A=O,

*B=C

*Rest of the cases where N(A) union N(B-C)=all of space

By imposing the condition that N(A)={0}, we ensure that the first doesn't happen, and when the third does,it implies B=C
Thus, A being one to one necessarily implies B=C.


text:
Q: Positive operator- definition I'm trying to learn functional analysis myself, and would be very happy if you could help me with some definitions I do not understand.
Let   $T:H \rightarrow  H$ be a linear operator, when $(H,\langle \cdot\rangle )$ is Hilbert space.
If I'm right, and correct me if I'm wrong, $T$ is "positive" iff: $\forall x \in H:\langle x,Tx \rangle \geq 0$.
Now, Let   $K:E \rightarrow  E$ be a linear operator, when $(E,\|\cdot\|)$ is Banach space.
Now, how can we define a positive operator for a Banach space?
Thanks for helping.


text:
Q: Landscape orientation for iPad? Frustrated by how simple this should be...
I'm trying to add landscape support to an existing iPad app of mine. Do I actually have to create a completely new view controller for landscape mode? (surely not as that is a complete pain!)? Or can I use the existing view controllers and design for landscape and portrait? The simulated metrics thing doesn't work because whenever I make changes in a view controller in landscape mode and switch back to portrait it messes everything up! I know how to switch the view to landscape programmatically, this is (at least i think) an 'interface builder' sort of issue.
Why is this so difficult to do/hard to find!? Might be worth mentioning I'm using Xcode 4.2 with storyboards rather than separate xibs. Surely I don't have to use a separate view and segues because I really can't be bothered wasting my time with that.
Any help would be nice! Thanks

A: Watch for -willRotateToInterfaceOrientation:duration: and change the frame of your interface elements when the rotation changes.


text:
Q: Restart Home programmatically I'm developing on Android. I have to restart home and all its components (widgets, shortcuts, etc..).
For example, when we have a Force Close, the home screen restart and reload all its components.

A:
I have to restart home and all its components (widgets, shortcuts, etc..).

No, you don't.

For example, when we have a Force Close, the home screen restart and reload all its components.

If you have a "Force Close", you cannot execute code. Hence, what you want is impossible.

A: You should be able to relaunch it ACTION_MAIN and CATEGORY_HOME intent. If you've just killed the app then this should restart it.


text:
Q: SQL query to find sum of a column I have a table where I have to get the output as follows:
ID - amount - TotalAmount
1  - 400    - 400
2 -  600    - 1000
3 -  400    - 1400

The table has two columns: ID & amount. The 'TotalAmount' should be created when the SQL script runs and hope, the rest of the sum is cleared from the above.
How can I do the above sum?? Please share ideas to do so. Thanks.

A: This is a cumulative sum.  The ANSI standard method is as follows:
select id, amount, sum(amount) over (order by id) as TotalAmount
from t;

Most, but not all databases, support this syntax.
The above is the "right" solution.  If your database doesn't support it, then a correlated subquery is one method:
select t.id, t.amount,
       (select sum(t2.amount) from t t2 where t2.id <= t.id) as TotalAmount
from t;

A: You didn't state your DBMS, so this is ANSI SQL:
select id, amount,
       sum(amount) over (order by id) as totalamount
from the_table

A: In SQL SERVER 2012 this Query is working fine. Try This:
SELECT
   ID,
   AMOUNT,
   SUM(AMOUNT)
   OVER(ORDER BY ID) AS TotalAmount
FROM
   YourTable;

A: select id, amount, sum(amount) as totalAmount from table_name order by id;


text:
Q: Check if Attribut with same value is already used I am writing a kind of TLV de-/serialization class.
Like protobuf-net I have a contract attribut for classes and a member attribut for properties. The member attributes have a Tag number like in protobuf.
Now I would like to check if a Tag number is already used, the best solution would be if there is some kind of compiler error for this. I also have postsharp if this will help.
The class structure looks like this:
[TlvContract]
public class Person{
    [TlvMember(1)]
    public String Name{get; set;}
    [TlvMember(2)]
    public Int32 ID{get; set;}
    // This should create a warning or compile error!!!!
    [TlvMember(1)]
    public String Town{get; set;}
}

A: Apart from Roslyn analyzers, PostSharp is a possible way to go.
Following is a basic implementation of such checks and error outputs:
[MulticastAttributeUsage(PersistMetaData = true)]
public class TlvContractAttribute : TypeLevelAspect
{
    public override void CompileTimeInitialize(Type target, AspectInfo aspectInfo)
    {
        Dictionary<int, PropertyInfo> indexes = new Dictionary<int, PropertyInfo>();

        foreach (PropertyInfo propertyInfo in target.GetProperties())
        {
            TlvMemberAttribute memberAttr =
                propertyInfo.GetCustomAttributes()
                    .Where(x => x is TlvMemberAttribute)
                    .Cast<TlvMemberAttribute>()
                    .SingleOrDefault();

            if (memberAttr == null)
            {
                Message.Write(MessageLocation.Of(propertyInfo), SeverityType.Error, "USR001",
                    "Property {0} should be marked by TlvMemberAttribute.", propertyInfo);

                continue;
            }

            if (indexes.ContainsKey(memberAttr.Index))
            {
                Message.Write(MessageLocation.Of(propertyInfo), SeverityType.Error, "USR002",
                    "Property {0} marked by TlvMemberAttribute uses Index {1}, which is already used by property {2}.",
                    propertyInfo, memberAttr.Index, indexes[memberAttr.Index]);

                continue;
            }

            indexes[memberAttr.Index] = propertyInfo;
        }
    }
}

It works in the assembly in which you define it. You just need to make sure that PostSharp actually runs on all assemblies where you want the check to work.
If you need a different base class for your attribute, you can also implement ITypeLevelAspect and ITypeLevelAspectBuildSemantics interfaces.


text:
Q: autocomplete in vaadin? I'm new to vaadin.  How do I do autocomplete (actually, more like google suggest) on a huge set of data that cannot be loaded in memory, but instead performing a JPA query on every key event.  Is it possible to capture key events on a textfield or combobox?

A: You could check out Henrik Paul's SuperImmediateTextField, which is a Vaadin add-on that allows you to set the client-to-server post delay in seconds. From that on it's common Java stack to get the flow as smooth as possible. Caching, JPA requests or something else. A couple of second's delay will at least slightly lessen the load to server side.

A: If you don't want to write a custom client-side widget or include another add-on, you can tweak Vaadin's ComboBox a bit to make it load suggestions from the database. You basically have to do three things to achieve that:

*

*Subclass com.vaadin.ui.ComboBox and overwrite its protected method
ComboBox#buildFilter() with your own implementation.

*Implement interface com.vaadin.data.Container.Filter with very
restricted functionality: your Filter only needs to transport the
current user input.

*Write an implementation of com.vaadin.data.Container that performs
the actual filter logic.

I described how to do that in more detail in a blog post.

A: Vaadin auto-complete add-on is available to achieve this. check this out:-https://vaadin.com/directory/component/autocomplete
Example below:
   Autocomplete autocomplete = new Autocomplete();

    autocomplete.setLimit(5);

    autocomplete.addChangeListener(event -> {
        String text = event.getValue();
        autocomplete.setOptions(findOptions(text));
    });

    autocomplete.addChangeListener(event -> {
        refreshContent(event.getValue());
    });

    autocomplete.addValueClearListener(event -> {
        peopleGrid.setItems(Collections.EMPTY_LIST);
    });

    autocomplete.setLabel("Find what you want:");
    autocomplete.setPlaceholder("search ...");

Complete code below :
https://github.com/vaadin-component-factory/autocomplete/blob/master/autocomplete-demo/src/main/java/com/vaadin/componentfactory/demo/AutocompleteView.java#L132

A: You may find this link helpful. I guess this is getting fixed in 6.5. There is also an addon if you want to check.
you need to consider this though
field value -> json -> vaadin servlet -> service (spring/ejb/pojo or whatever) -> JPA -> query -> result list (which may be huge initially)
and this all the way back to browser for every key press...
think about the end user's typing speed. By the time 1st keystroke's response comes back from the server, user might have completed the whole word.

A: The instant TextField should be what you are looking for. Take a look at the Sampler demo:
http://demo.vaadin.com/sampler/#TextFieldTextChangeEvent

A: maybe checkout this addon: https://vaadin.com/directory#!addon/suggestbox-add-on
comes with:
delay for server communication, e.g. wait till user finished typing              for n miliseconds
placeholder text like 'type your query here'
minimum length for input to query the server


text:
Q: Mouse's cursor size is not saved in Lubuntu 21.10 In LXQT Settings is option for changing mouse cursor size in Xorg (LXQT Settings->Keyboard and Mouse->Cursor https://drive.google.com/file/d/15bjIeK11kQV-WeTG5DbuMF6c6SndUXQG/view?usp=sharing) . But after reboot, cursor returns to it's initial size.
How to save this setting permanently?
Regards.


text:
Q: Nodejs : Kineticjs in nodejs I install the package Kineticjs in nodejs and have the following error message:

Kinetic.window = Kinetic.document.createWindow();
                                              ^
TypeError: undefined is not a function
    at /kinetic/kinetic.js:608:47

A: document.createWindowwas removed from jsdom 1.0.0-pre.1. Use jsdom 0.11.1 with kinetic

A: If you have problems like that, you can always read on documentation. also
console.log(typeof Kinetic.document.createWindow);

Also if u do not have access to source code or u can not simply find it. u can always output javascript code via simply reading it with simple I/O
http://serebrov.github.io/html/2013-12-02-node-core-module-source.html

here is example
fs = require('fs');
fs.writeFileSync('fs.js', fs.toString());
fs.writeFileSync('fs.readFileSync.js', fs.readFileSync.toString());

this will copy the source code of fs to new js file that u can read.


text:
Q: Java , Modular Inverse i have some mathematique function to do (for affine encryption) am looking for the Modular Inverse
for exemple
the modular inverse of A=5 and an alphabet of length 26 is 21
i have worked with this solution (A' =(n % 26 + 26) % 26) but it gives a wrong solution i need some help please :/

A: T = total elements in the set.
N = the number for which you want the "mod inverse".
I = the mod inverse.
I = T - (N % T)


text:
Q: Cómo seleccionar el área y lo que esta dentro de las fechas seleccionadas? ¿Cómo seleccionar el área y lo que esta dentro de las fechas seleccionadas?
Estoy trabajando en una pagina web e hice un query para mostrar el área y los valores que le corresponden al área seleccionada dentro de las fechas seleccionadas.
Este es el query:
var consulta = "SELECT * FROM produccion WHERE fecha BETWEEN #" + fecha+"# AND #" + fechaFinal + "#";

Y esta es la tabla:
+----+----------+---------+----------+----------+----------+-----------+
| id |   area   | grafica | grafica2 | grafica3 | grafica4 |   fecha   |
+----+----------+---------+----------+----------+----------+-----------+
| 40 |    IFE   |   90.5  |          |          |          |  4/2/2018 |
| 41 |    IFE   |         |   90.5   |          |          |  4/9/2018 |
| 42 |    IFE   |         |          |   90.5   |          | 4/16/2018 |
| 43 |    IFE   |         |          |          |   90.5   | 4/23/2018 |
| 44 | Seamless |   50.1  |          |          |          |  4/2/2018 |
| 45 | Seamless |         |   50.1   |          |          |  4/2/2018 |
| 46 | Seamless |         |          |   21.3   |          |  4/9/2018 |
+----+----------+---------+----------+----------+----------+-----------+


text:
Q: How can I use SignalR directly in ES6 classes I recently ran into an issue trying to call SignalR functions and receive data from SignalR using ES6 classes with the SignalR proxy. Visual Studio was throwing errors with the "myHub.server.function" syntax for mapped methods.
I would like to better "componentize" my code and SignalR is powering my backend comms (no REST on the backend). BTW, I am not using any more than SignalR, ES6 and JQUERY. Please, no responses about Angular et. Al.
Thanks

A: Not fancy but made it work for classic ASP.NET:
npm i signalr -S
npm i jquery -S
import $ from 'jquery';
window.$ = window.jQuery = require("jquery");
require("signalr");

export default class SignalRservice {

constructor (url){
    var con = $.hubConnection(url);
    this.connection = con.createHubProxy('ChatHub').connection;

    this.connection.start();
    }
}

For ASP.NET Core it is just fancy:
npm i @aspnet/signalr -S
import {HubConnection} from "@aspnet/signalr";

export default class SignalRservice {

constructor (){
    this.connection = new HubConnection('/ChatHub');

    this.connection.start();
    }
}


text:
Q: IIS Log files for ASP.NET website I am testing ASP.NET website and for that I have turned logging on at IIS6.0.
Following are the observations during testing:

*

*Each link, png image, MS Chart and CSS file has been requested separately, one after another.

*For request of say login page it is taking around 30-45 seconds to complete and in that page only 6 images are there and at log file it is observed that there are separate requests for each images one after another.

Can anybody help me to improve site performance and also I would like to know that is it possible that all requests would send to server parallel?

A: Yes it is possible to improve on the app speed by parallelizing the downloads !
I recommend going through google page-speed and yahoo's yslow, and read the practices that they propose. I felt it informative.
http://code.google.com/speed/page-speed/
http://developer.yahoo.com/yslow/help/index.html
Thanks

A: First of all, have you checked web-site Performance tab? Limits could've been set there. Also check that keep-alives are enabled (web site tab).
Then you should profile your server using System Monitor.
If everything mentioned is ok, you should check client side and what's between client and server.

A: What's happening is that the browser makes HTTP requests to the server for each object it finds on the page.  You can eliminate those requests, or reduce how often they happen, by enabling client-side caching.  For static files, you can configure that in IIS.
You can parallelize requests for images (not JS files) by assigning them to different domains; if they are all in a single domain, the browser will request only two at a time.
However, you question opens the door to a big subject.  In an attempt to provide a detailed answer, I ended up writing a book on the subject, called Ultra-Fast ASP.NET.  I cover the answer to the question from the OP in great detail in Chapter 2.


text:
Q: Formatting api JSON response to add attributes to an array I have the following api controller that returns a json representation of the query you see here:
public async Task<ActionResult<IEnumerable<CarDto>>> GetCarData(Guid carID)
{
    var carData = await (from cl in _context.CarList
                         join tl in _context.transmissionList
                             on cl.CId equals tl.CId
                         join to in _context.transmissionOptions
                             on tl.TId equals to.TId
                         where cl.CId == carID
                         select new CarDto
                         {
                             CarId = cl.CarId,
                             TransmissionId = tl.TId,
                             OptionId = to.OptionId,
                             GearId = to.GearId
                         })
                         .ToListAsync();
    return carData;
}

The returned json data looks like this:
[
    {
        "carId": "351a",
        "transmissionId": "ec7",
        "optionId": "a1",
        "gearId": "674532a"
    },
    {
        "carId": "351a",
        "transmissionId": "ec7",
        "optionId": "b7",
        "gearId": "5f9173f"
    },
    {
        "carId": "351a",
        "transmissionId": "ec7",
        "optionId": "c5",
        "gearId": "cf807"
    }
]

However, I'd like for it to be formatted such that there is a property called transmissionChoices that contains an array of the possible options.
Like this:
{
    "carId": "351a",
    "transmissionId": "ec7",
    "transmissionChoices": [
        {
            "optionId": "a1",
            "gearId": "674532a"
        },
        {
            "optionId": "b7",
            "gearId": "5f9173f"
        },
        {
            "optionId": "c5",
            "gearId": "cf807"
        }
    ]
}

Is there a way to get the controller to format it like that?

A: You can use the LINQ GroupBy method and then project the grouped results into the shape you want.
public async Task<ActionResult<IEnumerable<object>>> GetCarData(Guid carID)
{
    var carData = await (from cl in _context.CarList
                        join tl in _context.transmissionList
                            on cl.CId equals tl.CId
                        join to in _context.transmissionOptions
                            on tl.TId equals to.TId
                        where cl.CId == carID
                        select new
                        {
                            CarId = cl.CarId,
                            TransmissionId = tl.TId,
                            OptionId = to.OptionId,
                            GearId = to.GearId
                        })
                        .GroupBy(x => x.CarId)
                        .Select(g => new
                        {
                            CarId = g.First().CarId,
                            TransmissionId = g.First().TransmissionId,
                            TransmissionChoices = g.Select(x => new
                            {
                                OptionId = x.OptionId,
                                GearId = x.GearId
                            })
                        })
                        .ToListAsync();
    return carData;
}

Note that this is projecting the results into an anonymous type. Feel free to create a model that matches the schema you need and then use that model in the Select(...) projection.


text:
Q: Text view with rich markdown in SwiftUI (more than only bold and italic text) Android
In my app I need to visually style and highlight long texts that come from a DB. The texts are written as following:

Accept the <f>current</f> situation and <f>then</f> try to build a better one on top of it. Only then will you catch a break from all that getting away and will be able to think about how to actually improve.
<h>Resistance deepens the negative thoughts, acceptance releases them.</h>

On Android, I take these texts and parse them using Regex to replace the tags with something that works with the library. I'm using the SRML library to display it like this:

iOS
Now my question is: how do I reach a somewhat similar experience on iOS?
I'm using SwiftUI so far, but I can see that it's pretty limited in this specific regard. All I've found so far are libraries that helps you make it bold, italic or something other very minor:

*

*https://github.com/kyle-n/HighlightedTextEditor

*https://github.com/indragiek/MarkdownTextView
But I specifically need to highlight phrases, meaning color their background yellow. I then found this library, that offers some pretty complex functionality, but is written in Objective-C and I don't know how well that will work with my SwiftUI basis: https://github.com/ibireme/YYText

Is there any chance for me to get it working with SwiftUI components?
My best guess would be to do something like this (very basic pseudo code):
text = DB.getText
parser = StringParser(text)
content = ViewGroup()

while(parser.hasNextLine) { nextLine in
  if(nextLine.contains("<h>")) {
    var text = Text(nextLine)
                 .background(Color.yellow)
    content.add(text)
  } else if(...) {
    ...
  }

  // etc. etc.
}

And kind of build the resulting Text step by step from multiple pieces. But this looks kind of ugly to be honest. Any other ideas? And if not, how should I go about including that Cbjective-C library into a SwiftUI project?

A: With the help of a freelancer on Fiverr I solved it in the following way:
https://stackoverflow.com/a/69871902/1972372
Basically parsed the tags manually and kept track of the content types and order in an array, while keeping formatted Texts in another array. Then I could take that content and plant it into a ViewBuilder body function.
Unfortunately, SwiftUI doesn't let you change a Text's background color yet, without turning it into some View. So I had to make do with other, similar formattings for now.


text: Q: Prove that $f(x,y)=x^2y-y+3$ is a lipschitz continuous function So I need to prove that $f(x,y)=x^2y-y+3$ is a lipschitz continuous function with Lipschitz constant $\sqrt{\frac{4}{3}}$ in the circle of centre $(0,0)$ and radius 1, but I don't know how to do it. Can somebody help me?


text:
Q: I want to put a slider in a slidedown div I want to put this slider in the slideDown() function so that when the text is hovered the slider should come down.
I have given the code snippet that i was trying to work on, it includes the javascript, css, body.

AAA Laundry

if i remove the code for slideDown its working but otherwise it not.
please help.

A: I modified your code a little and used JQuery instead of Javascript,
also you used window.onload and $(document).ready which have almost the same purpose.
plz check this demo and see if that's what you wanted:-
http://jsfiddle.net/d3rtcyxn/


text:
Q: JavaScript Image Class - Merge two images next to each other is there a way to combine two images in one image class? I don't want to blend them, just put them next to each other...
I'm looking for something like this:
myImg = new Image()
myImg.src = "img1.jpg" + "img2.jpg"

Thanks!
Edit:
I need to combine them before putting them into the canvas for easier scroll-handling... so canvas or div is not an option.
Edit, II.:
I'm using a canvas through which I'm scrolling. But my image is chucked. It thought it would be the easiest way, when I merge my actual image with the following and "scroll" through this one instead of handling two seperate ones.

A: Not that I know of. An image element only support a single image. Either you would have to create two separate images and float them next to each other, or you could use a canvas element, and draw both images onto it side by side (if you don't have a very rare scenario at hand, the best solution is likely to use two separate images though).

A: You can't combine images like that using javascript, unless you use canvas or equivalent techniques.
If you just want to place them next to each other, create a container and append the images:
var container = document.createElement('div'),
    createImage = function(src) {
        var img = new Image();
        img.src = src;
    };
 container.appendChild( createImage('img1.jpg') );
 container.appendChild( createImage('img2.jpg') );

A: use JQuery
$('.container').append('');
$('.container').append('');


text:
Q: Error while trying to overload << operator I can't get  the below code to compile while trying to overload the << operator. Can anyone point whats going wrong?
#include <iostream>

std::ostream& operator<<(std::ostream& i, int n)
{
    return i;
}

int main()
{
    std::cout << 5 << std::endl;
    std::cin.get();
    return 0;
}

A: There is already defined the operator << for an object of the type int in the C++ standard library
basic_ostream<charT, traits>& operator<<(int n);

so this call of the operator in this statement
std::cout << 5 << std::endl;

is ambiguous because the standard operator is found due to the argument dependent lookup.
To disactivate the ADL you could write for example something like the following calling the operator explicitly with two arguments
#include <iostream>

std::ostream& operator<<(std::ostream& i, int n)
{
    return i.operator <<( n );
}

int main()
{
    operator <<( std::cout, 5 ) << std::endl;
    std::cin.get();

    return 0;
}

The program output is
5

Though it does not make a great sense.:)

A: Because more than one operator "<<" matches these operands.
std::ostream& operator<<(std::ostream& i, int n) has been defined.
Operator can be overload, not override.
operator works like this:
TypeA a = (TypeB)operand1 operator (TypeC)operand2
see operator as a function, it translates to this func:
TypeA operator(TypeB operand1, TypeC operand2)
Define the func twice would cause compile error.
To overload <<, try:
std::ostream& operator<<(std::ostream& i, OtherType n)
or
AnyType operator<<(AnyType i, AnyType n)
Just do not repeat.


text:
Q: Start job in X minutes I am trying to run a job 3 minutes after a controller's action was executed.
I tried this, with DelayedJob:
# in my controller

def index
  @books = Book.all
  Delayed::Job.enqueue(ReminderJob.new(params[:user_id]))
end

And in the ReminderJob.rb file:
class ReminderJob < Struct.new(:user_id)
  def perform
    p "run reminder job"
    # do something
  end
  handle_asynchronously :perform, :run_at => Proc.new { 3.minutes.from_now }
end

However, when accessing the index page, I don't see in the logs anything, and 3 minutes later nothing happens.
What did I do wrong ? Is there another recommended way to run a task "in X minutes from now" without using sleep ?

A: In this case I would use rails' built in package called ActiveJob.
See here how to setup and basic usage. You can use delayed_job as the backend.
In your case this code would work:
def index
  user = User.find(params[:user_id])
  ReminderJob.set(wait: 3.minutes).perform_later(user)
end

and your job:
class ReminderJob < ApplicationJob # assumes you have a /app/jobs/application_job.rb
  def perform(user)
    # do something with the user
  end
end


text:
Q: Terraform compliance: how do i check that my GCP resources have a label with a given key? I have just discovered terraform compliance and am testing it out against my terraform code that deploys resources to GCP.
GCP labels enable fine-grained cost analysis and every labels attribute is a map (bigquery_dataset#labels) so I would like to verify that every resource that has a labels argument includes a certain key that we use for analysing costs. Here is an example terraform configuration:
variable "project"{
 type = string
}

provider "google" {
  region = "europe-west2"
}

resource "google_bigquery_dataset" "dataset1" {
  dataset_id    = "dataset1"
  project       = var.project
  labels        = { "label1" : "some_value" }
}

resource "google_bigquery_dataset" "dataset2" {
  dataset_id    = "dataset2"
  project       = var.project
  labels        = { "anotherlabel" : "some_value" }
}

resource "google_bigquery_dataset" "dataset3" {
  dataset_id    = "dataset3"
  project       = var.project
}

dataset3 is not acceptable because it doesn't have any labels. dataset2 is unacceptable because while it does have labels, it doesn't have the one I want it to  have, label1
I would like to use terraform compliance to check for these anomolies but I can't figure out how. here is my feature file, test.feature:
Feature: Terraform Compliance

Scenario: My scenario
    Given I have any resource defined
    When it has labels
    Then it must contain label1

I then issue :
terraform init ^^ \
  terraform plan --var=project=myproject --out=plan.out && \
  terraform-compliance --planfile plan.out -f .

which produces this output:

terraform-compliance v1.3.24 initiated
. Converting terraform plan file.
 Features     : /tmp/tctest/
 Plan File    : /tmp/tctest/plan.out.json
 Running tests.
Feature: Terraform Compliance  # /tmp/terraformcompliancetest/test.feature
Scenario: My scenario
    Given I have any resource defined
    When it has labels
            Failure: google_bigquery_dataset.dataset2 (google_bigquery_dataset) does not have label1 property.
            Failure: google_bigquery_dataset.dataset3 (google_bigquery_dataset) does not have label1 property.
    Then it must contain label1
      Failure:

1 features (0 passed, 1 failed)
1 scenarios (0 passed, 1 failed)
3 steps (2 passed, 1 failed)
Run 1629659085 finished within a moment

Clearly this isn't giving me what I want. I've pored over the docs but can't figure out what I'm supposed to be putting in my feature file. Can anyone help?

UPDATE As requested on twitter, here is the contents of plan.out.json
{
    "format_version": "0.1",
    "terraform_version": "0.14.7",
    "variables": {
        "project": {
            "value": "myproject"
        }
    },
    "planned_values": {
        "root_module": {
            "resources": [
                {
                    "address": "google_bigquery_dataset.dataset1",
                    "mode": "managed",
                    "type": "google_bigquery_dataset",
                    "name": "dataset1",
                    "provider_name": "registry.terraform.io/hashicorp/google",
                    "schema_version": 0,
                    "values": {
                        "dataset_id": "dataset1",
                        "default_encryption_configuration": [],
                        "default_partition_expiration_ms": null,
                        "default_table_expiration_ms": null,
                        "delete_contents_on_destroy": false,
                        "description": null,
                        "friendly_name": null,
                        "labels": {
                            "label1": "some_value"
                        },
                        "location": "US",
                        "project": "myproject",
                        "timeouts": null
                    }
                },
                {
                    "address": "google_bigquery_dataset.dataset2",
                    "mode": "managed",
                    "type": "google_bigquery_dataset",
                    "name": "dataset2",
                    "provider_name": "registry.terraform.io/hashicorp/google",
                    "schema_version": 0,
                    "values": {
                        "dataset_id": "dataset2",
                        "default_encryption_configuration": [],
                        "default_partition_expiration_ms": null,
                        "default_table_expiration_ms": null,
                        "delete_contents_on_destroy": false,
                        "description": null,
                        "friendly_name": null,
                        "labels": {
                            "anotherlabel": "some_value"
                        },
                        "location": "US",
                        "project": "myproject",
                        "timeouts": null
                    }
                },
                {
                    "address": "google_bigquery_dataset.dataset3",
                    "mode": "managed",
                    "type": "google_bigquery_dataset",
                    "name": "dataset3",
                    "provider_name": "registry.terraform.io/hashicorp/google",
                    "schema_version": 0,
                    "values": {
                        "dataset_id": "dataset3",
                        "default_encryption_configuration": [],
                        "default_partition_expiration_ms": null,
                        "default_table_expiration_ms": null,
                        "delete_contents_on_destroy": false,
                        "description": null,
                        "friendly_name": null,
                        "labels": null,
                        "location": "US",
                        "project": "myproject",
                        "timeouts": null
                    }
                }
            ]
        }
    },
    "resource_changes": [
        {
            "address": "google_bigquery_dataset.dataset1",
            "mode": "managed",
            "type": "google_bigquery_dataset",
            "name": "dataset1",
            "provider_name": "registry.terraform.io/hashicorp/google",
            "change": {
                "actions": [
                    "create"
                ],
                "before": null,
                "after": {
                    "dataset_id": "dataset1",
                    "default_encryption_configuration": [],
                    "default_partition_expiration_ms": null,
                    "default_table_expiration_ms": null,
                    "delete_contents_on_destroy": false,
                    "description": null,
                    "friendly_name": null,
                    "labels": {
                        "label1": "some_value"
                    },
                    "location": "US",
                    "project": "myproject",
                    "timeouts": null
                },
                "after_unknown": {
                    "access": true,
                    "creation_time": true,
                    "default_encryption_configuration": [],
                    "etag": true,
                    "id": true,
                    "labels": {},
                    "last_modified_time": true,
                    "self_link": true
                }
            }
        },
        {
            "address": "google_bigquery_dataset.dataset2",
            "mode": "managed",
            "type": "google_bigquery_dataset",
            "name": "dataset2",
            "provider_name": "registry.terraform.io/hashicorp/google",
            "change": {
                "actions": [
                    "create"
                ],
                "before": null,
                "after": {
                    "dataset_id": "dataset2",
                    "default_encryption_configuration": [],
                    "default_partition_expiration_ms": null,
                    "default_table_expiration_ms": null,
                    "delete_contents_on_destroy": false,
                    "description": null,
                    "friendly_name": null,
                    "labels": {
                        "anotherlabel": "some_value"
                    },
                    "location": "US",
                    "project": "myproject",
                    "timeouts": null
                },
                "after_unknown": {
                    "access": true,
                    "creation_time": true,
                    "default_encryption_configuration": [],
                    "etag": true,
                    "id": true,
                    "labels": {},
                    "last_modified_time": true,
                    "self_link": true
                }
            }
        },
        {
            "address": "google_bigquery_dataset.dataset3",
            "mode": "managed",
            "type": "google_bigquery_dataset",
            "name": "dataset3",
            "provider_name": "registry.terraform.io/hashicorp/google",
            "change": {
                "actions": [
                    "create"
                ],
                "before": null,
                "after": {
                    "dataset_id": "dataset3",
                    "default_encryption_configuration": [],
                    "default_partition_expiration_ms": null,
                    "default_table_expiration_ms": null,
                    "delete_contents_on_destroy": false,
                    "description": null,
                    "friendly_name": null,
                    "labels": null,
                    "location": "US",
                    "project": "myproject",
                    "timeouts": null
                },
                "after_unknown": {
                    "access": true,
                    "creation_time": true,
                    "default_encryption_configuration": [],
                    "etag": true,
                    "id": true,
                    "last_modified_time": true,
                    "self_link": true
                }
            }
        }
    ],
    "configuration": {
        "provider_config": {
            "google": {
                "name": "google",
                "expressions": {
                    "region": {
                        "constant_value": "europe-west2"
                    }
                }
            }
        },
        "root_module": {
            "resources": [
                {
                    "address": "google_bigquery_dataset.dataset1",
                    "mode": "managed",
                    "type": "google_bigquery_dataset",
                    "name": "dataset1",
                    "provider_config_key": "google",
                    "expressions": {
                        "dataset_id": {
                            "constant_value": "dataset1"
                        },
                        "labels": {
                            "constant_value": {
                                "label1": "some_value"
                            }
                        },
                        "project": {
                            "references": [
                                "var.project"
                            ]
                        }
                    },
                    "schema_version": 0
                },
                {
                    "address": "google_bigquery_dataset.dataset2",
                    "mode": "managed",
                    "type": "google_bigquery_dataset",
                    "name": "dataset2",
                    "provider_config_key": "google",
                    "expressions": {
                        "dataset_id": {
                            "constant_value": "dataset2"
                        },
                        "labels": {
                            "constant_value": {
                                "anotherlabel": "some_value"
                            }
                        },
                        "project": {
                            "references": [
                                "var.project"
                            ]
                        }
                    },
                    "schema_version": 0
                },
                {
                    "address": "google_bigquery_dataset.dataset3",
                    "mode": "managed",
                    "type": "google_bigquery_dataset",
                    "name": "dataset3",
                    "provider_config_key": "google",
                    "expressions": {
                        "dataset_id": {
                            "constant_value": "dataset3"
                        },
                        "project": {
                            "references": [
                                "var.project"
                            ]
                        }
                    },
                    "schema_version": 0
                }
            ],
            "variables": {
                "project": {}
            }
        }
    }
}

A: Writing it from mobile, so didnt try thoroughly.
Can you please try ?
Scenario: My scenario
    Given I have any resource defined
    When it has labels
    Then it must have labels
    Then it must contain label1

As you see the fix is adding a "then" after "when" because all "When" directives are for filtering while "Then" directives drills down the resource data.
Hope it fixes :)
//Edit:
Here is the output I got ;
 Running tests.

Feature: test

    Scenario: My scenario
        Given I have any resource defined
        When it has labels
        Then it must have labels
        Failure: google_bigquery_dataset.dataset2 (any resource) does not have label1 property.
        Failure: google_bigquery_dataset.dataset3 (any resource) does not have label1 property.
        Then it must have label1
          Failure:

1 features (0 passed, 1 failed)
1 scenarios (0 passed, 1 failed)
4 steps (3 passed, 1 failed)

A: Had loads of help from @emre-erkunt and his reply almost gave me what I need (and will make that reply as an answer). I modified it slightly to include two scenarios:
Feature: Terraform Compliance

Scenario: Labels must be defined
    Given I have resource that supports labels defined
    When it has labels
    Then it must have labels
    Then its value must not be null

Scenario: Labels must include label1
    Given I have resource that supports labels defined
    When it has labels
    Then it must have labels
    Then it must have label1

Which returns:

terraform-compliance v1.3.24 initiated
. Converting terraform plan file.
 Features     : /tmp/tctest/
 Plan File    : /tmp/tctest/plan.out.json
 Running tests.
Feature: Terraform Compliance  # /tmp/tctest/test.feature
Scenario: Labels must be defined
    Given I have resource that supports labels defined
    When it has labels
    Then it must have labels
            Failure: labels property in google_bigquery_dataset.dataset3 is considered to be Null. It is set to None.
    Then its value must not be null
      Failure:

Scenario: Labels must include label1
    Given I have resource that supports labels defined
    When it has labels
    Then it must have labels
            Failure: google_bigquery_dataset.dataset2 (resource that supports labels) does not have label1 property.
            Failure: google_bigquery_dataset.dataset3 (resource that supports labels) does not have label1 property.
    Then it must have label1
      Failure:

1 features (0 passed, 1 failed)
2 scenarios (0 passed, 2 failed)
8 steps (6 passed, 2 failed)
Run 1629663083 finished within a moment

which is satisfactory and I think as close as I'm going to get to exactly what I want.
Massive thank you to Emre.


text:
Q: Replace ends of string in eclipse I am trying to refactor a large source base in a company I work in. Instead of using the print function in python 2.7x I want to use the logger function.
for example:
print "Sample print %d" % timestamp
With logger.info("Sample print %d" % timestamp)
so basically, I want to remove the print , and insert what remains into parentheses and logger.info (Ill assume all current prints are INFO until a full refactor is possible).
Thanks in advance

A: Search for (^\s+)print (.*)$
Replace with $1logger.info($2)
Python should complain pretty fast about all the places where a print goes over more than a single line. You'll have to fix those places manually.
Note: This skips comments
The alternative is to look into the source for 2to3.py which replaces print ... with print(...) to convert code from Python 2 to 3.


text:
Q: Vertical stack order of divs rather than horizontal?
Possible Duplicates:
How to stack divs from top to bottom in CSS
How to make div stack first vertically then horizontally?

Floating or inline elements stack like this:

-----------------
| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | 8 |
-----------------

But I would like to stack them like this:

-----------------
| 1 | 3 | 5 | 7 |
| 2 | 4 | 6 | 8 |
-----------------

Constraints: Arbitrary number of elements. All of same size. All elements must be on the same "level", meaning we cannot stack "pairs" of divs.
Is it possible?
EDIT: Forgot to mention, the container should expand horizontally so it's ok to use a "fixed" number of "rows".

A: I have two solutions.
First, use the CSS3 nth-of-type:
div:nth-of-type(even){margin:50px 0 0 -50px;}
This degrades gracefully into the un-indeal ordering, but the general formatting is preserved.
Also, you can achieve a similar effect by putting a class on every other item.
Demo

A: Set your column-count to 4 on the elements parent.
#your-parent-element-id {
    -moz-column-count: 4;
    -moz-column-gap: 10px;
    -webkit-column-count: 4;
    -webkit-column-gap: 10px;
    column-count: 4;
    column-gap: 10px;
}

Note that this will only work in relatively modern browsers.
See also: http://www.quirksmode.org/css/multicolumn.html

A: I believe the most manageable option that works in all browsers is to wrap every couple elements in another "column" div:

1

2

3

4

5

6

7

8

...
div.column {
  width:25%
  float:left;
}

Most html is served from a server-side programming language, usually with some sort of templating engine. Doing this in a templating engine such as ERB for Ruby or Smarty for PHP is  very simple.
For your "stacking" height problem, just assign a height to the inner divs
div.column div {
  height:200px;
}


text:
Q: CodeIgniter - pass variables to CSS I'm rewriting website on Code Igniter, and i need to load external TTF. MySQL db points path to that TTFs. Can I pass somehow these variables to CSS and make foreach loop to 'loads' these fonts.
I tried
$this->load->vars($data);

A: First, deal with serving dynamic CSS. My site has a controller called "resource" which allows me to serve CSS, JS, etc. (maybe images in the future).  It loads views based upon the segments passed to it in the url.
So, when http://mysite.com/resource/css/main.css is requested:

*

*My Resource controller (.../controllers/resource) handles any specifics of data handling (as is general with an MVC controller). It then loads:

*A generic view: ".../views/resources/css.php", passing it the name of the desired css file. This view prints out the header, specifying the Content-Type (important!) and any other generic stuff. Then it proceeds to load:

*The actual CSS file specified, here ".../views/resources/css/main.css.php".

It's a little overkill, but allows for a lot of flexibility, like you sound like you need.
Controller:
...
$segments = $this->uri->segment_array();
array_shift($segments);   // remove the first two
array_shift($segments);
$content['stylesheet'] = $segments[0] . ".php";  //e.g. main.css.php
$content['data'] = array();                      //Font data, etc
$this->load->view('resources/css.php', $content);
..

Generic resources/css.php
This loads up the actual .css.php stylesheet
<?php header("Content-Type: text/css"); // This is key! ?>
/* MySite CSS File (c) 2011 bla bla */
<?php
     $this->load->view("resources/css/$stylesheet", $data);
     echo "\n";
?>

Specific resources/css/main.css.php
<?php echo "/* I can use PHP in my CSS! */\n"; ?>
body { background-color: <?=$data['bg_color']?>; }
p { font-family: <?=$data['p_font_fam'];?>; }

A: You probably need to understand how you retrieve data from db and how you display them:
http://codeigniter.com/user_guide/database/index.html
good luck
EDIT:
what you need is probably something like that:
after you have retrieved the links from database and let's say you called them $ttf_links
 <?php
          foreach($ttf_links as $link){
        echo "<link rel='stylesheet' type='text/css' href={$link['row_name']} media='screen' />"
    }
    ?>

and then call the fonts you need in your css

A: Passing variables to a CSS doesn't work for as far as I know.
I have read something about CSS templating with PHP, but I can't find the link anymore. Will update this answer as soon as I found the link. But you could look for it yourself as well.
Update
Found it!: http://www.barelyfitz.com/projects/csscolor/

A: The easiest way I see you doing this is with file level CSS and changing values the usual way.

A: A workaround would be to use CSS in the page itself to load the fonts.

A: Here is the answer , I have implemented this and works fine
https://ellislab.com/forums/viewthread/220105/#1014374


text:
Q: MVC Authorize Attribute One Time In Controller This is CustomAuthorizeAttribute class content:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
         return (CurrentUser.IsInRole(MasterRole, ChildRole)) ? true : false;
    }
}

And my controller:
[CustomAuthorize(MasterRole="Master")]
public class HomeController : Controller
{
...
    [CustomAuthorize(ChildRole = "Child")]
    public ActionResult Slider()
    {
        return View();
    }
...
}

In this usage to CustomAuthorizeAttribute class ChildRole comin as "Child" it's OK but MasterRole coming null.
How can i define "MasterRole" just one time in controller, or is it posible?
I mean, its working as below syntax but i don't want to define MasterRole for every action as below:
    [CustomAuthorize(MasterRole = "Master", ChildRole = "Child")]
    public ActionResult Slider()
    {
        return View();
    }

A: Seeing that authorization attributes are evaluated on the controller before on the action you could abuse the authorize system a bit. You could set the master role on the context and then retrieve it in the authorize attribute on the action.
Add two new attributes like so:
public class SetMasterRoleAttribute : AuthorizeAttribute
{
    public string MasterRole;

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        httpContext.Items.Add("MasterRole", MasterRole);
        return true;
    }
}

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public string ChildRole;
    public string MasterRole;

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (string.IsNullOrEmpty(MasterRole))
        {
            MasterRole = httpContext.Items["MasterRole"] as string;
        }

        return (CurrentUser.IsInRole(MasterRole, ChildRole)) ? true : false;
    }
}

And then set up your controller and actions like this:
[SetMasterRole(MasterRole = "Master")]
public class HomeController : Controller
{
    [CustomAuthorize(ChildRole = "Child")]
    public ActionResult Index()
    {
        return View();
    }
}


text:
Q: fadeIn fadeOut jquery for both browsers I think fadeIn() fadeOut() jquery should run on mobile browsers too. But it's not working. See live demo for working in desktop browser and see live demo for not working in mobile browser. So I am looking forward to know the alternative way for fadeIn and fadeOut function which supports in mobile browsers.
newImg.fadeIn(1500,function(){
   oldImg.fadeOut('1500');
   oldImg.remove();
   clicked = false;
});

I just changed according to the @Frank Anneveld to this:
newImg.fadeIn(1500, function(){
      oldImg.fadeOut('1500', function(){
         oldImg.remove();
      });
      clicked = false;
   });

Which is having the fadeIn effect but not effective as similar as desktop browser. Anyway, what am I doing bad practice in my first placed code is that removing old image while fadeIn new image?

A: Point here is that oldImg.remove() is removed, while fadeOut is running.
For documentation see: http://api.jquery.com/fadein/
Maybe this will help:
   newImg.fadeIn(1500, function(){

      oldImg.fadeOut('1500', function(){
         oldImg.remove();
      });

      clicked = false;
   });

or make a cross-fade:
   newImg.fadeIn(1500, function(){
      clicked = false;
   });
   oldImg.fadeOut('1500', function(){
      oldImg.remove();
   });


text:
Q: What does it mean "inputs must be a list"? Below codes show me "inputs must be a list". at this.
outputs, states = rnn.rnn(lstm_cell, x, dtype=tf.float32)

When I define placeholder for input x. I have already set a shape as [None,None]. I think this shape is 2-dimensional array. However, the code continuously requires list type of x.
Below, I have attached all of my codes before training. And this codes are inserted into function of class.
x = tf.placeholder("float",[None,None])
y = tf.placeholder("float",[None])

lstm_cell = rnn_cell.BasicLSTMCell(self.n_hidden, forget_bias=1.0)

outputs, states = rnn.rnn(lstm_cell, x, dtype=tf.float32)

pred = tf.matmul(outpus[-1], self.weights['out']) + self.biases['out']
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y))
optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(cost)

correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

init = tf.initialize_all_variables()

self.sess = tf.Session()

self.sess.run(init)

Additionally, practical inputs will be float of word sequence and float of label formed as x=[["aaa","aaa","aaa"],["bbb","bbb"]], y=["c1","c2"].
At that, the first element array of x is labeled with "c1" and the second is "c2". Especially, size of each element array of x cannot be deterministic.

A: As stated by the documentation, the argument inputs of the function tf.nn.rnn() is:

inputs: A length T list of inputs, each a Tensor of shape [batch_size, input_size], or a nested tuple of such elements.

In your code, the argument inputs is x, a Tensor placeholder of shape [None, None]. In order for your code to work, x must be a list of T tensors of shape [None, input_lenght].
The following code generates a list of tensors as inputs and therefore the function tf.nn.rnn works.
import tensorflow as tf

x = tf.placeholder("float",[None,16])
y = tf.placeholder("float",[None])

lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(256, forget_bias=1.0)

inputs = []
for t in range(10):
        inputs.append(x)

print(len(inputs))

outputs, states = tf.nn.rnn(lstm_cell, inputs, dtype=tf.float32)

pred = tf.matmul(outputs[-1], self.weights['out']) + self.biases['out']
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y))
optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(cost)

correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

init = tf.initialize_all_variables()

self.sess = tf.Session()

self.sess.run(init)

Note how the placeholder x has a defined shape of [None, input_shape]. It won't work with a shape [None, None] because the first dimensions is the batch_size, which can be None, but the second dimension is the size of each item in the input sequence, and that value can't be None.


text:
Q: Arrow & textbox appear disoriented in Tabulator table The Arrow & textbox for the filter at the header row appears disoriented.

The arrow should appear at the right side and the search box should appear below title.
I am using the below imports in my html file.
<!-- Tabulator -->
<link href="https://unpkg.com/tabulator-tables@4.5.3/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.5.3/dist/js/tabulator.min.js"></script>

<!-- Jquery & Jquery UI -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

Any suggestions why this might be happenning?

A: That's quite weird because everything is loaded fine. Looks like you'll have to do some post mortem yourself here.
Whenever you have such queries related to unwanted CSS behavior try to inspect that in a browser inspector in a browser. In the Inspector(Firefox) or Elements(chrome) tab you will see styles which are applied to your element.
Try to toggle each style on/off by clicking on the ticks. You'll get what is happening wrong there.