Q:

PC XNA Development

I first interacted with XNA a few years ago when it had support for both PC and Xbox developing.
Now i see that the directions of development are Xbox and Windows Phone. Is the PC part gone or is it automatically included into the Xbox development.
We want to develop a game for PC only. Do I have enough support for it or the newest version of XNA shut it down?

A:

If you are looking to develop for Windows 8 also, then I would suggest looking into the MonoGame project. Here is a snippet from their website:

MonoGame is an Open Source implementation of the Microsoft XNA 4
  Framework. Our goal is to allow XNA developers on Xbox 360, Windows &
  Windows Phone to port their games to the iOS, Android, Mac OS X, Linux
  and Windows 8 Metro.  PlayStation Mobile development is currently in
  progress.

The develop3d branch is the branch you would want to look into. It's still in dev, but there have been quite a few games that use it.
As the above stated, Microsoft has been pretty tight lipped about the future of XNA. Here is a link to a article series about porting XNA to monogame

A:

The Windows Phone stuff got split off from the Xbox 360 stuff, due to Windows 8 and particularly Windows Phone 8 coming. In the process, Microsoft made a real mess of the create.msdn.com website.
The PC stuff (and some of the WP7 stuff) for XNA is still in with the Xbox stuff.
The latest version of XNA is 4.0. It still "works". I'm making a PC game using it. On the PC you can basically think of it as a really nice C# wrapper for DirectX 9 (plus a content pipeline). It works on the Desktop in Windows 8, but not in the new Metro-style UI.
Microsoft have been showing very, very little love for XNA since it started to show off Windows 8. They have said precisely nothing about the future of XNA. Maybe there will be a new version for the next Xbox. Or maybe 4.0 will be the last version. I don't think anyone outside Microsoft knows.


Q:

Why does traceroute from the command line work, but traceroute via Network Utility not work?

I am diagnosing some mysterious network latency that comes and goes with my wife's MacBook Pro.
As part of this diagnostic work, I fired up Network Utility and used its interface to traceroute to trace the route to www.google.com.  Somewhat oddly, all of the results were of the * * * variety.
Suspicious, I opened up traceroute directly from Terminal and issued traceroute www.google.com.  There was a * * * from the second hop (right after my 10.0.0.1 entry) but then everything flowed normally.
I then eliminated DNS issues by using traceroute against the IP address directly.
This behavior happens on all Macs in our house, so it's not computer-specific.
Here is the output from the command line (which worked):
traceroute to 173.194.33.116 (173.194.33.116), 64 hops max, 52 byte packets
 1  10.0.0.1 (10.0.0.1)  115.994 ms  1.265 ms  1.816 ms
 2  * * *
 3  te-5-2-ur02.bremerton.wa.seattle.comcast.net (68.87.205.57)  14.209 ms  12.736 ms  11.514 ms
 4  ae-22-0-ar03.seattle.wa.seattle.comcast.net (69.139.164.153)  18.753 ms  14.804 ms  15.076 ms
 5  he-1-4-0-0-10-cr01.seattle.wa.ibone.comcast.net (68.86.94.237)  19.233 ms
    he-1-7-0-0-10-cr01.seattle.wa.ibone.comcast.net (68.86.91.165)  18.523 ms
    he-1-12-0-0-10-cr01.seattle.wa.ibone.comcast.net (68.86.93.173)  16.625 ms
 6  he-0-11-0-1-pe04.seattle.wa.ibone.comcast.net (68.86.85.38)  15.435 ms  21.009 ms  14.535 ms
 7  23.30.207.2 (23.30.207.2)  16.739 ms  14.500 ms  15.909 ms
 8  209.85.249.34 (209.85.249.34)  16.002 ms  17.200 ms  16.781 ms
 9  209.85.244.63 (209.85.244.63)  15.472 ms  17.927 ms  15.836 ms
10  sea09s16-in-f20.1e100.net (173.194.33.116)  15.860 ms  27.057 ms  16.399 ms

And here is the output from Network Utility:

Leaving aside the &)$(*^#& problem that I'm actually trying to solve, what would account for why the two traceroute invocations would produce different output?  If it matters, traceroute-via-Network-Utility never works; the command line always does.

A:

Network Utility is using ICMP rather than the default UDP protocol used by traceroute. You can use the -I flag to get the same behaviour on the command line:
traceroute -I 173.194.33.116

I don't know of any way to force Network Utility to use UDP.
One explanation for this could be that your firewall/router is configured to block ICMP packets.


Q:

How can I throw a warning in Template::Toolkits CATCH block?

The code I am working on has a bunch of TRY/CATCH blocks in Template::Toolkit templates.  They look like this:
[% TRY; x = OBJ.method(data); CATCH; "<!-- error: $error -->"; END %]

This is bad from two perspectives.  First, the error is being inserted into the HTML handed to the user, and second, the error is hard to find for the developers.  In my opinion, all errors should be logged to the same error log.  Right now I do that through the warn function.  I have changed the code above to be
[% TRY %]
    [% x = OBJ.foo(data) %]
[% CATCH %]
    [% RAWPERL %]
        warn "error calling method foo on a bar object: " . $stash->get("error");
    [% END %]
[% END %]

but this feels far too verbose for what should be a simple thing.  Is there some better way I am ignorant of to do this?

A:

Great idea! Never thought of it myself, but will implement the solution for my own system now.
And it is possible out of the box!  The stderr filter prints output of a block to STDERR:
[% FILTER stderr %]
   Found a big problem
[% END %]

No MVC required, no code, just a better life.
A more advanced way to do it is to create an object within your controller whose job it is to log errors, so it can process them more intelligently:
[% logger.warn('Big Problem') %]
It could email them, put them into the log, or SMS to the developer you don't like.  ;-)


Q:

how to change the order of south migrations

I have around fifty migrations in my store app, some of them are schemamigration and some datamigration. Now i want to run 0039_add_column_is_worldwide before 0037_some_values_to_objects. So I changed there name 0037_add_column_is_worldwide and 0039_some_values_to_objects.
It works fine when i did syncdb for new db but while migrating for a new migration in existing db it gives this error.

raise exceptions.InconsistentMigrationHistory(problems)
  south.exceptions.InconsistentMigrationHistory: Inconsistent migration history
  The following options are available:
      --merge: will just attempt the migration ignoring any potential dependency conflicts.

I didn't want to lose my data, so is there anyway to change the order of these migrations?

A:

Migration are stored in DB when ran, so if you already applied these migrations south is going to get lost. Your alternatives:

flush the migration table (will cause all migration to run again if you call migrate)
rollback these migrations (before renaming)
fake these migrations (migrate --fake, but the numbers may conflict with the one in DB anyway)

Rollback seems the safest to me, just be sure everybody in your project do the same.
If you are still in dev and you have no prod database, you can always restart from zero:

flush the south db
migrate --fake


Q:

How to upgrade virtual environment from previous Python version?

I upgraded Python on my system from Python 3.5 to 3.6, and now all my virtualenvs created in Python 3.5 are no longer usable. How can I get a list of packages installed in a Python 3.5 virtualenv when I have only Python 3.6 installed? I need to setup a new Python 3.6 virtualenv with the same packages as in the old Python 3.5 virtualenv.
I know that I can look inside the lib/python3.5/site-packages directory and make the list manually, but I would prefer an automatic way of running e.g. pip freeze against the old virtual environment. I would prefer not to re-install the old version of Python.
I have tried the python -m venv --upgrade command, which has the help text "Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place.". However, this doesn't actually reinstall the packages in the virtualenv, it just creates an essentially empty directory named lib/python3.6/site-packages. Furthermore, I had to remove the broken symlink bin/python3.5 in the venv in order to even run python -m venv --upgrade against the old virtualenv.

A:

Use pkg_resources.find_on_path() to find packages using the same logic as pip freeze. This works even when the virtualenv is for an older version of Python:
rav@novascotia:~/venvs$ python
Python 3.6.1 (default, Mar 27 2017, 00:27:06)
[GCC 6.3.1 20170306] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg_resources
>>> entries = pkg_resources.find_on_path(None, './st-courses-3.5/lib/python3.5/site-packages')
>>> print('pip install \\\n%s' % ' \\\n'.join('%s==%s' % (o.project_name, o.version) for o in entries))
pip install \
websockets==3.2 \
webencodings==0.5 \
wcwidth==0.1.7 \
...

This is the trail of code that leads from pip freeze to find_on_path:

pip freeze accesses get_installed_distributions()
... which accesses pkg_resources.working_set
... which invokes working_set.add_entry() on each entry of sys.path
... which invokes find_distributions() on each entry
... which calls _find_adapter
... which results in find_on_path


Q:

Data modelling of group and users

I have a web app that lets users create groups.
On the front page of the app any user can - without registering - create a group and add other users to the group by entering names into a list of text inputs. The user that created the group is then supposed to be able to invite the people on the list by adding an email to each of the names. The reason I want the user to provide just names initially and ivitations by email later is that I want the user to be able to try out the app and its functionality before registration.
So I have two models Group and User with a many-to-many relationship. The user model requires a unique email address so obviously I can't create new user objects for each user in the group. So how would one make sure that the temporary users added to the groups will be mapped to the users that are created through the invitation or if the invited person already has a user in the app?
I was thinking about creating a Profile model that would have a name and belong to a group and a user but that way each user would have a profile for each of the groups he/she belongs to. I can't think of another alternative but there must be one...

A:

You need tools to dump dat info from your brain to a database model :)
http://wb.mysql.com/ or http://www.sequelpro.com/
Then you need to abstract that into your application.
http://datamapper.org/
After install all datamapper gems
gem install dm-core dm-do-adapter dm-migrations dm-sqlite-adapter dm-timestamps do_sqlite3
And finally you can start playing. In your Sinatra app.
require 'rubygems'
require 'dm-core' # http://datamapper.org/getting-started

configure :development do

  DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/hohohodb.db")

end

#...

class User

  include DataMapper::Resource

  property :id,          Serial   # http://datamapper.org/docs/properties
  property :username,    String
  property :email,       String
  property :created_at,  DateTime
  property :updated_at,  DateTime

  validates_uniqueness_of, :email # http://datamapper.org/docs/validations
  has n, :groups

end
# Create or Upgrade all tables at once
DataMapper.auto_upgrade!

get '/'
    erb :index
end

__END__

@@index
...

Hope this can be a good starting point # http://datamapper.org/docs/
have fun


Q:

How to use GDB to debug a big project?

Now I have a c language project which include three directories /bin, /inc and /src.
All of header files (.h) are included in /inc and all of source(.c) files are stored in /src, i.e. a.c, b.c, c.c..., the final generated executable file will locate in /bin.
after compling with makefile, all of obj files will be generated in /src/obj like a.o, b.o, c.o, d....! Moreover an final.exe executable file will be generated in the /bin directory.
Now if I want to debug it with GDB, how can I do it???
To debug those obj files in /src/obj? or somewhat else?
Many thanks for the kind help!

