text:
Q: Classify the main list into substituens using prolog I'm attempting to check if any element of the first list has a match on the second list. If matching found classify that element and split with that element, then we again check the rest of the list. If there are more matches found in particular classification then append the those lists.
I try some classify code below but it didn't correctly work. This order of the format is only work.
?- classify_substituens([1,2,ab,hj,de,as,t,pq,js,xy,ac],Ab,De,Pq,Xy,Rest).
Ab = [1, 2, ab],
De = [hj, de],
Pq = [as, t, pq],
Xy = [js, xy],
Rest = [ac].

My code:
classify_ab(N,Ab,R):-append(B,[ab|R],N),append(B,ab,Ab),!.
classify_de(N,De,R):-append(B,[de|R],N),append(B,de,De),!.
classify_pq(N,Pq,R):-append(B,[pq|R],N),append(B,pq,Pq),!.
classify_xy(N,Xy,R):-append(B,[xy|R],N),append(B,xy,Xy),!.

classify_substituens(List,Ab,De,Pq,Xy,Rest):-
    classify_ab(List,Ab_1,Rest_1),
    classify_de(Rest_1,De_1,Rest_2),
    classify_pq(Rest_2,Pq_1,Rest_3),
    classify_xy(Rest_3,Xy_1,Rest4),
classify_substituens(Rest_4,Ab_2,De_2,Pq_2,Xy2,Rest),
    append(Ab_1,Ab_2,Ab),
    append(De_1,De_2,De),
    append(Pq_1,Pq_2,Pq),
    append(Xy_1,Xy_2,Xy),
    !.
classify_substituens(List,[],[],[],[],List).

I want goals like below.
?- classify_substituens([1,2,ab,a,b,xy,as,t,xy,ac],Ab,De,Pq,Xy,Rest).
Ab = [1, 2, ab],
De = [],
Pq = [],
Xy = [a,b,xy,as,t,xy],
Rest = [ac].
?- classify_substituens([1,2,ab,a,b,de,s,t,ab,i,ac],Ab,De,Pq,Xy,Rest).
Ab = [1, 2, ab,s,t,ab],
De = [a,b],
Pq = [],
Xy = [],
Rest = [i,ac].

A: To simplify my life, I'm calling the atoms ab, de, pq and xy "endcaps."
endcap(ab).
endcap(de).
endcap(pq).
endcap(xy).

Your code happens to match this, which I think is simpler:
takeUpto(Token, List, PrefixToken, Remainder) :-
    append(Prefix, [Token|Remainder], List),
    append(Prefix, [Token], PrefixToken).

classify_substituens(List, Ab, De, Pq, Xy, Rest) :-
    takeUpto(ab, List, Ab, R0),
    takeUpto(de, R0, De, R1),
    takeUpto(pq, R1, Pq, R2),
    takeUpto(xy, R2, Xy, Rest).

This unfortunately still does not work. What you're trying to do is make bins and drop everything into the right bin. I see a way to do it with a single pass but it is fairly gross. I spent about 30 minutes on it and found it too difficult to debug. A verbal sketch would be this: delegate to a helper method with an accumulator, a "rest" variable and with two variables for each bin: one for input, one for output. The helper method has a case for getting an empty list; map the input variables to the output variables and the accumulator to the "rest" variable. Now the helper has a case for each "endcap" and they all look almost the same: append the accumulator to the singleton list of the endcap, and forward that to a recursive call as the new state variable for this endcap. It sounds easy but there are 11 variables involved and a lot of copy/paste.
I did come up with a solution though, which seems (to me) fairly easy to read and write. It is not efficient. Sorry.
First, I want to get the "substituens" of interest. I group them together and then label them with the particular flavor they have.
substituens(Acc, [], [], Acc).
substituens(Acc, [X|Xs], Subs, Rem) :-
    (   endcap(X) ->
        append(Acc, [X], Substituen),
        substituens([], Xs, RemainingSubs, Rem),
        append([X-Substituen], RemainingSubs, Subs)
    ;   append(Acc, [X], Acc1),
        substituens(Acc1, Xs, Subs, Rem)
    ).

This works like so:
?- substituens([], [1,2,ab,a,b,de,s,t,ab,i,ac], Y, Rem).
Y = [ab-[1, 2, ab], de-[a, b, de], ab-[s, t, ab]],
Rem = [i, ac] ;
false.

I didn't bother making a substituens/2 wrapper for this because I'm only going to call it from classify_substituens/6. Now I say, suppose I have some endcap category. Let me get all the stuff from this lookup table-like structure
condense(Category, Groups, Condensed) :-
    findall(Group, member(Category-Group, Groups), MyGroups),
    append(MyGroups, Condensed).

This depends on append/2, which is not ISO but probably is not super-hard to write since it's just the fixed-point of append/3.
These two helpers make short work of classify_substituens/6:
classify_substituens(List, Ab, De, Pq, Xy, Rest) :-
    substituens([], List, Subs, Rest),
    condense(ab, Subs, Ab),
    condense(de, Subs, De),
    condense(pq, Subs, Pq),
    condense(xy, Subs, Xy).

And there you have it:
?- classify_substituens([1,2,ab,a,b,de,s,t,ab,i,ac],Ab,De,Pq,Xy,Rest).
Ab = [1, 2, ab, s, t, ab],
De = [a, b, de],
Pq = Xy, Xy = [],
Rest = [i, ac] ;
false.

?- classify_substituens([1,2,ab,a,b,xy,as,t,xy,ac],Ab,De,Pq,Xy,Rest).
Ab = [1, 2, ab],
De = Pq, Pq = [],
Xy = [a, b, xy, as, t, xy],
Rest = [ac] ;
false.

Incidentally, this also shows me that one of your test cases is wrong. :) De must always end with de.
I do have a lingering sense that there may be an efficient and readable way to do this using DCGs or difference lists, but my DCG power is not quite strong enough to see it. Maybe someone else will try it?
So, kudos for a hard problem that makes no sense! This is one of the strangest questions I can recall on prolog in a long time! I really don't see why you would ever want this, but I hope my code helps, even though it is pretty amazingly inefficient.


text:
Q: Wait for a Redux action to return a value from API and based on the response need to navigate to Screen I am developing a simple signUp screen using react native. If the user enter all data (first name, last name, email) in the form, the entered data will get passed to the API and saved it to DB.I have a simple validation here ..i.e.. Once user submits I am dispatching the action to call API and the API will return true if the user entered email is already existing.
Based on the return result from the API, I need to proceed further.
if true (email already existing) I need to show some error message.
if false(email not existing) I need to navigate to next screen.
My Problem is while dispatching action it is not waiting for return value.
Below I have mention my code,
once submitted calling the js function to dispatch action,

My redux action

My log

redpajama_set_name: RedPajamaStackExchange


text:
Q: Entity framework, POCO, howto report progress to user during DB initialize? I am trying to figure out a way so I can report the progress on initialize DB schema stage
to user though a progress bar.
The problem is: I don't know where to call the 'ReportProgress' function? I am currently overwrite 'Seed' function to populate initial DB data, could I overwrite Database 'Initialize' function so the progress could be updated after the creation of each table?
EDIT:
According to this article: Creating a Code First Database Initializer Strategy
Implementation of IDatabaseInitializer and its function InitializeDatabase and
put my own database and table creating code inside should do what I want. Then instead
of inside Seed function, I could raise events inside InitializeDatabase. That should working, but I have yet reach a point that I need go though all these trouble to show progress of DB initialize to end user, now a waiting cursor works for me.

A: EF initializers do not expose the progress through any events.
Declare some events that you want to raise when some state changes in the seed method.
public class MyInitializer : CreateDatabaseIfNotExists<MyContext>
{
    public event EventHandler<SeedStateChangeEventArgs> SeedStateChange;

    protected virtual void Seed(MyContext context)
    {
       // create a table
       OnSeedStateChange(new SeedStateChangeEventArgs { Table = "Foo" });

       // create another table
       OnSeedStateChange(new SeedStateChangeEventArgs { Table = "Bar" });
    }

    protected virtual void OnSeedStateChange(SeedStateChangeEventArgs args)
    {
         // raise event here
    }
}

Then in your Form
var initializer = new MyInitializer();
initializer.SeedStateChange += MyStateChangeHandler;
Database.SetInitializer(initializer);

var context = new MyContext();
context.Database.Initialize(false);

This is just an outline of the concept. I haven't tried this


text:
Q: Slow profiling with Eclipse TPTP I've developing an application in Eclipse 3.6 and am trying to get some simple execution profiling statistics with TPTP (basically just the execution time analysis).
However, the profiling is running so slowing that it's barely possible to get a successful run, Eclipse sometimes crashes with OutOfMemoryErrors and I highly doubt that any of the execution time statistics are anything close to what I normally get. I guess it's running about 100th of normal speed, using 100% of a CPU.
Any ideas as to what could be causing this and how I could fix it?
System is Core i7 980 running Windows 7 64-bit, JVM is Sun JDK 1.6.20 in case that is relevant

A: Did you try with this eclipse.ini file for some optimization and hopefully and better runtime experience?.
Note: keep the Java1.6u20, or make sure ti use the 1.6u21 build 7 (not build 6).
That way, you will ensure the --launcher.XXMaxPermSize parameter (that you should set to an high value in order to facilitate your session) will be correctly recognized.

A: please try this
following is the instructions to switch built in profiling database with newer version

*

*close your eclipse ide

*browse to your-workspace-folder/.metadata/.plugins/org.eclipse.dltk.core.index.sql.h2

*copy all files under this folder to another location as a backup

*and delete all files with .db extension

*download latest version of H2 database for All Platforms zip from this link

*goto your-eclipse-folder\plugins\ and find the file something like org.h2_1.1.117.v201105142352.jar and copy it to some place as a backup

*extract the zip file downloaded on step 5

*you will find the file h2-1.3.170.jar under h2\bin\ folder

*rename h2-1.3.170.jar to the file name from the step 6 which is org.h2_1.1.117.v201105142352.jar

*after this you can put the file renamed in step 9 into the folder your-eclipse-folder\plugins\

*you can try to start your eclipse

please let me know if this makes your eclipse run faster


text:
Q: getting error only with vercel deployment when displaying props (works locally) I am building a headless wordpress CMS(and using next.js template) .
I was able to successfully deploy to the vercel servers, I then started to add some content, in this case the Wordpress title field.. and this works great on my local server and display the title properly with no errors.. but when I update my git it kills the vercel deployment and I get this error.. I also get this error if I try to use content or dangerouslySetHTML
to clarify, if I remove this, it deploys fine
{ page.title }
Unhandled error during request: TypeError: Cannot read property 'title' of undefined
--
17:01:15.529 | at Page (/vercel/workpath0/.next/serverless/pages/[slug].js:1634:412)

this is my page code [slug].js

import Head from 'next/head'
import Link from 'next/link'
import Container from '../components/container'
import MoreStories from '../components/more-stories'
import HeroPost from '../components/hero-post'
import Intro from '../components/intro'
import Layout from '../components/layout'
import { getAllPagesWithSlug, getAllPagesBySlug } from '../lib/api'
import { CMS_NAME } from '../lib/constants'
import Header from '../components/header'

export default function Page( {page} ) {

  return (
    <>
      <Layout>
        <Head>
          <title></title>
        </Head>
       <Header />
        <Container>

        { page.title }

        </Container>
      </Layout>
    </>
  )
}

export async function getStaticProps({ params }) {

  const data = await getAllPagesBySlug(params.slug)
  console.log(data)

  return {
    props: {
      page: data.page,

    },
  }
}

