Q:

Unable to get vertical scroll bars in an WPF TextBlock

I'm presenting text in a wpf TextBlock control (.Net 3.5). The content of the textblock varies depending on what the user selects in a list box. The text wraps, so I don't need an horizontal scroll bar. However, there is often more text than the amount the window can display, so I need a vertical scroll bar.
As I started searching I quickly found that the answer is to wrap the TextBlock in a ScrollViewer. However, It Does Not Work (TM) and I'm hoping someone can help me work out why.
This is the structure of the UI code:
<Window x:Class=..>
    <StackPanel>
        <ListBox HorizontalAlignment="Stretch"
                 VerticalAlignment="Top"  Height="200"
                 SelectionChanged="listbox_changed" SelectionMode="Single">
        </ListBox>
        <Button Click="Select_clicked">Select</Button>
        <ScrollViewer VerticalScrollBarVisibility="Auto">
            <TextBlock Name="textblock" TextWrapping="Wrap"/>
        </ScrollViewer>
    </StackPanel>
</Window>

When the user selects an item in the list box, some text associated with this item is presented in the TextBlock. I would have thought that the code as it stands should have been all that's required, but it never provides me with a scroll bar.
Searching and experimenting have given me two clues: the root of the problem might be related to me updating the content of the TextBlock dynamically, and that the TextBlock does not resize itself based on the new content. I found a posting that seemed relevant that said that by setting the Height of the TextBlock to its ActualHeight (after having changed its content), it would work. But it didn't (I can see no effect of this).
Second, if I set the height (during design time) of the ScrollViewer, then I do get a vertical scroll bar. For instance, if I set it to 300 in the xaml above, the result is almost good in that the window as first opened contains a TextBlock with a vertical scroll bar when (and only when) I need it. But if I make the window larger (resizing it with the mouse during runtime), the ScrollViewer does not exploit the new window size and instead keeps its height as per the xaml which of course won't do.
Hopefully, I've just overlooked something obvious..
Thanks!

A:

Because your ScrollViewer is in a StackPanel it will be given as much vertical space as it needs to display it's content.
You would need to use a parent panel that restricts the vertical space, like DockPanel or Grid.
<DockPanel>
    <ListBox DockPanel.Dock="Top" HorizontalAlignment="Stretch"
             VerticalAlignment="Top"  Height="200"
             SelectionChanged="listbox_changed" SelectionMode="Single">
    </ListBox>
    <Button DockPanel.Dock="Top" Click="Select_clicked">Select</Button>
    <ScrollViewer VerticalScrollBarVisibility="Auto">
        <TextBlock Name="textblock" TextWrapping="Wrap"/>
    </ScrollViewer>
</DockPanel>


Q:

Is it possible to render MSAA to RGBA32F texture in WebGL2?

Firstly, I have msaa working good, like this(abstract):
    sceneFramebuffer = new MultisampleRenderbuffer({
        msaa: 8,
        internalFormat: "RGBA8"
    });

    blitFramebuffer = new Framebuffer({
        internalFormat: "RGBA8",
        format: "RGBA",
        type: "UNSIGNED_INT"
    });

   Draw scene with sceneFramebuffer;

   sceneFramebuffer.blit(blitFramebuffer);

   Draw blitFramebuffer on the screen quad;

Now, I want to render sceneFramebuffer to RGBA32F for HDR purpose, and when I try this configuration:
sceneFramebuffer = new MultisampleRenderbuffer({
    msaa: 8
    internalFormat: "RGBA32F"
});

blitFramebuffer = new Framebuffer({
    internalFormat: "RGBA32F",
    format: "RGBA",
    type: "FLOAT"
});

I get this:
GL ERROR :GL_INVALID_OPERATION : glBlitFramebufferCHROMIUM: src and dst formats differ for color
But, when I set msaa: 0 for sceneFramebuffer it shows my scene but no msaa antialiasing ofcourse.
Is it possible somehow to combine multisampling and float output, which I'd use for hdr?
Thanks!

A:

Seem to work for me

function main() {
  const gl = document.querySelector('canvas').getContext('webgl2');
  if (!gl) {
    return alert('need webgl2');
  }
  // without this we can't render to RGBA32F
  if (!gl.getExtension('EXT_color_buffer_float')) {
    return alert('need EXT_color_buffer_float');
  }
  // just guessing without this we can't downsample
  if (!gl.getExtension('OES_texture_float_linear')) {
    return alert('need OES_texture_float_linear');
  }

  const msFB = gl.createFramebuffer();
  gl.bindFramebuffer(gl.FRAMEBUFFER, msFB);
  const msRB = gl.createRenderbuffer();
  gl.bindRenderbuffer(gl.RENDERBUFFER, msRB);
  const samples = 4;
  const internalFormat = gl.RGBA32F;
  const width = 16;
  const height = 16;
  gl.renderbufferStorageMultisample(
     gl.RENDERBUFFER, samples, internalFormat, width, height);
  gl.framebufferRenderbuffer(
     gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msRB);
  checkFramebuffer(gl);

  gl.clearColor(1,0,0,1);
  gl.clear(gl.COLOR_BUFFER_BIT);

  const texFB = gl.createFramebuffer();
  gl.bindFramebuffer(gl.FRAMEBUFFER, texFB);
  const tex = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, tex);
  const levels = 1;
  gl.texStorage2D(gl.TEXTURE_2D, levels, internalFormat, width, height);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.framebufferTexture2D(
      gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);

  checkFramebuffer(gl);

  // check before
  checkPixel(gl, 'before blit')

  gl.bindFramebuffer(gl.READ_FRAMEBUFFER, msFB);
  gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texFB);
  gl.blitFramebuffer(
     0, 0, width, height,
     0, 0, width, height,
     gl.COLOR_BUFFER_BIT, gl.LINEAR);

  console.log('ERROR?:', glEnumToString(gl, gl.getError()));

  gl.bindFramebuffer(gl.FRAMEBUFFER, texFB);
  checkPixel(gl, 'after blit:');
}

function checkFramebuffer(gl) {
  const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  if (status !== gl.FRAMEBUFFER_COMPLETE) {
    console.error(glEnumToString(gl, status));
  }
}

function checkPixel(gl, msg) {
  const pixel = new Float32Array(4);
  gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.FLOAT, pixel);
  console.log(msg, Array.from(pixel).join(', '));
}

function glEnumToString(gl, v) {
  const hits = [];
  for (const key in gl) {
    if (gl[key] === v) {
      hits.push(key);
    }
  }
  return hits.length ? hits.join(' | ') : `0x${v.toString(16)}`;
}

main();
<canvas></canvas>

Just to make it clear it has nothing to do with texStorage2D

function main() {
  const gl = document.querySelector('canvas').getContext('webgl2');
  if (!gl) {
    return alert('need webgl2');
  }
  // without this we can't render to RGBA32F
  if (!gl.getExtension('EXT_color_buffer_float')) {
    return alert('need EXT_color_buffer_float');
  }
  // just guessing without this we can't downsample
  if (!gl.getExtension('OES_texture_float_linear')) {
    return alert('need OES_texture_float_linear');
  }

  const msFB = gl.createFramebuffer();
  gl.bindFramebuffer(gl.FRAMEBUFFER, msFB);
  const msRB = gl.createRenderbuffer();
  gl.bindRenderbuffer(gl.RENDERBUFFER, msRB);
  const samples = 4;
  const internalFormat = gl.RGBA32F;
  const width = 16;
  const height = 16;
  gl.renderbufferStorageMultisample(
     gl.RENDERBUFFER, samples, internalFormat, width, height);
  gl.framebufferRenderbuffer(
     gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msRB);
  checkFramebuffer(gl);

  gl.clearColor(1,0,0,1);
  gl.clear(gl.COLOR_BUFFER_BIT);

  const texFB = gl.createFramebuffer();
  gl.bindFramebuffer(gl.FRAMEBUFFER, texFB);
  const tex = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, tex);
  const level = 0;
  gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, width, height, 0,
                gl.RGBA, gl.FLOAT, null);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.framebufferTexture2D(
      gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);

  checkFramebuffer(gl);

  // check before
  checkPixel(gl, 'before blit')

  gl.bindFramebuffer(gl.READ_FRAMEBUFFER, msFB);
  gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texFB);
  gl.blitFramebuffer(
     0, 0, width, height,
     0, 0, width, height,
     gl.COLOR_BUFFER_BIT, gl.LINEAR);

  console.log('ERROR?:', glEnumToString(gl, gl.getError()));

  gl.bindFramebuffer(gl.FRAMEBUFFER, texFB);
  checkPixel(gl, 'after blit:');
}

function checkFramebuffer(gl) {
  const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  if (status !== gl.FRAMEBUFFER_COMPLETE) {
    console.error(glEnumToString(gl, status));
  }
}

function checkPixel(gl, msg) {
  const pixel = new Float32Array(4);
  gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.FLOAT, pixel);
  console.log(msg, Array.from(pixel).join(', '));
}

function glEnumToString(gl, v) {
  const hits = [];
  for (const key in gl) {
    if (gl[key] === v) {
      hits.push(key);
    }
  }
  return hits.length ? hits.join(' | ') : `0x${v.toString(16)}`;
}

main();
<canvas></canvas>


Q:

Querying XML data with SQL

I have a log table with XML column. I studied several examples of querying XML but they don't match my needs.
Id   TimeStamp            Message    Properties
------------------------------------------------------------------------------
1    2015-10-27 08:45:38  Text       <properties><property key="time">23.10.2015 15:00:40</property><property key="interceptors">False</property></properties>
2    2015-10-27 09:21:09  Text       <properties><property key="Product">Azure</property><property key="Source">Azure Infrastructure</property></properties>
3    2015-10-27 16:51:32  Text       <properties><property key="Product">Azure</property><property key="Source">Azure Infrastructure</property><property key="Uptime">00:00:27.3874982</property></properties>
4    2015-10-28 11:03:25  Text       <properties><property key="Uptime">00:19:21.4729461</property></properties>

I want to have a result set of all node values where the property node has a key of 'uptime'. The result set could look like:
Id   Uptime
-----------------
3    00:00:27.3874982
4    00:19:21.4729461

A:

Below is one method which uses xquery expression with an attribute filter along with a CTE to avoid repeating the expression:
WITH Uptimes AS (
    SELECT
          Id
        , Properties.value('(/properties/property[@key="Uptime"])[1]', 'time(7)') AS Uptime
    FROM dbo.test
    )
SELECT Id, Uptime
FROM Uptimes
WHERE Uptime IS NOT NULL;


Q:

Error generando clases con xsd

La Agencia Tributaria española (AEAT) ha publicado una serie de xsd para el nuevo sistema de Suministro Inmediato de Información (SII) que entrará en vigor a partir de Julio de 2017. En otras ocasiones como con la entrada en vigor del SEPA he generado mis clases en .net a partir de estos ficheros.
En esta ocasión han publicado los diferentes esquemas en http://www.agenciatributaria.es/AEAT.internet/Inicio/Ayuda/Modelos__Procedimientos_y_Servicios/Ayuda_P_G417____IVA__Llevanza_de_libros_registro__SII_/Ayuda_tecnica/Informacion_tecnica_SII/Esquemas/Esquemas.shtml.
Al intentar generarlos con xsd.exe obtengo varios errores:

Generando SuministroInformacion.xsd (Donde
D:\Proyectos\IDI\S.I.I\v1.0.0\Documentacion\Esquemas\ es la ruta
local donde tengo el .xsd)
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0
Tools>xsd.exe /c /l:VB
D:\Proyectos\IDI\S.I.I\v1.0.0\Documentacion\Esquemas\SuministroInformacion.xsd
Obtengo el error
Microsoft (R) Xml Schemas/DataTypes support utility [Microsoft (R)
.NET Framework, Version 4.0.30319.18020] Copyright (C) Microsoft
Corporation. All rights reserved. Warning: cannot generate classes
because no top-level elements with complex type were found.

No se muy bien a que se refiere este error. Lo que si que he conseguido es importando el WSDL que también proporciona la Agencia Tributaria y que tiene referenciados los .xsd, usarlos para generar las clases.
No se muy bien que estoy haciendo mal.

A:

El problema es que xsd.exe necesita que se definan elementos para cada tipo en el xsd. Podrias hacerlo a mano pero si son muchas clases es un poco laborioso. Yo te recomiendo que utilices Xsd2Code. Es una extensión para visual studio (2008 o 2010).
Una vez instalada abres el visual studio, añades el archivo xsd al proyecto, y con el boton derecho pulsas en el. Seleccionas "Run xsd2code Generation", Generate y te genera una clase con todos los tipos definidos.
Espero que te sirva.


Q:

ASP.Net MVC and IIS 7 using Virtual Directory to a config file

I have an MVC application that is shared by many websites in IIS, but each needs it's own app settings.  In my Web.Config, I have the following:
<appSettings file="Config/AppSettings.config" />

Then, in IIS I set up virtual directories for each site's separate file.
To my astonishment, this did not work, but did when I tried it without using a virtual directory.  Any ideas?
I saw this post IIS Config file in virtual directory
which was very similar, but did not offer the response I was looking for.
I'm also open to other ways to accomplish the same thing; if such a solution exists.

A:

It's not possible to use a virtual directory (or even files outside of the current website; only the current folder, or a sub-folder) in 'appSettings file=...'.
One possible way to share setting across projects would be to do it at build-time - either by coping it in, or using a Linked File in VS to have it copied to the folder on publish.
If you really need this functionality on the server, you could try (though I can't say how well it would work) a Junction.


Q:

Training own model and adding new entities with spacy

I have been trying to train a model with the same method as #887 is using, just for a test case.
I have a question, what would be the best format for a training corpus to import in spacy. I have a text-file with a list of of entities that requires new entities for tagging.
Let me explain my case, I follow the update.training script like this:
nlp = spacy.load('en_core_web_md', entity=False, parser=False)

ner= EntityRecognizer(nlp.vocab, entity_types=['FINANCE'])

for itn in range(5):
    random.shuffle(train_data)
    for raw_text, entity_offsets in train_data:
        doc = nlp.make_doc(raw_text)
        gold = GoldParse(doc, entities=entity_offsets)

        nlp.tagger(doc)
        ner.update(doc, gold)
ner.model.end_training()

I add my training data as entity_offsets:
train_data = [
    ('Monetary contracts are financial instruments between parties', [(23, 44, 'FINANCE')])
]

This is working fine for the one example and new entity tag. Obviously I want to be able to add more than one example. The Idea is to create a text file with tagged sentences, the question is what format does spacy needs for training data, should I keep with entity_offset from the examples (this will be a very tedious task for 1000's of sentences) or is there another method to prepare the file, like:
financial instruments   FINANCE
contracts   FINANCE
Product OBJ
of O
Microsoft ORG
etc ...

And how can I pass the corpus in spcay using the mentioned method? Do I have to use the new created model or can I add the new entities to the old model, how can this be achieved?
UPDATE
I managed to import a file with training data that would be recognized by the training method described above.
The list will look like this:
Financial instruments can be real or virtual documents, 0 21 FINANCE
The number of units of the financial instrument, 27 47 FINANCE
or the number of derivative contracts in the transaction, 17 37 BANKING
Date and time when the transaction was executed, 23 34 ORDER
...

But the training is not performing well, I supposed this is due to the small training data. I get all entries in the test corpus tagged as FINANCE or all tagged by BANKING. How big does my train data need to be to get a better performance?
I guess I will have to annotate a bigger corpus for may training data. Can this be done in a different way?
What algorithm is behind the spacy Named Entity Recognizer?
Thanks for any help.
My Environment
spaCy version: 1.7.3
Platform: Windows-7-6.1.7601-SP1
Python version: 3.6.0
Installed models: en, en_core_web_md

A:

To provide training examples to the entity recogniser, you'll first need to create an instance of the GoldParse class. You can specify your annotations in a stand-off format or as token tags.
import spacy
import random
from spacy.gold import GoldParse
from spacy.language import EntityRecognizer

train_data = [
    ('Who is Chaka Khan?', [(7, 17, 'PERSON')]),
    ('I like London and Berlin.', [(7, 13, 'LOC'), (18, 24, 'LOC')])
]

nlp = spacy.load('en', entity=False, parser=False)
ner = EntityRecognizer(nlp.vocab, entity_types=['PERSON', 'LOC'])

for itn in range(5):
    random.shuffle(train_data)
    for raw_text, entity_offsets in train_data:
        doc = nlp.make_doc(raw_text)
        gold = GoldParse(doc, entities=entity_offsets)

        nlp.tagger(doc)
        ner.update(doc, gold)
ner.model.end_training()

Or to simplify this you can try this code
doc = Doc(nlp.vocab, [u'rats', u'make', u'good', u'pets'])
gold = GoldParse(doc, [u'U-ANIMAL', u'O', u'O', u'O'])
ner = EntityRecognizer(nlp.vocab, entity_types=['ANIMAL'])
ner.update(doc, gold)


Q:

What are the advantages/disadvantages on passing arguments to the AsyncTask constructor?

I am using AsyncTask and wondering what are the implications of passing the arguments to the constructor instead of passing them directly on the execute() call to the doInBackground(...) method, for example:
Call:
new SomeTask(bitmap, integer, "somestring").execute();

Class:
public class SomeTask extends AsyncTask<Void, Void, String> {
private String string;
private Bitmap image;
private int integer;

public SomeTask (Bitmap bmp, int someint, String s){
    this.image = bmp;
    this.string = s;
    this.integer = someint;
}

protected String doInBackground(Void... params) {
    // whatever
    return "string";
}

@Override
protected void onPostExecute(String result){
    // whatever
}

}
What are the advantages/disadvantages regarding design, elegance, reuse and performance?
Thank you.

A:

What are the advantages/disadvantages regarding design, ellegance, reuse and performance??

Use parameters to execute() if you will have an arbitrary number of the same type (e.g., several URLs as Strings that you want the task to download).
Use constructor parameters if you will have several parameters of distinct types, so you can take advantage of Java's compile-time type safety.
If you will have just one object to pass in (or none), both approaches are pretty much equivalent.


Q:

unknown module "child_process" in react native

React Native v0.23.0
Node v5.11.0
Windows 10 10586 (I try on OSX and get the same error)
I try to write var cp = require('child_process'); in react native, but get an error said Requiring unknown module "child_process". How to fixed it?

A:

Well, I got answer at this issue https://github.com/facebook/react-native/issues/7170


Q:

Python callable() built-in function returns false for an instance method

I am using Python version 3.6.
class Pen:
    def write(self):
        print("Writing")

def __call__(self,p):
    print("calling a pen object")

pen1 = Pen()

print(callable(pen1.write()))

The above Python example returns the following output
Writing
False

Why this behaviour?
Is an instance method not a callable in Python?

A:

pen1.write is callable, but not the results pen1.write(). This will call the method and pass its results (None) to the callable method as the argument. None is not callable.
Try:
print(callable(pen1.write))


Q:

What's the difference between "transfer" and "transference"?

Does their use depend on the context? Or are both words utterly equivalents?

A:

They are not the same. Transfer means generally to move something from one place to another. The thing can be anything that can be moved from place to place.


Q:

How to add dynamic height to a div along with its html code using jquery?

Here's the code not working while attempting to add the html code along with programmatic height..
$("table").after("

");

The div gets added but without the programmatic height.

A:

You are posting invalid html :
$("table").after('

');

JSFiddle


Q:

How to distribute SQL database with application?

I'm developing a WPF desktop application, and the database currently resides in SQL Server Express 2012. The app is undergoing acceptance testing, and periodically I have to backup my database and restore it on the tester's PC. This is setting alarm bells ringing that distribution is going to be a pain when we come to start working with customers - I don't like the idea of them having to use SSMS.
I wondered if there was any way to distribute the mdf file and have my application connect to that "directly"? I've seen examples of connection strings that specify an MDF file/path, and wondered if it was really that simple or does it still need attaching in SSMS first? (I'm guessing so, otherwise how would you configure things like users and roles?).

A:

Most applications I've encountered run SQL CREATE scripts during the installation process. I'd prefer that way, because when you will have to change your schema some time in the future (and you will), you will have to do something similar, because you cannot exchange the old MDF (with your users' data) against an empty updated one.


Q:

how to access npm registry data from my node app

I want to access npm registry from my nodejs app and retrieve say module/package name and git url for each of the modules/packages. How do I go about getting this npm registry data ? Do we have some existing modules that would help me do that ?
Any help is appreciated.

A:

Here's how I programmatically use the system copy of npm (instead of installing a separate copy of npm just to use it programmatically):
function loadNpm(cb) {
  require('child_process').exec('npm', function(err, stdout, stderr) {
    if (err) return cb(err);
    var m = /npm@[^ ]+ (.+)\n/i.exec(stdout);
    if (!m)
      return cb(new Error('Unable to find path in npm help message'));
    cb(undefined, require(m[1]));
  });
}

// usage ...
loadNpm(function(err, npm) {
  if (err) throw err;
  // load() is required before using npm API
  npm.load(function(err, npm) {
    if (err) throw err;
    // e.g. npm.search('ssh', true, function(err, results) { console.dir(results); });
  });
});


Q:

Parent and Child Shell Script Problem

I have two scripts parent.sh and child.sh. There is a variable in parent.sh which needs to be accessed by the child process. I have achieved this by exporting the variable in the parent script and the variable is available to the child process?
Is there any way that child can modify the value of the export variable defined in parent shell?
Parent.sh
#!/bin/bash
export g_var=2
./child.sh

child.sh
#!/bin/bash
g_var=`expr $g_var + 1 `   #This modification is available in child shell only.

A:

Most shells support the source built-in, which executes a script in the current shell rather than spawning a new one. In bash and a few others, the command . is equivalent to source. I haven't read it, but the POSIX shell standard might require the two to be equivalent. Try:
#!/bin/bash
export g_var=2
. ./child.sh

"child.sh" is the same as your example.


Q:

RewriteCond RequestURI why RegEx doesn't work?

i have a working RewriteCond like:
RequestURL:
http://www.myserver.com/images/gallery/summer/2013/2013-07-07/thumbs/001.jpg
RewriteCond %{REQUEST_URI} !images/gallery/summer/2013/*
RewriteRule ^images/gallery/summer/(.*)$ http://xyz.s3.amazonaws.com/$1 [P]

This works fine and the image is pulled from Amazon S3.
But why the heck a RegEx doesn't work in the RewriteCond like:
RewriteCond %{REQUEST_URI} !^images/gallery/summer/2013/(.*)$

It's just i want to understand why the above code works and the other doesn't?
THANK YOU

A:

REQUEST_URI begins with /, so instead of this one:
RewriteCond %{REQUEST_URI} !^images/gallery/summer/2013/(.*)$

try this:
RewriteCond %{REQUEST_URI} !^/images/gallery/summer/2013/(.*)$


Q:

How to get the SQL String From JPQLQuery

I'm using EclipseLink.
I've a JPQLquery and I want to get the sql String..
Now I'm doing in this way:
EJBQueryImpl qi = (EJBQueryImpl)jpqlQuery;
String sqlQueryString = qi.getDatabaseQuery().getSQLString();

The problem is that in the sqlQueryString the constant are replaced with ?
I've tried to get the values navigating the expressions trees (getSelectionCriteria() and getHavingCriteria()) but in this way I loose the type...
Do any one ever have a problem like this one?

A:

Quoted from the EclipseLink FAQ:

To see the SQL for a JPA Query you can
  enable logging on FINE or lower.
To get the SQL for a specific Query at
  runtime you can use the DatabaseQuery
  API.

Session session = em.unwrap(JpaEntityManager.class).getActiveSession();
DatabaseQuery databaseQuery = ((EJBQueryImpl)query).getDatabaseQuery();
databaseQuery.prepareCall(session, new DatabaseRecord());
String sqlString = databaseQuery.getSQLString();

This SQL will contain ? for
  parameters. To get the SQL translated
  with the arguments you need a
  DatabaseRecord with the parameter
  values.

Session session = em.unwrap(JpaEntityManager.class).getActiveSession();
DatabaseQuery databaseQuery = ((EJBQueryImpl)query).getDatabaseQuery();
String sqlString = databaseQuery.getTranslatedSQLString(session, recordWithValues);


Q:

best practice typing an Observable event with no value

I want to define a method returning an Observable but I don't have any data, what signature should I sue ?
myMethod(): Observable<null>;
myMethod(): Observable<void>;
myMethod(): Observable<{}>;

When coding the return in the method, I want to receive a next event in my first subscribe callback, so I can't use Observable.empty();
I could use the following :
myMethod(): Observable<null>; //I could use  return Observable.of(null);
myMethod(): Observable<void>; //I could use  return Observable.of(null);
myMethod(): Observable<{}>; //I could use  return Observable.of({});

I did not find an official way of doing it, but maybe there's a standard solution ... What is the best practice ?

A:

I think the best way is using myMethod(): Observable<void>; because null is still a valid value that is often used instead of an object for example. Also {} is an empty object (object with no properties).
You can emit values to void like this:
const s = new Subject<void>();
s.next();
s.next(void 0);

You can also map any existing Observable to Observable<void>:
source
  .pipe(
    mapTo(void 0),
  )
  ...


Q:

Show Article Tags in the Category List Layout

I am developing a site using joomla 3.2.3 where I've been adding some tags to my joomla articles that in the articles is displayed above it's content.
For listing I use the 'Menu Item Type: Articles > Category List' and I would like to have it display the articles Tags in the list as well, e.g. like this:
[Title] [Author] [Tags]
Since joomla doesn't support this option in the article manager option to show tags in the List-Layout, I've been trying to add it to the list by editing the List-Layout files.
Here I made a template override of:
com_content > Category
Which includes the list-files:

default.php
default.xml
default_article.php
default_children.php

Then I've tried modifying this file, which creates the list-layout:
.../templates/my_template/html/com_content/category/default_articles.php
To create the tag column for the list-layout I added this code in the section around line 100:
<?php if ($this->params->get('show_tags')) : ?>

         <?php echo JHtml::_('grid.sort', 'JTAG', 'tags', $listDirn, $listOrder); ?>

<?php endif; ?>

This created and displays a 2nd column in my category list view with the header title: Tags (if set to 'show' in Article Manager Option)
And to get the tags to display in the column fields, I figured that i need to add a code for the tags in the section around line 181, where I tried adding this code:

<?php endif; ?>
<?php if ($this->params->get('show_tags', 1)) : ?>
   <
      <?php $this->item->tagLayout = new JLayoutFile('joomla.content.tags'); ?>
      <?php echo $this->item->tagLayout->render($this->item->tags->itemTags); ?>
         <?php echo JText::sprintf('JTAG', $article->tags->itemTags); ?>

<?php endif; ?>

This is the code I need help with, since it doesn't fully work, it only shows the text 'tags' (from the 'JTAG') in the fields, and doesn't display the article's tag from the code:
<?php $this->item->tagLayout = new JLayoutFile('joomla.content.tags'); ?>
<?php echo $this->item->tagLayout->render($this->item->tags->itemTags); ?>

which I took from the Articles view default layout to see how the tags are rendered.
But this code apperently doesn't directly work in the Category list Layout or doesn't give any effect.

Tried to take a look at this post:
Article Tags shown in Article List-Layout
But have not been able to get the code in this post to work for me:

A:

So if you look at the weblinks category layout you'll see that tags for individual links are displaywed with this code:
<?php $tagsData = $item->tags->getItemTags('com_weblinks.weblink', $item->id); ?>
<?php if ($this->params->get('show_tags', 1)) : ?>
    <?php $this->item->tagLayout = new JLayoutFile('joomla.content.tags'); ?>
    <?php echo $this->item->tagLayout->render($tagsData); ?>
<?php endif; ?>

So what you need to do is set up the $tagsData correctly changing the alias name and also making sure that the id variable is correct.
You put this inside the code for the layout of an individual item on the list meaning in the blog_item.php file possibly right after the title.
    <?php $this->item->tagLayout = new JLayoutFile('joomla.content.tags'); ?>
    <?php echo $this->item->tagLayout->render($this->item->tags->itemTags); ?>


Q:

how can bind any string of text, so whenever you type it, it will be replaced into another string

I tried my best to describe it, I saw this functionality in some video about macos for noobs.
Basically you can bind any string of text, so whenever you type it, it will be replaced into another string. It seemed super easy.
Example, you bind
<something>

to xsy
So whenever you write xsy, it gets replaced by
<something>

etc

A:

Go to System Preferences > Keyboard > Text and add your text for Replace and With by clicking the + in the lower left of the window.
Once added, you can edit an entry by selecting the row and then click the field to open the edit window.
To remove a row, select it and then click the - in the lower left of the window.


Q:

no such table when i add a new table

i think function onUpgrade is not working becuase before i add a new table .it's not error.
when i add category table (a new table) . i change database_version = 2 from 1 when i run emulator .log cat sue "No such table category" and i don't know how to modify it. please check
and tell me why onUpgrade isn't work.
This is my code (BookDBHelper)
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class BooksDBHelper extends SQLiteOpenHelper {
//databse_name
public static String DATABSE_NAME = "bookguk";
// database_version
protected static final int DATABASE_VERSION = 2;  //  <<<---i have changed it to version 2 from version 1 when add a new table category

//table name
public static String TABLE_BOOK = "books";
public static String TABLE_IMAGE = "images";
public static String TABLE_INGREDIENT = "ingredients";
public static String TABLE_CATEGORY = "category";
//column_name
public static String KEY_ID = "id";
public static String KEY_TITLE = "title";
public static String KEY_SOLUTION = "solution";
public static String KEY_BOK_ID = "bookID";
public static String KEY_fILEPATH = "filepath";
public static String KEY_VALUE = "value" ;
public static String KEY_UNIT = "unit";
public static String KEY_NAME = "name";
public static String KEY_CAT_ID = "cat_id";

public static String BOOK_CREATE_SQL = "CREATE TABLE IF NOT EXISTS " + TABLE_BOOK + "(" +
                                ""+KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT," +
                                ""+KEY_TITLE+" TEXT(50) not null," +
                                ""+KEY_SOLUTION+" TEXT(255) not null," +
                                ""+KEY_CAT_ID+" INTEGER(11)," +
                                " FOREIGN KEY("+KEY_CAT_ID+") REFERENCE "+TABLE_CATEGORY+" ("+KEY_ID+"))";

public static String IMAGE_CREATE_SQL = "CREATE TABLE IF NOT EXISTS " + TABLE_IMAGE + "(" +
                                ""+KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT," +
                                ""+KEY_fILEPATH+" VACHAR(255)," +
                                ""+KEY_BOK_ID+" INTEGER(11)," +
                                " FOREIGN KEY("+KEY_BOK_ID+") REFERENCES "+TABLE_BOOK+" ("+KEY_ID+"))";

public static String INGREDIENT_CREATE_SQL = "CREATE TABLE IF NOT EXISTS " + TABLE_INGREDIENT + "(" +
                                ""+KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT," +
                                ""+KEY_VALUE+" DOUBLE(11)," +
                                ""+KEY_UNIT+" VACHAR(50)," +
                                ""+KEY_fILEPATH+" VACHAR(255)," +
                                ""+KEY_BOK_ID+" INTEGER(11)," +
                                " FOREIGN KEY("+KEY_BOK_ID+")REFERENCES "+TABLE_BOOK+" ("+KEY_ID+"))";

public static String CATEGORY_CREATE_SQL = "CREATE TABLE IF NOT EXISTS " + TABLE_CATEGORY + "(" +
                                ""+KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT," +
                                ""+KEY_NAME+" VACHAR(50) " +
                                ")";

//constructor
public BooksDBHelper(Context context) {
    super(context, DATABSE_NAME, null, DATABASE_VERSION);
    // TODO Auto-generated constructor stub
}

//create
@Override
public void onCreate(SQLiteDatabase db) {
            db.execSQL(CATEGORY_CREATE_SQL);
    db.execSQL(BOOK_CREATE_SQL);
    db.execSQL(IMAGE_CREATE_SQL);
    db.execSQL(INGREDIENT_CREATE_SQL);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_BOOK );
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_IMAGE );
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_INGREDIENT );
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CATEGORY );
    onCreate(db);

}

}

This is my operator (insert data to table category)
package com.example.mutitablesql.db;

import java.util.ArrayList;

import com.example.mutitablesql.entry.BookEntry;
import com.example.mutitablesql.entry.CategoryEntry;
import com.example.mutitablesql.entry.ImageEntry;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class BooksDB {
//นำ class booksDBHelper มาสร้างเป็น object
private BooksDBHelper helper;
private SQLiteDatabase db;

//สร้าง constructor
public BooksDB(Context context){
    // คำสั่ง เรียก constructor ของclass BooksDBHelper
    helper = new BooksDBHelper(context);
    db = helper.getWritableDatabase();
}

//insert into table category
public long insertCategory(String name){
    ContentValues values = new ContentValues();
    values.put(BooksDBHelper.KEY_NAME, name);
    return db.insert(BooksDBHelper.TABLE_CATEGORY, null, values);

}

my mainactivity code
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context = this;
    db = new BooksDB(context);

    db.insertCategory("ต้ม");
    db.insertCategory("ผัด");
    db.insertCategory("แกง");
    db.insertCategory("ทอด");
    db.insertCategory("ประเภทเส้น");
    db.insertCategory("เครื่องดื่ม");
    db.insertCategory("ของหวาน");
}

this is my logcat edit
09-02 09:47:29.869: E/SQLiteLog(1220): (1) near "REFERENCE": syntax error
09-02 09:47:29.889: D/AndroidRuntime(1220): Shutting down VM
09-02 09:47:29.889: W/dalvikvm(1220): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
09-02 09:47:29.919: E/AndroidRuntime(1220): FATAL EXCEPTION: main
09-02 09:47:29.919: E/AndroidRuntime(1220): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mutitablesql/com.example.mutitablesql.MainActivity}: android.database.sqlite.SQLiteException: near "REFERENCE": syntax error (code 1): , while compiling: CREATE TABLE IF NOT EXISTS books(id INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT(50) not null,solution TEXT(255) not null,cat_id INTEGER(11), FOREIGN KEY(cat_id) REFERENCE category (id))
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.os.Looper.loop(Looper.java:137)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.app.ActivityThread.main(ActivityThread.java:5041)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at java.lang.reflect.Method.invokeNative(Native Method)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at java.lang.reflect.Method.invoke(Method.java:511)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at dalvik.system.NativeStart.main(Native Method)
09-02 09:47:29.919: E/AndroidRuntime(1220): Caused by: android.database.sqlite.SQLiteException: near "REFERENCE": syntax error (code 1): , while compiling: CREATE TABLE IF NOT EXISTS books(id INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT(50) not null,solution TEXT(255) not null,cat_id INTEGER(11), FOREIGN KEY(cat_id) REFERENCE category (id))
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at com.example.mutitablesql.db.BooksDBHelper.onCreate(BooksDBHelper.java:67)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at com.example.mutitablesql.db.BooksDBHelper.onUpgrade(BooksDBHelper.java:82)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:257)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at com.example.mutitablesql.db.BooksDB.<init>(BooksDB.java:23)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at com.example.mutitablesql.MainActivity.onCreate(MainActivity.java:21)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.app.Activity.performCreate(Activity.java:5104)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
09-02 09:47:29.919: E/AndroidRuntime(1220):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
09-02 09:47:29.919: E/AndroidRuntime(1220):     ... 11 more

A:

Taking a look into your onUpgrade code:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

db.execSQL("DROP TABLE IF EXITS " + TABLE_BOOK );
db.execSQL("DROP TABLE IF EXITS " + TABLE_IMAGE );
db.execSQL("DROP TABLE IF EXITS " + TABLE_INGREDIENT );
db.execSQL("DROP TABLE IF EXITS " + TABLE_CATEGORY );
onCreate(db);

}
I realize that you have a mispelling error, EXITS is EXISTS


Q:

Why does "small"give an error about "char"?

Trying to compile an open source project with both VS2010, VS2012 in x86 and x86_64 on a windows platform running QT5.4.
A file named unit.h contains a part :
[...]
// DO NOT change noscale's value. Lots of assumptions are made based on this
// value, both in the code and (more importantly) in the database.
enum unitScale
{
   noScale = -1,
   extrasmall = 0,
   small = 1, // Line that causes errors.
   medium = 2,
   large = 3,
   extralarge = 4,
   huge = 5,
   without = 1000
};
[...]

Generates

error C2062: type 'char' unexpected
error C3805: 'type': unexpected token, expected either '}' or a ','

I tried every trick in my hat to solve it. I removed every use of the "small" enum in the code and I still get the error. But after having removed all the uses, I rename "small" to "smallo" everything is fine. It seems to indicate name collision but a file search gives me no references in the whole project. It's not any keyword I know of.
Got any ideas?
EDIT: Thanks to very helpful comments here is an even stranger version that works. Could somebody explain?
#ifdef small // Same with just straight "#if"
#pragma message("yes")
#endif
#ifndef small
#pragma message("no") // Always prints no.
#endif

#undef small
enum unitScale
{
   noScale = -1,
   extrasmall = 0,
   small = 1,
   medium = 2,
   large = 3,
   extralarge = 4,
   huge = 5,
   without = 1000
};

EDIT 2: The pragma directive was showing yes but only in files that had previously loaded the windows.h header, and it was lost in the compiler output in a sea of no.
Thanks everyone! What a quest.

A:

small is a defined in rpcndr.h. It is used as datatype for MIDL.


Q:

Matching a pattern with `match()` with extra condition

Expanding on a previous question (R: gsub of exact full string with fixed = T). [With huge thanks to everyone who helped there. Special thanks to @MrFlick]
I need to change "32 oz" to "32 ct" but only if extra condition "3" is met, not in any other case.
exact_orig   = c("oz"   ,"32 oz")
exact_change = c("20 oz","32 ct")
exact_flag   = c("1"    ,"3")

fixedTrue<-function(x,y) {
  m <- match(x, exact_orig)
  n <- match(y, exact_flag)
  x[!is.na(m) & n[!is.na(n)]]<- exact_change[m[!is.na(m)] & n[!is.na(n)]]
  x
}

print(fixedTrue(c("32 oz","oz oz","32 oz", "oz", "oz"),c("1","1","3","1","2")))

Result:
[1] "20 oz" "oz oz" "32 ct" NA      NA

Desired output:
[1] "32 oz" "oz oz" "32 ct" "20 oz" "oz"

Edit: tried the following
  x[!is.na(m&n)]<- exact_change[m[!is.na(m&n)]]

  print(fixedTrue(c("32 oz","oz oz","32 oz", "oz", "oz"),c("1","1","3","1","3")))

Got:
[1] "32 ct" "oz oz" "32 ct" "20 oz" "20 oz"

I don't see how first "32 oz" changes to "32 ct" if the flag in test case is "1" not "3"

A:

This works:
fixedTrue <- function(x, y) {
   toChange <- which(match(x, exact_orig) == match(y, exact_flag))
   x[toChange] <- exact_change[match(x[toChange], exact_orig)]
}

Amended to check positions in flag and orig the same
Slightly closer to original:
fixedTrue <- function(x, y) {
  m <- match(x, exact_orig); n <- match(y, exact_flag)
  x[which(m == n)] <- exact_change[m[which(m == n)]]
}


Q:

AC: Black Flag multiplayer functional?

I have recently seen this game on sale and I'm wondering - is the multiplayer part still available? By available I mean:

servers are still working
it is possible to find (or make) a game within an acceptable amount of time
(bonus) is it possible to create two-player games?

I know it's quite many years after the original release of this game, but maybe Ubisoft hasn't shut down the multiplayer part of this game?
Can anyone owning the game actually confirm it still works?
Edit: Forgot to mention - I'm playing on PC.

A:

Yes the servers are still functional, though it may not necessary seem like it because no one is ever on. Though many people still play AC4 Black Flag I just don't think anyone bothers with the multiplayer. Hope that helped! :D


Q:

Why am I getting the "format '%s' expects argument of type 'char *' but...." error here?

I'm pretty new to C and still catching onto the basics.  I am writing a very simple practice exercise which takes a phrase and reverses it.  I'm sure there are other problems with this code, but primarily on compilation of main.c, I am continually getting the error
main.c:14:9: warning: format '%s' expects argument of type char* but argument 2 has type 'int'   command not found
I have no idea why I am getting that error, could someone help me understand why?  Thank you!
My main.c
int main (int argc, char * argv [])
{

char word[] = "Happy Birthday!";

printf("%s\n", word);
reverse(word);
printf("%s\n", word);
printf("%s\n", reverse(word));
printf("%s\n", word);

system ("Pause");
return 0;
}

My reverse.c
#include<stdio.h>
#include<string.h>

char *reverse(char *word)
{
char *rev;
char *i;
char temp;

rev = word;
for (i = word; *i != '\0'; i++)
{
        if (i - word > 1)
                for (i--; word < i; word++, i--)
                {
                        temp = *word;
                        *word = *i;
                        *i = temp;
                }

return rev;
}

A:

If that's your entire main.c source file, then the compiler doesn't see a declaration of your reverse function.
In C89/C90, a call to an undeclared function would create an implicit declaration of that function returning a result of type int. If the function actually returns something other than int, as yours does, then the behavior is undefined.
C99 dropped this "implicit int" rule, making any call to an undeclared function a constraint violation, requiring a diagnostic.  You should find out how to coax your compiler to diagnose such a call.
The fix is to make a declaration of reverse visible in main.c.  The best way to do this is to create a header file, most likely reverse.h, that contains the declaration:
#ifndef REVERSE_H
#define REVERSE_H

char *reverse(char *word);

#endif

and #include that header in both main.c and reverse.c.  (Including it in main.c provides the declaration so the call can be compiled correctly. Including it in reverse.c lets the compiler conform that the declaration and definition are consistent.)


Q:

Find the matrix of a linear transformation with respect to two bases

Let $L: P_1 \rightarrow P_3$ be the linear transformation defined by
  $L(p(t)) = t^2 p(t)$.
Let $S = \{t, t+1\}$ be a basis for $P_1$ and $T = \{t^3, t^2-1, t,
 t+1\}$ be a basis for $P_3$.
Find the matrix of $L$ with respect to $S$ and $T$. Find $L(2t-3)$
  using the definition of $L$.

What I've tried so far and I do not know what to do next
$a_1 = t$
$L(a_1) = L(t) = t^2(t) = t^3$
$a_2 = t+1$
$L(a_2) = L(t+1) = (t+1)^2(t+1) = t^3+3t^2+3t+1$

A:

You have to represent the images of the elements of $S$ in the basis vectors of $T$. We have
$$L(t) = t^3 = 1t^3 + 0(t^2 - 1)+ 0t + 0 (t + 1),$$
hence $(1, 0, 0, 0)$ is the first column vector of the matrix of $L$, say $A$. Now note that $L(t + 1) = t^2 (t + 1) = t^3 + t^2$ and therefore
$$L(t + 1) = t^3 + t^2 = 1t^3 + 1(t^2 - 1) - 1t + 1(t + 1).$$
It follows that
$$A = \begin{pmatrix} 1 & 1 \\ 0 & 1 \\ 0 & -1 \\ 0 & 1 \end{pmatrix}.$$
I leave it to you to calculate $L(2t - 3)$.


Q:

Visual Studio XML Documentation : Attributes

This may be a simple question to people who have anything advanced with XML Documentation from Visual Studio.
I can generate the documentation for a class and members no problem, but I'm trying to figure out if there's a way to include attributes in that?
I'd like to include any property or method attributes in the documentation.
Thanks in advance,
Richard

A:

for example:
/// <summary>
/// The summary
/// </summary>
/// <attribute>[ChildActionOnly]</attribute>
[ChildActionOnly]
public void TheMember()
{

}

is valid. and you can even see it in the intellisense info.


Q:

Javascript animation scale sprite

This is the sprite I am using to animate an object through css. Every frame is 224px in width so the background-position property of the div is incremented by -224px every frame and the cycle goes on. The problem is that the width of my div is not fixed. I use percentage width of the div to stay resolution independent. So I want my 224px wide frame to scale over the width of the div and move left the same amount every frame. Hope it is clear to you. Here is the JS function used to animate the div.
function moveTail() {
    if ( typeof moveTail.counter == 'undefined' ) {
        moveTail.counter = 0;
        moveTail.object = $('#genietail');
    }

    if( moveTail.counter == 42 )
        moveTail.counter = -1;
    ++moveTail.counter;
    moveTail.object.css('background-position', moveTail.counter*-224 + "px 0px" );
}

A:

There are two ways of scaling a sprite image.
The first one is to play with the background-size CSS attribute. If your sprite size is for example 100px by 100px, by default background-size will take the value 100px 100px, but if you set it to 200px 200px it will double the image size that will be displayed.
In your case it would look like this :
var spriteSize = { height: 224, width : 224 * 20 };
var imageSize = { height: 224, width : 224 };
var backgroundWidth = Math.floor((moveTail.object.width()  / imageSize.width) * spriteSize.width);
var backgroundHeight = moveTail.object.height();

moveTail.object.css("background-size", backgroundWidth + "px " +  backgroundHeight + "px");
moveTail.object.css('background-position', moveTail.counter * -moveTail.object.width() + "px 0px" );

The second one is to use the CSS 3 attribute transform with scaleX and scaleY. If you want a div to double the size that is displayed you can do in CSS transform: scaleX(2) scaleY(2).


Q:

How do I insert attribute values with the REST API?

Including them in the Attribute collection of a Stock Item doesn't seem to work -- even if I make sure the attribute ids already exist in the db.  When I do the PUT request, the rest of the data in the record is inserted, but not the attributes.  The response even returns an empty attribute array instead of what I sent to it.
Do I need to extend the API for this to work?  If so, does anyone have any examples?  I haven't been able to find any yet.
The request is:
http://localhost/acum172100034/entity/Default/17.200.001/StockItem
The body is:
{
  "InventoryID": {
    "value": "RGTONYIT166"
  },
  "Attributes": [
    {
      "AttributeID": {
        "value": "Item Attribute"
      },
      "Value": {
        "value": "2"
      }
    }
  ]
}

The PUT response is:
{
    "id": "665e403c-d310-4bb4-9759-e2487dd5abc7",
    "rowNumber": 1,
    "note": null,
    "ABCCode": {},
    "Attributes": [],
    "AutoIncrementalValue": {},
    "AverageCost": {
        "value": 0
    },
    "BaseUOM": {
        "value": "EA"
    },
    "COGSAccount": {
        "value": "50000"
    },
    "COGSSubaccount": {
        "value": "CON000"
    },
    "Content": {},
    "CurrentStdCost": {
        "value": 0
    },
    "DefaultIssueLocationID": {
        "value": "R1S1"
    },
    "DefaultPrice": {
        "value": 0
    },
    "DefaultReceiptLocationID": {
        "value": "RECEIVING"
    },
    "DefaultWarehouseID": {
        "value": "WHOLESALE"
    },
    "DeferralAccount": {},
    "DeferralSubaccount": {},
    "Description": {
        "value": "tonyitem166 - blah blah 2"
    },
    "DimensionVolume": {
        "value": 3
    },
    "DimensionWeight": {
        "value": 2
    },
    "DiscountAccount": {},
    "DiscountSubaccount": {},
    "ImageUrl": {},
    "InventoryAccount": {
        "value": "12100"
    },
    "InventoryID": {
        "value": "RGTONYIT166"
    },
    "InventorySubaccount": {
        "value": "CON000"
    },
    "IsAKit": {
        "value": false
    },
    "ItemClass": {
        "value": "CONSUMER  200FITNESS"
    },
    "ItemStatus": {
        "value": "Active"
    },
    "ItemType": {
        "value": "Finished Good"
    },
    "LandedCostVarianceAccount": {
        "value": "52400"
    },
    "LandedCostVarianceSubaccount": {
        "value": "CON000"
    },
    "LastCost": {
        "value": 0
    },
    "LastModified": {
        "value": "2018-10-02T17:13:38.707-04:00"
    },
    "LastStdCost": {
        "value": 0
    },
    "LotSerialClass": {
        "value": "NOTTRACKED"
    },
    "Markup": {
        "value": 0
    },
    "MaxCost": {
        "value": 0
    },
    "MinCost": {
        "value": 0
    },
    "MinMarkup": {
        "value": 0
    },
    "MSRP": {
        "value": 0
    },
    "PackagingOption": {
        "value": "Manual"
    },
    "PackSeparately": {
        "value": false
    },
    "PendingStdCost": {
        "value": 0
    },
    "POAccrualAccount": {
        "value": "20100"
    },
    "POAccrualSubaccount": {
        "value": "CON000"
    },
    "PostingClass": {
        "value": "CON"
    },
    "PriceClass": {},
    "PriceManager": {},
    "PriceWorkgroup": {},
    "ProductManager": {},
    "ProductWorkgroup": {},
    "PurchasePriceVarianceAccount": {
        "value": "52300"
    },
    "PurchasePriceVarianceSubaccount": {
        "value": "CON000"
    },
    "PurchaseUOM": {
        "value": "EA"
    },
    "ReasonCodeSubaccount": {
        "value": "CON000"
    },
    "SalesAccount": {
        "value": "40000"
    },
    "SalesSubaccount": {
        "value": "CON000"
    },
    "SalesUOM": {
        "value": "EA"
    },
    "StandardCostRevaluationAccount": {
        "value": "52110"
    },
    "StandardCostRevaluationSubaccount": {
        "value": "CON000"
    },
    "StandardCostVarianceAccount": {
        "value": "52100"
    },
    "StandardCostVarianceSubaccount": {
        "value": "CON000"
    },
    "SubjectToCommission": {
        "value": false
    },
    "TaxCategory": {
        "value": "TAXABLE"
    },
    "ValuationMethod": {
        "value": "Average"
    },
    "VolumeUOM": {},
    "WeightUOM": {},
    "custom": {},
    "files": []
}

A:

This ended up being an issue with my own code that was apparently hiding the attributes from the view so that they wouldn’t update.  Once I resolved that, now it's working by just include them in the Attributes collection.


Q:

Use cases for categories in Machine Learning

I started learning the concepts of machine learning.
I would like to know some of the use case scenarios for below

Classification
Regression
Clustering
Anomaly detection
Dimension reduction

And I would even like to know under which category the above mentioned list falls?(Is it in supervised or unsupervised or reinforcement )

A:

General note
You should not think about types of tasks in ML as something that has assigned label "supervised/unsupervised/...". This is not how it works. You can say that usually given task is solved using supervised/unsupervised learning, but this is just this. You can generate approach which has any label with any task in practise.
Actual answer
These parts of ML were originally well defined, but with progress in the field many of them merged, and now we have much more types of problems (like semi-supervised learning, weakly supervised classification, representation learning), so I stress that I refer to the original meaning of each

Classification

Defined as a problem of looking for a mapping from objects to a finite set of classes. Usually each object has just one class (but there are generalizations to multiple ones).
Real life examples:

Face recognition (we are given a face and answer who is it)
Drug discovery (we are given a compound and we answer if it is a drug or not)

Type of learning: usually supervised

Regression

We are looking for a mapping to a infinite number values, with valid ordering, for example real numbers.
Real life examples:

Predicting for much money a user will spend in our shop based on his characteristic
Predicting power consumption in the next month
Predicting stock prices

Type of learning: usually supervised

Clustering

Usually defined as finding a structure in data, without access to any sample of such structure (later on with many modifications such as constrained clustering, weakly supervised clustering)
Real life examples:

Given set of images of stars, do they form some distinguishable types of stars?
Given users activity on our website - are there distinguishable usage scenarios that we can find?

Type of learning: usually unsupervised

Anomaly detection

Given a set of "normal" observations build amodel to answer "is new observation normal, or is it an anomaly?"
Real life examples:

We have record of a valid engine parameters and need a method to alarm as that it starts to behave "weird" (even though we do not know from the past what kind of "weird" we are looking for)
We have recordings from camera of usual people behaviour, we want method to alarm as that "something unusual is happening" (without specifing what)

Type of learning: usually unsupervised

Dimension reduction

This is just a preprocessing step. Given high dimensional data we seek for a lower-dimensional representation which is usable in other tasks.
Real life examples:

We have set of high-dimensional data (like patients records) and want to visualize it (draw on a plane)
We have a problem of classification and our methods fail - we need to reduce dimensionality to increase scores

Type of learning: usually unsupervised
Reinforcment
None of the above is reinforcment learning. Reinforcment learning can be applied to any of the above, if we simply have some 'environment' saying that our method is doing 'good' or 'bad' (so instead of saying 'I want this image to be classified as cat' it only says 'I see that you classified this image as a plane, well.. it is not!').
In other words - we do any  task, but we do have humans who judge is our method good or bad, but they do not give as correct answers.


Q:

Creating a float[] from a javax.vecmath.Matrix4f

What order should I populate a float[] using contents of mMVPMatrix before passing into glUniformMatrix4fv?
I'm using the javax.vecmath library.
initialize variables
Matrix4f mMVPMatrix = new Matrix4f();
Matrix4f mProjectionMatrix;
Matrix4f mViewMatrix;

set values in GLEventListener.init()
mProjectionMatrix = createPerspectiveProjection(60.0f, width / height, 0.1f, 100.0f); // method that returns an object of type `Matrix4f`
mViewMatrix = new Matrix4f();
mViewMatrix.setIdentity();

update in GLEventListener.display()
mMVPMatrix = mProjectionMatrix;
mMVPMatrix.mul(mViewMatrix);

get reference to glsl variable during draw
mMVPMatrixHandle = gl2.glGetUniformLocation(shaderProgram, "uMVPMatrix");
gl2.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);

uMVPMatrix is a glsl variable ..
#version 120

uniform mat4 uMVPMatrix;
attribute vec4 vPosition;

void main() {
    gl_Position = uMVPMatrix * vPosition;
}

A:

By default, OpenGL assumes that matrices are stored in column major order. Based on the Matrix4f documentation, the numbering of the matrix elements is row major. For example:

m01: The second element of the first row.

So if m is a Matrix4f, you can build a float array v with elements in column major order with:
float[] v = {m.m00, m.m10, m.m20, m.m30,
             m.m01, m.m11, m.m21, m.m31,
             m.m02, m.m12, m.m22, m.m32,
             m.m03, m.m13, m.m23, m.m33};

The 3rd argument of glUniformMatrix4fv() also lets you choose if the matrix should be transposed while loading it into the uniform. If your values are column-major, you will use false. But if for some reason you have your values in row-major order, you can also use true as the argument, instead of shuffling the values around.


Q:

An Example where $gHg^{-1} \ne g^{-1}Hg$

I was trying to think of an example where $gHg^{-1} \ne g^{-1}Hg$.  I couldn't think of one, but I am curious if the following reasoning demonstrates that, at the very least, such an example must exist:
Let $H$ be a non-normal subgroup of $G$ and let $g \in G - H$.  Then it is possible that $gHg^{-1} \ne g^{-1}Hg$ since if we supposed otherwise we would have
$$\begin{align}
gHg^{-1}   & = g^{-1}Hg \\
g^2Hg^{-1} & = Hg\\
g^2        & = e\\
g          & = e
\end{align}$$
which is impossible since we assumed $g \in G - H$.

A:

You won't come up with a counterexample when $G$ is abelian (why?).  So your best bet is to try it with $G$ being non-abelian, and the simplest non-abelian group is $S_3$.
Moreover, you are bound to fail if $g = g^{-1}$ (why?).  So let's try letting $g = (1,2,3)$, in cycle notation.  For our subgroup $H$, let's pick one which involves elements that don't commute with $g$.  So we're going to want a transposition in our subgroup.  So let's take $H = \{ \text{id}, (1,2) \}$, the subgroup consisting of the identity permutation and the transposition interchanging $1$ and $2$.
Try computing $g H g^{-1}$ and $g^{-1} H g$ for this example.  (It will work; but if it hadn't, the best thing to do would be to try to understand why it didn't work and try to come up with the next simplest example that wouldn't be sure to fail based on the reasons you know to this point.)


Q:

Group By only if column has a NULL value

I have a View in SQL which displays orders and the products on that order, and also the list that the products have been assigned to. What i am trying to do is use a Group By if the products have not been assigned to a list but display the ones that have been assigned individually.
For example my View looks like this:
+---------+--------------+-------------+
| fkOrder | fkProductID  |  fkListID   |
+---------+--------------+-------------+
|   1     |     10       |    NULL     |
|   1     |     10       |    NULL     |
|   1     |     10       |    NULL     |
|   1     |     10       |     1       |
|   1     |     10       |     1       |
|   2     |     20       |    NULL     |
|   2     |     20       |    NULL     |
|   2     |     20       |    NULL     |
|   2     |     20       |    NULL     |
|   2     |     20       |     1       |
+---------+--------------+-------------+

But i would like it to look like this:
+---------+--------------+-------------+
| fkOrder | fkProductID  |  fkListID   |
+---------+--------------+-------------+
|   1     |     10       |    NULL     |
|   1     |     10       |     1       |
|   1     |     10       |     1       |
|   2     |     20       |    NULL     |
|   2     |     20       |     1       |
+---------+--------------+-------------+

At the moment i have been able to get this result using a Group By:
+---------+--------------+-------------+
| fkOrder | fkProductID  |  fkListID   |
+---------+--------------+-------------+
|   1     |     10       |    NULL     |
|   1     |     10       |     1       |
|   2     |     20       |    NULL     |
|   2     |     20       |     1       |
+---------+--------------+-------------+

I have been browsing for similar questions to mine but i still haven't been able to find an answer that works for me. I am aware that i may of read an answer that could be what i need but due to my inexperience in SQL I don't know. So i thought i would just ask myself.
I have tried removing the Group By from the fkListID Column but i get the error : 'fkListID' is invalid in the select list because it is not contained in either an aggregate function or the Group By clause so i tried all of the other options provided within the drop down other than Group By but couldn't get the desired result.
I feel instead that it's somewhere along the lines of having a Group By WHERE fkListID IS NULL but keep getting syntax errors.
Or possibly a CASE WHEN statement on a column but again i just don't know.
Any links to a question that has an answer appropriate to me, or an answer, would be great.

A:

As presented, your data has no primary key.  You can do this using union all:
select fkOrder, fkProductID, fkListID
from myview
where fkListID is not null
union all
select distinct fkOrder, fkProductID, fkListID
from myview
where fkListID is null


Q:

How to best tell if a generic type parameter can be serialized by protobuf-net?

I am writing some custom generic data structures. How can I ensure that the generic type passed in can be serialized by protobuf-net? Since protobuf-net doesn't rely on interfaces, I can't constrain the type parameter in that way. I thought about runtime testing of the type inside the constructor, but I can't even use PrepareSerializer<T> because that relies on the type being a reference type. I could simply attempting a serialization and deserialization, but this seems messy at best. What's the best way to verify the a given generic type can be serialized?

A:

XmlProtoSerializer has to make a similar determination. For example:
static int GetKey(TypeModel model, ref Type type, out bool isList)
{
    if (model != null && type != null)
    {
        int key = model.GetKey(ref type);
        if (key >= 0)
        {
             isList = false;
             return key;
        }
        Type itemType = TypeModel.GetListItemType(type);
        if (itemType != null)
        {
            key = model.GetKey(ref itemType);
            if (key >= 0)
            {
                isList = true;
                return key;
            }
        }
    }

    isList = false;
    return -1;
}

If that returns a negative value it can't be serialised. I could make this available in a more supported bool CanSerialize(Type) if that would be helpful?


Q:

How do I setup virtualenv on a production Windows server using IIS and Helicon Zoo?

We are currently testing Django on a live server using Windows 2008 webserver and IIS7. To run Django projects on IIS we use Helicon Zoo (Python hosting package with Django).
The plan is to host multiple clients on that webserver and we would like to use virtualenv, so we can upgrade python packages for specific clients, without affecting the others.
The specific question is; when we have several virtualenvs on the server, how do we set up the different Django sites under IIS to use a specific virtualenv?
Thanks in advance for your time and answers,
Erik

A:

It is not quite clear to me whether you need different versions of Python or different versions of modules, used in the application.
To have different python versions you can install another python manually, then go to applicationHost.config file, find . Engines declarations will be listed there. Create a copy of "python.2.7.wsgi" and edit the copy, name it like "python.2.5.wsgi" and change executable name path. This is how you can declare more engines with different versions and settings. Here you can find more information: Helicon Zoo Module documentation
As for Python modules, it is supposed that modules are installed locally in the client's web site in \python_modules\ directory. When you create new Django application using Helicon Zoo, it is configured to use isolated environment by default, you only need to learn how to use it right and tell your clients to follow guidelines. You can find the information in this article: Running Django on Windows (with performance tests)


Q:

Es posible usar efectivamente CREATE ROLE y sus privilegios, GRANT y REVOKE dentro de una funcion en postgresql (version 9.4))

Tengo que construir dos funciones para usarlas en la creación de roles y en la asignación de un rol a un grupo según su categoría en postgresql.
He aquí el código: La primera función es para crear un usuario y llamar a mi segunda función que asignará ese usuario a un grupo según su categoría.
CREATE OR REPLACE FUNCTION sp_addlogin(
IN _usuario character varying(30),
IN _contraseña character varying(4),
IN _categoria integer)
RETURNS text AS
$BODY$
declare mensaje text;
BEGIN
IF(select count(rolname) FROM pg_roles where rolname = _usuario) = 0 THEN
    EXECUTE FORMAT ('CREATE USER %I', _usuario, 'LOGIN PASSWORD %I',    _contraseña);
    PERFORM sp_adduser(_usuario, _categoria);
    mensaje = 'Usuario de BD agregado con exito';
ELSE
    RAISE 'Ya existe un rol con el mismo nombre, especifique';
END IF;
return mensaje;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;

CREATE OR REPLACE FUNCTION sp_adduser(
IN _usuario character varying(30),
IN _categoria integer)
RETURNS text AS
$BODY$
declare
mensaje text;
BEGIN
IF(SELECT count(rolname) FROM pg_roles WHERE rolname = _usuario) = 1 THEN
    IF(_categoria = 1 or _categoria = 2)THEN
        EXECUTE FORMAT ('GRANT', gestores, 'TO', _usuario);
        mensaje = 'Usuario añadido al grupo gestores';
    END IF;

    IF(_categoria = 3)THEN
        EXECUTE FORMAT ('GRANT', administradores, 'TO', _usuarrio);
        mensaje = 'Usuario añadido al grupo administradores';
    END IF;
 ELSE
    RAISE 'El usuario indicado no existe, reintente';
 END IF;
 return mensaje;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;

Al ejecutar la primera función genera este error:
ERROR:  column "gestores" does not exist
LINE 1: SELECT FORMAT ('GRANT', gestores, 'TO', _usuario)
                            ^
QUERY:  SELECT FORMAT ('GRANT', gestores, 'TO', _usuario)
CONTEXT:  PL/pgSQL function sp_adduser(character varying,integer) line 7     at EXECUTE statement
SQL statement "SELECT sp_adduser(_usuario, _categoria)"
PL/pgSQL function sp_addlogin(character varying,character varying,integer)     line 6 at PERFORM

********** Error **********

ERROR: column "gestores" does not exist
SQL state: 42703
Context: PL/pgSQL function sp_adduser(character varying,integer) line 7 at     EXECUTE statement
SQL statement "SELECT sp_adduser(_usuario, _categoria)"
PL/pgSQL function sp_addlogin(character varying,character varying,integer)    line 6 at PERFORM

Llevo un par de horas buscando como solucionarlo, pero francamente no sé qué estoy haciendo mal. Soy principiante en SQL y postgres, espero puedan ayudarme. Saludos.

A:

Sí, se puede. El problema con tu código es que gestores es un identificador, el postgres entiende que es una variable o el nombre de una columna, pero no hay una variable definida (en la sección declare) con ese nombre, ni el EXECUTE está en un SELECT con un FROM cuya tabla (o cláusula FROM) tiene una columna llamada gestores.
Entonces si gestores es el nombre de la tabla habría que poner
EXECUTE FORMAT('GANT gestores ON'...

si no hay que declarar la variable


Q:

Ember- Setting properties to default state after a successful save

I've got a pretty long form containing 10+ dynamically populated forms
Those are some of the properties
  metadata : {},
  creators : [],
  subjects : [],
  contributors : [],
  dates : [],
  identifiers : [],
  descriptions : [],
  geolocations : [],
  alternateidentifiers : [],
  sizes : [],
  formats : [],
  rights : [],
  files : [],
  newMetaDataRecord : null,

  // Choices from backend
  resourceTypesGeneral : null,
  contributorsType : null,
  dateType : null,
  relatedIdentifTypes : null,
  relationType : null,
  descriptionType : null,

  //BACKEND errorLOG array
  errorMessageObject : [],

  // Validations
  invalidCreatorsList : [],
  validCreators : false,

  invalidSubjectsList : [],
  validSubjects : true,

  invalidContributorsList : [],
  validContributors : true,

  invalidDatesList : [],
  validDates : true,

  invalidIdentifiersList : [],
  validIdentifiers : true,

  invalidDescriptionsList : [],
  validDescriptions : true,

  invalidGeosList : [],
  validGeos : true,

  invalidalternateIdentifiersList : [],
  validAlternates : true,

  invalidSizesList : [],
  validSizes : true,

  invalidFormatsList : [],
  validFormats : true,

  invalidRightsList : [],
  validRights : true,

I used to have a function called
setFormToDefaultState : function(){
    this.set('metadata', this.createEmptyMetaData());
    this.set('metadata.resource_type', this.createEmptyResourceType());
    this.createEmptyCreator();
  },

Which is similar to Initialize
init : function(){
    this._super();

    this.set('metadata', this.createEmptyMetaData());
    this.set('metadata.resource_type', this.createEmptyResourceType());
    this.createEmptyCreator();
  },

That kind of did work when i had less properties, but now there's almost 30 properties to set default and i wonder if there's an easier solution for this. Doing it in route does not work either, since on reNavigation fields would be lost (already filled in data).
So is there a function to reset.all() ?
Current solution
var arProperties = ["creators", "subjects", "contributors", "dates", "identifiers", "descriptions", "geolocations", "alternateidentifiers", "sizes", "formats", "rights", "files", "titles", "taxons", "invalidTaxonsList", "invalidCreatorsList", "invalidSubjectsList", "invalidContributorsList", "invalidDatesList", "invalidIdentifiersList", "invalidDescriptionsList", "invalidGeolocationsList", "invalidAlternateidentifiersList", "invalidSizesList", "invalidFormatsList", "invalidRightsList", "invalidTitlesList"];
    arProperties.forEach(function(arProperty) {
      self.set(arProperty, []);
    });
    var trueProperties  = ["formInvalid", "validTaxons", "validSubjects", "validContributors", "validDates", "validIdentifiers", "validDescriptions", "validGeolocations", "validAlternateidentifiers", "validSizes", "validFormats", "validRights"];
    trueProperties.forEach(function(trueProperty){
      self.set(trueProperty, true);
    });

A:

I've implemented this by setting a property on route . So if you enter the route for the first time, model gets loaded, then the property changes and on the second visit to route the "return" gets called. This way your inputs stay the same and u can still easily reset all properties.
import RouteMixin from 'appkit/misc/routemixin';
export default Ember.Route.extend(Ember.SimpleAuth.AuthenticatedRouteMixin, RouteMixin, {
  model : function(){
  var self = this;

    if(Ember.isNone(self.get('controller.routeHasBeenLoaded'))){
         return Ember.RSVP.hash({

            invalidTaxonsList : [],
            validTaxons : true,

            invalidCreatorsList : [],
            validCreators : false,

            invalidSubjectsList : [],
            validSubjects : true,

            invalidContributorsList : [],
            validContributors : true,

            invalidDatesList : [],
            validDates : true,

          });
    } else {
        return;
    }
  },
 }

});

Controller
init : function(){
 this._super();
 this.set('routeHasBeenLoaded', true)
}


Q:

How to do this particular string sequence?

I was wondering to do a particular sequence of strings. I tried to use permutations and combinations from itertools, but I didn't figure it out how to do it. This kind of sequences always takes the next word. It is difficult to explain, but easier to understand by looking at an output example
OUTPUT EXPECTATION
Original string:
“people are good good people are great great people are awesome people are good good people are awesome”

Sequence of Words to Check:
1 word sequence:
“people”, “are”, “good”, “great”, “awesome”.

2 word sequence:
“people are”, “are good, “good good”, “good people”, “are great”, “great great”, “great people” ...

3 word sequence:
“people are good”, “are good good”, “good good people”, “good people are” ...

4 word sequence ... until 20 word sequence.

The code that I made is simple, and get correctly the first word secuence, but not the rest of it.
def sequences(lst):
    for count_seq in range(1, 21):
        if count_seq == 1:
            for i in dict.fromkeys(permutations(iterable=lst, r=count_seq)):
                x = ' '.join(list(i))
                print(x)
        else:
            for i in dict.fromkeys(permutations(iterable=lst, r=count_seq)):
                x = ' '.join(list(i))
                print(x)

lst = string.split(' ')
sequences(lst=lst)

A:

Try this:
x = "people are good good people are great great people are awesome people are good good people are awesome"

words = x.split()
two_gram = [' '.join(words[i:i+2]) for i in range(len(words))]
print(two_gram)

three_gram = [' '.join(words[i:i+3]) for i in range(len(words))]
print(three_gram)


Q:

How to create a directory in Visual Studio Code tasks.json in windows?

I'm trying to write a task to create a directory using Visual studio Code tasks (in tasks.json) for windows users using the mkdir command, it's working well except when the folder already exists.
tasks.json
{
    "label": "(release) create build directory",
    "type": "shell",
    "linux": {
        "command": "mkdir -p ./build/release"
    },
    "windows": {
        "command": "mkdir .\\build\\release", // Not working when folder already exists !
    }
},

What I tried:
"command": "IF NOT EXIST .\\build\\release mkdir .\\build\\release"
But then I get the error:
At line:1 char:3
+ IF NOT EXIST .\build\release mkdir .\build\release
+   ~
Missing '(' after 'IF' in if statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingOpenParenthesisInIfStatement

If it is not possible to do it this way, is it possible to run this task by ignoring the exit code ? ( so that the tasks continue to build my project)
Environment:
Visual Studio code 1.40.2
Windows 10 Pro x64

A:

I found a way of doing it by using cmd.exe with /C option (Run Command and then terminate)
{
    "label": "(release) create build directory",
    "type": "shell",
    "linux": {
        "command": "mkdir -p ./build/release"
    },
    "windows": {
        "command": "cmd",
        "args": ["/C", "if not exist .\\build\\release mkdir .\\build\\release"]
    }
},


Q:

Chrome inline extension on verified site throws error: No Chrome Web Store item link found

I have followed the deployment instruction of an inline installation of my extension on a site that I have verified.
<link rel="chrome-webstore-item" href="https://chrome.google.com/webstore/detail/jakgfopmadhihjajjegmbnaiimjbmdlk">

And for the button:
Install me

But when I press the button i get this strange error:
Uncaught No Chrome Web Store item link found.

A:

I know the question is very old but in case if someone else is facing:
You need to provide the URL and call back functions in the function chrome.webstore.install().
Here is the code:
in the  put <link rel="chrome-webstore-item" href="https://chrome.google.com/webstore/detail/jakgfopmadhihjajjegmbnaiimjbmdlk">
and call via javascript:
chrome.webstore.install('https://chrome.google.com/webstore/detail/jakgfopmadhihjajjegmbnaiimjbmdlk',
    function(d){
       console.log('installed')
    },
    function(e){
       console.log('not installed: '+ e)
    });

Source: https://developer.chrome.com/webstore/inline_installation


Q:

Python: Inserting command line arguments from a variable length list

I'm joining up a few videos with VLC. However the number of videos I'm joining varies. I've been able to get it to work with a constant amount of variables in my output file list with:
p = sub.Popen(['C:\\Program Files\\VideoLAN\\vlc\\vlc.exe',
           outputFileList[0],
           outputFileList[1],
           outputFileList[2],
           'vlc://quit',
           '--sout-keep',
           '--sout=#gather:standard{access=file,dst=D:\\movies\\' + fileName + '.mov}',
           '--sout-keep'],
           stdout=sub.PIPE,
           stderr=sub.PIPE)

However I'm having trouble figuring out how to provide a varying number of arguments. Sometimes I want to joint 2 videos, sometimes 3, etc. I can't simply loop through and add items in the command line itself (at least I gave it a go). And I can't just provide a list in place of the individual items since it's looking for a string path for each.
Any help would be appreciated.

A:

Just concatenate your lists:
p = sub.Popen(['C:\\Program Files\\VideoLAN\\vlc\\vlc.exe'] +
              outputFileList +
              ['vlc://quit',
               '--sout-keep',
               '--sout=#gather:standard{access=file,dst=D:\\movies\\' + fileName + '.mov}',
               '--sout-keep'],
              stdout=sub.PIPE,
              stderr=sub.PIPE)


Q:

Why's my code wrong when looking for duplicates?

I'm trying to solve this Leetcode problem https://leetcode.com/problems/contains-duplicate-ii/
I'm not sure why my code's incorrect.  I've followed the problem and tried to write it out as best as I could but it didn't work.
Can someone point out what I did wrong?
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        boolean flag = false;
        int ans = 0;

        for(int i = 0; i < nums.length; i++) {
            for(int j = i + 1; j < nums.length; j++) {
                if(nums[i] == nums[j]) {
                    flag = true;
                }

                if(flag) {
                    ans = Math.abs(nums[i] - nums[j]);
                }

                if(ans <= k) {
                    return true;
                }
            }
        }
        return false;
    }
}

A:

Math.abs(nums[i] - nums[j]) is the problem
You're checking if the values of the numbers are <= k and instead you should check on the indices.
Do as follow:
public boolean containsNearbyDuplicate(int[] nums, int k) {
   boolean flag = false;
   int ans = 0;

   for(int i = 0; i < nums.length; i++) {
      for(int j = i + 1; j < nums.length; j++) {
         if(nums[i] == nums[j]) {
            if( Math.abs(i - j) <= k) return true;
         }
      }
   }
   return false;
}


Q:

По привычке - вводное?

Может ли " по привычке" быть вводным и нужна ли запятая в этом предложении?
Азербайджанская сторона не только продолжает провокации и артиллерийский обстрел мирных населенных пунктов Нагорного Карабаха, но и, по привычке, пытается перевернуть все с ног на голову, обвиняя карабахскую сторону в нанесении ударов по азербайджанским населенным пунктам.

A:

Может ли " по привычке" быть вводным?

Может.
Из "Словаря лингвистических терминов" Т.В. Жеребило:

вводные компоненты
<…>
Говорящий оценивает содержание высказывания с разных позиций, чему
  соответствуют грамматические значения вводных компонентов, выражающих:
<...>
г) степень обычности, нормальности сообщаемого: В.к. – по обыкновению,
как обычно, по привычке, как водится, как правило, как всегда, как
иногда бывает, случается и т.п.

То же и у  Леканта:

Оценку обычности высказывания выражают следующие вводные конструкции:
  по обыкновению, как обычно, по привычке…

Примеры из Нацкорпуса:

Мы все трое в испуге подскочили, понимая, по привычке, что надо куда-то идти. [Анатолий Приставкин. Кукушата или жалобная песнь для
  успокоения сердца (1992)]
Ляля, по привычке, закрыла лицо ладонями, но никто не хотел щадить... [Аркадий Львов. Двор (1981)]
А когда я, по привычке, попробовал опять подумать о чём-нибудь человеческом, то у меня, к моему удивлению, на этот раз ничего не
  получилось. [Валерий Медведев. Баранкин, будь человеком! (1957)]
Это были воронки, на которые он, по привычке, сначала не обратил внимания. [В. П. Катаев. Сын полка (1944)]
Они сели, по привычке, на свои места, как сидели обычно в классе: Сеня Пичугин и Шура Капустина впереди, а Костя Рожков сзади всех, на
  последней парте. [Л. А. Кассиль. У классной доски (1942)]

.
Ну а выделять ли запятыми по привычке в приведённом в вопросе предложении? Однозначно на этот вопрос, думаю, нельзя ответить.  Читаете без пауз — не выделяйте; читаете с паузами — выделите.
В таких случаях решение о постановке знаков препинания принимает автор текста.

A:

1) Обстоятельственная падежная форма "по привычке" (как другие нераспространенные обстоятельства)  обособляется очень редко, так как обычно вписывается в структуру предложения, но исключения бывают. В этом случае обособленное обстоятельство имеет значение добавочного сообщения, например:
А когда я, по привычке, попробовал опять подумать о чём-нибудь человеческом, то у меня, к моему удивлению, на этот раз ничего не получилось. Мы уже закончили! ― недовольно, по привычке, ответил начмед.Первое время я покупал ватрушки на двоих и грел полный чайник, по привычке. Рассказывали друг другу много анекдотов и уже не на кухне, но некоторые полушепотом, по привычке.
2) Может быть,  "по привычке" не часто называют вводным словом, хотя по значению оно напоминает тематику вводных слов, называемую степенью обычности  (как обычно, как всегда).
3) В заданном предложении семантика "по привычке" не совсем обычная, скорее здесь имелось в виду "по своему обыкновению". А вот это обстоятельство обособляется уже чаще, например: Воланд, по своему обыкновению, находился в спальне, а где был кот ― неизвестно (М. А. Булгаков).
4) Подводя итог можно сказать, что в нашем случае обособление факультативное, но оно имеет определенный смысл: обособленное обстоятельство выделяется, подчеркивается. Можно также сказать, что обособленный оборот является средством художественной выразительности, так как выражает ироническое отношение автора к описываемой ситуации.


Q:

JavaScript How to define an array of undefined length of empty objects?

var array = [];

var object = {};

Now, I need an array of empty objects.
array[0] = {};
array[1] = {};
//........
//........

and
var array = [{}];

is obviously not right.
How to define array of (empty) objects in JS?
var array = [{},{},{},{},.........];

Thanks.
EDIT:
The reason I need is the same reason that having an array with undefined length is useful, and mathematically natural in some cases.
I need object wrappers, and for initialization, it's just an empty object, like some values are null or undefined in many cases.
so, I'll have
var object = {};
array[0].value = 'foo', array[1].value = 'bar'.....
However, I do need multiple object wrappers, and the number is not pre-determined, so consequently, I need an arrays of the objects.
So, I am sorry, I modify my Question title
JavaScript How to define an array of undefined length of empty objects?

A:

In your array, pushing object in any way is right. That's totally ok. like:
var arr = [];
arr.push({}); // ok
aa[1] = {} // also ok

or:
var arr = [{}, {}, {}]; // the way you are doing is also fine

Or, if you want to do it via loop, that is also fine. Like:
var arr = [];
for(var i=0; i<5; i++){
    arr[i] = {};
}

A:

Arrays can grow and shrink dynamically. So from a certain point of view, they are already of undefined length. You can always add new objects to it if you want to.
You can also create a helper function which checks first if an object exists at a certain position and if not, creates a new one.
You mentioned array[2].value = 'foo' as an example. Here is a helper function that you could use:
function getObjectAtIndex(arr, index) {
    return arr[index] || (arr[index] = {});
}

and then, instead of writing array[2].value = 'foo', you'd write:
getObjectAtIndex(array, 2).value = 'foo'


Q:

How to fetch multiple duplicate value count in sql

i have database in which user device id and device registerd date (cr_date) stored i want to fetch list of total count of registerd devices on same day with date wise
Here below display table structure
device_ID   | cr_date
--------------------
    1       | 2016-06-02 18:02:13
    2       | 2016-06-02 18:03:58
    3       | 2016-06-02 18:04:11
    4       | 2016-06-03 18:04:33
    5       | 2016-06-03 18:04:33
    6       | 2016-06-04 18:04:44

and i want below result
count   |  date
---------------------------------
    3   |   2016-06-02
    2   |   2016-06-03
    1   |   2016-06-04

i used below query but dosent get success
SELECT device_type, count(*) AS duplicate_count
FROM (
 SELECT device_type FROM tbl_app_deviceregister
 GROUP BY device_type HAVING COUNT(device_type) > 0
) AS t

A:

Did you want this;)
SELECT count(1) as `count`, date_format(cr_date, '%Y-%m-%d') as `date`
FROM tbl_app_deviceregister
GROUP BY `date`
ORDER BY `count` DESC


Q:

Calling multiple sub-processes sequentially

I need to be able to call a bash command every few milliseconds and I am trying to use the sub-process to do so. I currently use:
p = subprocess.Popen(command, universal_newlines=True, cwd=CurrentWorkingDirectory ,shell=True, stdout=subprocess.PIPE)

and have a timer firing the command at the times needed.
My question is, if I am calling these commands through the use of subprocess.Popen, will this be opening new terminals to run each command? I want to make sure I don't run into any memory usage issues as I will be calling thousands of these commands.
What is the best way to go about this?

A:

Whatever you do, there are probably better alternatives than starting a thousand of processes in a minute whether you run out of memory or not.
To run subprocesses sequentially, use subprocess.check_call instead of subprocess.Popen.

will this be opening new terminals to run each command?

No, unless the command itself starts a new terminal.


Q:

Disk utility, shrink 1 partition, expand the other

I have two partitions on my external HDD, I shrinked 1 partition (Macintosh Lion) in order to expand the other (Macintosh HD), but I can't drag the lower right corner to expand of the 'Macintosh HD' partition, I can only do it with the 'Macintosh Lion' one, ideas?

A:

Yes, Disk Utility can’t edit space in the “middle” of the disk, only space on the “ends”.
There is an app called iPartition that sounds like it does what you need. From the website:

iPartition makes it easy to create, destroy, resize or format partitions on your hard disks, whether internal, external, fixed or removable.

Two caveats: first, I’ve never used iPartition myself, so I can’t comment on its reliability. I’ve used their other product (iDefrag), which was very stable and I’d recommend, but not iPartition. Also, according to archived blog post, iPartition doesn’t work with Lion FileVault partitions. Don’t know if that affects you.


Q:

why this bash script (flow control if else) doesn't work

setjdk()
{
     if ["$1" == "a"]
         then echo "A"
     elif ["$1" == "b"];
         then echo "B"
     else
        echo "Cow"
     fi

}

The above bash function aims to output different result based on the first given parameter value. However, when it doesn't work as expected. when I type in "setjdk a", i got the following result:
-bash: [a: command not found
-bash: [a: command not found
Cow

A:

[ is a command. Commands need whitespace between their arguments.
[ "$1" == "a" ]


Q:

Installed on edit trigger ... which sheet was edited?

Example:
https://spreadsheets.google.com/ccc?key=0Am8IA9FchrLbdHlkbWFMOWtZa1Y0RWpMNUV5Q3RMaVE&hl=en&authkey=CPXlr5UL
When you install an on-edit trigger, your function gets passed the start and end rows and columns. But not which sheet was edited.
Naturally, my first thought was to grab SpreadsheetApp().getActiveSheet() but that doesn't work.
Edit any cell in the example spreadsheet. The installed on-edit trigger will fill in values to Sheet1 telling you what you edited. Now switch to sheet 2 or sheet 3 and edit something. It always reports that Sheet1 was edited.
The trigger's code:
function my_on_edit(e) {

  //the object passed in, e, doesn't know what sheet was edited. Really!

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var spreadsheetname = ss.getName();

  var thesheet = ss.getActiveSheet();

  var sheetname = thesheet.getName();

  //Tell us what was edited, please.
  ss.getSheetByName("Sheet1").getRange("A2:E2").setValues([[ spreadsheetname, sheetname, e.range.rowStart, e.range.columnStart, Utilities.jsonStringify(e)]]);

}

How can I get the sheet edited? Is this my mistake or is this a bug? Or a deficiency in how they're doing the event handling?

A:

I crossposted this question to the google apps script help forum:
http://www.google.com/support/forum/p/apps-script/thread?tid=535e1d8ff33a731f&hl=en
Henrique Abreu replied with an answer; that this is a deficiency with how Google Apps Script does installed onedit triggers. But he also gave an undocumented workaround:

There's two undocumented things I use to find out which sheet was edited.
  First, by inspecting the parameter passed to the installable edit function, I found out a "gridId" parameter, which is the ID of the sheet (same number we see on the url ...#gid=).
  And the sheet.getSheetId(), which shows up in the code editor but not in the docs.
  Here is an example:

function my_on_edit(e) {
  var s = findSheetById_(e.gridId);
  var r = e.range;
  s.getRange(r.rowStart, r.columnEnd+1).setValue( s.getName() );
}

function findSheetById_(id) {
  var sheets = SpreadsheetApp.getActive().getSheets();
  for( var i in sheets )
    if( sheets[i].getSheetId() == id )
      return sheets[i];
  throw 'Unable to find sheet with id: '+id;
}


Q:

How to add git hook to the remote repository?

I've created a pre-commite hook and it works on my local machine, but I don't know how can I share this hook with my collegs
I will be grateful for any help.
Thanks in advance Denis

A:

It’s important to note that client-side hooks are not copied when you
  clone a repository.

On Server side, the 1st hook is pre-receive.
Not everything is possible in this one, depending on what you want to do before the commit, but that's the place to do stuff if you want to do it for everybody who use the repository.
Note: You have to have access to the git server to do that.
Edit:
For global settings, take a look at https://stackoverflow.com/a/8842663/3445619
But this solution requires a new git init to be done by everyone.
If you don't have access to the git server or want to apply code ruler/styler, I would recommend to ask your colleague to make a link from .git/hooks/pre-commit to a versioned file where you can edit your own pre-commit hook for everyone.
Or simply share your file with them, if it will never change. (But this will have to be done for every newcomers).


Q:

PHP check if pass 5 minutes between two dates

I am trying to check if pass 5 minutes between two dates.
Here is my code:
    $time = strtotime("+5 minutes").'
';
$var = '1518219956';
$e1 = date("d-m-Y H:i",$time);
$e2 = date("d-m-Y H:i",$var);
if($var > $time){
    echo 'true
';
    echo 'Time: '.$e1.'
 Var:'.$e2;
} else{
    echo 'false
';
    echo 'Time: '.$e1.'
 Var: '.$e2;
}

I am sorry but I lost myself with this timestamps..

A:

Sorry, I don't mean to be rude but I was confused by the question. What I designed here was to see if time B is five minutes after Time A.
A few notes:
No need to bother with strtotime or date. Just keep everything in unix time. Compare the seconds by using 60 * 5. 60 for 60 seconds in a minute and 5 for the number of minutes.
<?php
//Time A
$timeA = '1518223062';

//Time B (Which I set at the current time)
$timeB = time();

//five minutes in seconds
$fiveMinutes = 60 * 5;

//check if current time is after 5 minutes the initial time
if ( ($timeA+$fiveMinutes) <= $timeB) {
  echo "True";
}
else {
  echo "False";
}

?>


Q:

get url data via get method

How can i get a param from my url??

?access_token=Atza|IQEBLjAsAhR6-eMBCha6N7pV6bZ3i1Z3kv2IrgIUfOwQ_NUK0yf4e4Cb3lWsqA91zrmc7JRnwtNtQH1U433_A9odU1QF6O-RR4hHPuU5_1i1XZZyg7Sk_P0hs6cLzMaLQzaZ0JZtYhWsoCWBDu8Piuu3AHq8wu4mPQdTFaaCvT4tP-gHPBFu5Cu5uPbrPli-VOYo51sWSRFEWYFpzypjxkU4Ti-Y8bzFjcHo6RYJF6jXvIE8a4ZVG-5bX2k9ftjvsJQQsOsywh8ir3wJkVm9I-rG_RfuGf_OiCwZ5pbn63k0161Gwr4Phv0TaUjBV-UaCfBjFP7eiBwmKL53hPPYiUFakRmHKctVp1PodOMo83y1ovuX7XZfQujmWHrvkJmfDOgjiuqxOLnGhK_xCbu09hFNLwMvcV15E19OQ_247S68j2c9nSLDVeH1HKOGzxsgeQnNFfIMzTmOPNx8zThQeD5upjDFbxfrIDGNZeApJWWUVgfJLkbnvdAem_K1qeQNAnWp8IwRgoWWr7wNip5Dm5LXA64z4vQsT_NkykoOdFWE943Pd1nGOIAbcTe_AEdsjuibZ3azJ4TfVVPtgG8J9KMcxxe6npnb35sMI-kqOgDb3J4&token_type=bearer&expires_in=3600&scope=profile
  payments%3Awidget payments%3Ashipping_address

I want to get access token data on my phtml page!
I used <?php echo $this->getRequest()->getParam('access_token');?> but not wroking for access_token
How can get that??

A:

in magento way
Mage::app()->getRequest()->getParam('access_token');
Mage::app()->getRequest()->getParam('token_type');
Mage::app()->getRequest()->getParam('expires_in');

in simple php
$_GET['access_token'];
$_GET['token_type'];
$_GET['expires_in'];

for access token
$url=parse_url(Mage::helper('core/url')->getCurrentUrl());

$fragment = $url['fragment'];

$access_token = preg_replace('/&token_type=(.*)/',"",$fragment);

A:

This code work for me! As i see that access_token was encoded on a array.
$amazon_data = json_decode($_REQUEST['amazon_Login_state_cache']);
access_token = $amazon_data->access_token;

Thank you all for sharing your knowledge