A:

You can either debug an application by starting it with GDB
%> gdb <your_executable>

or what is usually easier is to start your application and then attach the debugger to the process using the PID.
%> gdb -p <pid>

For command line options, just type gdb -h and while running inside of gdb
help is always available by typing "help" on the gdb command line.
Here is a quick cheat sheet and a tutorial site on some common commands.
As Arkaitz mentioned, be sure to compile your code so that it has the necessary debug information included in the executable.
If debugging from the command line is a bit daunting, there are some UIs available that use GDB.  I do a lot of my debugging in Eclipse using gdb.
Once you get started down the gdb path, I'm sure you'll have more questions and I encourage you to ask those more specific questions on SO.
Good luck.


Q:

Using XSLT 2.0 to replace unknown number of strings

We have user-editable XML configuration files for our software, which is then unmarshalled in our Java application. We want to allow us or our users be able to add new variables to be used in strings within the configuration file.
I have XML with this structure:
<root>
    <variables>
        <key1>foo</key1>
        <key2>bar</key1>
        ...
        <keyn>nthbar</keyn>
    </variables>

    <some-tag>PlainText.${key1}.${keyn}.${key2}.MorePlainText</some-tag>
    <other-tag>${key3}</other-tag>
</root>

I'm aware that I can use XSLT 2.0 to do something like this to replace the values for known keys:
<xsl:variable name="key1" select="root/variables/key1/text()" />
<xsl:variable name="key2" select="root/variables/key1/text()" />
...
<xsl:variable name="keyn" select="root/variables/key1/text()" />

<xsl:template match="text()">
    <xsl:value-of select="replace( replace( replace( ., '\$\{val1\}', $key1), '\$\{val2\}', $key2), '\$\{valn\}', $keyn)" />
</xsl:template>

The trouble is that this isn't very flexible. A new replace() needs to wrap the existing replace() calls every time a new key is added, and a new variable would need to be declared in the corresponding xsl file.
Is there a slick way using XSLT to refer to tags like value by using something like ${keyn} in a string elsewhere in an XML file?

A:

You can use a key to match your variables/* elements and you can use analyze-string to find the {$var} in text nodes:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:key name="variables" match="variables/*" use="local-name()"/>

    <xsl:variable name="main-root" select="/"/>

    <xsl:template match="@* | * | comment() | processing-instruction()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="root/variables"/>

    <xsl:param name="variable-pattern" as="xs:string">\$\{(\w+)\}</xsl:param>

    <xsl:template match="text()">
        <xsl:analyze-string select="." regex="{$variable-pattern}">
            <xsl:matching-substring>
                <xsl:value-of select="key('variables', regex-group(1), $main-root)"/>
            </xsl:matching-substring>
            <xsl:non-matching-substring>
                <xsl:value-of select="."/>
            </xsl:non-matching-substring>
        </xsl:analyze-string>
    </xsl:template>

</xsl:stylesheet>

I guess it would be better to raise an error if a match is found but key('variables', regex-group(1), $main-root) does not find any definition:
<xsl:template match="text()">
    <xsl:analyze-string select="." regex="{$variable-pattern}">
        <xsl:matching-substring>
            <xsl:variable name="var-match" select="key('variables', regex-group(1), $main-root)"/>
            <xsl:choose>
                <xsl:when test="$var-match">
                    <xsl:value-of select="$var-match"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:message select="concat('No match found for $', regex-group(1))"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:matching-substring>
        <xsl:non-matching-substring>
            <xsl:value-of select="."/>
        </xsl:non-matching-substring>
    </xsl:analyze-string>
</xsl:template>


Q:

How to convert CNContact to CNMutableContact?

I need to get contact, change it, and store back.
CNContactStore().unifiedContacts gives me CNContact instance, but CNSaveRequest().update requires CNMutableContact.
How to convert CNContact to CNMutableContact?

A:

Just found a way:
let mutableContact = contact.mutableCopy() as! CNMutableContact


Q:

Create caption without float *and* without caption package?

In the appendix of my thesis, there is a large number of tables and longtables which does not need to float, as they shall appear one after the other just how they fit on the pages (and it is no problem if the bottom third of a page would stay empty).
(The appendix is structured by some headings and sometimes there is also a short paragraph or two to explain something about the data shown in the tables. So I explicitely do want to appear the tables directly and not float "elsewhere" - apart from the explaining text.)
So I thought it would be easier to let pdflatex typeset the tables (tabular) directly, which works well as long as I don't need captions.
But I found that I can not use the \caption-command in those tabulars.
This question was asked already, but both solutions require the use of the caption package which seems to be incompatible with longtable or KOMA-script classes (which I need).
So is there another way to use \captions without floats?
I'm using the KOMA-script class scrbook.

A:

The package caption isn't incompatible with KOMA or longtable.
You don't need the package caption because KOMA provides the command captionof
\documentclass{scrartcl}
\begin{document}
\listoffigures
\section{foo}
\begin{center}
\rule{3cm}{3cm}
\captionof{figure}{bla}
\end{center}
\end{document}

A:

The classes of KOMA Script offer the \captionof command for captions outside floats.
\captionof{floattype}[List entry]{Full caption}

It isn't yet documented in the English version of the user guide.

A:

For LaTeX users that don't use a KOMA-script class, yet for some reason still don't want to load the caption package: There's the tiny capt-of package that also offers the \captionof command.


Q:

Why didn't Taki write his name on Mitsuha's hand?

When Taki meets Mitsuha by the shrine, just before the meteor strikes the town, Taki tells Mitsuha that they should write each other's names on their hands.
Instead of writing his name, Taki instead writes "I love you" on her hand, leaving Mitsuha with no way to remember his name.
Why didn't Taki write his name on Mitsuha's hand?

A:

I think it was a sweet gesture that showed a little insight into Taki's character. It shows that he is young, in love, and struggling to find a way to share his feelings with Mitsuha.
At that moment when an opportunity presented itself for him to confess without having to say it out loud (the horror! :D), he foolishly thought it was more important to tell her how he feels than what his name was.
Very frustrating, probably done on purpose by the writer but not completely baseless.


Q:

Is it possible to use querySelector() on a dynamically created element?

I'm using appendHtml() in a loop to dynamically add li elements (with unique IDs in the string) to a ul. When I need to access these dynamically created li elements by their IDs to, for example, create nested lists, querySelector() returns null. If I should be able to do this, then there could very well be bugs in my code. But I want to make sure this is the case.

A:

It doesn't matter how elements are added, if the are part of the DOM querySelector can find them.


Q:

Converting 2 column data file to row format

i am Beginner Unix user,trying to convert a file having 2 columns to a row format data file.
Sample data file : HEADER Count: 6 , EMPID, EMPNAME,SALARY,DEPT,AGE,JOD
col1;col2

empid;1001
empname;ABC
salary;3000
dept;ABC
age;24
JOD;20170101
empid;2001
salary;5000
dept;XYZ
age;27
JOD;20170303
empid;1002
empname;MAN
salary;11000
dept;SCI
age;30
JOD;20180607
empid;1005
empname;NAME
salary;10200
dept;XYZ
JOD;20161212

Below is the code i have tried, but i am not getting desired output.
awk '
BEGIN {FS=';'
       OFS=';'
       RS="\n"
Print An = "empid", Bn = "empname", Cn = "salary", Dn = "Dept", En = "age", Fn = "DOJ"
     }
     {
     A=B=C=D=E=F=" "
     for ( i = 1; i<=NF; i++)
          {
           if($i == An)
                A = $(i+1)
           if($i == Bn)
                B = $(i+1)
           if($i == Cn)
                C = $(i+1)
           if($i == Dn)
                D = $(i+1)
           if($i == En)
                E = $(i+1)
           if($i == Fn)
                F = $(i+1)
             }
            print A, B, C, D, E, F
             }' FILE.txt >New_file.txt

let me know if anything is required from my side.
i am using PUTTY for unix, 64 bit intel core i5-5300U CPU, 2.30GHz.
Could  you please help me out with this.I would be very helpful.
Regards,
Naresh

A:

Since you don't have a consistent number of fields in each input record, a 2-pass approach is required to avoid having to hard-code column names in your code:
$ cat tst.awk
BEGIN { FS=OFS=";" }
NR==FNR {
    if ( !($1 in colNrs) ) {
        colNrs[$1] = ++numCols
        hdr = (numCols>1 ? hdr OFS : "") $1
    }
    next
}
FNR == 1 { print hdr }
{ colNr = colNrs[$1] }
colNr in vals { prt() }
{ vals[colNr] = $2 }
END { prt() }

function prt(   colNr) {
    for (colNr=1; colNr<=numCols; colNr++) {
        printf "%s%s", vals[colNr], (colNr<numCols ? OFS : ORS)
    }
    delete vals
}

.
$ awk -f tst.awk file file
empid;empname;salary;dept;age;JOD
1001;ABC;3000;ABC;24;20170101
2001;;5000;XYZ;27;20170303
1002;MAN;11000;SCI;30;20180607
1005;NAME;10200;XYZ;;20161212

To use the above awk script in a shell script:
#!/bin/env bash

... other shell stuff ...

awk '
BEGIN { FS=OFS=";" }
NR==FNR {
    if ( !($1 in colNrs) ) {
        colNrs[$1] = ++numCols
        hdr = (numCols>1 ? hdr OFS : "") $1
    }
    next
}
FNR == 1 { print hdr }
{ colNr = colNrs[$1] }
colNr in vals { prt() }
{ vals[colNr] = $2 }
END { prt() }

function prt(   colNr) {
    for (colNr=1; colNr<=numCols; colNr++) {
        printf "%s%s", vals[colNr], (colNr<numCols ? OFS : ORS)
    }
    delete vals
}
' file file

... other shell stuff ...


Q:

ReactJs toggle Button to open Menu

I built a React component, Toggle Menu, which gets triggered by a button. I'm not able to see the menu open/close after the initial open. A bit lost on how to get started to fix this issue... This is the example I used for reference How to Build a Sliding Menu Using ReactJS
export default class ToggleMenu extends React.Component {

  showRight = () => {
    this.right.show();
  }

  constructor(props) {
    super(props);
    this.showRight = this.showRight.bind(this);
  }

  render() {

    return (

        <button onClick={this.showRight}>Show Right Menu!</button>
        <Menu ref={right => this.right = right} alignment="right">
        <MenuItem hash="first-page">First Page</MenuItem>
        <MenuItem hash="second-page">Second Page</MenuItem>
        <MenuItem hash="third-page">Third Page</MenuItem>
      </Menu>

    );
  }
}

export default class Menu extends React.Component {
    state = {
      visible: false,
    };

    show() {
      this.setState({ visible: true });
    }

    hide() {
      this.setState({ visible: false });
    }

    render() {
      const { visible } = this.state;

      return (

          {
            visible &&

{this.props.children}

          }

      );
    }
}

A:

By moving the State into the main ToggleMenu, you can have this component maintain the visibility of the Menu.
class ToggleMenu extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            visible: false
        };

        this.toggleMenu = this.toggleMenu.bind(this);
    }

    toggleMenu() {
        this.setState({visible: !this.state.visible})
    }

    render() {
        return (

                <button onClick={this.toggleMenu}>Show Right Menu!</button>
                {this.state.visible && <Menu alignment="right">
                <MenuItem hash="first-page">First Page</MenuItem>
                <MenuItem hash="second-page">Second Page</MenuItem>
                <MenuItem hash="third-page">Third Page</MenuItem>
                </Menu>}

        );
    }
}

This allowed me to change your menu into a Stateless Component:
const Menu = ({alignment, children}) => (

{children}

);

I have created a webpackbin here (now with animation): https://www.webpackbin.com/bins/-Klh1VM-n4RDCkEbkK67
For transitions and animation, I recommend you look at https://github.com/reactjs/react-transition-group

A:

export default class ToggleMenu extends React.Component {

  constructor(props) {
    super(props);
    this.state = { rightMenu: false }
    this.showRight = this.showRight.bind(this);
  }

  showRight = () => {
    this.setState({ rightMenu: !this.state.rightMenu })
  }

  render() {

    return (

      <button onClick={this.showRight}>Show Right Menu!</button>
      <Menu className={ this.state.rightMenu ? "displayBlock" : "displayNone"} ref={right => this.right = right} alignment="right">
      <MenuItem hash="first-page">First Page</MenuItem>
      <MenuItem hash="second-page">Second Page</MenuItem>
      <MenuItem hash="third-page">Third Page</MenuItem>
      </Menu>

    );
  }
}

//Style code
.displayBlock{ display: block }
.displayNone{ display: none}

A:

class App extends React.Component {
  state = {
    messageVisibility: true
  }

  toggleMessage = () => {
    this.setState({
      messageVisibility: !this.state.messageVisibility
    })
  }

  render() {
    return(

        <button onClick={this.toggleMessage}>Toggle Message</button>
        {this.state.messageVisibility ?
Toggle Content
 : null}

    )
  }

}


Q:

GridView imageAdapter doesn't work

I have gridView in fragment
     @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        //
        Bundle savedInstanceState) {

    if (container == null) {
        Log.e("Null container", "Null");

        return null;
    }
    Log.e("fragment1", "fragment1 reached!");
    View view =  inflater.inflate(R.layout.menu1_fragment, container, false);
    GridView gridView = (GridView)view.findViewById(R.id.gridview1);
    gridView.setAdapter(new ImageAdapter(this.getActivity()));

    Log.e("fragment1", "fragment1 reached!");

    return (GridView)inflater.inflate(R.layout.menu1_fragment, container, false);
}

But the adapter doesn't work, it doesn't reach overridden getView method.
Constructor:
public ImageAdapter(Context c) {
    mContext = c;
    Log.e("ImageAdapter", "constructor");
}

GetView method:
 @Override
public View getView(int position, View convertView, ViewGroup parent) {
    Log.e("ImageAdapter", "dsfdsf");
    ImageView imageView;
    if (convertView == null) {  // if it's not recycled, initialize some attributes
        imageView = new ImageView(mContext);
        if (DefinedValues.width/3 < DefinedValues.height/4)
        imageView.setLayoutParams(new GridView.LayoutParams
                (DefinedValues.height/4, DefinedValues.height/4));
        else
            imageView.setLayoutParams(new GridView.LayoutParams
                    (DefinedValues.width/3-5, DefinedValues.width/3-5));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }

    imageView.setImageResource(mThumbIds[position]);
    return imageView;
}

A:

In the onCreateView, you are inflating the xml twice, one you are editing and then you are returning a non edited one..
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    //
    Bundle savedInstanceState) {

if (container == null) {
    Log.e("Null container", "Null");

    return null;
}
Log.e("fragment1", "fragment1 reached!");
View view =  inflater.inflate(R.layout.menu1_fragment, container, false);
GridView gridView = (GridView)view.findViewById(R.id.gridview1);
gridView.setAdapter(new ImageAdapter(this.getActivity()));

Log.e("fragment1", "fragment1 reached!");

return view;
}


Q:

Birthday countdown Calculator in PHP

I want to develop BirthDay CountDown calculator in PHP
User input the date DD-MM-YYYY
I have a days differnce calculator, but it calculates the days from between two specified years.
$daysfrom = $_POST['daysfrom'];
$daysto = $_POST['daysto'];
echo 'Difference of days B.W ' . $daysfrom . '-'.$daysto.' are';
    $daysto = strtotime($daysto);
    $daysfrom = strtotime($daysfrom);
    $datediff = $daysto - $daysfrom;
    echo floor($datediff / (60 * 60 * 24));

And I have tried this calculate days between birthday.(I know this is not right)
User will input MM-DD-YYYY and it should calculate days between months.
Ex: - Input: 13-03-1993
Output: (Assume todays date is 10-03-2014), it should display 03 Days left
 if (isset($_POST['daysto'])) {
       $daysto = $_POST['daysto'];
       echo 'Your birthday comes within ';
       $daysto = strtotime($daysto);
       $now = strtotime(date('d-m'));
       $datediff = $daysto - $now;
       echo $datediff / 60 / 60 / 24;
     }

A:

You could just change the birth date to have the same year as the current date, then run the date_diff().
$birthdate = strtotime("13-03-1993");
$today = strtotime("10-03-2014");
$fixedBirthdate = date_create(date("Y", $today) . "-" . date("m", $birthdate) . "-" . date("d", $birthdate));

$diff = date_diff(date_create(date("d-m-Y", $today)), $fixedBirthdate);
echo $diff->format("%R%a days");

There's probably a way to simplify some of that. I'm not that great with PHP syntax overall.
EDIT: With the use of date_parse_from_format(), I'd probably do something along these lines.
NOTE: This will work with both "13-03-1993" AND just "13-03".
$birthdateArray = date_parse_from_format("d-m-Y", "13-03");
$todayArray = date_parse_from_format("d-m-Y", "10-03-2014"); //In the real thing, this should instead grab the actual current date

$birthdate = date_create($todayArray["year"] . "-" . $birthdateArray["month"] . "-" . $birthdateArray["day"]);
$today = date_create("10-03-2014"); //This should also be actual current date

$diff = date_diff($today, $birthdate);
echo $diff->format("%R%a days");


Q:

What is the difference between different pybind11's type conversion options?

I have a project where i am mixing cpp and python code.
For multiple reasons, the frontend needs to be in python and the backend in cpp.
now, i am looking for a solution as for how to pass my python object to cpp. one think to note is the fact that the backend needs to callback into python at some point for calculating some numbers where the python function will return a list of floats.
I have been looking at pybind type conversion options defined here:
https://pybind11.readthedocs.io/en/stable/advanced/cast/index.html
However, to me it seems like options 1 is kind of easy to use as i can see here:
https://pybind11.readthedocs.io/en/stable/advanced/classes.html#overriding-virtual-functions-in-python
so i am wondering, why would someone choose number 3? how does it compare with option 1?
Many thanks

A:

Yes, if the main code is in C++ and the bindings are well fleshed out, then option 1 is the easiest to work with, as in that case the bound C++ objects are as natural to use in Python as native Python classes. It makes life easier because you get full control over object identity and whether or not to copy.
For 3, I'm finding pybind11 to be too aggressive with copying when using callbacks (as seems to be your use case), e.g. with numpy arrays it's perfectly possible to work with the buffer on the C++ side if it is verified to be contiguous. Sure, copying will safeguard against memory problems, but there's too little control given over copying v.s. non-copying (numpy has the same problem tbs).
The reason why 3 exists is mostly because it improves usability and provides nice syntax. For example, if we have a function with this signature:
void func(const std::vector<int>&)

then it is nice to be able to call it from the Python side as func((1, 2, 3)) or even func(range(3)). It's convenient, easy to use, looks clean, etc. But at that point, there is no way out but to copy, since the memory layout of a tuple is so different from a std::vector (and the range does not even represent an in-memory container).
Note carefully however, that with the func example above, the caller could still decide to provide a bound std::vector<int> object, and thus pre-empt any copying. May not look as nice, but there is full control. This is useful, for example if the vector is a return value from some other function, or is modified in between calls:
v = some_calc()   # with v a bound C++ vector
func(v)
v.append(4)       # add an element
func(v)

Contrast this to the case where a list of floats is returned after calculating some numbers, analog to (but not quite) your description:
std::list<float> calc()

If you choose "option 1", then the bound function calc will return a bound C++ object of std::list<float>. If you choose "option 3", then the bound function calc will return a Python list with the contents of the C++ std::list<float> copied into it.
The problem that arises with "option 3" is that if the caller actually wanted a bound C++ object, then the values need to be copied back into a new list, so a total of 2 copies. OTOH, if you choose "option 1" and the caller wanted instead a Python list, then they are free to do the copy on the return value of calc if desired:
res = calc()
list_res = list(res)

or even, if they want this all the time:
def pycalc():
    return list(calc())

Now finally to your specific case where it is a Python callback, called from C++, that returns a list of floats. If you use "option 1", then the Python function is forced to create a C++ list to return, so for example (with type cpplist the name given to a bound type std::list<float>):
def pycalc():
    return cpplist(range(3))

which a Python programmer would not find pretty. Instead, by choosing "option 3", checking the return type and doing a conversion if needed, this would be valid as well:
def pycalc():
    return [x for x in range(3)]

Depending on the overall requirements and typical use cases then, "option 3" may be more appreciated by your users.


Q:

Display result of multi index array groupby in pandas dataframe

I have a data frame which looks like:
        D        Type    Value
0       1        A          2
1       1        B          4
2       2        C          1
3       1        A          1

I want to group by D and Type and sum the values.
data=df.groupby(['D','Type']).sum()

print(data)

Which gives me this result:
D      Type               Value
1       A                    3
        B                    4
2       C                    3

But I want it in this format:
D      A         B        C
1      3         4        Nan
2      Nan       Nan      3

A:

UPDATE:
r = df.pivot_table(index=['D'], columns='Type', aggfunc='sum').reset_index()
r.columns = [tup[1] if tup[1] else tup[0] for tup in r.columns]
r.to_csv('c:/temp/out.csv', index=False)

Result:
D,A,B,C
1,3.0,4.0,
2,,,1.0

Original answer:
you can use pivot_table() method:
In [7]: df.pivot_table(index=['D'], columns='Type', aggfunc='sum', fill_value=0)
Out[7]:
     Value
Type     A  B  C
D
1        3  4  0
2        0  0  1

or with NaN's:
In [8]: df.pivot_table(index=['D'], columns='Type', aggfunc='sum')
Out[8]:
     Value
Type     A    B    C
D
1      3.0  4.0  NaN
2      NaN  NaN  1.0

PS i think you have a typo in your groupby... section:
In [10]: df.groupby(['D','Type']).sum()
Out[10]:
        Value
D Type
1 A         3
  B         4
2 C         1

there should be C --> 1 instead of C --> 3


Q:

Using URLs to launch intents - several possible duplicates

How to register some URL namespace (myapp://app.start/) for accessing your program by calling a URL in browser in Android OS?
How to implement my very own URI scheme on Android
Android Respond To URL in Intent
On blackberry and android : calling native application from a web browser?

Should any of these be closed as duplicates?

A:

The first two should definitely be closed as exact duplicates of the third, which has an accepted answer and was the earliest question.
The fourth is a maybe, since it also concerns Blackberry apps.


Q:

Angular6.x Library not exposing all members in public_api.ts

After updating my project to the latest version of Angular (6.0.4) i wanted to finally separate my code into different libraries.
The setup is as followed:

CMS - app
Client - app
Core - Library with shared members for both apps

I created 3 empty projects and started moving all my components and services into the right folders. After finally finished all these edits and removing the TS errors, my build is still failing. It seems like my CMS app can't find any of the modules, components or services defined in my library. My library is building correctly and seems to contain all these elements.
ERROR in ./src/app/app.module.ts
Module not found: Error: Can't resolve '**\Webdictaat.Client\dist\core\core' in '**\Webdictaat.Client\projects\cms\src\app'

My library contains a public_api.ts which looks like it's working correctly BUT the generated core.ts file does not contain all exported members. For example, the wd-core.module which is on the second line of the public_api.d.ts
The real question: What am i doing wrong in my library that not all members are exported?
//dist/core/public_api.d.ts
export * from './lib/avatar/avatar.component';
    export * from './lib/wd-core.module';
export * from './lib/modal-component/modal-component.component';
export * from './lib/game-elements/game-elements.module';
export * from './lib/core/html-outlet.directive';
export * from './lib/services';
export * from './lib/models';

//dist/core/core.d.ts
//No wd-core.module :(
/**
 * Generated bundle index. Do not edit.
 */