export async function getStaticPaths() {
  const allPages = await getAllPagesWithSlug()

  return {

     //paths:  [ { params: { slug: '${node.uri}' } }  ],
    paths: allPages.edges.map(({ node }) => `/${node.slug}`) || [],
    fallback: true,
  }
}

this is my query  lib/api
const API_URL = process.env.WORDPRESS_API_URL

async function fetchAPI(query, { variables } = {}) {
  const headers = { 'Content-Type': 'application/json' }

  if (process.env.WORDPRESS_AUTH_REFRESH_TOKEN) {
    headers[
      'Authorization'
    ] = `Bearer ${process.env.WORDPRESS_AUTH_REFRESH_TOKEN}`
  }

  const res = await fetch(API_URL, {
    method: 'POST',
    headers,
    body: JSON.stringify({
      query,
      variables,
    }),
  })

  const json = await res.json()
  if (json.errors) {
    console.error(json.errors)
    throw new Error('Failed to fetch API')
  }
  return json.data
}

export async function getAllPagesBySlug($id) {
  const data = await fetchAPI(`
    {

        page(id: "${$id}", idType: URI) {
            uri
            slug
            content
            title
            featuredImage {
              node {
                sourceUrl
              }
            }
          }
    }
  `)
  return data
}


text:
Q: Materialized view created successfully but giving query too long error on refreshing I have created a materialized view.
CREATE MATERIALIZED VIEW apps.RPRO_BILLED_CONTRACTS_MV
REFRESH COMPLETE
START WITH SYSDATE
NEXT (sysdate+1/1440) with rowid
AS "query";

it got created successfully and is returning rows on select * operation.
However I wanted to check whether it is refreshing or not and turns out it was not.
I ran the manual refresh command as :
BEGIN
DBMS_SNAPSHOT.REFRESH('RPRO_BILLED_CONTRACTS_MV');
end;

Now this returns error:
Error report
ORA-32411: materialized view definition query exceeds the maximum length
ORA-06512: at "SYS.DBMS_SNAPSHOT", line 2563
ORA-06512: at "SYS.DBMS_SNAPSHOT", line 2776
ORA-06512: at "SYS.DBMS_SNAPSHOT", line 2745
ORA-06512: at line 2

32411. 0000 -  "materialized view definition query exceeds the maximum length"
*Cause:    The materialized view definition query exceeds the 64K limit.
*Action:   Change the materialized view definition query so that it does not exceed
           the maximum length of 64K.

I'm confused, if the query is too long, how come the view got created and returning values but not refreshing. Please help.

A: The CREATE process for a Materialized View is different to the REFRESH process.
During CREATE, the Materialized View can be created using any length SQL statement. During REFRESH, the 64K limit described below is enforced:
http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_6002.htm
A possible workaround is to chain your materialized view creation. If you can breakdown your query into smaller chunks you can build your final materialized view using a subquery that itself references materialized views.


text:
Q: Initialize form using the dictionary from request.POST I want to have a 'save' form option which will save the data to database to Draft table. (So I don't mix it with the submitted data).
When the user click submit, I create a draft and fill it with the POST data.
 Draft.objects.get_or_create(email=email)
 draft.data = post_to_json(self.request.POST)
 draft.save()

Post_to_json does the following
def post_to_json(post):
    dictionary = {}
    for key in post.keys():
        data = post.getlist(key)
        dictionary[key] = data
    return json.dumps(dictionary)

it saves the POST as it is so if email was a input field and skills where a multicheckbox in POST there is {"email": ["my@mail.com"], "skills": ["01", "02", "03", "04"]} and post_to_json saves it that way. (If I would just dump it I'd get {email": "my@mail.com", "skills": "04"} so some skills would be lost(Not to mention that it wouldn't initialize properly in the form)).
Now I have a problem how to initialize the Form when the user returns and want to continue in the process.
I tried to do:
def get_initial(self):
    draft_uuid = self.kwargs.get('uuid')
    draft = Draft.objects.get(uuid=draft_uuid)
    return json.loads(draft.data)

But then in the browser I have prefilled ["my@mail.com"] instead of just my@mail.com.
How does Django work that it can actually prefill the form just fine when I do MyFormClass(request.POST) but it fails when I try to convert the POST to dictionary and then use it the same way?
So my goal is to load the data from a dictionary to a form so it's prefilled in the browser.
Any ideas how to do it?

A: Convert your data back into {field: value} format and set as form initial wherever you instantiate the form.
https://docs.djangoproject.com/en/1.9/ref/forms/fields/#initial
Why can't you do this -
data =  user.get_initial()  # Giving you the json format
mcb_fields = ("skills",)   #If you have more such fields, write their name here
init_data = {}
for key, value in data.iteritems():
     if key in mcb_fields:
        init_data.update({key :value})  # check if you have to convert each value to int or if it accepts string (this is in str format)
     else:
        init_data.update({key :value[0]})
form = SomeDraftForm(initial =init_data)


text:
Q: PHP 7 Error on old theme - Prestashop 1.6 / Thirtybees: 'Cannot use string offset as an array' I'm trying to install an 'old' (2018) Prestashop 1.6 theme on PHP 7.2 but it seems that part of the theme code is deprecated PHP wise. Maybe the way the array is declared? Can you please help as I think line 1263 needs to rewritten:
Cannot use string offset as an array
in file modules/leotempcp/leotempcp.php at line 1263

1261:        if ($directories) {
1262:            foreach ($directories as $dir) {
1263:                $output['skins'][basename($dir)]['name'] = $this->l(basename($dir));
1264:                if (file_exists($dir.'/icon.png')) {
1265:                    $output['skins'][basename($dir)]['icon'] = _PS_BASE_URL_._THEME_DIR_.'css/skins/'.basename($dir).'/icon.png';
1266:                }
1267:            }
1268:        }

Your help is appreciated


text:
Q: Get all items except max value from each group - mysql Due to some bug, we have got duplicate user entries in our table, I want to create a temp table with all rows except the latest record

id  name  unique_id  created_at
-----------------------------------------
1   aaaa  1          2018-01-20 13:40:30
2   aaaa  1          2017-01-20 13:40:30
3   aaaa  1          2016-01-20 13:40:30
4   bbbb  2          2018-01-20 13:40:30
5   bbbb  2          2017-01-20 13:40:30
6   bbbb  2          2016-01-20 13:40:30
7   cccc  3          2018-01-20 13:40:30
8   cccc  3          2017-01-20 13:40:30
9   cccc  3          2016-01-20 13:40:30

what would be the query to get the following result, so that I can store it in another table

id  name  unique_id  created_at
----------------------------------------
2   aaaa  1          2017-01-20 13:40:30
3   aaaa  1          2016-01-20 13:40:30
5   bbbb  2          2017-01-20 13:40:30
6   bbbb  2          2016-01-20 13:40:30
8   cccc  3          2017-01-20 13:40:30
9   cccc  3          2016-01-20 13:40:30

A: DELETE FROM user WHERE id IN (SELECT id, MAX(created_at) from user GROUP BY unique_id)

A: You appear to be asking for:
create temporary table t as
    select u.*
    from users u
    where u.id < (select max(u2.id) from users u2 where u2.unique_id = u.unique_id);

If performance is an issue, you want an index on users(unique_id, id).

A: Since I had millions of records, I did something like this, using 3 temp tables
-- get all max value in individual group

create temporary table max_value_table as select id,unique_id from users c inner join (select max(created_at)as date1, unique_id as pi from users group by unique_id having count(*) > 1) d on c.created_at = d.date1;
-- join with original(users) table get only duplicate records (to ignore the ids' of single occurrence)
create temporary table duplicate_value_table  as select c.id,name,c.unique_id,c.created_at from users c inner join max_value_table t on c.unique_id = t.unique_id;
-- join duplicate_value_table table with tamp and store it in result_table

create temporary table result_table as select t2.id,name,t2.unique_id,t2.created_at from duplicate_value_table t2 inner join max_value_table t1 on t1.unique_id = t2.unique_id and t2.id != t1.id;

now, result_table has all values which can be deleted later.


text:
Q: Accessing underlying DbDataReader in Dapper I am querying a Teradata database using Dapper with no issues. However, I'd like now to retrieve the records count before fetching rows. TdDataReader exposes a RecordsReturned property with this information. How can I retrieve this data while using Dapper to map query results?

A: I was able to achieve this using IDbConnection.ExecuteReader and IDataReader.Parse according to @Jeroen comment.
var reader = connection.ExecuteReader(...);
var dataReader = ((IWrappedDataReader)reader).Reader;
var records = ((TdDataReader)dataReader).RecordsReturned;
var data = reader.Parse<T>();


text:
Q: How to use Rmarkdown to write academic paper based on LaTeX Template How to use R markdown to write academic paper based on the LaTeX template not available in R studio R markdown template.
I want use R Markdown to write academic paper based on the LaTeX template for Computer Science Proceedings from Springer available here. I downloaded the file. It contains the following files:

*

*LNS_Sample.tex

*lincs.csl

*samplepaper.tex

*spincs04.bst

What I did: I created a new Rmarkdown file and saved it in the same location where I saved the above files. I wrote the YAML header as shown below and included the template. But, when I knitted the document, I only saw the contents in the template file (LNS_Sample.tex) appear in the PDF. Anything I type after the YAML header does not appear in the generated PDF. Only the contents in the LaTeX template appear. How can I use the template in R markdown?
---
title: "Sentiment Analysis with Domain Specific"
output:
  pdf_document:
    template: LNS_Sample.tex
---

## I write sample text here , but it does not show


text:
Q: What is the change in mongoose version 5 & 6 for model function import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Document, Schema as MongooseSchema, model } from "mongoose";

export type BookDocument = Book & Document;

@Schema()
export class Book {
  _id: MongooseSchema.Types.ObjectId;

  @Prop({ required: true, unique: true })
  name: string;
}

export const BookSchema = SchemaFactory.createForClass(Book);

export const BookModel = model<BookDocument>("Book", BookSchema);

Here, using mongoose version 6.0.2 & BookSchema is giving error. But in version 5.0.2 it is working file. @nesjs/mongoose version in 9.2.1 . What is the issue behind this version changes?
Expected BookSchema will work perfectly for mongoose version 6


text:
Q: How do I create a function that will return a value in a dictionary for each row within a data sheet using Python? I need to create a new column in my table for a state region that populates a region for every row of data (each having a state). How do I write a function to call upon a dictionary for each row item?
I have about 30,000 row items, and I believe a loop would take too long. I am certain there is some way to do this with dictionaries. I've tried using different methods to call this but cannot seem to get it to populate the correct data.
states = {
        'AK': 'Alaska',
        'AL': 'Alabama',
        'AR': 'Arkansas',
        'AZ': 'Arizona',
        'CA': 'California',
        'CO': 'Colorado',
        'CT': 'Connecticut',
        'DC': 'District of Columbia',
        'DE': 'Delaware',
        'FL': 'Florida',
        'GA': 'Georgia',
        'HI': 'Hawaii',
        'IA': 'Iowa',
        'ID': 'Idaho',
        'IL': 'Illinois',
        'IN': 'Indiana',
        'KS': 'Kansas',
        'KY': 'Kentucky',
        'LA': 'Louisiana',
        'MA': 'Massachusetts',
        'MD': 'Maryland',
        'ME': 'Maine',
        'MI': 'Michigan',
        'MN': 'Minnesota',
        'MO': 'Missouri',
        'MS': 'Mississippi',
        'MT': 'Montana',
        'NC': 'North Carolina',
        'ND': 'North Dakota',
        'NE': 'Nebraska',
        'NH': 'New Hampshire',
        'NJ': 'New Jersey',
        'NM': 'New Mexico',
        'NV': 'Nevada',
        'NY': 'New York',
        'OH': 'Ohio',
        'OK': 'Oklahoma',
        'OR': 'Oregon',
        'PA': 'Pennsylvania',
        'RI': 'Rhode Island',
        'SC': 'South Carolina',
        'SD': 'South Dakota',
        'TN': 'Tennessee',
        'TX': 'Texas',
        'UT': 'Utah',
        'VA': 'Virginia',
        'VT': 'Vermont',
        'WA': 'Washington',
        'WI': 'Wisconsin',
        'WV': 'West Virginia',
        'WY': 'Wyoming'
}

state_abbrev = {v: k for k, v in states.items()}

state_code = {
    'AK': '10','AL': '4', 'AR': '9', 'AR': '6', 'CA': '9', 'CO': '8',  'CT': '1', 'DC': '3', 'DE': '3', 'FL': '4',
'GA': '4', 'HI': '9', 'IA': '7', 'ID': '10', 'IL': '5', 'IN': '5', 'KS': '7', 'KY': '4', 'LA': '6',
'MA': '1', 'MD': '3', 'ME': '1', 'MI': '5', 'MN': '5','MO': '7', 'MS': '4', 'MT': '8', 'NC': '4',
'ND': '8', 'NE': '7', 'NH': '1', 'NJ': '2', 'NM': '6','NV': '9', 'NY': '2', 'OH': '5', 'OK': '6',
'OR': '10', 'PA': '3', 'PR': '2', 'RI': '1', 'SC': '4', 'SD': '8', 'TN': '4', 'TX': '6', 'UT': '8',
'VA': '3', 'VI': '2', 'VT': '1', 'WA': '10', 'WI': '5', 'WV': '3', 'WY': '8', 'PI': '9'
    }

state_region = {v: k for k, v in state_code.items()}

def get_region():
    return [state_region[i] for i in fulldf['state']]
fulldf["Region"] = get_region()
fulldf.tail()
Returns key error 'MA', expected to return a new column named "Region" that populates the region for each "state" listed.
KeyError                                  Traceback (most recent call last)
<ipython-input-338-6afc1e48556a> in <module>
 33     return [state_region[i] for i in fulldf['state']]
 34
---> 35 fulldf["Region"] = get_region()
 36 fulldf.tail()
 37

<ipython-input-338-6afc1e48556a> in get_region()
 31
 32 def get_region():
---> 33     return [state_region[i] for i in fulldf['state']]
 34
 35 fulldf["Region"] = get_region()

<ipython-input-338-6afc1e48556a> in <listcomp>(.0)
 31
 32 def get_region():
---> 33     return [state_region[i] for i in fulldf['state']]
 34
 35 fulldf["Region"] = get_region()

KeyError: 'MA'

A: Your get_region function is flawed. It should be:
def get_region():
    return [state_region[i] for i in fulldf['state']]

Python comprehensions are optimized enough for that function to be fine for a 30k length dataframe.


text:
Q: How to auto "click" I'm making a blackjack game and have a <button id='standBtn'>Stand</button>.
I want to get this button "clicked" automatically if(score(myCards) === 21){/* click Stand button */}

A: You need to use .click() function, like this:
if(score(myCards) === 21){
    document.getElementById('standBtn').click();
}

Or simply,if you use jquery
if(score(myCards) === 21){
    $('#standBtn').click();
}


text:
Q: What does "kind enough to die" phrase mean? What does "kind enough to die" phrase mean? Rocket told this to Thor in avengers endgame, not to save her mother(when they came to the past), and to prioritize their task to save the half of the universe who are kind enough to die. if I can remember.
Does this mean that these people don't deserve to die? or something similar?

A: It's a figurative use of the idiom be kind enough:

[Merriam-Webster]
formal
  —used to make a request
  // Would you be kind enough to show me the way?

In Endgame, it's a kind of sarcastic reference to the past happening in a way that wasn't factual:

*

*Thanos: "Hey, I'm looking for some volunteers. I need about half of you to die when I snap my fingers. Which of you would be kind enough to do that for me?"

*(many people raise their hands)

*Thanos: "Thank you very much!"

*Rocket (years later): "Those people were kind enough to die."

In reality, permission wasn't asked, nor was it given. It had nothing to do with politeness or anybody deserving to die. That's why it's a sarcastic reference to the event and the dead.


text:
Q: What is the purpose of []= method on nil Since ruby 2.3.0, you can call []= method on nil. I don't understand the purpose of this method.
For instance:
nil[1] = 1
# or
nil['foo'] = 'bar'

but [] method does not exist:
nil[1]
# => NoMethodError: undefined method `[]' for nil:NilClass

The ruby 2.3.0 changelog does not mention that changes, although it seems close to the safe navigation operator.
What is the purpose of this operator?

A: That method isn't documented in Ruby 2.3.0 and I cannot reproduce this behavior in Ruby 2.3.1 (both examples raise NoMethodError: undefined method '[]=' for nil:NilClass).
Furthermore I reinstalled 2.3.0 and was only partly able to reproduce your examples:
$ rbenv install 2.3.0
Downloading ruby-2.3.0.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.3/ruby-2.3.0.tar.bz2
Installing ruby-2.3.0...
Installed ruby-2.3.0 to /Users/spickermann/.rbenv/versions/2.3.0

$ rbenv shell 2.3.0

$ ruby -v
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin15]

$ irb
irb   > RUBY_VERSION
irb  => "2.3.0"
irb   > nil[1] = 1
irb  => nil
irb   > nil['foo'] = 'bar'
NoMethodError: undefined method `[]=' for nil:NilClass
  from (irb):3
  from /Users/spickermann/.rbenv/versions/2.3.0/bin/irb:11:in `<main>'