export * from './public_api';
export { BaseModalService as ɵg } from './lib/core/basemodal.service';
export { GroupByPipe as ɵv } from './lib/core/group-by.pipe';
export { ArraySortPipe as ɵw } from './lib/core/order-by.pipe';
export { ProcessTokenComponent as ɵx } from './lib/core/process-token.component';
export { DirtyGuard as ɵk } from './lib/core/security/dirty.guard';
export { wdApi as ɵb } from './lib/core/wd.service';
export { WdFilterPipe as ɵu } from './lib/core/wdfilter.pipe';
export { DialogComponent as ɵs } from './lib/dialog/dialog.component';
export { ModalComponentComponent as ɵy } from './lib/modal-component/modal-component.component';
export { NavMenuService as ɵm } from './lib/nav-menu/nav-menu.service';
export { AccountService as ɵa } from './lib/services/account.service';
export { AchievementService as ɵi } from './lib/services/achievement.service';
export { AssignmentService as ɵn } from './lib/services/assignment.service';
export { ConfigService as ɵd } from './lib/services/config.service';
export { DialogService as ɵe } from './lib/services/dialog.service';
export { DictaatService as ɵc } from './lib/services/dictaat.service';
export { GoogleAnalyticsEventsService as ɵq } from './lib/services/google-analytics.service';
export { ImageService as ɵh } from './lib/services/images.service';
export { ParticipantService as ɵo } from './lib/services/participantService';
export { PollService as ɵr } from './lib/services/poll.service';
export { QuizService as ɵf } from './lib/services/quiz.service';
export { RatingService as ɵj } from './lib/services/rating.service';
export { StylingService as ɵp } from './lib/services/styling.service';
export { VideoService as ɵl } from './lib/services/video.service';
export { SpinnerComponent as ɵt } from './lib/spinner/spinner.component';

Full Github project:
https://github.com/Webdictaat/Webdictaat.Client/tree/update6
Library project
https://github.com/Webdictaat/Webdictaat.Client/tree/update6/projects/core
CMS app project
https://github.com/Webdictaat/Webdictaat.Client/tree/update6/projects/cms

A:

I found (by trail and error) that ng-packagr, which is used by Angular 6 to package your libraries, does not properly handle imports exposed through "barrel" files named "index.ts" that are referenced by their parent directory name.
So, in your public_api.ts file, where you have, for instance,
export * from './lib/services';

you need to change it to
export * from './lib/services/index';

This is annoying, and I was hoping that it would be fixed, or at least well documented, when the Angular CLI incorporated it, but alas, it seems not.
It's actually not clear to me whether this is an ng-packagr issue or an Angular issue (possibly with ngc), but there is an issue at https://github.com/dherges/ng-packagr/issues/195 that describes what's going on, and that links to some Angular issues, and a pull request for Angular to partially fix it.
In other words, it's complicated.
In the meantime, I find that just referring directly to the index.ts file makes it work.

A:

What you need to do is put all that needs to be available outside of the library in the public_api.ts file like already the first answer suggests. This is the intention of this file and needs to be done so you can use the library correctly. Also the issue with the index.ts files is real so if you still get issues after the changes just export all in the public_api.ts.
Then you do the imports from 'core' not 'core/core' or even a longer path like you do in your code now. For example in your dictaat.module.ts it should look like this:
import { WdCoreModule, DictaatService } from 'core';

If it does not work like this it means the exports are missing in the public_api.ts file.


Q:

Animate Single Character in String Swift

How can we animate a single character within a string? ie: I have the string: "Hey ". I would like to animate the emoji by setting it to rotate back and forth so it looks like it's waving.
To detect the emoji, I'm using:
extension String {
// Not needed anymore in swift 4.2 and later, using `.count` will give you the correct result
var glyphCount: Int {
    let richText = NSAttributedString(string: self)
    let line = CTLineCreateWithAttributedString(richText)
    return CTLineGetGlyphCount(line)
}

var isSingleEmoji: Bool {
    return glyphCount == 1 && containsEmoji
}

var containsEmoji: Bool {
    return unicodeScalars.contains { $0.isEmoji }
}

I'm using the emoji code here: Find out if Character in String is emoji?.
I'm unsure how to set up the animation

A:

I've very slightly modified this excellent answer by Rob in this post.
override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        animateEmojiBackandForth("")
    }

    func animateEmojiBackandForth (_ searchText: String) {
        let beginning = textView.beginningOfDocument

        guard let string = textView.text,
            let range = string.range(of: searchText),
            let start = textView.position(from: beginning, offset: string.distance(from: string.startIndex, to: range.lowerBound)),
            let end = textView.position(from: beginning, offset: string.distance(from: string.startIndex, to: range.upperBound)),
            let textRange = textView.textRange(from: start, to: end)
            else { return }

        textView.selectionRects(for: textRange)
            .forEach { selectionRect in
                guard let snapshotView = textView.resizableSnapshotView(from: selectionRect.rect, afterScreenUpdates: false, withCapInsets: .zero) else { return }
                snapshotView.frame = view.convert(selectionRect.rect, from: textView)
                view.addSubview(snapshotView)
                UIView.animate(withDuration: 1, delay: 0, options: .autoreverse, animations: {
                    snapshotView.transform = CGAffineTransform(rotationAngle: CGFloat( CGFloat.pi / 4))
                }, completion: { _ in
                    snapshotView.removeFromSuperview()
                })
        }
    }

You can modify the duration of the animation and the angle of the "wave" if you wish. I hope this was helpful!


Q:

Getting toolbar list options in same order as they are displayed

I am building options for a drop down menu on a toolbar from a database table, giving the id's for the options the same value as the index in the table, however ordered alphabetically by the description of the option. The visual drop down comes out sorted nicely, however when I ask for a list of all options, they are sorted by id, i.e. getAllListOptions() and forEachListOption(). Are there ways to lookup the option list in the "right" order to pick say the first option in the list, other than sorting the list again myself?
To emphasize, the problem is ID's are not in ascending order when options are sorted by description, however dhtmlx order them internally in ascending order by value instead of by name as they should. I.E, say option with ID of 8 comes out top of list, the first option in the internal list should be "8" not what ever is the smallest ID (in my case 2).
Website is MVC and back-end is MS SQL Server, data structures, like option lists, are passed back through razor scripts as XML.
I.E. the ajax call to get the option list is passed through the bussiness layer to the DAL, which request a list of objects sorted on description. The razor script then creates the XML like this
<item id="tbbOptions" type="buttonSelect" title="@(Messages.Lookup("Config"))" selected="-1" text="@Messages.Lookup("Config_Select")">
    @foreach (Analysis oAnalysis in Model.Analysis)
    {
        if (!string.IsNullOrEmpty(oAnalysis.SecondaryField))
        {
            <item type="button" id="@(oAnalysis.ID)" img="blueprint.png" imgdis="blueprint.png" text="@string.Format("{0}", oAnalysis.Description)" />
        }
        else
        {
            <item type="button" id="@(oAnalysis.ID)" img="blueprint.png" imgdis="blueprint.png" text="@string.Format("{0}", oAnalysis.Description)" />
        }
    }
</item>

SQL query:
    public List<Analysis> GetConfig()
    {
        return UnitOfWork.Database.Fetch<Analysis>("SELECT * FROM [Analysis] ORDER BY [Description]");
    }

A:

After scouring through the javascript source code for the dhtmlx toolbar, I constructed a solution that seem to do what I want. Apparently there are no functions that expose the visual options, so only way to access is through attributes on the object.
In case others run into the same issue, here is what I did:
//Get all visible options
var asList = this.objPull[this.idPrefix + "tbb" + sChart].p_tbody.childNodes;
//If options exist for Chart set drop-down to first option in list
if (asList.length > 0) {
    this.setListOptionSelected("tbb" + sChart, asList[0].idd);
    this.setItemText("tbb" + sChart,"<strong>{0}</strong>".format(this.GetSelectedItemText("tbb" + sChart)));
}


Q:

Count Ifs for Unique Values based on Unique Name

I have a list of records submitted by customers and my list of records contains duplicate submissions.
What formula can I use in a macro to count the list of unique records based on each customer?
See my example data
Record Name       Submitted By           Status
Lead-123           Peter H               Rejected
Lead-495           Carlos Sinbad         Rejected
Lead-496           Carlos Sinbad         Approved
Lead-101           Timothy Johnson       Approved
Lead-421       Timothy Johnson       Approved
Lead-421       Timothy Johnson       Approved
Lead-421       Timothy Johnson       Approved
Lead-421       Timothy Johnson       Rejected
Lead-393       Derik Fauster         Recalled
Lead-393       Derik Fauster         Approved
Lead-422       Derik Fauster         Rejected
Lead-422       Derik Fauster         Rejected
Lead-422       Derik Fauster         Rejected