It seems like NilClass#[]= doesn't work properly in Ruby 2.3.0. Since it was completely removed in 2.3.1, I guess that this method or this behavior was added by accident.
Update: Cary Swoveland pointed out in a comment on another question that this behavior was a bug and was fixed in later versions (see: https://bugs.ruby-lang.org/issues/11976).

A: That seems to be actually a bug in 2.3.0 - https://bugs.ruby-lang.org/issues/11976
It does not evaluate the arguments:
nil[undefined_index_variable] = raise "Fooo!" # => nil


text:
Q: Homology with coefficients i am starting to study homology groups and i have a question, maybe is a dumb question but if someone could help me would be great.
The question is
$H_i(X,A)=H_i(X,A;\mathbb{Z})?$
I mean equal or isomorphic, i think that the answer is yes(it seems obvious at least for me) but i may be wrong so if someone could tell if i am right or not before i continue reading further, thanks

A: Yes, usually when writing $H_*(X,A)$ without specifying a coefficient group, then you implicitly mean $H_*(X,A;\mathbb{Z})$.


text:
Q: add multiple columns to subset of data.table with := my question is an extension to the previously answered one here:
Add multiple columns to R data.table in one function call?
I'm having problems assigning multiple new columns if the data.table has a key according to which I subset. Example:
library(data.table)
example(data.table)
DT[J("a")]
   x y  v  m
1: a 1 42 42
2: a 3 42 42
3: a 6 42 42

i.e. DT has a key(DT) = c("x", "y"), and I want to assign 2 new columns new1 and new2 in one call, similar to the above solution. I do this:
DT[J("a"),c("new1","new2") := list(c(1,2,3),c(3,2,1)),with=FALSE]

but I get that
   x y  v  m new1
1: a 1 42 42    1
2: a 3 42 42    2
3: a 6 42 42    3
4: b 1  4  5   NA
5: b 3  5  5   NA
6: b 6  6  5   NA
7: c 1  7  8   NA
8: c 3  8  8   NA
9: c 6  9  8   NA

i.e. behaviour as expected (assign values to where x==a, NA else), but only for the first column. Is that my mistake or is it a bug?
Notice that without subsetting DT, this works perfectly:
DT[,c("new1","new2") := list(c(1,2,3),c(3,2,1)),with=FALSE]
   x y  v  m new1 new2
1: a 1 42 42    1    3
2: a 3 42 42    2    2
3: a 6 42 42    3    1
4: b 1  4  5    1    3
5: b 3  5  5    2    2
6: b 6  6  5    3    1
7: c 1  7  8    1    3
8: c 3  8  8    2    2
9: c 6  9  8    3    1

A: Well spotted: it's a new bug. Please file a bug.report(package="data.table").
Thanks.
===
Now fixed in v1.8.3. Bug#2215 and latest NEWS.


text:
Q: Django - Query models where id equals attribute on python list I need to query all models where the ID matches the 'id' attribute of JSON array, something like that:
I have 3 saved model objects with respective ID's:
ID 1
ID 3
ID 4

I have a JSON array like that:
[{'id' : 1}, {'id' : 2}, {'id' : 5}]

I want to filter in that way:
model.objects.filter('Objects by ID that is not listed in the JSON array')

The result of the filter should be a list with models objects that the ID is not in the JSON:
result = [model_pk=3, model_pk=4]

Any ideas?

A: You can use exclude method to achieve that:
ids = [i['id'] for i in json_array]
qs = model.objects.exclude(id__in=ids)


text:
Q: RequireJS + Bootstrap Datepicker + Locale Files I'm switching our project to modules. So most things are working, but some components have some issues. Main issue seems localization files.
If I had the solution for this example, I could fix the other issues in my project.
I'm using Bootstrap Datepicker from here https://bootstrap-datepicker.readthedocs.org/
Requirejs Config:
 require.config({
   baseUrl: "Scripts",
   paths: {
        ... some more like jquery and jquery-ui...
        "bootstrap-datepicker": "bootstrap-datepicker",
        "bootstrap-datepicker-de": "./locales/bootstrap-datepicker.de",
   }
   shim: {
    'bootstrap-datepicker-de': ['bootstrap-datepicker']
   }
});

App.ts:
... some more imports like jquery and jquery-ui...
import "bootstrap-datepicker";
import "bootstrap-datepicker-de";
... init App ...

bootstrap-datepicker.de.js
    ; (function ($) {
    $.fn.datepicker.dates['de'] = {
        days: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"],
        daysShort: ["Son", "Mon", "Die", "Mit", "Don", "Fre", "Sam"],
        daysMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
        months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
        monthsShort: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
        today: "Heute",
        monthsTitle: "Monate",
        clear: "Löschen",
        weekStart: 1,
        format: "dd.mm.yyyy"
    };
}(jQuery));

When I load my page I get this error:
bootstrap-datepicker.de.js:7 Uncaught TypeError: Cannot set property 'de' of undefined
at bootstrap-datepicker.de.js:7
at bootstrap-datepicker.de.js:19

A: We had the same issue and solved it by moving this code into the constructor of our viewmodel
$(document).ready(() => {
        (function($){
            (<any>$.fn.datepicker).dates['de'] = {
                days: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"],
                daysShort: ["Son", "Mon", "Die", "Mit", "Don", "Fre", "Sam"],
                daysMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
                months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
                monthsShort: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
                today: "Heute",
                monthsTitle: "Monate",
                clear: "Löschen",
                weekStart: 1,
                format: "dd.mm.yyyy"
            };
        }($));

        $('#date').datepicker({
            format: 'dd.mm.yyyy',
            autoclose: true,

            language: "de",

            orientation: 'left bottom'
        });
    });


text:
Q: How to upload image using fileuploadfield extjs + php I am new at using extjs. And I've been having a hard time uploading image to server. I have seen a lot of examples which I made as a guide. But I can seem to get a successful result.
Here's my code for my view:
items: [{
xtype: 'fileuploadfield',
id: 'form-file',
emptyText: 'Select image',
name: 'image-upload',
buttonText: 'Browse',
buttonConfig: {
iconCls: 'upload-icon'
}
},
{
xtype: 'button',
//action: 'submit',
text: 'Upload',
handler: function(){
var form = this.up('form').getForm();
form.submit({
url: 'uploadproc.php',
waitMsg: 'Loading data...',
success: function(fp, o) {
msg('Success', 'Processed file "' + o.result.file + '" on the server');
}
});

}
}

],

and here's my uploadproc.php file
<?php

$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["image-upload"]["name"]);
$extension = end($temp);
if ((($_FILES["image-upload"]["type"] == "image/gif")
|| ($_FILES["image-upload"]["type"] == "image/jpeg")
|| ($_FILES["image-upload"]["type"] == "image/jpg")
|| ($_FILES["image-upload"]["type"] == "image/pjpeg")
|| ($_FILES["image-upload"]["type"] == "image/x-png")
|| ($_FILES["image-upload"]["type"] == "image/png"))
&& ($_FILES["image-upload"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["image-upload"]["error"] > 0)
{
echo "Return Code: " . $_FILES["image-upload"]["error"] . "
";
}
else
{
echo "Upload: " . $_FILES["image-upload"]["name"] . "
";
echo "Type: " . $_FILES["image-upload"]["type"] . "
";
echo "Size: " . ($_FILES["image-upload"]["size"] / 1024) . " kB
";
echo "Temp file: " . $_FILES["image-upload"]["tmp_name"] . "
";

if (file_exists("upload/" . $_FILES["image-upload"]["name"]))
{
echo $_FILES["image-upload"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["image-upload"]["tmp_name"],
"upload/" . $_FILES["image-upload"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["image-upload"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>

I keep getting this error:
Uncaught Ext.JSON.decode(): You're trying to decode an invalid JSON String: Invalid file
I saved my uploadproc.php file inside my folder but outside the js folder. I'm really new to this and If someone could help me. Thank you very much.

A: Your server should be returning structured JSON (string) instead of normal string. JSON is a representation of javascript object which usually gets created from JSON on the client-end. Javascript is then using that object to easily interact with data.
I changed uploadproc.php file to build JSON and return it. Did some changes to javascript too, so different error/success messages gets displayed.
I increased minimal upload file size ($_FILES["image-upload"]["size"]), in bytes it is pretty small. That probabbly solves the 'Invalid file' error.
This works for me:
<?php
$allowedExts = array(
    "gif",
    "jpeg",
    "jpg",
    "png"
);
$temp        = explode(".", $_FILES["image-upload"]["name"]);
$extension   = end($temp);

$infoString = "";

if ((($_FILES["image-upload"]["type"] == "image/gif") || ($_FILES["image-upload"]["type"] == "image/jpeg") || ($_FILES["image-upload"]["type"] == "image/jpg") || ($_FILES["image-upload"]["type"] == "image/pjpeg") || ($_FILES["image-upload"]["type"] == "image/x-png") || ($_FILES["image-upload"]["type"] == "image/png")) && ($_FILES["image-upload"]["size"] < 9999999)
//&& ($_FILES["image-upload"]["size"] < 20000)
    && in_array($extension, $allowedExts)) {
    if ($_FILES["image-upload"]["error"] > 0) {
        die("{'success': false, 'error': '" . $_FILES["image-upload"]["error"] . "'}");
    } else {
        $infoString .= " Upload: " . $_FILES["image-upload"]["name"] . "
";
        $infoString .= " Type: " . $_FILES["image-upload"]["type"] . "
";
        $infoString .= " Size: " . ($_FILES["image-upload"]["size"] / 1024) . " kB
";
        $infoString .= " Temp file: " . $_FILES["image-upload"]["tmp_name"] . "
";

        if (file_exists("upload/" . $_FILES["image-upload"]["name"])) {
            die("{'success': false, 'error': '" . $_FILES["image-upload"]["name"] . " already exists.'}");
        } else {
            move_uploaded_file($_FILES["image-upload"]["tmp_name"], "upload/" . $_FILES["image-upload"]["name"]);
            $infoString .= " Stored in: " . "upload/" . $_FILES["image-upload"]["name"];
        }
    }
} else {
    die("{'success': false, 'error': 'File too big or invalid!'}");
}

echo "{'success': true, 'updateInfo': '" . $infoString . "'}";

Ext.create('Ext.form.Panel', {
    renderTo: Ext.getBody(),
    items: [{
        xtype: 'fileuploadfield',
        id: 'form-file',
        emptyText: 'Select image',
        name: 'image-upload',
        buttonText: 'Browse',
        buttonConfig: {
            iconCls: 'upload-icon'
        }
    }, {
        xtype: 'button',
        //action: 'submit',
        text: 'Upload',
        handler: function () {
            var form = this.up('form').getForm();
            form.submit({
                url: 'uploadproc.php',
                waitMsg: 'Loading data...',
                success: function (form, action) {
                    Ext.Msg.alert('Successful upload!', 'Image update info: ' + action.result.updateInfo);
                },
                failure: function (form, action) {
                    Ext.Msg.alert('Failure!', 'Error info: ' + action.result.error);
                }
            });
        }
    }],
});

Try googling about json, php json response, ajax/json...


text:
Q: PHP MySQL: INET_ATON does not save data? I am trying to store ip addresses into my database and I am using INET_ATON as below,
$sql = "
INSERT INTO pin (
    page_id,
    user_id,
    pc_name,
    ip,
    geolocation,
    created_on
)VALUES(
    ?,
    ?,
    ?,
    ?,
    ?,
    NOW()
)";

$result = $this->connection->executeSQL($sql,array(
$this->page_id,
$this->user_id,
$this->getComputerName(),
'INET_ATON("123.136.106.104")',
$this->getGeoLocation()
));

But I can't get it converted or saved into the ip field in the db. I get 0 instead of number.
What should I do? What have I done incorrectly with the SQL?

A: You problem is not in INET_ATON function - but in how PDO (I assume it is PDO) interprets bound parameter. You can act like this instead:
$sql = "
INSERT INTO pin (
    page_id,
    user_id,
    pc_name,
    ip,
    geolocation,
    created_on
)VALUES(
    ?,
    ?,
    INET_ATON(?),
    ?,
    ?,
    NOW()
)";

and pass your IP:
$result = $this->connection->executeSQL($sql,array(
$this->page_id,
$this->user_id,
$this->getComputerName(),
"123.136.106.104",
$this->getGeoLocation()
));


text:
Q: Fetch a particular part of the url in python I am using python and trying to fetch a particular part of the url as below
from urlparse import urlparse as ue

url = "https://www.google.co.in"
img_url = ue(url).hostname

Result
www.google.co.in

case1:
Actually i will have a number of urls(stored in a list or some where else), so what i want is, need to find the domain name as above in the url and fetch the part after www. and before .co.in, that is the string starts after first dot and before second dot which results only google in the present scenario.
So suppose the url given is url given is www.gmail.com, i should fetch only gmail in that, so what ever the url given, the code should fetch the part thats starts with first dot and before second dot.
case2:
Also some urls may be given directly like this domain.com, stackoverflow.com without www in the url, in that cases it should fetch only stackoverflow and  domain.
Finally my intention is to fetch the main name from the url that gmail, stackoverflow, google like so.....
Generally if i have one url i can use list slicing and will fetch the string, but i will have a number of ulrs, so need to fetch the wanted part like mentioned above dynamically
Can anyone please let me know how to satisfy the above concept ?

A: Why can't you just do this:
from urlparse import urlparse as ue
urls = ['https://www.google.com', 'http://stackoverflow.com']
parsed = []
for url in urls:
    decoded = ue(url).hostname
    if decoded.startswith('www.'):
        decoded = ".".join(decoded.split('.')[1:])
    parsed.append(decoded.split('.')[0])
#parsed is now your parsed list of hostnames

Also, you might want to change the if statement in the for loop, because some domains might start with other things that you would want to get rid of.

A: What about using a set of predefined toplevel doamains?
import re
from urlparse import urlparse

#Fake top level domains... EG: co.uk, co.in, co.cc
TOPLEVEL = [".co.[a-zA-Z]+", ".fake.[a-zA-Z]+"]

def TLD(rgx, host, max=4): #4 = co.name
        match = re.findall("(%s)" % rgx, host, re.IGNORECASE)
        if match:
            if len(match[0].split(".")[1])<=max:
                return match[0]
        else:
            return False

parsed = []
urls = ["http://www.mywebsite.xxx.asd.com", "http://www.dd.test.fake.uk/asd"]
for url in urls:
    o = urlparse(url)
    h = o.hostname
    for j in range(len(TOPLEVEL)):
        TL = TLD(TOPLEVEL[j], h)
        if TL:
            name = h.replace(TL, "").split(".")[-1]
            parsed.append(name)
            break
        elif(j+1==len(TOPLEVEL)):
            parsed.append(h.split(".")[-2])
            break

print parsed

It's a bit hacky, and maybe cryptic for some, but it does the trick, and nothing more has to be done :)

A: Here is my solution, at the end, domains holds a list of domains you expected.
import urlparse
urls = [
    'https://www.google.com',
    'http://stackoverflow.com',
    'http://www.google.co.in',
    'http://domain.com',
    ]
hostnames = [urlparse.urlparse(url).hostname for url in urls]
hostparts = [hostname.split('.') for hostname in hostnames]
domains = [p[0] == 'www' and p[1] or p[0] for p in hostparts]
print domains # ==> ['google', 'stackoverflow', 'google', 'domain']

Discussion

*

*First, we extract the host names from the list of URLs using urlparse.urlparse(). The hostnames list looks like this:
[ 'www.google.com', 'stackoverflow.com, ... ]

*In the next line, we break each host into parts, using the dot as the separator. Each item in the hostparts looks like this:
[ ['www', 'google', 'com'], ['stackoverflow', 'com'], ... ]

*The interesting work is in the next line. This line says, "if the first part before the dot is www, then the domain is the second part (p[1]). Otherwise, the domain is the first part (p[0]). The domains list looks like this:
[ 'google', 'stackoverflow', 'google', 'domain' ]

*My code does not know how to handle login.gmail.com.hk. I hope someone else can solve this problem as I am late for bed. Update: Take a look at the tldextract by John Kurkowski, which should do what you want.


text:
Q: Change users wallpaper without logging in as the user in XP I have admin access to the computer.
What I want to do is change a users wallpaper to something else but without logging in as the user.
There must be a config file or something where these settings are kept for the user.
I'm assuming it's in /Documents and Settings/UserName but I haven't found the file.

A: The per-user wallpaper setting is stored, in the registry, as a REG_SZ value named Wallpaper, under the key HKEY_CURRENT_USER\Control Panel\Desktop.
If the user is logged in, or their hive is otherwise mounted, you would find the key under HKEY_USERS\User's SID.  If the user is not logged in, you would need to mount their hive under HKEY_USERS first.  User hives are found in the user's profile, %USERPROFILE%, typically under "C:\Documents and Settings\username\" (Windows XP) or C:\Users\username\ (Windows 7) and are named "NTUSER.DAT".
Alternatively, you could use Group Policy to enforce a specific wallpaper.


text:
Q: Execute Nohup command with input In UNIX, I have a process that I want to run using nohup. However, this process will at some point wait at a prompt where I have to enter yes or no for it to continue. So far, in UNIX I have been doing the following:
nohup myprocess <<EOF
y
EOF

So I start the process 'myprocess' using nohup and pipe in a file with 'y' then close the file. The lines above are effectively three separate commands - i.e. I hit enter on the first line in UNIX, then I get a prompt where I enter 'y' and then press enter to then finally type 'EOF' and hit return again. So this works perfectly, but my problem is below.
I want to now execute this in Perl, but I am not sure how I can execute this command, as it is over three lines. I don't know if the following will work:
my $startprocess = `nohup myprocess <<EOF &
y
EOF
`

A: If you just want to write a single y to the stdin of the process, you can do this:
(echo y | nohup myprocess) &

If you want to keep writing y for every prompt that comes up, the coreutil yes exists for exactly this purpose -- it will keep writing whatever you tell it to to stdout. Its default is to output "y", so you can just:
(yes | nohup myprocess) &

but if you need something else you can pass it as an argument


text:
Q: Android App Play sound when holding down a button new android dev hopeful here. I've been attempting to implement an app that, upon holding down the "ok" button, it will play the default ringtone in a loop.
What I have so far
package com.tick.helloAndroid;

import net.technologichron.android.control.NumberPicker;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
//import android.widget.TextView;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.Toast;

public class main extends Activity implements OnTouchListener {
    private int REQUEST_ENABLE_BT = 1;
    private MediaPlayer mp;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         // Set up the window layout
         setContentView(R.layout.main);

         final Button zero = (Button) this.findViewById(R.id.ok);
         zero.setOnTouchListener(this);
         Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
         mp.setDataSource(this, alert);

    }
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {

        case MotionEvent.ACTION_DOWN:
            mp.setLooping(true);
            mp.start();

        case MotionEvent.ACTION_UP:
            mp.pause();
        }

        return true;
    }
}

From doing some searching on SO, this seems to work for some people, however, the line
mp.setDataSource(this, alert);

seems to not work. By not work, I mean that it forces an "Unhandled Exception Error", which upon doing a try-catch statement,
  try {
        mp.setDataSource(this, alert);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        Toast.makeText(this, "args", Toast.LENGTH_LONG).show();
        finish();
        return;
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        Toast.makeText(this, "sec", Toast.LENGTH_LONG).show();
        finish();
        return;
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        Toast.makeText(this, "illega", Toast.LENGTH_LONG).show();
        finish();
        return;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Toast.makeText(this, "io", Toast.LENGTH_LONG).show();
        finish();
        return;
    }

compiles without any error but crashes when I try to run the app on the android emulator, it does not print any of the above catches' strings.
Any thoughts and ideas about what I have done incorrectly will be most appreciated.
edit:  could it be from the fact that the emu does not have a ringtone?

A: forgot to instantiate mp....hahahahha


text:
Q: Predicate com CAST Acessando o banco de dados .sqlite via sql normalmente, posso utilizar a função CAST('coluna' as decimal).
Via NSPredicate utilizando CoreData, como faço a mesma coisa? Possuo uma coluna do tipo String e preciso fazer um cast para decimal.

A: É possível sim ter CAST em um NSPredicate.
A sintaxe é:
CAST(<o que vai ser convertido>, 'classe destino')

Exemplo:
NSArray *array = @[@"10.0", @"8.99"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"CAST(self, 'NSNumber') > %@", [NSNumber numberWithDouble:9.0]];

NSLog(@"%@", [array filteredArrayUsingPredicate:predicate]);

Em seu caso, assumindo que a propriedade de sua entidade no CoreData seja "latitude":
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"CAST(latitude, 'NSNumber') > %@", [NSNumber numberWithDouble:9.0]];

Mais exemplos aqui (Em inglês): http://funwithobjc.tumblr.com/post/1677163679/creating-an-advanced-nspredicateeditorrowtemplate


text:
Q: strace: ld-linux fails to run a simple test binary I am trying to compile some stuff for an embedded system that I'm trying to build upon. However, when running binaries I've built for the system I am met with failed to map segment from shared object: Invalid argument. This happens to anything that does more than simple loops and prints.
In the name of debugging this, I've built a binary (testbin) that simply lists the contents of the current directory:
#include<stdio.h>
#include<dirent.h>

int main(void)
{
    DIR *d;
    struct dirent *dir;
    d = opendir(".");
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            printf("%s\n", dir->d_name);
        }
        closedir(d);
    }
    return(0);
}

As the system is somewhat uncooperative in terms of libraries, I have to override it all, so I run programs this way: ./ld-linux.so.3 ./testbin which produces:
./testbin: error while loading shared libraries: ./shitls: failed to map segment from shared object: Invalid argument

...as suspected, testbin also struggles as soon as external libraries are needed. I managed to statically compile strace for the system, which somehow runs just fine. So I'm fairly sure that the culprit is whenever libc.so is needed.
When running strace on my testbin via ld-linux.so.3 like this: ./strace ./ld-linux.so.3 ./testbin
..I am presented with something to work with:
execve("./ld-linux.so.3", ["./ld-linux.so.3", "./testbin"], 0xbee2b554 /* 74 vars */) = 0
brk(NULL)                               = 0xb873c000
open("./testbin", O_RDONLY)             = 3
read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\2\0(\0\1\0\0\0\311\203\0\0004\0\0\0"..., 512) = 512
lseek(3, 1920, SEEK_SET)                = 1920
read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 1240) = 1240
lseek(3, 1601, SEEK_SET)                = 1601
read(3, "A2\0\0\0aeabi\0\1(\0\0\0\0057-A\0\6\n\7A\10\1\t\2\n\4\22"..., 51) = 51
fstat64(3, {st_mode=S_IFREG|0777, st_size=5379, ...}) = 0
getcwd("/mnt/output", 128)    = 22
mmap2(0x5241ae00, 4096, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0) = -1 EINVAL (Invalid argument)
close(3)                                = 0
writev(2, [{iov_base="./testbin", iov_len=9}, {iov_base=": ", iov_len=2}, {iov_base="error while loading shared libra"..., iov_len=36}, {iov_base=": ", iov_len=2}, {iov_base="./testbin", iov_len=9}, {iov_base=": ", iov_len=2}, {iov_base="failed to map segment from share"..., iov_len=40}, {iov_base=": ", iov_len=2}, {iov_base="Invalid argument", iov_len=16}, {iov_base="\n", iov_len=1}], 10./testbin: error while loading shared libraries: ./testbin: failed to map segment from shared object: Invalid argument
) = 119
exit_group(127)                         = ?
+++ exited with 127 +++

...but I'm not fluent in reading strace output. Any pointer as to where the running of the binary croaks?

A: It looks like your development sysroot is not matching the sysroot libs on the target. One option is to locate the proper cross-development tools for your chip. Another option is to pull the rootfs from the target and try to build against it inside your qemu setup. For example:
LDFLAGS = -L/rootfs-mipsel/mipsel-linux-gnu -lusb-1.0 -ludev

Also, the cross-compiler can take the desired rootfs as argument: --sysroot=/opt/rootfs-mipsel.
Your current development tools inside qemu may use a different ld.so version than that of the target. After compilation it can be edited with patchelf:
patchelf --set-interpreter /lib/ld.so.1 a.out


text:
Q: Wither skeleton spawning Can I make a wither skeleton farm in the over world? Or does it have to be in a nether fortress. Just wondering because I'm trying to get a stack of nether stars

A: As @Topcode said, wither skeletons only spawn inside nether fortresses. There are, however, designs for farms that you can build in the nether.


text:
Q: Windows powershell script triggered by PSExec is not killing Powershell process when it finishes running I need to complete a series of tasks across several Windows 2008 servers that need elevated permissions and as such I've had to create a series of scheduled tasks that i'm running via psexec. Since they have to run in sequence, I found and modified a powershell script that 'stalls' until scheduled tasks are completed on remote machines. The problem I have is that when I launch the script with psexec on the remote machine, once it completes running (indicated by a message in the console output) PowerShell.exe doesn't exit cleanly, but rather hangs out and holds up the entire process. I need powershell to quit after the delay script exits, but even with an exit keyword at the end it stays in memory and prevents the process from finishing. I'm not terribly experienced with powershell so I'll attach my script in case I'm doing something foolish in it:
while($true) {
$status = schtasks /query /tn "AutoDeploy"| select-string -patt "AutoDeploy"
if($status.tostring().substring(64,7) -eq "Running") { "Waiting for task to complete..." } else { break }
start-sleep -s 5
}
"Task complete."
exit

Thanks in advance for any insight.

A: This works for me (using a different task name) and doesn't hang psexec:
$taskName = "AutoDeploy"
while (1)
{
    $stat = schtasks /query /tn $taskName |
                Select-String "$taskName.*?\s(\w+)\s*$" |
                Foreach {$_.Matches[0].Groups[1].value}
    if ($stat -ne 'Running')
    {
        "Task completed"
        break
    }
    "Waiting for task to complete"
    Start-Sleep 5
}


text:
Q: Why is the Markov property implied by the existence of a transition matrix? If $\left(X_n\right)_{n\in\mathbb{N}_0}$ is an $E$-valued stochastic process with distributions $\left(P_x\space:\space x\in E\right)$ satisfying
$$\mathrm{P}_x\left(X_0=x\right)=1$$
and stochastic kernel $\kappa\left(x,B\right)=\mathrm{P}_x\left(X\in B\right)$, then the Markov property (namely "for every $A\in\mathcal{B}\left(E\right)$, every $x\in E$ and all $i,j\in\mathbb{N}_0$ we have $\mathrm{P}_x\left(\left.X_{i+j}\in A\space\right|\mathcal{F}_i\right)=\kappa_j\left(X_i,A\right)$") is implied if for every $A\in\mathcal{B}\left(E\right)$, every $x\in E$ and every $i\in\mathbb{N}_0$ we have
$$\mathrm{P}_x\left(\left.X_{i+1}\in A\space\right|\mathcal{F}_i\right)=\kappa_1\left(X_i, A\right)$$ where $$\kappa_j\left(x, A\right):=\mathrm{P}_x\left(X_j\in A\right)$$
The following fact, easily derived from the given data, can be used without proof:
$$\kappa_{n+1}=\kappa_n\cdot\kappa_1:=\intop_E\kappa_n\left(\cdot, \mathrm{d}x\right)\kappa_1\left(x,\cdot\right)$$
with $\kappa_0\left(x,\cdot\right):=\delta_x\left(\cdot\right)$, the Dirac measure.
This is Theorem 17.11 from Klenke's book (p. 350, Chapter 17: "Markov Chains")

Hint
If I understand correctly, all that needs be shown is that for all $m\in\mathbb{N}_0$,
$$\mathrm{P}_x\left(\left.X_{i+m}\in A\space\right|\mathcal{F}_i\right)=\kappa_m\left(X_i, A\right)$$

A: Induction over $j\geqslant1$. The case $j=1$ is the hypothesis. Assume that the property holds for some $j\geqslant1$. Then $\mathrm P(X_{i+j+1}\in A\mid \mathcal F_{i+1})=\kappa_j(X_{i+1},A)$ and $\mathcal F_i\subseteq \mathcal F_{i+1}$, hence, by the tower property,
$$
\mathrm P(X_{i+j+1}\in A\mid \mathcal F_{i})=\mathrm E(\kappa_j(X_{i+1},A)\mid \mathcal F_i).
$$
For every suitable function $u$, $\mathrm E(u(X_{i+1})\mid \mathcal F_i)=v(X_i)$, where
$$
v(\,\cdot\,)=\int u(y)\kappa_1(\,\cdot\,,dy).
$$
Applying this to $u=\kappa_j(\cdot,A)$, one gets
$$
v(\,\cdot\,)=\int \kappa_j(y,A)\kappa_1(\,\cdot\,,dy)=(\kappa_1\cdot \kappa_j)(\,\cdot\,,A).
$$
Note that $\kappa_{j+1}=\kappa_j\cdot \kappa_1$ is also $\kappa_{j+1}=\kappa_1\cdot \kappa_j$, hence the RHS above is $\kappa_{j+1}(\,\cdot\,,A)$, which proves as desired that
$$
\mathrm P(X_{i+j+1}\in A\mid \mathcal F_{i})=\kappa_{j+1}(X_i,A).
$$


text:
Q: how to backup the tables and not the views Using mysqldump I can backup my database. But my database has a lot of views with huge amount of data which I dont need. I only want to backup the real tables with data.
Currently I'm doing:
mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql

Is there a way to backup only the real tables without the views?

A: Views don't store any data in MySQL. View are like stored queries, not stored data. There is no content to the view, and it will not increase the size of your backup more than the size of the definition of the view. That is, the CREATE OR REPLACE VIEW statement is the only thing that ends up in your mysqldump output related to that view.
But to answer your question: no, there's no specific option to exclude all views.
You can exclude individual names (whether they are tables or views) with the --ignore-table=db.table option. But you'd have to list every view individually.
Another option is to mysqldump with a user who lacks the SHOW VIEW privilege. This will exclude views from the backup, but will generate an error. You can skip errors and continue the backup if you use the --force option.


text:
Q: jQuery UI Tabs not working stack.
we're working on a site: http://rodneycrowell.wpengine.com
it's a single page scroller, with quite a lot of widgets.
the first widget on the home page is set up with jQuery UI Tabs.
we've enqueued the styles, and jQuery ui through the functions.php file
like so:
function ahso_scripts() {

    wp_register_script( 'jquery-easing', CHILD_URL . '/library/js/jquery.easing.1.3.js', array('jquery'), '1.3', TRUE );
    wp_register_script( 'jquery-smoothness', CHILD_URL.'/library/js/jquery.smoothscroller.js', array('jquery-easing'), '1.0', TRUE );
    wp_register_style( 'jquery-ui-custom', CHILD_URL.'/library/css/jquery-ui-1.9.0.custom.css', '', '1.9.0', 'all' );

    // only on the home page
    if ( is_front_page() ) {

        wp_enqueue_script( 'jquery-easing' );
        wp_enqueue_script( 'jquery-smoothness' );

        // jquery-ui-tabs
        wp_enqueue_style( 'jquery-ui-custom' );
        wp_enqueue_script( 'jquery-ui-tabs' );
    }

}
add_action( 'wp_enqueue_scripts', 'ahso_scripts' );

and on the page-home.php template, we're instantiating the jQuery Ui Tabs like so:
<script type="text/javascript">
    //<![CDATA[
    jQuery(document).ready(function() {
        jQuery("#tabs").tabs();
    });
    //]]>
</script>
<!--[if lt IE 9]-->
<script type="text/javascript">
    //<![CDATA[
    jQuery(function() {
        jQuery("#tabs").tabs("option", "disabled", false);
    });
    //]]>
</script>
<!--[endif]-->

the markup is a little funny, as i've been trying things, not passing in '$' as an alias, using (document).ready(), troubleshooting.
for some reason, the tabs won't instantiate, or work, we're getting no errors in the console for the tabs,
granted, there's a lot going on in some of the widgets, but this issue appeared long before we added anything to those,
what's really giving me grief, is we've already done this on another site in pretty much the same manner, and it works. http://granthammond.com
if you look down at the bottom of the sidebar, you'll see some tabs,
the only big difference being those are output by a shortcode, vs. these, which are echoed out in a page template.
thanks again stack.

A: The javascript portion of jQuery UI Tabs IS working. If you look at source and click on the different tab titles, the correct css classes are being added. However, the tab styles that are necessary aren't included in your jQuery UI stylesheet =]

A: Sure, that you got a static front page?
Try
if ( is_home() OR is_front_page() )
{
    // ...

instead.


text: Q: Multiple comparisons of Box-Cox transformed data I'm working on a dataset of highly-skewed data that I have transformed using Box-Cox. I have 2 groups (healthy controls and diseased participants) and I need to perform multiple comparisons (to compare the two groups across different frequency bands). Within each comparison, I am using the same lambda for the Box-Cox transformation (so both groups are equally transformed for the same frequency), but ideally, lambda would vary across frequencies (because for some frequencies the data is more skewed than for others). Is this correct? Can I proceed with multiple comparisons correction over the p-values of my data transformed with different lambda values? I have tried to find a common value of lambda but failed so far.


text:
Q: Como acessar parametro de classe Python Bom dia amigos,
Estou fazendo uma script para uma GUI com o Tkinter para um projeto de gerador de senha. Criei inicialmente duas classe: uma que cria o container principal (myApp) e outra que cria o primeiro Frame da tela (Frame1). Agora precisa criar uma segundo Frame (Frame2) logo abaixo do top porém preciso acessar um parametro da classe Frame1 dentro da classe Frame2 e não estou conseguindo fazer.
from tkinter import *
from geradorSenha import *

class Frame1(LabelFrame):
    def __init__(self, container):
        super().__init__(container)
        self.config(text="Escolha seu tipo de senha", width=400,
                    height=100)
        self.columnconfigure(0, minsize=400)
        self.grid(row=0, padx=10)

        self.var = IntVar()

        self.Rb1 = Radiobutton(self, text="Somente letras",
                               variable=self.var, value=1)
        self.Rb1.grid(column=0, row=0, sticky=W)

        self.Rb2 = Radiobutton(self, text="Somente números",
                               variable=self.var, value=2)
        self.Rb2.grid(column=0, row=1, sticky=W)

        self.Rb3 = Radiobutton(self, text="Letras mais números",
                               variable=self.var, value=3)
        self.Rb3.grid(column=0, row=2, sticky=W)

        self.Rb4 = Radiobutton(self, text="Letras mais caracteres especiais",
                               variable=self.var, value=4)
        self.Rb4.grid(column=0, row=3, sticky=W)

        self.Rb5 = Radiobutton(self, text="Letras, caracteres especiais e números",
                               variable=self.var, value=5)
        self.Rb5.grid(column=0, row=4, sticky=W)

        self.escolha_button = Button(self, text='Escolha')
        self.escolha_button.grid(column=0, row=5, pady=5)
        self.escolha_button.config(command=self.escolha)

    def escolha(self):
        return self.var.get()

class Frame2(LabelFrame):
    def __init__(self, container):
        super().__init__(container)
        self.config(text="Frame 2", width=200,
                    height=100)
        self.columnconfigure(1, minsize=200)
        self.etiqueta = Label(self, text=Frame1.escolha) #QUERO PEGAR O PARAMETRO DA CLASSE FRAME1 AQUI
        self.etiqueta.grid(column=0, row=1)
        self.grid(row=1)

class myApp(Tk):
    def __init__(self):
        super().__init__()
        self.title("Gerador de Senhas")
        self.geometry("420x400")

myGui = myApp()
frame1 = Frame1(myGui)
frame2 = Frame2(myGui)
myGui.mainloop()

A: Você tem duas classes Frame1 e Frame2, se você deseja acessar um parâmetro do Frame1 dentro do Frame2, nesse caso do teu código é necessário passar no momento da criação do Frame2, exemplo:
Primeiro você define que a Classe Frame2 vai receber um novo parâmetro, nesse caso com nome parametro_que_voce_deseja.
class Frame2(LabelFrame):
    def __init__(self, container, parametro_que_voce_deseja):
        super().__init__(container)
        self.parametro_que_voce_deseja = parametro_que_voce_deseja
        # Resto do código aqui

No momento da criação do Frame2, você passa o parametro_que_voce_deseja (do Frame1) para dentro de Frame2.
myGui = myApp()
frame1 = Frame1(myGui)
frame2 = Frame2(myGui, frame1.parametro_que_voce_deseja)
myGui.mainloop()


text:
Q: Given a list of n integers, find the minimum cardinality subset with sum greater than or equal to x Given an unsorted (multi)set of integers in the form of array, find minimum cardinality subset whose sum is greater than or equal to a const integer x.
eg:- Our set is {4 5 8 10 10} and x=15 so the minimum cardinality subset with sum  >=x is {5 10}
Is there a polynomial time algorithm to solve this problem? Can one reduce an optimization instance of subset sum into that problem?
This problem is related to but different from: Given a list of n integers , find the minimum subset sum greater than X  in this previous question, the author asked for a subset whose sum is closest to x, and here we want any subset >=x but with the minimum number of elements

A:
Is there a polynomial time algorithm to solve this problem?

Yes. In fact, brute force will get you your desired outcome.

*

*Sort the list: O(n log n)

*Start from the end with the maximum value (either end depending on how you sorted (i.e. ascending or descending order)) and add values until you have reached your goal: O(n)
Overall, this algorithm has O(n log n) complexity, which lives in polynomial time.
There probably is a better algorithm, but I'm not sure. I know one can find the nth largest value in O(n) time, however you will have to perform this m times, where m represents the minimal cardinality. Thus, for this approach, the overall complexity is O(m * n) which is still polynomial.
The first approach gives O(n log n) regardless of the size of the minimal cardinality. The second approach gives a better best case (i.e. the cardinality ends up being 1, which means the overall complexity is O(n)), however the worst case is O(n^2) which means the entire list is checked.

Can one reduce an optimization instance of subset sum into that problem?

I don't think so. Targeting a specific value for the sum is a bit different than what we are doing. For example, given a list and two different values, we would perform the exact same steps for the given problem. For each value, the only difference is when we surpass our value. For the subset sum problem, we could have vastly different outcomes for each value.


text:
Q: Integrate cordova camera plugin in an app I'm having some doubts regarding how to integrate the camera plugin, how to make it work properly. Do I need to create specific buttons in the html and add the functions via JavaScript? Do I only need to declare the function?
Any help would be appreciated.


text:
Q: ¿Cómo saber si una lista contiene al menos un elemento de otra lista? Tengo una clase Recetas que tiene una List<String> listaIngredientes.
Por otro lado, tengo una List<String> ingredientes. Quiero filtrar la lista de Recetas con sólo las recetas que contenga al menos un item de la lista ingredientes.
Intento lo siguiente:
val ingredientes: List<String> = user.getIngredientes()
val listaFiltrada = listaRecetas.filter {it.listaIngredientes.containsAll(ingredientes)}

Pero el error aquí es que containsAll me filtra si todos los ingredientes están en la lista listaIngredientes y yo solo quiero que al menos exista un ingrediente.
Si hago lo mismo con:
val ingredientes: List<String> = user.getIngredientes()
val listaFiltrada = listaRecetas.filter {it.listaIngredientes.contains()}

No puedo pasar la lista ingredientes porque me pide un sólo elemento (String).
Alguna sugerencia?

A: La opción más eficiente es usar la función any que sirve para verificar si una lista (o cualquier objeto iterable) contiene al menos un elemento que cumpla cierta condición. En tu caso la condición sería que el elemento exista en la otra lista:
val listaFiltrada = listaRecetas.filter { receta ->
    receta.listaIngredientes.any { it in ingredientes }
}

que tambíen se puede escribir así
receta.listaIngredientes.any { ingredientes.contains(it) }

o así
receta.listaIngredientes.any(ingredientes::contains)

Si esperas que la lista ingredientes tenga más elementos que receta.listaIngredientes, sería más eficiente invertir el orden
val listaFiltrada = listaRecetas.filter { ingredientes.any(it.listaIngredientes::contains) }

Otra opción puede ser usar la función intersect para buscar los elementos en común y luego verificar si es mayor a 0
val listaFiltrada = listaRecetas.filter {
    it.listaIngredientes.intersect(ingredientes).isNotEmpty()
}

pero esto siempre será más lento porque necesita recorrer completamente la lista. En cambio any() termina el bucle al encontrar el primer elemento que satisfaga la condición.


text:
Q: Is the PayPal APP-ID account or app specific? I just got issued a PayPal APP-ID, but was wondering:
Is this APP-ID tied to the PayPal account I used to apply for it, or can it be used with any of my accounts?
ie. say I apply on apps.paypal.com with my business PayPal, paypal@jessedevelopment.example.com. I get approved.
Now, with the same application, I want to also sell my service as a freelancer, so I add the API credentials for my personal PayPal account jessefreelancer@example.com into my application. Do I have to reapply and get a new APP-ID for use with this new account since it's a new PayPal account, or could I still use the same APP-ID since it's the same application?
Thanks.

A: They are tied to the PayPal account. Though ownership can be transferred in some cases, you can't share an existing AppID across multiple PayPal accounts.


text:
Q: JQuery Datatables Table-tools, remove PDF export I use the table-tools when creating my datatables. This creates the export functionality for Excel, CSV, PDF and Print. I want to remove the PDF options. How is this done?
<TABLE aria-describedby="DataTables_Table_1_info" role="grid" id="DataTables_Table_1" class="table table-tools table-dynamic dataTable   " style="">

A: This solution has worked for me put it in fnDrawCallback function
$(tableName).dataTable({

 "fnDrawCallback":function () {
                   var table = $(tableName).DataTable();
                   table.buttons('.buttons-pdf').disable();
                      //or

               $(table.buttons('.buttons-pdf').nodes()).css("display", "none");

            }
});


text:
Q: use enum as a model to create a new object? I have an enum as follows:
export enum TableViewTypes {
    user = 'users',
    pitching = 'pitching',
    milestones = 'milestones',
    mediaList = 'mediaList',
    contacts = 'contacts'
}

and I need to use it to dynamically create and object so something like this:
const newObject = {[keyof TableViewTypes]: false};

with an expected output of:
newObject = {
    user: false,
    pitching: false,
    milestones: false,
    mediaList: false,
    contacts: false
}

currently typescript complains about this...
What is the best way to go about this?

A: You could make a function that makes a new object and fills its properties with a value you specify, using keys from an existing object:
function fillProps<T, V>(t: T, v: V) {
  const ret = {} as {-readonly [K in (string & keyof T)]: V};
  (Object.keys(t) as (string & keyof T)[]).forEach(k => ret[k]=v);
  return ret;
}

const newObject = fillProps(TableViewTypes, false);

I'm pretty sure that at runtime this will evaluate to what you want, and the compiler will interpret it as of the type:
const newObject: {
    user: boolean;
    pitching: boolean;
    milestones: boolean;
    mediaList: boolean;
    contacts: boolean;
}

Hope that helps.  Good luck.


text:
Q: How to avoid "make" redoing a library I have a project for school.
In the root dir, I have 3 subdirs which all have a makefile (because there will be 3 executable files), and there is 1 lib dir.
This dir contains my library source files (*.c, *.h).
I have a makefile in the libdir:
##
## Makefile for corewar in /home/rihan_a/Projets/psu/corewar/lib
##
## Made by adnan rihan
## Login   <rihan_a@epitech.net>
##
## Started on  Fri Dec  9 09:28:07 2011 adnan rihan
## Last update Fri Dec  9 10:45:27 2011 adnan rihan
##

NAME=           libwar

SRC=            explode.c               \
                get.c                   \
                has_char.c              \
                int_to_bigendian.c      \
                my_die.c                \
                my_getnbr_t.c           \
                my_memset.c             \
                my_power_rec.c          \
                my_putstr.c             \
                my_strcat.c             \
                my_strcmp.c             \
                my_strlen.c             \
                my_strncpy.c            \
                my_strndup.c            \
                op.c                    \
                wt_len.c                \
                xmalloc.c

OBJ=            $(SRC:.c=.o)

ARFLAGS=        rcs
CFLAGS=         -Wall

all:            pack

obj_dbg:
                $(CC) -g -c $(SRC)

debug:          obj_dbg all

pack:           $(OBJ)
                $(AR) $(ARFLAGS) $(NAME).a $(OBJ)

clean:
                $(RM) $(OBJ)

fclean:         clean
                $(RM) $(NAME).a

My problem is when I do make, everything is ok, and for make debug also.
But when I do make debug a second time, it doesn't remake the .o, but does the ar rcs everytime.
I want to avoid it, because when I request make -C ../lib for the other makefiles, they all relink because the lib changed (because ar was run each time).

A: You have no check on the library.  One way would be to replace
pack:           $(OBJ)
                $(AR) $(ARFLAGS) $(NAME).a $(OBJ)

by
pack: $(NAME).a

$(NAME).a: $(OBJ)
        $(AR) $(ARFLAGS) $(NAME.a) $(OBJ)

so the library would not be remade if it is up to date.

A: debug:          obj_dbg all

Do you need all again there? or just all?


text:
Q: Codeigniter Users Login Check I'm a novice with Code Igniter and I'm currently building my own user system. I'm curretly on the login process and I have implemented a check for whether a user is currently logged in or not.
In my header I then want to display a link to 'Log Out' if they are already logged in, or 'Log In' if they are not logged in currently.
I have a working function in my index controller as follows, the $loginstatus variable is sent to the my page header view:
function check_session()
{
    //Check session status

            $session = $this->session->userdata('login_state');

            $default = "Log In";

            if ($session == 1)
            {
                $url = site_url('index.php/users/logout');
                $status = "Log Out";

            }
            else
            {
                $url = site_url('index.php/users/login');
                $status = $default;
            }

        $loginstatus = array(
                        "url" => $url,
                        "status" => $status
                        );

        return $loginstatus;
}

Because it is currently only in the index controller the $loginstatus is not generated for the header view for other pages and this is my problem.
Where would I put this function so that it always loads before my header? I tried creating a libary with a 'Common' class and then autoloading that but I ended up with lots of problems.
Thanks in advance.

A: If you are using CI version bellow 2.0 then create new class in application/libraries/MY_Controller.php, otherwise in application/core/MY_Controller.php and all of your application controllers should extend from it. In this class in the __construct method you will check for the login status and send it to the views.

class MY_Controller extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        //Get the status which is array
        $login_status = $this->check_session();

        //Send it to the views, it will be available everywhere

        //The "load" refers to the CI_Loader library and vars is the method from that library.
        //This means that $login_status which you previously set will be available in your views as $loginstatus since the array key below is called loginstatus.
        $this->load->vars(array('loginstatus' => $login_status));
    }

    protected function check_session()
    {
        //Here goes your function
    }
}

Also make sure your application controllers extend from this class

//application/controllers/index.php

class Index extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
    }
}