What I want
# of Unique Records Submitted     Submitted By
1                                 Peter H
2                                 Carlos Sinbad
2                                 Timothy Johnson
2                                 Derik Fauster

I have tried this
Sub CountUniqueValues()
Dim LstRw As Long, Rng As Range, List As Object
LstRw = Cells(Rows.Count, "A").End(xlUp).Row
Set List = CreateObject("Scripting.Dictionary")

For Each Rng In Range("A2:A" & LstRw)
  If Not List.Exists(Rng.Value) Then List.Add Rng.Value, Nothing
Next

MsgBox "There are " & List.Count & " unique values in column A from row 2 down."

End Sub

But I can only get the unique records for Record Name and I can't tie it with a unique Submitted By.

A:

I have answered my own question. I am able to count unique records based on a name criteria.
Below is my modified code that captures all the data in my range and counts the records accordingly.
Dim lnNumber2 As Long
Dim rnFormula2 As Range

With ActiveSheet
    lnNumber2 = .Range("B5000").End(xlUp).Row
    Set rnFormula2 = .Range("I15:I" & lnNumber2)
    rnFormula2.FormulaR1C1 = _
        "=SUMPRODUCT(((Sheet2!R2C2:R5000C2=Sheet1!RC[-7]))/COUNTIFS(Sheet2!R2C1:R5000C1,Sheet1!R2C1:R5000C1&"""",Sheet2!R2C2:R5000C2,Sheet2!R2C2:R5000C2&""""))"

End With


Q:

Distinction between a program and library

Typically the CLR deals with two kinds of binary:
A program has a file name ending in .exe, is marked as a program in the PE header, and has an entry point.
A library has a file name ending in .dll, is marked as a library in the PE header, has no entry point, and has metadata describing the callable functions it contains.
What parts of this distinction are actually enforced?
For example, I think the extension in the filename doesn't actually matter for anything except the command search path; once the file is being read, the filename is ignored and only the PE header counts. Is this correct?
Can you take a program and treat it as a library, referring to it from another program and calling some of its functions without using its entry point?
Can a library have an entry point? If so, can it be run like a program?

A:

If you create a .Net class library, add a Main method and rename the output dll to be exe it won't run. As you state, the PE header is not set up correctly for execution. You can treat a .Net program as a .Net library. Ultimately both are just managed assemblies that declare types.
So in summary. Only a managed application can be executed directly. Any managed assembly can be referenced and it's classes consumed (assuming framework version compatibility, type visibility etc)
If you are in this situation however, referencing an exe as a library, it's time to think about splitting out common functionality into a library that many applications can reference. Applications should never need to reference code in other applications.


Q:

Call swift from c

I saw someone use swift code from android, using @_cdecl swift functions. I am able to compile to native using swiftc -emit-object, but when trying to link, I cant get the linker to work correctly..
I am trying to use g++ or clang(++) to compile and link a native swift object, has someone successfully done this already?
The errors I get are listed below:
Undefined symbols for architecture x86_64:

"__T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC", referenced from:
      __T04main4testyyF in main.o
"__T0SSN", referenced from:
      __T04main4testyyF in main.o
"__T0s27_allocateUninitializedArraySayxG_BptBwlFyp_Tgq5", referenced from:
      __T04main4testyyF in main.o
"__T0s5printySayypGd_SS9separatorSS10terminatortF", referenced from:
      __T04main4testyyF in main.o
"__T0s5printySayypGd_SS9separatorSS10terminatortFfA0_", referenced from:
      __T04main4testyyF in main.o
"__T0s5printySayypGd_SS9separatorSS10terminatortFfA1_", referenced from:
      __T04main4testyyF in main.o
"_swift_bridgeObjectRelease", referenced from:
      __T04main4testyyF in main.o
"_swift_bridgeObjectRetain", referenced from:
      __T04main4testyyF in main.o

So basically I have two questions, can it be done and how?
John.

A:

So thanx to amine.ahd's pointer, I had the iphoneos toolchain location linked instead of the mac osx's.
The following command actually compiled and let me run a c program that calls a swift native library, even with parameters (char* on the c side, UnsafePointer on the swift side).
clang -o m m.o -lshared -L/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx  -L.

*-lshared is the libshared.so library that is compiled using the following command:
clang -shared -o libshared.so main.o -L/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx

Notice the main.o, this got produced using the following command:
swiftc main.swift -emit-object

Thanx for the hints


Q:

How to show that this set isn't a regular surface?

I'm trying to solve this exercise from Do Carmo's Differential Geometry of Curves and Surfaces, and I want a hint on how to do it. The exercise is:
Is the set $S =\left\{(x,y,z)\in \mathbb{R}^3 \mid z=0, \ \ x^2+y^2\leq1 \right\}$ a regular surface ?
Well, for me this isn't a regular surface because the set $S$ is not relatively open in the $xy$ plane, however I'm not sure how to prove this formally. I thought on first proving that a subset of a regular surface is a regular surface itself if and only if it's open relative to the set we know it's a regular surface. Then I show that the $xy$ plane is a regular surface and then $S$ cannot be a regular surface because it's not open relative to the $xy$ plane.
Is this line of thought correct ? Thanks in advance for the help!

A:

It looks to me like you're thinking too hard. For $S$ to be a regular surface in $\mathbb{R}^3$, every point of $S$ must have a neighborhood in $\mathbb{R}^3$ whose intersection with the surface is the regular image of an open set of $\mathbb{R}^2$. Points on the boundary of $S$ (i.e., satisfying the equality in the defining equation) don't have such neighborhoods.


Q:

Appending data to an encrypted file

I'd like to append data to an already encrypted file (AES, CBC-Mode, padding PKCS#7) using CryptoStream without reading and writing the whole file.
Example:
Old Content: "Hello world..."
New Content: "Hello world, with appended text"
Of course I would have to read individual blocks of data and append then to a already present block. In the above mentioned example I would have to read the number of bytes present in the first block (14 bytes) and append two bytes to the first block, then writing the rest of the appended text
"Hello world, wi"
"th appended text"

One problem I am facing is that I am unable to read the number of bytes in a data block. Is there a way to find out the number of bytes present (in the example, 14)?
Additionally I am stuck since the CryptoStreamMode only has members for Read and Write, but no Update.
Is there a way to accomplish my desired functionality using CryptoStream?

A:

It is a little complex, but not too much. Note that this is for CBC mode + PKCS#7!
Three methods: WriteStringToFile will create a new file, AppendStringToFile will append to an already encrypted file (works as WriteStringToFile if the file is missing/empty), ReadStringFromFile will read from the file.
public static void WriteStringToFile(string fileName, string plainText, byte[] key, byte[] iv)
{
    using (Rijndael algo = Rijndael.Create())
    {
        algo.Key = key;
        algo.IV = iv;
        algo.Mode = CipherMode.CBC;
        algo.Padding = PaddingMode.PKCS7;

        // Create the streams used for encryption.
        using (FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write))
        // Create an encryptor to perform the stream transform.
        using (ICryptoTransform encryptor = algo.CreateEncryptor())
        using (CryptoStream cs = new CryptoStream(file, encryptor, CryptoStreamMode.Write))
        using (StreamWriter sw = new StreamWriter(cs))
        {
            // Write all data to the stream.
            sw.Write(plainText);
        }
    }
}

public static void AppendStringToFile(string fileName, string plainText, byte[] key, byte[] iv)
{
    using (Rijndael algo = Rijndael.Create())
    {
        algo.Key = key;
        // The IV is set below
        algo.Mode = CipherMode.CBC;
        algo.Padding = PaddingMode.PKCS7;

        // Create the streams used for encryption.
        using (FileStream file = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            byte[] previous = null;
            int previousLength = 0;

            long length = file.Length;

            // No check is done that the file is correct!
            if (length != 0)
            {
                // The IV length is equal to the block length
                byte[] block = new byte[iv.Length];

                if (length >= iv.Length * 2)
                {
                    // At least 2 blocks, take the penultimate block
                    // as the IV
                    file.Position = length - iv.Length * 2;
                    file.Read(block, 0, block.Length);
                    algo.IV = block;
                }
                else
                {
                    // A single block present, use the IV given
                    file.Position = length - iv.Length;
                    algo.IV = iv;
                }

                // Read the last block
                file.Read(block, 0, block.Length);

                // And reposition at the beginning of the last block
                file.Position = length - iv.Length;

                // We use a MemoryStream because the CryptoStream
                // will close the Stream at the end
                using (var ms = new MemoryStream(block))
                // Create a decrytor to perform the stream transform.
                using (ICryptoTransform decryptor = algo.CreateDecryptor())
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    // Read all data from the stream. The decrypted last
                    // block can be long up to block length characters
                    // (so up to iv.Length) (this with AES + CBC)
                    previous = new byte[iv.Length];
                    previousLength = cs.Read(previous, 0, previous.Length);
                }
            }
            else
            {
                // Use the IV given
                algo.IV = iv;
            }

            // Create an encryptor to perform the stream transform.
            using (ICryptoTransform encryptor = algo.CreateEncryptor())
            using (CryptoStream cs = new CryptoStream(file, encryptor, CryptoStreamMode.Write))
            using (StreamWriter sw = new StreamWriter(cs))
            {
                // Rewrite the last block, if present. We even skip
                // the case of block present but empty
                if (previousLength != 0)
                {
                    cs.Write(previous, 0, previousLength);
                }

                // Write all data to the stream.
                sw.Write(plainText);
            }
        }
    }
}

public static string ReadStringFromFile(string fileName, byte[] key, byte[] iv)
{
    string plainText;

    using (Rijndael algo = Rijndael.Create())
    {
        algo.Key = key;
        algo.IV = iv;
        algo.Mode = CipherMode.CBC;
        algo.Padding = PaddingMode.PKCS7;

        // Create the streams used for decryption.
        using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
        // Create a decrytor to perform the stream transform.
        using (ICryptoTransform decryptor = algo.CreateDecryptor())
        using (CryptoStream cs = new CryptoStream(file, decryptor, CryptoStreamMode.Read))
        using (StreamReader sr = new StreamReader(cs))
        {
            // Read all data from the stream.
            plainText = sr.ReadToEnd();
        }
    }

    return plainText;
}

Example of use:
var key = Encoding.UTF8.GetBytes("Simple key");
var iv = Encoding.UTF8.GetBytes("Simple IV");

Array.Resize(ref key, 128 / 8);
Array.Resize(ref iv, 128 / 8);

if (File.Exists("test.bin"))
{
    File.Delete("test.bin");
}

for (int i = 0; i < 100; i++)
{
    AppendStringToFile("test.bin", string.Format("{0},", i), key, iv);
}

string plainText = ReadStringFromFile("test.bin", key, iv);

How does the AppendStringToFile works? Three cases:

Empty file: as WriteStringToFile
File with a single block: the IV of that block is the IV passed as the parameter. The block is decrypted and then reencrypted together with the passed plainText
File with multiple blocks: the IV of the last block is the penultimate block. So the penultimate block is read, and is used as the IV (the IV passed as the parameter is ignored). The last block is decrypted and then reencrypted together with the passed plainText. To reencyrpt the last block, the IV used is the penultimate block.


Q:

реверс-инжеринг

Есть-ли то, от чего отталкиваться в любом случае?
Не могу понять, как правильно нужно действовать, не могу найти нужный материал.
Знаю, что многие с легкостью реверсят многие источники.
Многим также интересно, как это делается. Многие рассказывают, как это делается - но очень много воды!
Нужно четкое понятие: с чего начать, что взять, что нужно знать - желательно пояснить весь алгоритм.

A:

Нужно: знать ассемблер (или p-code) целевой платформы, IDA Pro, отладчик под целевую платформу. А потом опыт нарабатывать, алгоритмов теоретических под любые случаи не бывает.


Q:

Camera calibration/pin hole camera model and working out 3d position

I have a calibrated camera and have the intrinsic parameters. I also have the extrinsic parameters relative to a point (the world origin) on a planar surface in the real world. This point I have set as the origin in the real world coordinates [0,0,0] with a normal of [0,0,1].
From these extrinsic parameters I can work out the camera position and rotation in the world plane 3d coordinates using this here: http://en.wikipedia.org/wiki/Camera_resectioning
Now I have a second point which I have extracted the image coordinates for [x, y]. How do I now get the 3d position of this point in the world coordinate system?
I think the intuition here is that I have to trace a ray that goes from the optical center of the camera (which I now have the 3D position for as described above), through the image plane [x,y] of the camera and then through my real world plane which I defined at the top.
Now I can intersect a world coordinate 3d ray with a plane as I know normal and point on that plane. What I don't get is how I find out the 3d position and direction when it leaves the image plane through a pixel. It's the transformation through different coordinate systems that is confusing me.

A:

If you have the extrinsics then it is very easy. Having extrinsics is the same as having "camera pose" and the same as having the homography. Check this post in stackoverflow.
You have extrinsics, also called camera pose, which is described as a translation and a rotation:
$\displaystyle Pose =\begin{bmatrix}R|t \end{bmatrix} = \begin{bmatrix}R_{11} &R_{12}&R_{13}&t_x\\R_{21}&R_{22}&R_{23}&t_y\\R_{31}&R_{32}&R_{33}&t_z \end{bmatrix} $
You can get Homography from Pose this way:
$\displaystyle   H = \frac{1}{t_z}\begin{bmatrix}{R_{1x}}&{R_{2x}}&{t_x}\\{R_{1y}}&{R_{2y}}&{t_y}\\{R_{1z}}&{R_{2z}}&{t_z}\end{bmatrix}$
Then you can project your 2D points into the corresponding 3D points by multiplying the Homography by the points:
$p_{2D}=\begin{bmatrix}x &y &1\end{bmatrix}\quad$ add $\quad z=1\quad$ to make them homogeneous
$p_{3D}=H*p_{2D}  $
$p= p / p(z)\quad$   Normalize the points

A:

You have two options, use back projection or projection between two planes (homography).
With back projection you take a pseudo inverse of you camera matrix $P$ and multiply the result with your homogenous presentation of image point:
$$
P = K\begin{bmatrix}R & -R\textbf{C}\end{bmatrix}
\\
\textbf{X}_{reprojected} = P^+\textbf{x}
$$
Now you have a 3D line which travels trough the camera center $\textbf{C}$ and point $\textbf{X}$. If you want, you can convert this to some more easily dealt with presentation. For example with one point and direction vector (remember to normalize the homogenous coordinates $\textbf{V} = \omega\begin{bmatrix}X & Y & Z & 1\end{bmatrix}^T$ such that scale factor $\omega=1$ before the actual calculations):
$$
\textbf{u} = \textbf{X}_{reprojected}-\textbf{C} \\
\textbf{v} = \frac{ \textbf{u} }{\|\textbf{u}\|} \\
\textbf{L}(t) = \textbf{C} + t\textbf{v}
$$
If you have plane $\Pi = \begin{bmatrix}\pi_1 & \pi_2 & \pi_3 & \pi_4\end{bmatrix}^T, \pi_1X + \pi_2Y + \pi_3Z + \pi_4 = 0$  you can solve the equation $\textbf{L}(t) = \Pi$ for $t$.
If you decide to use homography, you need to compute the $3\times3$ homography matrix $H$ which is defined as projection between the imaged plane and the plane of camera sensor:
$$
\textbf{X}_{plane} = \begin{bmatrix}X & Y & 0 & 1\end{bmatrix}^T \\
\textbf{x} = P\textbf{X}_{plane}
= H\begin{bmatrix}X & Y & 1\end{bmatrix}^T
$$
Now if you know $\textbf{x}$:
$$
\textbf{X}_{plane} = H^{-1}\textbf{x}
$$
If you did not compute the $H$ while calibrating the camera (probably using direct linear transformation, DLT), you can use following formulation:
$$
H = R + \frac{1}{d}\textbf{T}\textbf{N}^T
$$
Where $d$ is the dinstance of the camera from the plane and $\textbf{T} = -R\textbf{C}$. (Ma, Soatto, Kosecká, Sastry - An invitation to 3-D Vision From Images to Geometric Models, p. 132)


Q:

Why is scanf ignoring the last value?

I'd like to read in a line of CSV from the command line. The user enters it in the form age, HH:MM:SS, number.
I've written the following:
int age;
char timestamp[8];
int number;