In your views you can do this:
<a href="<?php echo $loginstatus['url']; ?>"><?php echo $loginstatus['status']; ?>
This is possible cause the CI_Loader vars() method is doing extract to the parameters passed to it.


text:
Q: Error on line 5, column 10 of pubspec.lock: Expected ':'. ╷ 5 │ archive: When I run flutter pub get it shows,
> flutter pub get
Running "flutter pub get" in flutter_dropdown...                 1,922ms
Error on line 5, column 10 of pubspec.lock: Expected ':'.
  ╷
5 │   archive:
  │          ^
  ╵
Running "flutter pub get" in example...
pub get failed (65;   ╵)

Flutter version was 2.0.3 and updated to 2.2.3 check if that solves with the dart version to latest. Seems like versions are not the cause.

A: This happend to me whe I have git conflicts in my pubspec.yaml file. Specifically, I was updating my pub package and solved conficts in package but forget to solve in example pubspec.yaml conflicts. So, the pubspec.lock generation failed due to that issue.


text:
Q: [Macromedia][SQLServer JDBC Driver][SQLServer]Invalid object name 'column_name' In my ColdFusion 11 website (with SQL Server 2008 R2), the following cfquery is throwing the above error:
<cfquery name="deleteGrantModificationItems" datasource="#dsource#">
  DELETE col_key FROM myTable
  WHERE col_key = <cfqueryPARAM value = "#appkey#" CFSQLType = "CF_SQL_VARCHAR">
</cfquery>

When I run the sql profiler to capture the query, I get:
Declare @p1 int
Set @p1=NULL
exec sp_prepexec @p1 output,N'@P1 varchar(8000)',N'DELETE col_key FROM myTable
WHERE col_key = @P1 ','000000001644'
select @p1

when I run the above in the Query Analyzer, I get the following error:
Msg 208, Level 16, State 1, Line 1
Invalid object name 'col_key'.
Msg 8180, Level 16, State 1, Procedure sp_prepexec, Line 1
Statement(s) could not be prepared.

I've been unable to find the cause of the error.

A: You have a syntax error because you should use DELETE FROM table_name ... like:
<cfquery name="deleteGrantModificationItems" datasource="#dsource#">
  DELETE FROM myTable
  WHERE col_key = <cfqueryPARAM value = "#appkey#" CFSQLType = "CF_SQL_VARCHAR">
</cfquery>

DELETE doc:

[ WITH  [ ,...n ] ] DELETE
[ TOP ( expression ) [ PERCENT ] ]
[ FROM ]


text:
Q: CSS background image on top of  How does one repeat this 1px x 1px CSS background image on top of the HTML ?
http://jsfiddle.net/hjv74tdw/1/
I came across CSS show div background image on top of other contained elements, however it seems to require an extra div. Ideally I wish I didn't have to use a div at all, but according to CSS Background-image over HTML img that's not really possible, at least not for a 100% width responsive scenario.