scanf("%d,%8[^,],%d", &age, timestamp, &number;
printf("%d, %s, %d", age, timestamp, number);

When I enter 23, abcd, 9 it prints 23, abcd, 9
When I enter 23, abcdefghijklmno, 9 it prints 23, abcdefgh, 0
How can I fix this?

A:

Weak format used in scanf() and UB
%8[^,] (read 8 char that are not ',') reads " HH:MM:S" into space that is too small @Weather Vane.  So if the undefined behavior of storing 8 char and a null character into timestamp[8] does not kill the code, attempting to read the 2nd S and match against a ',' will stop the scan @Marc B.  Not checking the return value, (a big no-no), further hides the fact number is not written.
char timestamp[8];
//     12345678
// age, HH:MM:SS, number
scanf("%d,%8[^,],%d", &age, timestamp, &number;`

Instead
char buf[100];
fgets(buf, sizeof buf, stdin);

// 1 bigger for the null character
char timestamp[8+1];

//                  v-- add space              check result --v
if (sscanf(buf, "%d, %8[^,],%d", &age, timestamp, &number) == 3) {
  printf("%d, %s, %d", age, timestamp, number);
} else {
  puts("Input data scan failed");
}

scanf() is evil.  Save time, avoid headaches.  Use fgets().
This ad brought to you by the "Practice Safe Input" committee.


Q:

Sub-pixel accuracy scatter plots with matplotlib?

Note: I figured out a solution to this question while writing it. My answer is below.
Is there an easy way to get sub-pixel antialiased placement of circles using matplotlib? I was able to create the following .gif but the fact that the motion of the circles steps by integer pixels is really bugging me.

I can of course render a large image (plt.savefig("image.png",dpi=1000)) and scale down, but the added complexity is a pain (this is an example for students, so importing extra tools will annoy the students and installing extra tools will annoy campus IT!)
import matplotlib.pyplot as plt
from math import sin,cos
x=[]
y=[]
#Create 41**2 particles in the unit square
for i in range(41):
    for j in range(41):
        x.append(i*0.05-1.0)
        y.append(j*0.05-1.0)
#5 second video at 30 fps = 150 frames
for n in range(150):
    plt.close('all')
    fig, axes = plt.subplots(figsize=(5,5))
    #some cool motion
    for i in range(len(x)):
        x[i]+=0.001*cos(x[i]+3*y[i])
        y[i]+=0.001*sin(6*x[i]-4*y[i])
    #create the scatter plot
    axes.scatter(x,y,s=3,antialiased=True)
    axes.set_xlim(-1.4,1.4)
    axes.set_ylim(-1.4,1.4)
    axes.set_aspect('equal')
    plt.savefig("out/fig%03d.png"%n,dpi=80)

A:

You may be interested in https://github.com/anntzer/mplcairo, a new cairo-based backend for Matplotlib which I originally wrote exactly because I was unhappy with this issue.  It does not display the aforementioned problem, while maintaining reasonable performance.


Q:

Why do I have to state networks twice in docker-compose.yml?

I'm a bit confused. In docker-compose.yml file:
version: "3"
networks:
  proxy:
    external: true
services:
  eliko:
    image: irmscher/eliko:v1
    labels:
      - traefik.backend=eliko
      - traefik.frontend.rule=Host:eliko.bloggercraft.com
      - traefik.docker.network=proxy
    networks:
      - proxy

Why do I have to specify network twice? First time in networks: proxy and 2nd time within the services networks: -proxy?
I actually have created 'proxy' network with docker network create proxy beforehand. I thought networks: within the docker-compose CREATE networks, so I decided to remove it and only leave the network name within my services (eliko) header. But then I have received an error: ERROR: Service "eliko" uses an undefined network "proxy"
So my question is.. what does this exactly do:
networks:
  proxy:
    external: true

Since, as far as I understand, this:
    networks:
      - proxy

connects to a network, so the previous supposed to create the network? What if I create a network with docker network create, is it identical or?
A bit confused here...

A:

The top-level networks stanza is telling docker-compose "these are the networks that exist".  Without that, docker-compose wouldn't know what to do when you try to connect your eliko container to the proxy network.  You'd get this:
ERROR: Service "eliko" uses an undefined network "proxy"

Remember that in the standard case, networks in docker-compose are prefixed with the project name.  If you have a non-external network, like this:
version: "3"
networks:
  proxy:
services:
  eliko:
    image: irmscher/eliko:v1
    labels:
      - traefik.backend=eliko
      - traefik.frontend.rule=Host:eliko.bloggercraft.com
      - traefik.docker.network=proxy
    networks:
      - proxy

Then compose will actually create a network named project_proxy (where project is by default the name of the directory that contains your docker-compose.yml).  It's only because you've declared the network to be external that compose knows you want to use an existing network.


Q:

Admob Issue - Unable to instantiate fragment com.google.android.gms.$PlaceholderFragment

Following the https://developers.google.com/mobile-ads-sdk/docs/admob/android/quick-start tips I've experienced an issue with inflating fragments. Google play services lib is added in libs/ and as a project dependency, also tried with external reference to sdk. Manifest has added meta-data on top of application tag like:
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

AdFragment class is set in main_activity view at the bottom of view..:
<RelativeLayout ... >
...
<fragment
        android:id="@+id/adFragment"
        android:name="com.puzzle.activities.MainActivity$AdFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />
</RelativeLayout>

The AdFragment class is placed in Activity:
public static class AdFragment extends Fragment {

    private AdView mAdView;

    public AdFragment() {
    }

    @Override
    public void onActivityCreated(Bundle bundle) {
        super.onActivityCreated(bundle);

        // Gets the ad view defined in layout/ad_fragment.xml with ad unit
        // ID set in
        // values/strings.xml.
        mAdView = (AdView) getView().findViewById(R.id.adView);

        // Create an ad request. Check logcat output for the hashed device
        // ID to
        // get test ads on a physical device. e.g.
        // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
        AdRequest adRequest = new AdRequest.Builder().addTestDevice(
                AdRequest.DEVICE_ID_EMULATOR).build();

        // Start loading the ad in the background.
        mAdView.loadAd(adRequest);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_admob, container, false);
    }

    /** Called when leaving the activity */
    @Override
    public void onPause() {
        if (mAdView != null) {
            mAdView.pause();
        }
        super.onPause();
    }

    /** Called when returning to the activity */
    @Override
    public void onResume() {
        super.onResume();
        if (mAdView != null) {
            mAdView.resume();
        }
    }

    /** Called before the activity is destroyed */
    @Override
    public void onDestroy() {
        if (mAdView != null) {
            mAdView.destroy();
        }
        super.onDestroy();
    }

}

AdFragment xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id" >
    </com.google.android.gms.ads.AdView>

</RelativeLayout>

An error output is:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.puzzle/com.puzzle.activities.MainActivity_}: android.view.InflateException: Binary XML file line #43: Error inflating class fragment
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2189)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2216)
    at android.app.ActivityThread.access$600(ActivityThread.java:149)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:153)
    at android.app.ActivityThread.main(ActivityThread.java:5022)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1032)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:790)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #43: Error inflating class fragment
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:261)
    at android.app.Activity.setContentView(Activity.java:1874)
    at com.puzzle.activities.MainActivity_.setContentView(MainActivity_.java:45)
    at com.puzzle.activities.MainActivity_.onCreate(MainActivity_.java:36)
    at android.app.Activity.performCreate(Activity.java:5032)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2153)
    ... 11 more
Caused by: java.lang.ClassCastException: com.puzzle.activities.MainActivity$AdFragment cannot be cast to android.app.Fragment
    at android.app.Fragment.instantiate(Fragment.java:577)
    at android.app.Fragment.instantiate(Fragment.java:552)
    at android.app.Activity.onCreateView(Activity.java:4680)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
    ... 23 more

Appreciate your ideas.

A:

The stacktrace states ClassCastException: com.xx.activities.MainActivity$AdFragment cannot be cast to android.app.Fragment. But there is no reference to this class elsewhere. The description in your Activity layout XML is android:name="com.puzzle.activities.MainActivity$AdFragment". Note the difference in package.
It appears that you are actually loading another layout XML in your Activity than the one you showed us. Check your Activity's onCreate.

AdFragment extends from Fragment.
What is the import for Fragment?
import android.app.Fragment;

or
import android.support.v4.app.Fragment;

I suspect it is the latter and the Activity loading the Fragment extends android.app.Activity when it needs to extends android.support.v4.app.FragentActivity
Essentially you are combining support classes with non-support classes.


Q:

Using git fast-export to export a repo starting at a given commit

I am currently trying to merge the current repo at work with one that was converted from my work's old svn repo. I want the new repo (we'll call it A) to be merged with the current working repo (B).
B is the result of a failed attempt to convert the svn repo to git with the history intact. A is the second attempt. If I just merge B with A, there will be duplicate commits for everything in the old svn repo. I would like to only include the history from B that happened after the last svn commit.
I am looking at git-fast-export, but I haven't found any documentation that would help me. Should I use git-fast-export, or is there a better way? How would I use git-fast-export or something else to do the merge?

A:

If you have only one branch to merge back, then another way would be to use grafts (see "gardening tips -- grafting branches"):

Add B as a remote for A: "remoteB",
find the SHA1 of A representing the SVN repo converted (and from which new commits were done): "SHA1-A",
find the SHA1 of B representing the next commit after the SVN repo converted (that is, the first of the new commits done from the failed SVN conversion): "SHA1-B",
See this example:

You can override parents of a commit in Git using a file called grafts, which needs to reside in .git/info/.
  It consists of several lines with commit hashes separated by a space character, where the first hash is the commit you want to define parents for, and the following hashes are the parents.
Note: you must use full hashes, not abbreviated ones.
To fix the history above, we must define the parents in .git/info/grafts:

SHA1-B SHA1A

Make that graft permanent:
git filter-branch --tag-name-filter cat -- --all

Make a local branch reference the HEAD of B branch you just grafte,.
git branch Bmaster remoteB/master

Merge your two branches (and you can remove the 'remoteB' repo, you don't need it anymore).


Q:

Solr: QueryElevationComponent requires StrField uniqueKeyField error

I recently installed solr. The example index (found at apache-solr-#.#.#\example\solr) seems to work, and, once copied to my solr home directory, I am able to access it through the admin pages. However when I try to implement a new index by replacing the schema.xml content with (taken from here):
<?xml version="1.0" encoding="UTF-8" ?>
  <schema name="example" version="1.2">
  <types>
      <fieldType name="string" class="solr.StrField" sortMissingLast="true" omitNorms="true" />
      <fieldType name="int" class="solr.TrieIntField" precisionStep="0" omitNorms="true" positionIncrementGap="0" />
      <fieldType name="date" class="solr.TrieDateField" omitNorms="true" precisionStep="0" positionIncrementGap="0" />
      <fieldType name="text" class="solr.TextField" positionIncrementGap="100">
          <analyzer type="index">
              <tokenizer class="solr.WhitespaceTokenizerFactory" />
              <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="true" />
              <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0" splitOnCaseChange="1" />
              <filter class="solr.LowerCaseFilterFactory" />
              <filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt" />
          </analyzer>
        <analyzer type="query">
          <tokenizer class="solr.WhitespaceTokenizerFactory" />
          <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true" />
          <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="true" />
          <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="0" catenateNumbers="0" catenateAll="0" splitOnCaseChange="1" />
          <filter class="solr.LowerCaseFilterFactory" />
          <filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt" />
        </analyzer>
      </fieldType>
      </types>
  <fields>
      <field name="fileid" type="int" indexed="true" stored="true" required="true" />
      <field name="doctext" type="text" indexed="true" stored="false" required="false" />
      <field name="title" type="text" indexed="true" stored="false" required="false" />
      <field name="datecreated" type="date" indexed="true" stored="false" />
  </fields>
  <uniqueKey>fileid</uniqueKey>
  <defaultSearchField>doctext</defaultSearchField>
  <solrQueryParser defaultOperator="OR" />
  </schema>

I am receiving a configuration error, which seems to suggest that the uniqueKeyField must be implemented with a StrField type (something I find hard to believe is actually the case?)):
"HTTP Status 500 - Severe errors in solr configuration. ... org.apache.solr.common.SolrException: QueryElevationComponent requires the schema to have a uniqueKeyField implemented using StrField at org.apache.solr.handler.component.QueryElevationComponent.inform(QueryElevationComponent.java:157) at org.apache.solr.core.SolrResourceLoader.inform(SolrResourceLoader.java:508) at..."
My googling has turned up very little to help, so I am hoping there might be someone around here who might have come across this issue and/or have some ideas how to resolve it?
Thanks in advance for any advice, Bea.

A:

Yes, at the moment QueryElevationComponent  requires a string unique key. This limitation is documented in the Solr wiki.
Here's the issue in the project JIRA.


Q:

Nginx rewrites for URL that must have a dash

This one allows everything with .html extension that contains no slashes:
rewrite ^/([^/]+).html$ ...

I need to add another catch to it: URL must contain at least one dash, then it can be rewritten.
How to do that?

A:

Just use logic. Word with at least one dash could be expressed as two words with dash between them. So solution is simple:
rewrite ^/([^/]+-[^/]+)\.html$.

Also you forgot to escape dot (.)  so your regexp also match url /somesstrangehtml


Q:

Erro ao gerar XML

Fiz um sistema em PHP para exibir arquivo XML, mas está dando o seguinte erro:
This page contains the following errors:
error on line 29 at column 1: Extra content at the end of the document
Below is a rendering of the page up to the first error.
(A imagem pra que vejam que até o que é do banco ele me trás):

Meu arquivo index.php:
<?php

    include("config.php");
    include("conexao.php");

    $sql = 'select id, descricao, margem, custo, estoque from produtos';

    $resultado = mysqli_query(DBConnect(), $sql) or die (mysqli_error(DBConnect()));

    $xml = new DOMDocument('1.0', 'UTF-8');
    $xml->preserveWhiteSpace = false;
    $xml->formatOutput = true;

    $produtos = $xml->createElement('Produtos');

    while($dados = mysqli_fetch_object($resultado))
    {
        $item = $xml->createElement('Item');
        $descricao = $xml->createElement('descricao', $dados->descricao);
        $margem = $xml->createElement('margem', $dados->margem);
        $custo = $xml->createElement('custo', $dados->custo);
        $estoque = $xml->createElement('estoque', $dados->estoque);

        $item->appendChild($descricao);
        $item->appendChild($margem);
        $item->appendChild($custo);
        $item->appendChild($estoque);

        $produtos->appendChild($item);
    }

    $xml->appendChild($produtos);

    header('content-type: text/xml');
    print $xml->saveXML();

?>

<!DOCTYPE html>
<html>

    <head>

        <title> Testando conexão </title>

    </head>

    <body>

        <?php

            $teste = DBConnect();

            if($teste)
            {
                echo "Conectado com sucesso!";
            }
            else
            {
                echo "Conexão falhou!";
            }

        ?>

    </body>

</html>

Meu arquivo config.php:
<?php

    define('HOSTNAME', '127.0.0.1');
    define('USERNAME', 'root');
    define('PASSWORD', null);
    define('DATABASE', 'cadastro');
    define('CHARSET' , 'utf8');

?>

Meu arquivo conexao.php:
<?php

    function DBConnect()
    {
        $sql = mysqli_connect(HOSTNAME, USERNAME, PASSWORD, DATABASE) or die(mysqli_error());
        mysqli_set_charset($sql, CHARSET) or die(mysqli_error($sql));

        return $sql;
    }

?>

A:

Como a própria descrição do erro informa, você está inserindo informações alheias extras após criar o XML a partir da linha <!DOCTYPE html>.
Para parsear o XML corretamente, remova tudo que estiver da linha <!DOCTYPE html> para baixo. Se remover a linha header('content-type: text/xml'); o erro some, mas você terá como resultado uma página HTML normal (embora inválida).


Q:

how to speed up map insertion?

Looks like I finally improved a little map insertion speed (sorting before inserting). What do you think about these results ? Are there anymore optimisations ?
#include <map>
#include <iostream>
#include <algorithm>

int main (int argc, char* argv []) {
  //a map<size_t, size_t> random initilisation
  std::map<size_t, size_t> m0, m1;
  {
     std::vector<std::pair<size_t, size_t> > t (10000, std::pair<size_t, size_t> ((size_t) -1, (size_t) -1));
     std::vector<std::pair<size_t, size_t> >::iterator i (t.begin ());
     for (; i != t.end (); ++i) {
       i->first = rand () % 1000000;
       i->second = rand () %1;
     }
     m0.insert (t.begin (), t.end ());
     m1 = m0;
   }
   //vins :
   std::vector<std::pair<size_t, size_t> > vins (10000, std::pair<size_t, size_t> (0, 0));
   {
     std::vector<std::pair<size_t, size_t> >::iterator i (vins.begin ());
     for (; i != vins.end (); ++i) {
       i->first = rand () % 1000000;
       i->second = rand () %1;
     }
   }
   //normal insertion
   clock_t t0 (clock ()), t1 (t0);
   {
     m0.insert (vins.begin (), vins.end ());
   }
   t1 = clock ();
   std::cout << "normal insertion took " << (size_t) (t1 -  t0) << " ticks" << std::endl;
   //sort + hint insertion
   t0 = t1;
   {
     std::sort (vins.begin (), vins.end (), [] (std::pair<size_t, size_t>& p0, std::pair<size_t, size_t>& p1)->bool {
       return (p0.first < p1.first ? true:false);
     });
     std::map<size_t, size_t>::iterator ihint (m1.begin ());
     //std::vector<std::pair<size_t, size_t> >::iterator i (vins.begin ());
     //imroved and more C++11 solution
     std::for_each (vins.begin (), vins.end (), [&ihint, &m1] (std::pair<size_t, size_t>& p) {
       ihint = m1.insert (ihint, p);
     });
   }
   t1 = clock ();
   std::cout << "insertion after sorting took " << (size_t) (t1 - t0) << " ticks" << std::endl;
   if (m0 != m1) std::cout << "but insertion is nok" << std::endl;
   else std::cout << "and insertion is ok" << std::endl;
}

A result on a Lenovo Think Centre :
insertion took 2355 ticks
sort then insertion took 1706 ticks
and insertion is ok

A:

If you don't need your items to be ordered, then using std::unordered_map  is usually a better choice than std::map - it uses a hashtable rather than a balanced tree in most implementations, which means that operations are on average O(1) rather than O(log n). In addition, it can have a performance boost from cache-locality, as the underlying data structure (array) is usually more cache-friendly than a tree.
Enabling -O3 (or similar optimisation level) might increase the performance of your code, but is unlikely to effect the performance of the map's insertion/find operations (as it's already been compiled). Bear in mind that using -Ofast means the compiler no longer needs to strictly adhere to the standards, which is usually not a great idea - use it if performance is critical and you've checked your code works as expected with it, but usually -O3 is enough.

On my machine (Debian, g++ 6.3.0), using a few runs and taking rough averages:
 Configuration             Normal Hint Insertion   Hint Insertion
 ------------------------- ----------------------- ----------------
  std::map,           -O0                    9750             9200
  std::map,           -O3                    8000             4250
  std::unordered_map, -O0                    7000             9700
  std::unordered_map, -O3                    4200             5000


Q:

Connect sharepoint management shell with site collection admin in 1 site only and remove content type under in _Hidden Group

how connect in sharepoint management shell of 1 site only without an access in https://org-admin.sharepoint.com, I have an site collection admin in 1 site of this sharepoint and i need to connect it in sharepoint management shell to remove content type under in _Hidden Group thanks.

A:

Yes, you could do that.
Demo PowerShell code for your reference:
$adminUPN="xxx@xxx.onmicrosoft.com"

$userCredential = Get-Credential -UserName $adminUPN -Message "xxx"

Connect-PnPOnline -Url https://xxx.sharepoint.com/sites/wendy -Credentials $userCredential

#Get content type from _Hidden group
Get-PnPContentType|? { $_.Group -eq '_Hidden' }
#remove "ContentType1" content type
Remove-PnPContentType -Identity "ContentType1" -Force

Get-PnPContentType|? { $_.Group -eq '_Hidden' }

Note: $adminUPN could be just the site collection administrator of site collection, in my test, it could work well.
Result:


Q:

Logging in Django

I'm trying to figure out logging in Django (checking out Python logging itself for the first time too for that matter).
I have the following in my settings.py
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/home/afzalsh/logs/debug.log',
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

This is the exact code as what Django documentation has as the first example.
Then I have a log message in a class based view.
import logging
.
.
.
class StationHome(View):
    .
    .
    .
    def post(self,request, pk):
        station = Station.objects.get(pk=pk)
        form = StationForm(request.POST, instance=station)
        if form.is_valid():
            logger = logging.getLogger(__name__)
            logger.error("Yep!")
            form.save()
            return HttpResponseRedirect(reverse("home_station",
                                                kwargs={'pk':pk},
                                            )
                                    )
        else:
            return HttpResponse("Form Invalid")
.
.
.

The debug.log file has got created but it doesn't get populated with any message on going through the particular code. The expected process do happen.

A:

You've requested the logger associated with __name__, so you get one named the same as the current Python module. However, the only one you've actually configured is "django.request". You should use that in your call to getLogger instead.


Q:

check if sorl-thumbnail has already cached an image

I'm running a django app with sorl-thumbnail and a lot of remote images (sorl loads image from external source).
Ideally I'd like to check if sorl has already cached an image in my template, and if not, load the image with ajax.
Reading the doc I found a exist method which seems to always return true
{% thumbnail item.image "160x200" crop="center" as im %}
    {% if im.exists %}
        <img src="{{ im.url }}">
    {% else %}
        <!-- load image with ajax -->
    {% endif %}
{% endthumbnail %}

Is there a method I can use to check if a image has already been cached in a template?

A:

I ended up using a method for my model.
This is some dirty raw sql using expensive %LIKE%.
def has_image_cached(self):
        from django.db import connection
        cursor = connection.cursor()
        cursor.execute("SELECT * FROM thumbnail_kvstore WHERE value LIKE %s",['%'+self.imageurl+'%'])
        row = cursor.fetchone()
        if row is None:
            return False
        return True


Q:

popToRootViewController is crashing when more than two view controllers are being popped

I have a strange situation with calling popToRootViewController on my navigation controller. If there are only one or two view controllers on top of the root to pop, it works just fine. If there are more than two view controllers on top of the root on the stack, it crashes. I've looked around all of the popToRootViewController complaints on this site and others and have tried setting animated to NO. This does not help. I've also seen some people citing an issue with iOS 3.0 with popToRootViewController on very old posts, but I am developing on iOS 4.0.
To be more explicit, if my stack looks like this: RootVC --> VC1 --> VC2. And then I do
[self.navigationController popToRootViewControllerAnimated:NO];

from VC2, it pops to the root as expected. However, if my stack looks like this: RootVC --> VC1 --> VC2 --> VC3 and then do the same exact thing from VC3, it crashes. Any clues as to what could be the problem? I apologize if this is a really dumb question. I'm a newcomer to iPhone developement.
I am using the following code for pushing each of my views onto the stack:
-(void)pushViewNamed:(NSString *)viewname
{
    iOvulate_3AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

    NSString *viewControllerName=viewname;
    UIViewController *targetViewController=[[NSClassFromString(viewControllerName) alloc] initWithNibName:viewControllerName bundle:nil];

    [self.navigationController pushViewController:targetViewController animated:YES];

    if ( [appDelegate.pdbool intValue] == 0 )
    {
        [viewControllerName release];
        [targetViewController release];
    }
}

I put the conditional release there because it solved a different problem I was having where IBActions on any view beyond the third view on the stack weren't working--as in touching inside a button was causing a message to be sent to a nil object that was supposed to be the view controller (or something like that?) and causing EXC_BAD_ACCESS error. Could this "fix" be causing the memory management problems you speak of?

A:

Why don't you try looking at each of the View Controllers on your nav stack? Use:
[self.navigationController.viewControllers objectAtIndex:index];

To see the view controller at the corresponding index. If they appear all fine, then it must be something else in your code that is causing the crash. Hope that helps!


Q:

Function Now not working properly on windows lock

I've build an alert system which fires every 30 mins 24/7. It fires at the right time even when windows is locked but im getting a hard time taking the date and hour.
I'm using Date = Now but instead taking the real time it is showing something totally different like this:

As you can see on the screenshot, on the pop up says 27/08/2138 13:30:00 when it should be 29/04/2019 13:00:00
This only happens if the computer is locked. Any suggestion or workaround?
Here is the code if you need it, even though the code works fine:
Sub Actualizar_Online()

    Dim Inicio As Long, Fin As Long, Fecha As Date, Hora As Date

    AhorroMemoria True
    Declaraciones
    Hora = Now
    If Minute(Hora) > 30 Then
        Hora = TimeSerial(Hour(Hora), 0, 0)
    ElseIf Minute(Hora) < 30 Then
        Hora = TimeSerial(Hour(Hora) - 1, 30, 0)
    End If
    HoraInforme = Hora + Date
    Fecha = Date
    CargarDia
    With wsDB
        Inicio = .Cells.Find("SUR").Row
        Fin = .Cells.Find(Date - 1, After:=.Cells(Inicio, 1)).Row
        If Inicio <> Fin Then .Rows(Inicio & ":" & Fin - 1).Delete
        .Rows(.Cells(.Rows.Count, 1).End(xlUp).Row + 1 & ":" & .Rows.Count).Delete
    End With
    wb.RefreshAll
    Segmentaciones

    wsAlerta.Cells(2, 1) = HoraInforme
    wsAlerta.Calculate
    ComprobarMail
    AhorroMemoria False

End Sub

A:

This may not be the bug, but it is a bug with similar output:
Hora = Now
If Minute(Hora) > 30 Then
    Hora = TimeSerial(Hour(Hora), 0, 0)
ElseIf Minute(Hora) < 30 Then
    Hora = TimeSerial(Hour(Hora) - 1, 30, 0)
End If

The Now function returns the Date + Time.  Your code will trim Hora to just time (rounded down to the nearest half-hour) if the minutes are >30 or < 30 - however, it will do nothing if the minutes are exactly 30.  Then, you are adding the Date on again
   Date    |  Time |       Now        |        Hora      |   HoraInforme
29/04/2019 | 11:04 | 29/04/2019 11:04 |       11:00      | 29/04/2019 11:04
29/04/2019 | 12:47 | 29/04/2019 12:47 |       12:30      | 29/04/2019 12:30
29/04/2019 | 13:30 | 29/04/2019 13:30 | 29/04/2019 13:30 | 27/08/2138 13:30

Change your If Minute(Hora) > 30 to If Minute(Hora) >= 30, and change Hora = Now to Hora = Time