.test {
  background: url(http://placehold.it/1/1) repeat;
  position: relative;
  z-index: 100;
  width: 200px;
}
.test img {
  width: 100%;
  display: block;
  position: absolute;
  z-index: 50;
}

A: You could use a pseudo-element. In this example, the :after pseudo element is absolutely positioned relative to the parent element. It takes the dimensions of the entire parent element, and the size of the parent element is determined by the size of the child img element.

.test {
  display: inline-block;
  position: relative;
}
.test:after {
  content: '';
  position: absolute;
  top: 0; right: 0;
  bottom: 0; left: 0;
  background: url(http://placehold.it/20x20/1) repeat;
}

As a side note, your example wasn't working for a couple of reasons. The parent element has a background image, but since the child element establishs a stacking context within the parent element, it's not possible for the parent's background image to appear above the child img element (unless you were to completely hide the img element). This is why the z-indexs weren't working as expected.
In addition, the img element was absolutely positioned. In doing so, it is removed from the normal flow, and since it was the only child element, the parent element therefore collapses upon itself and it doesn't have any dimensions. Thus, the background image doesn't show up. To work around this, you would either have to set explicit dimensions on the parent element (height/width), or you could remove the absolute positioning on the child img element.

A: Another way, is to set content to empty and set a background, for example:
img {
    background: url(...) center center no-repeat;
    background-size: cover;
    content: '';
    display: block;
    width: 800px;
    height: 100px;
}

Here is a demo:
http://jsfiddle.net/infous/effmea8x/
In this demo the first image is standard but with unproportional width and hight, the second one is with the background. The first one is scaled badly, the second one is OK.

A: Here's what I did for my solution. Essentially, I'm using the "IMG" as a placeholder. So that my Background image maintains the correct proportions as the browser resizes.
.image-overlay {
  background-image: url("insert image here");
  display: inline-block;
  position: relative;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}
.image-overlay img {
  opacity: 0;
}

HTML


text:
Q: jQuery: Animate to vertical position I have a vertical menu (html list) with an arrow image (as a div). I would like the arrow to slide vertically to the clicked position.
Should be a pretty simple animate!

A: Click here to see this in action.
HTML

Click

Here

And

Watch

The

Magic

Happen

♦

CSS
ul { list-style:outside circle; padding-left:20px; }
li { cursor: pointer; }
#bullet { color:#0c0; padding:1px 0 0 3px; position:absolute; top:200px; }

Important part is #bullet { position:absolute; }
jQuery (in $(document).ready)
$('li').bind('click', function(e) {
    var offset = $(e.target).offset();
    $('#bullet').animate({'top':offset.top},600);
});

Pretty simple!

A: Like following perhaps:
$('#arrow_image').animate($('#vertical_menu').position(), 'slow');

position might be offset depending on context.
Edit: erm, read question wrong :)
to move it to mouse position in a click handler:
var click_handler = function(event) {
  $('#arrow_image').animate(
    {
      left: event.pageX - $('#vertical_menu').offset().left
    }, 'slow');
}

left depends as usual on context where the arrow image is located in DOM, if it's absolute positioned in relation to body then pageX is sufficient.


text:
Q: Setting (or changing) the ACL for an object in an S3 bucket using put_acl() in R? get_acl() returns a string representation of XML showing the current ACL. This works as expected.
According to ?put_acl and AWS docs, I should be able to edit the ACL and put_acl() to set a new one.
Example
Suppose we insert a new grant inside the existing ACL to give public read access to an object in a bucket
library(aws.s3)
original_acl <- get_acl("object_name", "bucket_name")

public_access_grant <- '<Grant><Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group"><URI>http://acs.amazonaws.com/groups/global/AllUsers</URI> </Grantee><Permission>READ</Permission></Grant>'

# Split existing ACL into two
original_acl_part_1 <- substr(original, 1, nchar(original) - 42)
original_acl_part_2 <- substr(original,  nchar(original) - 42 + 1, nchar(original))

# Paste the chunks back together with the new grant included
new_acl_in_xml_as_a_string <- paste0(original_part_1, public_access_grant, original_part_2)

At this point, I should be able to set the new ACL, like so
put_acl(object=object_name, bucket=bucket_name, body=new_acl_in_xml_as_a_string)

Unexpected result
A quick test using get_acl() shows the ACL hasn't changed from its original
Question
What's going on and why wasn't the ACL updated as expected?


text:
Q: what is ## in c? I have seen this snippet:
#define kthread_create(threadfn, data, namefmt, arg...) \
    kthread_create_on_node(threadfn, data, -1, namefmt, ##arg)

*

*what does ## stand for ?

*what is the meaning of ## when it appears out of a macro ?

A: Contrary to the other answers, this is actually GCC extension. When pasting variable args directly in, a problem occurs if no extra args were passed. Thus, GCC makes ## when used with __VA_ARGS__ or a varargs variable (declared with argname...). To paste if it contains a value, or remove the previous comma if not.
The documentation for this extension is here:

Second, the '##' token paste operator has a special meaning when placed between a comma and a variable argument. If you write
#define eprintf(format, ...) fprintf (stderr, format, ##__VA_ARGS__)

and the variable argument is left out when the eprintf macro is used, then the comma before the '##' will be deleted. This does not happen if you pass an empty argument, nor does it happen if the token preceding '##' is anything other than a comma.
eprintf ("success!\n")
      ==> fprintf(stderr, "success!\n");

The above explanation is ambiguous about the case where the only macro parameter is a variable arguments parameter, as it is meaningless to try to distinguish whether no argument at all is an empty argument or a missing argument. In this case the C99 standard is clear that the comma must remain, however the existing GCC extension used to swallow the comma. So CPP retains the comma when conforming to a specific C standard, and drops it otherwise.

A: This "pastes" whatever passed in arg to the macro expansion.
Example:
kthread_create(threadfn, data, namefmt, foo, bar, doo);

Expands to:
kthread_create_on_node(threadfn, data, -1, namefmt, foo, bar, doo);


text:
Q: Django: Mark as Read "Notifications" I'm working on a school project. Right now any user can ask a question.
In order to notify all the users when any users asks a question I've created a new app & notifying them through the simple 'view' whenever a question is asked. But it's just plain notifications yet.
How can I mark them read once a user opens the Notification tab? Just like on social networks!

A: I suggest you to use ContentType to make a dynamic notifications fo any models. This snippet below is an example how to implement the notification system;
1. in your models.py
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.utils.translation import ugettext_lazy as _

class ContentTypeToGetModel(object):

    """
    requires fields:
        - content_type: FK(ContentType)
        - object_id: PositiveIntegerField()
    """

    def get_related_object(self):
        """
        return the related object of content_type.
        eg: <Question: Holisticly grow synergistic best practices>
        """
        # This should return an error: MultipleObjectsReturned
        # return self.content_type.get_object_for_this_type()
        # So, i handle it with this one:
        model_class = self.content_type.model_class()
        return model_class.objects.get(id=self.object_id)

    @property
    def _model_name(self):
        """
        return lowercase of model name.
        eg: `question`, `answer`
        """
        return self.get_related_object()._meta.model_name

class Notification(models.Model, ContentTypeToGetModel):
    # sender = models.ForeignKey(
    #    User, related_name='notification_sender')

    receiver = models.ForeignKey(
        User, related_name='notification_receiver')

    content_type = models.ForeignKey(
        ContentType, related_name='notifications', on_delete=models.CASCADE)

    object_id = models.PositiveIntegerField(_('Object id'))
    content_object = GenericForeignKey('content_type', 'object_id')

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    STATUS_CHOICES = (
        ('reply', _('a reply')),
        ('comment', _('a comment')),
        ('message', _('a message'))
    )
    status = models.CharField(
        _('Status'), max_length=20,
        choices=STATUS_CHOICES, default='comment')

    is_read = models.BooleanField(
        _('Is read?'), default=False)

    def __str__(self):
        title = _('%(receiver)s have a %(status)s in the %(model)s:%(id)s')
        return title % {'receiver': self.receiver.username, 'status': self.status,
                        'model': self._model_name, 'id': self.object_id}

    class Meta:
        verbose_name_plural = _('notifications')
        ordering = ['-created']

2. in your views.py
from django.views.generic import (ListView, DetailView)
from yourapp.models import Notification

class NotificationListView(ListView):
    model = Notification
    context_object_name = 'notifications'
    paginate_by = 10
    template_name = 'yourapp/notifications.html'

    def get_queryset(self):
        notifications = self.model.objects.filter(receiver=self.request.user)

        # mark as reads if `user` is visit on this page.
        notifications.update(is_read=True)
        return notifications

3. in your yourapp/notifications.html
{% extends "base.html" %}

{% for notif in notifications %}
  {{ notif }}

  {# for specific is like below #}
  {# `specific_model_name` eg: `comment`, `message`, `post` #}
  {% if notif._model_name == 'specific_model_name' %}
    {# do_stuff #}
  {% endif %}
{% endfor %}

So, when I creat that notifications?
  eg: when the other user send a comment to receiver on this post.

from django.contrib.contenttypes.models import ContentType

def send_a_comment(request):
    if request.method == 'POST':
        form = SendCommentForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            #instance.sender = request.user
            ...
            instance.save()

            receiver = User.objects.filter(email=instance.email).first()
            content_type = ContentType.objects.get(model='comment')

            notif = Notification.objects.create(
                receiver=receiver,
                #sender=request.user,
                content_type=content_type,
                object_id=instance.id,
                status='comment'
            )
            notif.save()

How about menu? Like this stackoverflow, facebook, instagram, or else?

you can handle it with templatetags, eg:
# yourapp/templatetags/notification_tags.py

from django import template

from yourapp.models import Notification

register = template.Library()

@register.filter
def has_unread_notif(user):
    notifications = Notification.objects.filter(receiver=user, is_read=False)
    if notifications.exists():
        return True
    return False

and the navs.html menu:
{% load notification_tags %}

{% if request.user.is_authenticated %}

          {% if request.user|has_unread_notif %}

          {% else %}

          {% endif %}

{% endif %}

A: First you need ManyToManyField for user module who is readed a post.
profile.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
subscribed = models.ManyToManyField(User, related_name='subscribed', blank=True)
readed = models.ManyToManyField("blogs.BlogPost", related_name='readed', blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return str(self.user.username)

class Meta:
    ordering = ("-created",)

If you have a blog model like this:
class BlogPost(models.Model):
author = models.ForeignKey(Profile, on_delete=models.CASCADE)
post_title = models.CharField("Post Title", max_length=150, unique=True)
post_content = models.TextField("Content")
created = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return self.post_title

class Meta:
    ordering = ("-created",)

You need to create a button function in blog posts view.
def mark_as_read_button(request):
if request.method == "POST":
    my_profile = Profile.objects.get(user=request.user)
    post = request.POST.get("post_pk")
    obj = BlogPost.objects.get(pk=post)

    if obj in my_profile.readed.all():
        my_profile.readed.remove(obj)
    else:
        my_profile.readed.add(obj)
    return redirect(request.META.get("HTTP_REFERER"))
return redirect("blogs:subscribed-blogs")

Then you can use is in the template file like this:
{% extends 'base.html' %}

{% block title %}Subscribed Blog Posts{% endblock %}

{% block content %}
{% for post in posts %}

{{ post.post_title }}

    {% if post in readed %}
        <form action="{% url "blogs:mark_as_read" %}" method="POST">
            {% csrf_token %}
            <input type="hidden" name="post_pk" value={{ post.pk }}>
            <button type="submit" class="btn btn-danger btn-sm">Mark as unread</button>
        </form>
    {% else %}
        <form action="{% url "blogs:mark_as_read" %}" method="POST">
            {% csrf_token %}
            <input type="hidden" name="post_pk" value={{ post.pk }}>
            <button type="submit" class="btn btn-success btn-sm">Mark as read</button>
        </form>
    {% endif %}

{{ post.created }}

{{ post.post_content }}

{% endfor %}
{% endblock %}

Good coding.


text:
Q: javascript extension error: Cannot perform modifications I'm building a custom dynamicValue extension for paw. However i'm not able to set header in the evaluate method. See the sample code below:
evaluate(context) {
  const request = context.getCurrentRequest();
  request.setHeader('Content-Type', this.contentType); // <-- this gives warning
  return this.createSignable(request); // This returns a base64 string.
}

I get the warning saying Javascript extension error: Cannot perform modifications and the header is not set. ( when i comment out request.setHeader call, i get no warnings)

Can anyone please help me resolve this issue?

A: This is correct, you cannot use setters (set any value) in a dynamic value. In fact, the way Paw evaluates dynamic values is asynchronous and as multiple evaluations can take place simultaneously it would be impossible to record the modifications. For this reason, Paw is simply denying changes and no change is persisted during evaluation.
In the documentation, it's specified that these methods (like setHeaders) is only available for importer extensions. Sorry for the inconvenience!
I think to achieve what you're trying to do, you would need two dynamic values one set in the Authorization header and one set in the Content-Type header.
Alternatively, in the future we're going to add request post-processors, so you'll be able to mutate the computed request ready to be sent to the server for additional modifications.