Q: How to Store Boost Factor of Field in Index in lucene I am using lucene to search in the address book like product. I want to boost the search results according to some specific criteria. (e.g. Match in location field should have greater relevance than match in name of entity.) This is fixed criteria for my case.
I am trying to store the boostfactor with Field by calling SetBoost() method while indexing. But then also result's score is not as expected. It's considering same boost value for every field.
Can anybody suggest me where I am going wrong?
Code I am using to build the index.
Directory objIndexDirectory =
  FSDirectory.Open(new System.IO.DirectoryInfo(<PathOfIndexFolder>));
StandardAnalyzer objAnalyzer =
  new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
IndexWriter objWriter = new IndexWriter(
  objIndexDirectory, objAnalyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
Document objDocument = new Document();
Field objName =
  new Field("Name", "John Doe", Field.Store.YES, Field.Index.ANALYZED);
Field objLocation =
  new Field("Location", "NY", Field.Store.YES, Field.Index.NOT_ANALYZED);
objLocation.SetBoost((2f);
objDocument.Add(objName);
objDocument.Add(objLocation);
objWriter.AddDocument(objDocument);

What I am trying to achieve is,
Assuming there is three entries in index:

*

*John Doe, NY

*John Foo, New Jercy

*XYZ, NY

In this case if the search query is "John NY", then result should have relevance like

*

*John Doe, NY

*XYZ, NY

*John Foo, New Jercy

A: I can't figure out what you think is wrong with your approach, but here is the code I was using to test with:
class Program
{
    static void Main(string[] args)
    {
        RAMDirectory dir = new RAMDirectory();

        IndexWriter writer = new IndexWriter(dir, new StandardAnalyzer());

        AddDocument(writer, "John Doe", "NY");
        AddDocument(writer, "John Foo", "New Jersey");
        AddDocument(writer, "XYZ", "NY");

        writer.Commit();

        BooleanQuery query = new BooleanQuery();
        query.Add(new TermQuery(new Term("Name", "john")), BooleanClause.Occur.SHOULD);
        query.Add(new TermQuery(new Term("Location", "NY")), BooleanClause.Occur.SHOULD);

        IndexReader reader = writer.GetReader();

        IndexSearcher searcher = new IndexSearcher(reader);
        var hits = searcher.Search(query, null, 10);

        for (int i = 0; i < hits.totalHits; i++)
        {
            Document doc = searcher.Doc(hits.scoreDocs[i].doc);
            var explain = searcher.Explain(query, hits.scoreDocs[i].doc);
            Console.WriteLine("{0} - {1} - {2}", hits.scoreDocs[i].score, doc.ToString(), explain.ToString());
        }
    }

    private static void AddDocument(IndexWriter writer, string name, string address)
    {
        Document objDocument = new Document();
        Field objName = new Field("Name", name, Field.Store.YES, Field.Index.ANALYZED);
        Field objLocation = new Field("Location", address, Field.Store.YES, Field.Index.NOT_ANALYZED);
        objLocation.SetBoost(2f);
        objDocument.Add(objName);
        objDocument.Add(objLocation);
        writer.AddDocument(objDocument);
    }
}

This code does return the results in the order you wish.  In fact it returns them in that order for this set if you exclude the boost.  I'm not an expert on Lucene scoring, but I believe this is because you are matching "NY" exactly for "XYZ, NY", and the "John" query is a partial match.  You can read the details printed out via the Explain class.

A: Have you tried MultiFieldQueryParser?


Q: Sql query for joining three tables I have three tables
 Users
ID || login   || name     || crypted_password  || salt
 2 || teacher1|| teacher1 || #@@EDGCH          || SDWH@##

Role(main)
id||name
3 ||teacher

Role_users
id || role_id || user_id
2  ||  3      ||  2

now from these three tables i want to fetch crypted_password and salt value of user whose role=teacher.
how can it be done!!

A: You can use the join syntax to join tables according to the matching fields:
SELECT crypted_password, salt
FROM   users
JOIN   role_users ON users.id = role_uses.user_id
JOIN   role ON role_users.role_id = role.id
WHEN   role.name = 'teacher'

A: Join Like this
SELECT U.*
FROM USER U
JOIN Role_Users RU ON RU.UserID = U.ID
JOIN Role R ON R.ID = RU.Role_ID
WHERE <Your Conditions here>

A: select crypted_password,salt
from Users U
inner join Role_users RU on RU.user_id = U.ID
inner join Role R on R.id = RU.role_id
where R.name='teacher'


Q: Rewrite Rule Not Redirecting To The Specified File Recently I started working with .htaccess file to redirect API call to a specific file. However, even though my .htaccess file is working (tested it with just text on top of the file and I get "Internal Server Error") my rule is not working. Instead, Index.php is always read. The goal is, whenever the url ends with "myOwnAPI/" it takes you to the file "somefile.php". All files(index.php, somefile.php, .htaccess) leave in the same directory.
The .htaccess file contains just one rule.
Please help.
httpd.conf file
<Directory />
    AllowOverride All
    Require all denied
</Directory>

AllowOverride All

.htaccess file
RewriteEngine on

RewriteRule   ^myOwnAPI/?$   somefile.php  [NC,L]

A: Every url start with a "/" so
RewriteRule   ^myOwnAPI/?$   somefile.php  [NC,L]

won't ever match.
Change it to
RewriteRule   ^/myOwnAPI/?   /somefile.php  [NC,L]

Moreover, please read the offical documentation https://httpd.apache.org/docs/2.4/rewrite/flags.html if you need to "pass" the parameters to the new url (flag QSA).


Q: How to provide collection name in nodejs/mongoose/ for $out I have a field called pin_count which has a count of another field called pins but due to broken logic the count of both fields mismatched, so I am writing migration script using migrate-mongo and below is what I did. But not sure why it's not working.
I have tested below which is working fine:
db.pins.aggregate([
    { '$addFields': {
        'pin_count': { '$size': '$pins'}
    }},
    { "$out": "pins" }
]);

But, the same in migrate-mongo()(https://www.npmjs.com/package/migrate-mongo) plugin isn't working.
'use strict';

const BPromise = require('bluebird');
const types = ['pins`];

module.exports = {
  up(db) {
      return BPromise.resolve(types).mapSeries(col => {
          return db.collection(col).aggregate([
              { '$addFields': {
                  'pin_count': { '$size': '$pins'}
              }},
              { "$out": col }
          ]);
      });
  },

  /**
   * No need to have down script since this is a correction of the data
   */
  down: function (db) {

  }
};

Document structure:
{"_id" : ObjectId, "pins" : [ 'da', 'dal' ], "pin_count" : 4}


Q: Cannot get meteor.js to return mongo collection So I am trying to return a mongoDB database value to a template in my Meteor.js project.  The code that I am using is below.
Template.ResourceManager.helpers({
BoosterOneFuel : function(){
        return resources.findOne({system : "booster1"}).fuel;
}

});

However, this always returns null.  When I try to alert it, the alert also says that this value is null.  Mongo can find it when I run this line in the console while running meteor mongo:
db.Resources.findOne({system : "booster1"}).fuel;

But meteor cannot.  (This is on a localhost, so meteor mongo should affect meteor's database)
I don't think its a problem with meteor loading before mongo does, because the following still doesn't work :
if(resource.find({system : "booster1"}))
     alert(resources.findOne({system : "booster1"}).fuel);

Anybody know whats going on here?
Thanks in advance.

A: Assuming the collection is actually called resources - i.e. you have something that looks like:
resources = new Mongo.Collection('Resources');

Then it sounds like you just need to publish the documents to the client:
server/publishers.js
Meteor.publish('resources', function() {
  return resources.find();
});

client/subscriptions.js
Meteor.subscribe('resources');

Of course the subscription could happen in your template or router instead of globally, but that's beyond the scope of this question.
Also note you should add a guard to your helper. For example:
Template.ResourceManager.helpers({
  BoosterOneFuel : function() {
    var b1 = resources.findOne({system : "booster1"});
    return b1 && b1.fuel;
  }
});


Q: Using Spring MVC Frame work , How to iterate a list and create pins in bingmap? I'm using API version 8 and while running this code , I can able to get
only one pin which has data in first object in the list.
Here List has objects from object we have Latitude , Longitude , Title and Description.
Iteration is done successfully but only first data is reflected in the BingMap.
How can I get all the pins from the list and that reflected in BingMap.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>

<title></title>
<meta charset="utf-8" />

            <c:forEach var="message" items="${list}">

                    <input id="lat" type="hidden" value="${message.lat}" /> <input
                        id="lon" type="hidden" value="${message.lon}" /> <input
                        id="title" type="hidden" value="${message.title}" /> <input
                        id="description" type="hidden" value="${message.description}" />

            </c:forEach>

A: This isn't really a Bing Maps question, but more of a Spring MVC question. Looking at your HTML the first issue I see is that each item in your table has an ID assigned to them. ID's are meant to be unique in HTML, but with the code you have you will end up creating multiple elements with the same ID which is technically creating an invalid HTML and you will only be able to retrieve the last item by ID. Pulling your data from t a table like this likely isn't the best way to implement your application. There is likely some way to generate a JSON object using Spring MVC, however I'm not familiar with Spring MVC development. If you want to continue with the method you are using I would suggest changing the ID's to classes and then you will be able to retrieve the elements by class name. Here is an example worth trying.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 <!DOCTYPE html>

 <title></title>
 <meta charset="utf-8" />

             <c:forEach var="message" items="${list}">

                     <input class="lat" type="hidden" value="${message.lat}" /> <input
                         class="lon" type="hidden" value="${message.lon}" /> <input
                         class="title" type="hidden" value="${message.title}" /> <input
                         class="description" type="hidden" value="${message.description}" />

             </c:forEach>


Q: OpenGL Red Book 8th - First Example gives black box (Ubuntu) After getting the first example program compiled from the 8th edition OpenGL Programming Guide after many alterations suggested by many sites, I am the proud owner of a black box - a vast improvement from the hours before, but it's embarrassing to admit that I've watch most of this with a debugger and unless something basic is wrong with the program, I have no clue where to look. Other OpenGL examples have run, but I'm trying to get the first example in the new book to run.
My box:
john@zerofluid:~/Downloads$ glxinfo | grep OpenGL
OpenGL vendor string: NVIDIA Corporation
OpenGL renderer string: GeForce GT 610/PCIe/SSE2
OpenGL version string: 4.3.0 NVIDIA 313.30
OpenGL shading language version string: 4.30 NVIDIA via Cg compiler
OpenGL extensions:

Linux zerofluid 3.8.0-26-generic #38-Ubuntu SMP Mon Jun 17 21:43:33 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
(latest 13.04 Ubuntu)
I have a problem - it's way too much code to post here, but it is the first example of the book - as small as it gets and I have no idea of where the problem really is. It would be cool if someone actually wants to help - I'd feed it back to the author of the book. Yes, the LoadShader was found elsewhere and might be the problem, but it was supposed to be a solution. It's kind of hard to have any faith in the book when I can't get the first example to compile.
It can be found here:
https://github.com/kestess/opengl8thfirstexample.git

A:
it's way too much code to post here

Not really.
Try this:
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <vector>
#include <iostream>

struct Program
{
    static GLuint Load( const char* vert, const char* geom, const char* frag )
    {
        GLuint prog = glCreateProgram();
        if( vert ) AttachShader( prog, GL_VERTEX_SHADER, vert );
        if( geom ) AttachShader( prog, GL_GEOMETRY_SHADER, geom );
        if( frag ) AttachShader( prog, GL_FRAGMENT_SHADER, frag );
        glLinkProgram( prog );
        CheckStatus( prog );
        return prog;
    }

private:
    static void CheckStatus( GLuint obj )
    {
        GLint status = GL_FALSE, len = 10;
        if( glIsShader(obj) )   glGetShaderiv( obj, GL_COMPILE_STATUS, &status );
        if( glIsProgram(obj) )  glGetProgramiv( obj, GL_LINK_STATUS, &status );
        if( status == GL_TRUE ) return;
        if( glIsShader(obj) )   glGetShaderiv( obj, GL_INFO_LOG_LENGTH, &len );
        if( glIsProgram(obj) )  glGetProgramiv( obj, GL_INFO_LOG_LENGTH, &len );
        std::vector< char > log( len, 'X' );
        if( glIsShader(obj) )   glGetShaderInfoLog( obj, len, NULL, &log[0] );
        if( glIsProgram(obj) )  glGetProgramInfoLog( obj, len, NULL, &log[0] );
        std::cerr << &log[0] << std::endl;
        exit( -1 );
    }

    static void AttachShader( GLuint program, GLenum type, const char* src )
    {
        GLuint shader = glCreateShader( type );
        glShaderSource( shader, 1, &src, NULL );
        glCompileShader( shader );
        CheckStatus( shader );
        glAttachShader( program, shader );
        glDeleteShader( shader );
    }
};
#define GLSL(version, shader) "#version " #version "\n" #shader

const char* vert = GLSL
(
    400 core,
    layout( location = 0 ) in vec4 vPosition;
    void main()
    {
        gl_Position = vPosition;
    }
);

const char* frag = GLSL
(
    400 core,
    out vec4 fColor;
    void main()
    {
        fColor = vec4( 0.0, 0.0, 1.0, 1.0 );
    }
);

enum VAO_IDs { Triangles, NumVAOs };
enum Buffer_IDs { ArrayBuffer, NumBuffers };
enum Attrib_IDs { vPosition = 0 };

GLuint VAOs[NumVAOs];
GLuint Buffers[NumBuffers];

const GLuint  NumVertices = 6;

void init(void)
{
    glGenVertexArrays(NumVAOs, VAOs);
    glBindVertexArray(VAOs[Triangles]);

    GLfloat  vertices[NumVertices][2] = {
        { -0.90, -0.90 },  // Triangle 1
        {  0.85, -0.90 },
        { -0.90,  0.85 },
        {  0.90, -0.85 },  // Triangle 2
        {  0.90,  0.90 },
        { -0.85,  0.90 }
    };

    glGenBuffers(NumBuffers, Buffers);
    glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    GLuint program = Program::Load( vert, NULL, frag );
    glUseProgram(program);

    glVertexAttribPointer(vPosition, 2, GL_FLOAT, GL_FALSE, 0, (void*)(0) );
    glEnableVertexAttribArray(vPosition);
}

void display(void)
{
    glClear(GL_COLOR_BUFFER_BIT);

    glBindVertexArray(VAOs[Triangles]);
    glDrawArrays(GL_TRIANGLES, 0, NumVertices);

    glutSwapBuffers();
}

int main(int argc, char** argv)
{
     glutInit(&argc, argv);
     glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
     glutInitWindowSize(512, 512);
     glutInitContextVersion(4, 0);
     glutInitContextProfile(GLUT_CORE_PROFILE);
     glutCreateWindow(argv[0]);

     glewExperimental = GL_TRUE;
     if( GLEW_OK != glewInit() )
         exit(EXIT_FAILURE);

     init();

     glutDisplayFunc(display);
     glutMainLoop();
}

No reason to request a 4.3 context if you're using #version 400 core.


Q: how to convert a WebView into an ImageView? i have a WebView of an html page which shows only one image
http://www.google.fr/intl/en_com/images/srpr/logo1w.png
webView = (WebView) findViewById(R.id.webView);
webView.loadUrl("http://www.google.fr/intl/en_com/images/srpr/logo1w.png");

is there a simple way to turn it into an ImageView ?

A: try this:
webView.buildDrawingCache();

Bitmap bmap = imageView.getDrawingCache();

imageView.setImageBitmap(bmap);

A: You can open an InputStream pointing to the image URL (using URLConnection), and create a Drawable from it using Drawable.createFromStream. You can then set the Drawable onto the ImageView.

A: As per your above comment: ok you are right it must be easier getting the image directly... how do i do that ? Do i look in bitmap doc ?, i assume you want to load image from web and want to display the same in imageview, if this is the case then refer this to get exactly: How to display image from URL on Android

A: Bitmap btmp = mwebview.getDrawingCache(true);

this will return the Bitmap image in webview.
And the bitmap can be set to image view by:
imageView.setImageBitmap(bmap);


Q: Drawing rectangle underneath PIXI.Text In a word game I am trying to draw score as white numbers above a blue (or red) rectangle:

For example, in the above screenshot it is the number "13".
Here is my entire class Score.js (with currently hardcoded WIDTH and HEIGHT):
"use strict";

function Score(color) {
        PIXI.Container.call(this);

        this.interactive = false;
        this.buttonMode = false;
        this.visible = false;

        this.bgGraphics = new PIXI.Graphics();
        this.bgGraphics.beginFill(color, 1);
        this.bgGraphics.drawRect(0, 0, Score.WIDTH, Score.HEIGHT);
        this.bgGraphics.endFill();
        this.addChild(this.bgGraphics);

        this.text = new PIXI.Text('XXX', {font: '20px Arial', fill: 0xFFFFFF});
        this.text.x = 1;
        this.text.y = 1;
        this.addChild(this.text);
}

Score.prototype = Object.create(PIXI.Container.prototype);
Score.prototype.constructor = Score;

Score.WIDTH  = 36;
Score.HEIGHT = 24;

Score.prototype.setText = function(str) {
        this.text.text = str;
}

I wonder, how to modify my setText() function, so that a new rectangle is drawn on each call - as a bounding rectangle for the str argument?
I have looked at the PIXI.Text.getBounds() method, but it returns a Matrix and not a Rectangle...

A: I think you can just use this.text.width.  This has historically had some bugs associated with it, but it should be working right in the latest version.


Q: Entity Framework SetInitializer and Seed Data Having difficulty figuring out why my database will not seed:
Here is what I have in my Global.asax code:
protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();

        Database.SetInitializer(new DataContextInitializer());
        DataContext db = new DataContext();
        db.Database.Initialize(true);

        WebSecurity.InitializeDatabaseConnection("DataContext", "UserModels", "Id", "UserName", autoCreateTables: true);

    }

and here is the DataContextInitializer:
public class DataContextInitializer : CreateDatabaseIfNotExists<DataContext>
 {
    protected override void Seed(DataContext context)
    {
        if (!WebSecurity.Initialized)
        {
            WebSecurity.InitializeDatabaseConnection("DataContext", "UserModels", "Id", "UserName", autoCreateTables: true);
            WebSecurity.CreateUserAndAccount("admin", "12345");
        }

        var roles = (SimpleRoleProvider)Roles.Provider;
        var membership = (SimpleMembershipProvider)Membership.Provider;

        if (!roles.RoleExists("admin"))
        {
            roles.CreateRole("admin");
        }
        if (membership.GetUser("admin", false) == null)
        {
            membership.CreateUserAndAccount("admin", "12345");
        }
        if (!roles.GetRolesForUser("admin").Contains("admin"))
        {
            roles.AddUsersToRoles(new[] { "admin" }, new[] { "admin" });
        }
    }
}

While debugging, the SqlException that I get is "There is already an object named ... in the database." Any idea why this would occur?

A: These are the steps I took:

*

*Copied seed logic to the Migrations Configuration.cs file.

*Excluded an old migration from the project

*Within package console manager performed add-migration and gave it a name

*Then ran update-database -verbose -force AFTER making sure that WebMatrix.WebData reference properties had 'CopyLocal = true'

I hope this helps someone.


Q: JsDoc group multiple @typedef into one configuration file I have a project where I have to define multiple jsDoc's @typedef for describing multiple custom object types required by functions in the project.
I'm wondering if I could group all these @typedef together into a single module/configuration file and reference them project-wide?
Otherwise I would have to write these custom @typedef into multiple modules, and given that most of these have many properties this could create very big comment blocks that makes the modules ugly and difficult to read.


Q: How to run multiple methods parallely and get outputs from each of them in java I want to run three different methods in parallel to improve the performance in Java. Also I need to get the outputs from all the three of them. Below is the sample which I have tried. here, I'm not sure how to retrieve the returned string values. Please help me to add(concatenate all the three strings to total).
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class test {

    public static void main(String[] args) {
        String total = "";

        Callable<String> callable1 = new Callable<String>()
        {
            @Override
            public String call() throws Exception
            {
                String t1 = "";
                t1 = method1();
                return t1;
            }
        };

        Callable<String> callable2 = new Callable<String>()
        {
            @Override
            public String call() throws Exception
            {
                String t2 = method2();
                return t2;
            }
        };

        Callable<String> callable3 = new Callable<String>()
        {
            @Override
            public String call() throws Exception
            {
                String t3 = method3();
                return t3;
            }
        };

        List<Callable<String>> taskList = new ArrayList<Callable<String>>();
        taskList.add(callable1);
        taskList.add(callable2);
        taskList.add(callable3);

        ExecutorService executor = Executors.newFixedThreadPool(3);

        try
        {
            executor.invokeAll(taskList);
            //total = ;(want to concatenate all the strings here).

            System.out.println(total);
        }
        catch (InterruptedException ie)
        {
            //do something if you care about interruption;
        }

    }
    public static String method1()
    {
        System.out.println("method1");
        return "1";

    }

    private static String method2()
    {
        System.out.println("method2");
        return "2";
    }

    private static String method3()
    {
        System.out.println("method3");
        return "3";
    }

}

A: As taskList is a List<Callable<String>>, executor.invokeAll(taskList) returns a List<Future<String>> containing a Future<String> corresponding to each task in taskList.  You need to save that List<Future<String>> so that you can later get at the results of your tasks.  Something like this:
List<Future<String>> futureList = executor.invokeAll(tasklist);
String result = futureList.get(0).get() +
                futureList.get(1).get() +
                futureList.get(2).get();

In addition to InterruptedException, Future.get() can also throw CancellationException and ExecutionException so you need to be prepared to deal with these in your try block.

A: As you have very few number of task, you can create 3 CompletableFutures and stream over it and join it.
CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> method1());
CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> method2());
CompletableFuture<String> task3 = CompletableFuture.supplyAsync(() -> method3());

String concate = Stream.of(task1, task2, task3)
        .map(CompletableFuture::join)
        .reduce("", (s1, s2) -> s1 + s2);
System.out.println(concate);

A: Adding on top of @Govinda answer -
You can create Stream of CompletableFutures by using the supplyAsync factory method and complete them by calling CompletableFuture::join and concat by calling Collectors.joining().
CompletableFuture<String> task1 = CompletableFuture.supplyAsync(Test::method1);
CompletableFuture<String> task2 = CompletableFuture.supplyAsync(Test::method2);
CompletableFuture<String> task3 = CompletableFuture.supplyAsync(Test::method3);

String concat =
    Stream.of(task1, task2, task3).map(CompletableFuture::join).collect(Collectors.joining());

System.out.println(concat);


Q: How do i add fabricjs-canvas objects in json format to a indexed array in php? I'm trying to make a database system to handle the saved fabricjs canvases. For every thing to work i need the canvas objects
json=canvas.toDatalessJSON; // in javascript

...to be saved in php as .json file in a indexed array system that allows me to load and add more canvas objects or delete objects.
The thing troubling me is how to actually structuring this. What i'm trying here is something like:
... The json structure i'm considering ...
["1"]{Object:.....}
["2"]{Object:.....}
["4"]{Object:.....} (["3"] deleted in this case)

... Trying to create in php ...
$i="1";
$A=[];
$A[$i]=[];
array_push($A[$i],json_decode($json));
$newjson=json_encode($A);

But this is obviously not the way to make it. Any ideas ?
EDIT 1
Thank's for your answer @Michael. I ended up not using exactly what you propose. But i accept it as the answer that let my to a solution. In my solution i'm adding the index to the object, and unset the index when i'm going to use the object.
Create:
$dataA=array();
$dataB=json_decode($data,true);
$dataB["index"]= $ThumbIndex;
$dataA[]=&$dataB;
$data=json_encode($dataA);
file_put_contents($filename.'.json',$data);

Add:
$data0=file_get_contents($filename.'.json');
$dataA=json_decode($data0,true);
$dataB=json_decode($data,true);
$dataB["index"]= $ThumbIndex;
$dataA[]=&$dataB;
$data=json_encode($dataA);
file_put_contents($filename.'.json',$data);

A: Assuming you are trying to overwrite element "1" in your json object using php, try this:
$newjson = json_decode($json, true);
$newjson["1"] = Array();
$newjson = json_encode($newjson);

If you want to add an element:
$newjson = json_decode($json, true);
$newjson[] = Array();
$newjson = json_encode($newjson);


Q: Removing tuples that have the same pair of values from a list I want to remove all the tuples that have the same pair of values, e.g. [(1,1), (2,3), (2,2), (3,4)] I want [(2, 3), (3, 4)]. I am working in Haskell. This is what I tried:
unique [] = []
unique (x:xs) = if (fst x) == (snd x) then unique (xs) else x:[]

And the output was:
[(2,3)]

I am confused on why (3, 4) did not appear.

A: Because your else case says:
unique [] = []
unique (x:xs) = if (fst x) == (snd x) then unique (xs) else x:[]
It thus says if fst x is not equal to snd x, then we return x : [] (or shorter [x]), and we are done. So it does not perform recursion on the rest of the list.
We can solve this by adding recursion on the rest of the list, like:
unique [] = []
unique (x:xs) = if fst x == snd x then unique xs else x : unique xs
That being said, we can use a filter here, like:
unique :: Eq a => [(a, a)] -> [(a, a)]
unique = filter (\(x, y) -> x /= y)
or even shorter:
unique :: Eq a => [(a, a)] -> [(a, a)]
unique = filter (uncurry (/=))
We thus retain all elements for which the first element x is not equal to the second element y.


Q: not a valid identifier - bash script error while execution I'm getting following error while I try to capture process ids in my shell script.....
$bash ./restartjbossserver.sh
./restartjbossserver.sh: line 10: `i=$(ps -ef | grep "jboss" | grep -v "grep" | awk '{print $2}')': not a valid identifier

And this is my script....
for i=$(ps -ef | grep "jboss" | grep -v "grep" | awk '{print $2}')
do
echo $i
if [ $i != NULL ]
then
echo "Killing JBos Process.."
kill -9 $i
echo "Killed Joss Process..."
fi
done

sleep 10s

echo "Deleting JBoss Cache..."

rm -rf /home/cbsmsblapp/opt/EAP-6.3.0/jboss-eap-6.3/domain/tmp/*
echo " Deleted JBoss Cache..."

sleep 10s

nohup /home/cbsmsblapp/opt/EAP-6.3.0/jboss-eap-6.3/bin/domain.sh  & >nohup.out

A: The syntax for iterating over a list is
for i in $( ...

not
for i=$( ...

A: Have a look at the pkill and pgrep commands.  You could just pkill jboss.


Q: Two function in a event on React-Native How to put two function in a event like onValueChange?
I tried with
  onValueChange={(selected) => this.setState({selected}),this.state.eventOnChange}>

A: What about:
onValueChange={(selected) => {
    this.setState({selected});
    this.state.eventOnChange();
}}

A: Component.setState() is asynchronous and may be locked on the second call while it is still doing the first.
Do the second call in a callback like this:
onValueChange=
    { (selected) => {
        this.setState(
            {category:selected},() => {this.filter();} // Add Functions That's you want to call.
        )
    }
}

A: Resolved with the following code:
<TextInput
      style={{height: 40, width: 200, borderColor: 'gray', borderWidth: 1, }}

      onChangeText={(text) => this.setState({
        text
      }, () => {
        this._onChangeText();
      })
      }
      autoCorrect={false}
      underlineColorAndroid='rgba(0,0,0,0)'
      value={this.state.text}
    />

Thanks to @pinewood.

A: onValueChange={(itemValue, itemIndex) =>  this.setState({id: itemValue}),this.getOtherFunction }


Q: why shell for expression cannot parse xargs parameter correctly I have a black list to save tag id list, e.g. 1-3,7-9, actually it represents 1,2,3,7,8,9. And  could expand it by below shell
for i in {1..3,7..9}; do for j in {$i}; do echo -n "$j,"; done; done
1,2,3,7,8,9

but first I should convert - to ..
echo -n "1-3,7-9" | sed 's/-/../g'
1..3,7..9

then put it into for expression as a parameter
echo -n "1-3,7-9" | sed 's/-/../g'  | xargs -I @ for i in {@}; do for j in {$i}; do echo -n "$j,"; done; done
zsh: parse error near `do'

echo -n "1-3,7-9" | sed 's/-/../g'  | xargs -I @ echo @
1..3,7..9

but for expression cannot parse it correctly, why is so?

A: Because you didn't do anything to stop the outermost shell from picking up the special keywords and characters ( do, for, $, etc ) that you mean to be run by xargs.
xargs isn't a shell built-in; it gets the command line you want it to run for each element on stdin, from its arguments.  just like any other program, if you want ; or any other sequence special to be bash in an argument, you need to somehow escape it.
It seems like what you really want here, in my mind, is to invoke in a subshell a command ( your nested for loops ) for each input element.
I've come up with this; it seems to to the job:
echo -n "1-3,7-9" \
| sed 's/-/../g'  \
| xargs -I @  \
bash -c "for i in {@}; do for j in {\$i}; do echo -n \"\$j,\"; done; done;"

which gives:
{1..3},{7..9},

A: Could use below shell to achieve this
# Mac newline need special treatment
echo "1-3,7-9" | sed -e 's/-/../g' -e $'s/,/\\\n/g' | xargs -I@ echo 'for i in {@}; do echo -n "$i,"; done' | bash
1,2,3,7,8,9,%

#Linux
echo "1-3,7-9" | sed -e 's/-/../g' -e 's/,/\n/g' | xargs -I@ echo 'for i in {@}; do echo -n "$i,"; done' | bash
1,2,3,7,8,9,

but use this way is a little complicated maybe awk is more intuitive
# awk
echo "1-3,7-9,11,13-17" | awk '{n=split($0,a,","); for(i=1;i<=n;i++){m=split(a[i],a2,"-");for(j=a2[1];j<=a2[m];j++){print j}}}' | tr '\n' ','
1,2,3,7,8,9,11,13,14,15,16,17,%

A: echo -n "1-3,7-9" | perl -ne 's/-/../g;$,=",";print eval $_'


Q: Exclude .csproj from VisualStudio 2012 .sln when using Mono Compiler I want to build my VisualStudio 2012 solution (.sln) with Mono, but it cannot compile projects that rely on VisualStudio-specific assemblies.  E.g.
xbuild ServerResource.sln
...
HypervResourceControllerTest.cs(18,17): error CS0234: The type or namespace name `VisualStudio' does not exist in the namespace `Microsoft'. Are you missing an assembly reference?

In this case, HypervResourceControllerTest.cs(18,17) is a reference to Visual Studio test tools:
using Microsoft.VisualStudio.TestTools.UnitTesting;

Since I don't need the testing environment to compile, can I tell the Mono compiler to bypass a specific project in a .sln?

A: Create a new configuration, tell xbuild to use it:

*

*In Visual Studio, create a new configuration that excludes the projects you're not interested in. -(Build -> Configuration Manager..., select  on the Active solution platform: drop down list)

*Using the Configuration Manager, remove unwanted solutions from the configuration.

*Next, close VisualStudio, which will save changes to the .sln and .csproj  The .sln will record which projects are associated with the configuration.  The .csproj will record the settings of the configuration, such as whether TRACE or DEBUG is defined.

*Finally, when calling xbuild assign your configuration's name to the Configuration property.
E.g.
xbuild /p:Configuration="NoUnitTests" ServerResource.sln

The above will build the projects associated with the NoUnitTests configuration.


Q: What is -c and nrow doing in this function? What is the purpose of -c and nrow in this function?
bdf <- by(bdf, bdf$Serial_number, function(SN, k) {
                     SN[-c(1:k, (nrow(SN)-k+1):nrow(SN)),]
                     }, k = 10)

by() splits the data frame bdf by the second argument Serial_number and applys the function function(SN, k) in the third argument. I don't understand the body of the function.

A: c() creates a vector. - makes the numbers in the vector negative. The vector is in the "row" position of [, so it is omitting the rows from 1 to k, and from nrow(SN) - k + 1 to the end of the data frame. So it's chopping off the first k and last k - 1 rows of the data frame.


Q: How to create a dijit/Dialog for a specific HTML Div and use Div's elements as its content? Learning from http://dojotoolkit.org/reference-guide/1.9/dijit/Dialog.html, I know how to create dijit/Dialog widget programmatically and dynamically. But now I need to update the implementation of a form within our application which has many inputs. I want to create a dijit/Dialog for the specific DIV, and hope its div elements will be this dialog's elements. How is it possible?

A: Please try the following code. This code, will remove your div node from it's parent. div will be moved into body tag.
dojo.require("dijit.Dialog");

var myDialog=new dijit.Dialog(
    {
        title:"Dialog Title",
        content:dojo.byId("divNodeID")
    }
);

myDialog.show();

Hope this helps you. Thanks!

A: If you surround your  with the HTML that will create a Dialog, it should work.
For example, if your code is:
<form>
   ... some HTML ...
</form>

then consider coding:
<div data-dojo-type="dijit/Dialog" data-dojo-id="myDialog" title="MyTitle">
   <form>
      ... some HTML ...
   </form>
</div>


Q: Is there a Rails gem for management of a "multi-visit pass" scenario? I'm a Rails noob. I'm looking to implement an application where users can purchase a multi-visit pass, then spend the credits week-by-week.
For example, register and login, then purchase 10 visits at a gym - the system should list 10 remaining visits. Sign up to a class and 9 remaining visits are listed. When the credits are low, remind the user to top them up with another 10-visit pass, etc.
I know I can use Devise and CanCan to manage the authentication and authorisation aspects.
My question is whether there's already a gem to handle the management of the user's credits, or whether I'd need to write this from scratch.
I've searched https://rubygems.org/gems/rails with no luck, but it's entirely possible I'm missing something obvious.

A: I don't think there is a gem to do that, but it should be pretty simple to code:

*

*Add remaining_visits to your User model and table.

*Do current_user.update(remaining_visits: current_user.remaining_visits+10) when a ticket is purchased.

*Copy Devise sessions controller into app/controllers/devise/sessions_controller.rb.

*Inside this controller, add this kind of code to create (where the user logs in): current_user.update(remaining_visits: current_user.remaining_visits-1).

Note: Instead of copying Devise sessions controller you can just overwrite the create action.


Q: Evaluate Matlab symbolic function I have a problem with symbolic functions. I am creating function of my own whose first argument is a string. Then I am converting that string to symbolic function:
f =  syms(func)

Lets say my string is sin(x). So now I want to calculate it using subs.
a = subs(f, 1)

The result is sin(1) instead of number.
For 0 it works and calculates correctly. What should I do to get the actual result, not only sin(1) or sin(2), etc.?

A: You can use also use eval() to evaluate the function that you get by subs() function
f=sin(x);
a=eval(subs(f,1));
disp(a);
a =

    0.8415

A: syms x
f = sin(x) ;

then if you want to assign a value to x , e.g. pi/2 you can do the following:
subs(f,x,pi/2)
ans =

1

A: You can evaluate functions efficiently by using matlabFunction.
syms s t
x =[ 2 - 5*t - 2*s, 9*s + 12*t - 5, 7*s + 2*t - 1];
x=matlabFunction(x);
then you can type x in the command window and make sure that the following  appears:

x

x =
@(s,t)[s.*-2.0-t.*5.0+2.0,s.*9.0+t.*1.2e1-5.0,s.*7.0+t.*2.0-1.0]

you can see that your function is now defined by s and t. You can call this function by writing x(1,2) where s=1 and t=1. It should generate a value for you.
Here are some things to consider: I don't know which is more accurate between this method and subs. The precision of different methods can vary. I don't know which would run faster if you were trying to generate enormous matrices. If you are not doing serious research or coding for speed then these things probably do not matter.


Q: Pyspark: how to read CSV file with additional lines so I am having the following CSV file. It has some additional strings between the valid rows. Excel seems to do a good job when reading those(and just ignores the additional ones).

However, the story with spark is a bit different.

I have set it as spark.read.csv(path, header=True, multiLine=True, sep='|')
Is there some simple way to handle it?


Q: How to test redirect to created instance in Flask Having following function in  views.py:
def ask_question():
        form = QuestionForm()
        if form.validate_on_submit():
            question = Question(title=form.title.data, text=form.text.data)
            db.session.add(question)
            db.session.commit()
            return redirect('/questions/%d/' % question.id)
        return render_template('ask_question.html', form=form)

How can I get an id of created model to put it in assertion?
def test_can_post_question(self):
    response = self.tester.get('/new-question')
    self.assert_200(response)
    form = self.get_context_variable('form')
    self.assertIsInstance(form, QuestionForm)
    response = self.tester.post('/new-question', data={'title': 'What about somestuff in Flask?',
                                                       'text': 'What is it?'})
    self.assertRedirects(response, '/questions/%d' % created_question.id)
                                                     #^ how can I get id of created model here?

I'm using Flask, Flask-SQLAlchemy, Flask-Testing

A: Query the created question object. As a side effect, you can test that the question was created.
...
q = Question.query.filter_by(title='What about somestuff in Flask?').first()
self.assertRedirects(response, '/questions/%d/' % q.id)


Q: how to generate dynamic menu and components in angular based on API response I want to (propably) dynamically generate some number of menu positions and components reffering to these menu positions based on API response. Response to c# backend would be made on application start in app.component.ts. Those menu positions would be statuses of proceesing items (for example "finished", "in progress" etc.) and html in every component should look almost identically (just table with positions from sql database, only difference between them was sql query made to database with different "where" clause). Now it is two statuses, but in future it could be 7 more, so I don't want to create a new component in angular every time I add new status in backend. So what I should be looking for? And after receiving response from api where should I store this answer? (In order to have those components all time, I don't want them to dissapear after page reload or anything else).

A: When displaying data fetched from an API it's good practice to implement a model controller view pattern where the date is downloaded by the controller (a service), saved in the model which is marked with the @Injectable() decortator and is injected in the view component you're displaying the data. So your fetched data is stored in the model and can be accessed everywhere you need it.
The controller can look something like that:
@Injectable({
    providedIn: 'root'
})
export class StatusService{
    constructor(private http : HttpClient)
    { }

    public getStatus() : Observable<any>
    {
        return this.http.get('http://myapi.com/getstatus');
    }
}

The model is just storing this data:
export class Status
{
    public id : number;
    public type: string;
}

@Injectable()
export class StatusModel
{
    public statuses: Status[];

    constructor(private statusService : StatusService)
    { }

    public getStatus() : Observable<Status[]>
    {
        return this.statusService.getstatus().pipe(map((status: Status[]) =>
        {
            this.statuses = data;
            return this.statuses ;
        }));
    }
}

In you component (view) you're injecting the StatusModel in the constructor and make the API request:
@Component({
    selector: 'app-status',
    templateUrl: './status.component.html',
    styleUrls: ['./status.component.scss'],
})
export class StatusComponent implements OnInit {
    constructor(public statusModel : StatusModel)
    {
        this.getStatus();
    }

public getStatus() : void
    {
        this.statusModel.getStatus().subscribe(
            (data) =>
            {
                console.log(data);
            },
            (error) =>
            {
                console.log(error);
            }
        );
    }
}

In your HTML you can dispay these statuses stored in statusModel.statuses using *ngFor like that:

{{status.id}

{{status.type}}

You can also use *ngIf to display different statuses differently or ngClass to set specific style classes for specific statuses.


Q: Wrong output in printing values using for loop in C I wrote a simple C program to print all the multiples of 3 but there is some error during runtime my code is:
#include <stdio.h>

void main(void) {
    int i, x;
    for(i = 1; i < 1000; i++) {
        x = i % 3;
        if(x == 0) {
            printf("%d\n", i);
        }
     }
}

the problem is that if I enter numbers greater than 891 till 1000 in the loop the output is starting from 6 instead of 3 and if i write the code as above than the output is starting from 114. for the values less than or equal to 891 it is showing the correct output.

A: Make sure you can view all output:
reuts@reuts-K53SD:~/ccccc$ cat mmph.c && gcc mmph.c
#include<stdio.h>
main(){

    int i,x;
    for(i=1;i<1000;i++)
    {
        x=i%3;

        if(x==0){
            printf("%d\n",i);

        }
    }
}
reuts@reuts-K53SD:~/ccccc$ ./a.out | egrep "^3$|999"
3
999

As you can see, this works. Your output is probably truncated.


Q: (Karate) How to intercept the XHR request response code? I am testing a login functionality on a 3rd party website. I have this url example.com/login . When I copy and paste this into the browser (chrome), page sometimes load, but sometime does not (empty blank white page).
The problem is that I have to run a script on this page to click one of the elements (all the elements are embedded inside #shadow-root). If the page loads, no problem, script is evaluated successfully. But page sometimes does not load and it returns a 404 in response to an XHR request, and as a result, my * eval(scrip("script") step returns "js eval failed...".
So I found the solution to refresh the page, and to do that, I am considering to capture the xhr request response. If the status code is 404, then refresh the page. If not, continue with the following steps.

Now, I think this may work, but I do not know how to implement karate's Intercepting HTTP Requests. And firstly, is that something doable?
I have looked into documentation here, but could not understand the examples.
https://github.com/karatelabs/karate/tree/master/karate-netty
Meanwhile, if there is another way of refreshing the page conditionally, I will be more than happy to hear about it. Thanks anyone in advance.

A: First, using JavaScript you should be able to handle shadow roots: https://stackoverflow.com/a/60618233/143475
And the above answer links to advanced examples of executing JS in the context of the current page. I suggest you do some research into that, try to take the help of someone who knows JS, the DOM and HTML well - and you should be find a way to know if the XHR has been made successfully or not - for e.g. based on whether some element on the page has changed etc.
Finally here is how you can do interception: https://stackoverflow.com/a/61372471/143475


Q: ms-access queries I never really did ms access queries, but today I need one. I have 2 tables, models and orders. From first table one 2 fields are of interest here: number and color, from second only number which can only be equal to values of number from table "models" . What I need is to select most frequent color. In mysql that would be something like
    SELECT models.color, orders.number  FROM  models
    INNER JOIN orders ON (orders.number =models.number)
    group by color
    order by count(color) desc limit 1

But in ms-access that doesn't seem to work
How do you write query to do same thing in ms-access?

A: try this:
SELECT TOP 1 models.color, COUNT(orders.number)  FROM  models
INNER JOIN orders ON (orders.number=models.number)
GROUP BY models.color
ORDER BY 2 desc

A: All you need is to get rid of limit and use Top 1 instead:
SELECT Top 1 models.color  FROM  models
INNER JOIN orders ON (orders.number =models.number)
group by color
order by count(color) Desc

However, there is a caveat for Top n, in MS Access, Top n will return matches, so if several items have the same count, all will be returned. If this does not suit, you can work around this by ordering by a unique id as well:
order by count(color) desc, OrderID

Note also that number is a reserved word.


Q: Job for docker.service failed because the control process exited with error code while trying to start docker service in Manjaro[Arch] Getting this error while running docker pull manjarolinux/base:
Using default tag: latest
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

List of the previous commands that I've run:
sudo groupadd docker
sudo usermod -aG docker $(whoami)
sudo chown $(whoami) /var/run/docker.sock

Output of sudo dockerd --debug which had warnings or errors:
WARN[0000] containerd config version `1` has been deprecated and will be removed in containerd v2.0, please switch to version `2`, see https://github.com/containerd/containerd/blob/main/docs/PLUGINS.md#version-header
#and
WARN[2022-11-18T14:38:01.266464955+05:30] failed to load plugin io.containerd.snapshotter.v1.devmapper  error="devmapper not configured"
#and
WARN[2022-11-18T14:38:01.266829045+05:30] could not use snapshotter devmapper in metadata plugin  error="devmapper not configured"
#and
ERRO[2022-11-18T14:38:01.267936333+05:30] failed to initialize a tracing processor "otlp"  error="no OpenTelemetry endpoint: skip plugin"
#and
ERRO[2022-11-18T14:38:01.279926226+05:30] failed to mount overlay: no such device       storage-driver=overlay2


Q: Jquery button toggle show hide div I have these two divs on a page with two buttons beneath them to control hiding and showing them respectively.

Im Blue

Im Red

Blue

Red

I am using this javascript at the moment on the onclick of link.
function toggle_visibility(id) {

    var e = document.getElementById(id);

    console.log(e);
    if(e.style.display == 'none') {
        e.style.display = 'block';
    } else {
        e.style.display = 'none';
    }
}

It works however how do I make it so that clicking one button will disable the other. So clicking blue will show the blue div and hide the red div, then disable the button and enable the other button so the same can be donw but in reverse.
I have made a fiddle with the code i am using on my page which works, but on the fiddle its not? not sure why, ill post it anyway.
EDIT _ Fiddle Now Working. Thanks.
JSFIDDLE

A: You can't execute your js method before the elements get loaded.  so wrap your code in head/body
check this fiddle

A: Here is a possible solution (no jQuery) : http://jsfiddle.net/wared/A6w5e/.
As you might have noticed, links are not "disabled", I simply save the id of the DIV which is currently displayed in order to check the requested id before toggling : if (current !== id).
Another thing to note is that toggle_visibility is overwritten (only once) inside itself. It might look weird, but it's just a way to create a closure in order to enclose the variable named current inside a private context. The goal is to avoid polluting the parent scope.
Lastly, I've modified the original code to hide all divs except the one targeted by id.
function toggle_visibility(id) {
    var current = 'Blue';
    (toggle_visibility = function (id) {
        var div, l, i;
        if (current !== id) {
            current = id;
            div = document.getElementsByClassName('toggle360');
            l = div.length;
            i = 0;
            for (; i < l; i++) {
                div[i].style.display = div[i].id === id ? 'block' : 'none';
            }
        }
    })(id);
}

A: Wrap your code in head or body.
You are executing your code before DOM is created
Fiddle Demo

A: A couple people have commented why it doesn't work in fiddle. To answer the question....
It easy to toggle visibility using jquery if there are only two divs:
$(document).delegate('.flashlinks a', 'click', function () {
  $('.toggle360').toggle();
});

I would use a css class to disable the links. Then I would select what to do with the click based on if the class was present:
$(document).delegate('.flashlinks a:not(".disabled")', 'click', function () {
  $('.toggle360').toggle();
  $('.flashlinks a').toggleClass("disabled");
});

$(document).delegate('.flashlinks a.disabled', 'click', function () {
  e.preventDefault();
});

and in my css I would have something like
.disabled {
    color: black;
    text-decoration:none;
}

jsfiddle


Q: g++ __FUNCTION__ replace time Can anyone tell when g++ replaces the __FUNCTION__ 'macro' with the string containing the function name? It seems it can replace it not until it has check the syntactical correctness of the source code, i.e. the following will not work
#include <whatsneeded>
#define DBG_WHEREAMI __FUNCTION__ __FILE__ __LINE__

int main(int argc, char* argv)
{
  printf(DBG_WHEREAMI "\n"); //*
}

since after preprocessing using
g++ -E test.cc

the source looks like
[...]

int main(int argc, char* argv)
{
  printf(__FUNCTION__ "test.cc" "6" "\n"); //*
}

and now the compiler rightly throws up because the *ed line is incorrect.
Is there any way to force that replacement with a string to an earlier step so that the line is correct?
Is __FUNCTION__ really replaced with a string after all? Or is it a variable in the compiled code?

A: You are using __FUNCTION__ like a preprocessor macro, but it's a variable (please read http://gcc.gnu.org/onlinedocs/gcc/Function-Names.html).
Try printf("%s", __FUNCTION__) just for testing and it will print the function name.

A: __FUNCTION__ is not standard. Use __func__. As the documentation says, it's as if:
<ret-type> function_name( <args> )
{
    static const char __func__[] = "function-name";
    ...

A: In C/C++, the preprocessor will turn "my " "name " "is " "Bob" into the string literal "my name is Bob"; since __FILE__ and __LINE__ are preprocessor instructions, "We are on line " __LINE__ will pass "We are on line 27" to the compiler.
__FUNCTION__ is normally a synonym for __func__. __func__ can be thought of as a pseudo-function that returns the name of the function in which it is called. This can only be done by the compiler and not by the preprocessor. Because __func__ is not evaluated by the preprocessor, you do not get automatic concatenation. So if you are using printf it must be done by printf("the function name is %s", __func__);

A:
Is there any way to force that replacement with a string to an earlier step so that the line is correct?

No. __FUNCTION__ (and its standardized counterpart, __func__) are compiler constructs. __FILE__ and __LINE__ on the other hand, are preprocessor constructs. There is no way to make __FUNCTION__ a preprocessor construct because the preprocessor has no knowledge of the C++ language. When a source file is being preprocessed, the preprocessor has absolutely no idea about which function it is looking at because it doesn't even have a concept of functions.
On the other hand, the preprocessor does know which file it is working on, and it also knows which line of the file it is looking at, so it is able to handle __FILE__ and __LINE__.
This is why __func__ is defined as being equivalent to a static local variable (i.e. a compiler construct); only the compiler can provide this functionality.

A: Is this what you want?
#include <stdio.h>

#define DBG_WHEREAMI(X) printf("%s %s(%d): %s\n",__func__,__FILE__,__LINE__,X)

int main(int argc, char* argv)
{
  DBG_WHEREAMI("Starting");
}

Note: Since you marked this as C++ you should probably be using the iostreams to make sure it's type safe.

A: printf("%s" __FILE__ __LINE__ "\n", __FUNCTION__);

Yeah, I know that's not really the same.

A: Note that if you create a class, you can build a message from any number of types as you'd like which means you have a similar effect to the << operator or the format in a printf(3C). Something like this:
// make sure log remains copyable
class log
{
public:
  log(const char *function, const char *filename, int line)
  {
    f_message << function << ":" << filename << ":" << line << ": ";
  }
  ~log()
  {
    //printf("%s\n", f_message.str().c_str()); -- printf?!
    std::cerr << f_message.str() << std::endl;
  }

  log& operator () (const char *value)
  {
    f_message << value;
  }
  log& operator () (int value)
  {
    f_message << value;
  }
  // repeat with all the types you want to support in the base class
  // (should be all the basic types at least)
private:
  sstream f_message;
};

// start the magic here
log log_error(const char *func, const char *file, int line)
{
  log l(func, file, line);
  return l;
}

// NOTE: No ';' at the end here!
#define LOG_DEBUG  log_error(__func__, __FILE__, __LINE__)

// usage sample:
LOG_DEBUG("found ")(count)(" items");

Note that you could declare the << operators instead of the (). In that case the resulting usage would be something like this:
LOG_DEBUG << "found " << count << " items";

Depends which you prefer to use. I kind of like () because it protects your expressions automatically. i.e. if you want to output "count << 3" then you'd have to write:
LOG_DEBUG << "found " << (count << 3) << " items";


Q: show ruby date as a RFC 3339 timestamp Does anyone know how I can convert a ruby time class instance into a RFC 3339 timestamp?
The output should be something like this:

"2013-10-13T13:34:52.000+02:00"

A: require 'date'
Time.now.to_datetime.rfc3339


Q: Using class properties in angular templates I am trying to use a property from a template in angular. It doesn't work and I can't figure out why. I've set up an example here:
https://github.com/Fulkerson/angular-property
It is the example from the Tour of Heroes. My commit adds the property propname which simply returns name and uses it in the dashboard (main page).
Basically what I want to do is add multiple properties that process a field in different ways. But why is it I cannot use the properties from templates, and how can accomplish what I want to do in another way?

A: The data returned by the heroService.getHeroes method is plain JSON object (without the getter you defined in the Hero class). If you want to use the getter defined in the class you have to return an Array of real Hero instance.
1/ We add a constructor for the Hero class in app/hero.ts for convenience
  constructor ({id,name} = {id: undefined, name: undefined}) {
    this.id = id;
    this.name = name;
  }

2/ Instead of returning plain js data from heroService we map to obtain an array of Hero instance in dashboard.component.ts
getHeroes(): void {
    this.heroService.getHeroes()
      .subscribe(heroes =>
        this.heroes = heroes
        .slice(1, 5)
        .map(hero => new Hero(hero))
      );
  }

And Tadaa !
Here is the stackblitz created upon your github repo

A: Well, your problem is that, though you're adding a new getter to the Hero class, in the dashboard you're listing the heroes coming from the service. The problem is that the service is mocking data, and that data is, in truth, a simple array of objects (defined in in-memory-data.service.ts):
const heroes = [
      { id: 11, name: 'Mr. Nice' },
      { id: 12, name: 'Narco' },
      { id: 13, name: 'Bombasto' },
      { id: 14, name: 'Celeritas' },
      { id: 15, name: 'Magneta' },
      { id: 16, name: 'RubberMan' },
      { id: 17, name: 'Dynama' },
      { id: 18, name: 'Dr IQ' },
      { id: 19, name: 'Magma' },
      { id: 20, name: 'Tornado' }
    ];

In the original example this does not matter as the Hero class is used there basically as an interface or type annotation. You, however, are giving that class methods, but those methods do not exist in the array.
So, basically, your template is trying to access a propname property from the items of this array. That property, as you see, is undefined. As a result, you don't see the name in the page. To avoid this, just change the definition of the array:
const heroes = [
      Object.assign(new Hero(), { id: 11, name: 'Mr. Nice' }),
      ...
    ];

(you can also give Hero a constructor with parameters and use it instead of Object.assign). This way you'll get an array of true Hero objects.


Q: How do debug Bot code accessed via DirectLine API? We are developing a bot that will primarily be accessed using the DirectLine API. As the bot and the client app are still in development, the development is made difficult by the fact that we cannot Debug both the client app and bot on one box since DirectLine API can't connect back to the local box.
What's the story there? Any recommendations on best way to do this?

A: Take a look at ngrok.  The basic version is free.

ngrok allows you to expose a web server running on your local machine to the internet. Just tell ngrok what port your web server is listening on.


Q: javascript delete not working rails i have a partial am rendering which works well when am creating through javascript but deleting it via javascript is not working , maybe there is something am doing wrong but ma code is thus ...
the partial rendering
 <ul id="<%= dom_id(feed) %>">
        <%= render :partial => feed.talks %>

the partial

        <%= link_to image_tag(talk.user.image.url(:tiny)),talk.user,:style=> "width: 7%; padding-right: 0px;", :class=> "pull-left img_client"%>

          <%= link_to talk.user.username, talk.user %>: <%= talk.details %>

          <%="#{time_ago_in_words(talk.created_at)} ago "%>

          <% if current_user.id == talk.user_id %>
          <%= link_to "x", talk, method: :delete, data: { confirm: "You sure?" },remote: true, class: 'pull-right' %>

          <% end %>

create.js.erb   which works fine
$('.feed #<%= dom_id(@feed) %>').html("<%= j render(@feed.talks) %>");
$("#new_talk")[0].reset();

destroy.js.erb which doesnt delete unless a full page relod
$('.unstyled custumer_say_<%= @talk.id %>').remove();

seems there is something am not doing right

A: $('.unstyled custumer_say_<%= @talk.id %>').remove();

You're calling something that doesn't exist as far as I can see
Change your ul to this:
<ul id="unstyled custumer_say_<%= @talk.id %>" class="unstyled custumer_say" style="list-style: none;">

And the destroy.js.erb to
$("#unstyled custumer_say_<%= @talk.id %>").remove();

Notice the double quotes


Q: Android Events: When implementing interfaces is it better to use the outer class or anonymous classes This is an example of using outer class
public class MyActivity extends Activity implements OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mylayout);
        findViewById(R.id.myid).setOnClickListener(this));
    }
    public void onClick(View v){...}
}

This is an example of anonymous classes
public class MyActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mylayout);
        findViewById(R.id.myid).setOnClickListener(new OnClickListener() {
            public void onClick(View v){...}
        }));
    }
}

A: Performance and efficiency are slightly a  more important consideration in Android. Something considered to be half baked optimization effort, sometimes makes sense in android.(like we should not use enum but java int enum pattern). So to the answer to your question is.
If you have to register multiple onClick listeners, Implement interface and use switch case within it.
If you have to register only one on click listener, use anonymous class. (Android developers prefers anonymous class, whenever possible. Limiting the scope ;))


Q: Start application when file is received via Bluetooth My application should start when any file is received via Bluetooth.
Please tell me, which intent is fired when a file is received via Bluetooth?

A: There's no such specific intent action which tells that a file is downloaded. However, you should listen for the following broadcast to detect that a phone is disconnected and then check programatically if a file is downloaded.
<intent-filter>
    <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED"/>
</intent-filter>


Q: Just scaling a rectangle I'm trying to start with processing.
Now I'm just trying to scale a rectangle. I have found this example:
float a = 0.0;
float s = 0.0;

void setup()
{
  size(200,200);
  rectMode(CENTER);
  frameRate(30);
}

void draw()
{

  s = s + 0.04;

  translate(width/2, height/2);
  scale(s);
  rect(0, 0, 50, 50);

}

It scales smoothly the rectangle but I'm a bit surprise because for resizing a rectangle I expected the sizing parameters (3rd and 4th) of rect() were modified, something like this way:
float r = 1;

void setup()
{
  size(200,200);
  rectMode(CENTER);
  frameRate(30);
}

void draw(){

    rect(width/2, height/2, r, r);

    r += 1;

}

but this way doesn't scale the rectangle smoothly. So, should I use the first approach instead of the second one even if I find it the second one more natural? Any comment will be wellcome.
Regards
Javier

A: The first solution is quite complex, you are not actually scaling the rectangle, but rather the projection matrix. The projection matrix is the series of mathematical operations that are applied before something is drawn to the screen. You can think of it as a camera, but it is far more complex than that.
I actually put the code side by side and didn't notice that much difference in the smoothness. I also added a few tweaks, so that may have helped :)
float r = 1;
float s = 0.0;

void setup()
{
  size(200,200);
  rectMode(CENTER);
  frameRate(30);
  smooth();
}

void draw(){
   rect(width/4, height/2, r, r);
   r += 1.4;
   translate(width/2, height/2);
   scale(s);
   translate(-width/2, -height/2);
   rect(width/2, height/2, 50, 50);
   s += 0.04;
}

The main change that I made was to turn on smooth. I think that because you didn't have it on, the top square drawing was jumping to each pixel, but with the tranlation / scale operation, it would smooth those over. The other thing I did, was to translate back to the top left after doing the scale operation. This is important to do so that things draw where you expect them to. You will notice that the scaling rect now scale out from the center.


Q: Angularjs ui-grid export functionality, Display dynamic data in the exporterPdfHeader Using Angularjs,ui-grid and uiGridExporterService exporting the data in the grid view. I'm using this export option in report functionality so when I export (PDF) need to display the filtered inputs in the PDF view.
$scope.gridOptions2 = {
    enableSorting: true,
    enableColumnMenus: false,
      columnDefs: [
      // { field: 'id', width: '60', displayName: 'S.No', cellTemplate: ''},
      // { field: 'id',   displayName: 'S.No', visible: false},
      { field: 'reg_id',  width: '130',   displayName: 'Id', enableSorting: false},
      { field: 'name', width: '160', displayName: 'Username', enableSorting: false}
      ],
      exporterMenuCsv: false, // ADD THIS

      exporterPdfDefaultStyle: {fontSize: 11},
      exporterPdfTableStyle: {margin: [10, 30, 30, 30]},
      exporterPdfTableHeaderStyle: {fontSize: 11, bold: true, italics: false, color: 'blue' },

      exporterPdfHeader: {
        margin: 20,
        columns: [{
          text: "Employee Salary Detail", alignment: 'center', style: 'defaultStyle',
          text: "Month : "+ $scope.monthVal, alignment: 'right', style: 'defaultStyle',
          width: 150
        }]
    },
      exporterFieldCallback : function ( grid, row, col, value ) {
        if ( col.name === 'status' ) {
          value = decodeStatus( value );
        }
        return value;
      },
      exporterPdfFooter: function ( currentPage, pageCount ) {
        return { text: currentPage.toString() + ' of ' + pageCount.toString(), style: 'footerStyle' };
      },
      exporterPdfCustomFormatter: function ( docDefinition ) {
        docDefinition.styles.headerStyle = { fontSize: 22, bold: true };
        docDefinition.styles.footerStyle = { fontSize: 10, bold: true };
        return docDefinition;
      },

      exporterPdfOrientation: 'landscape',
      exporterPdfPageSize:'A4',  // exporterPdfMaxGridWidth = Defaults to 720 (for A4 landscape), use 670 for LETTER
      exporterPdfMaxGridWidth: 600,    // bug, for A4, default is 720, set to 600 solve my problem.
      exporterExcelFilename: 'myFile.xlsx',
      exporterExcelSheetName: 'Sheet1',
      onRegisterApi: function (gridApi) {
        $scope.grid2Api = gridApi;
    }
  };

Need to pass the selected inputs  into the $scope.monthVal.
exporterPdfHeader: {
        margin: 20,
        columns: [{
          text: "Employee Salary Detail", alignment: 'center', style: 'defaultStyle',
          text: "Month : "+ $scope.monthVal, alignment: 'right', style: 'defaultStyle',
          width: 150
        }]
    },


Q: Creating a custom Authorize attribute with specific rules I'm trying to create a custom Authorize attribute to do the following:

*

*If the user has a role of "Regular user" - he is redirected to /index/subscribe

*All other users(Administrator,Subscriber) gets access to /Search/Index

This is when the user tries to open up the Search controller. I made the custom Authorize attribute like this:
public class DenyRegularUser : System.Web.Mvc.AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("~/User/Logon");
                return;
            }

            if (filterContext.HttpContext.User.IsInRole("Regular user"))
            {
                filterContext.Result = new RedirectResult("~/Index/Subscribe");
            }
        }
    }

And this is my Search controller:
namespace WebApplication2.Controllers
{
    [DenyRegularUser(Roles ="Regular user")]
    public class SearchController : Controller
    {
        // GET: Search
        public ActionResult Index()
        {
            return View();
        }
    }
}

But for some reason, even when I update the user's role from Regular user to Administrator or Subscriber, I get redirected to login page: /user/login...
This shouldn't happen as the login functionality works perfectly and I get the role of the user...
What am I missing out here??

A: This may help.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class DenyRegularUser  : AuthorizeAttribute
{
    public DenyRegularUser() :
        base()
    {

    }

    protected override bool IsAuthorized (System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (AuthorizeRequest(actionContext))
        {
            return true;
        }
        return false;
    }

    protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        //Code to handle unauthorized request
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.TemporaryRedirect);
        actionContext.Response.Headers.Add("Location", "~/Index/Subscribe");
    }

    private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        //Write your code here to perform authorization
    }
}

I believe the IsAuthorized method is the correct way to override the AuthorizeAttribute.


Q: Two Python instances, same libraries I currently have both Python 2.6 and 2.7 running on my Linux machine.
Now, from Python 2.7, I can't access the libraries that I installed through package manager for Python 2.6.
I tried uninstalling the library and installing it back with Python 2.7 installed as my default runtime. No luck.
How can I share libraries between two Python instances? Is there a more correct way to do this than just copying them?
If useful: my Linux distro is Debian, and my package manager is apt.

A: You should be able to install the files to an external location and define the environment variable PYTHONPATH to point to the directory that contains the modules.

A: You should have now both a /usr/lib/python2.6 folder and a /usr/lib/python2.7. Try creating links inside the 2.7 folders to the required files or folders inside the 2.6 folder.


Q: Convert an RDD to a DataFrame in Spark using Scala I have textRDD: org.apache.spark.rdd.RDD[(String, String)]
I would like to convert it to a DataFrame. The columns correspond to the title and content of each page(row).

A: Use toDF(), provide the column names if you have them.
val textDF = textRDD.toDF("title": String, "content": String)
textDF: org.apache.spark.sql.DataFrame = [title: string, content: string]

or
val textDF = textRDD.toDF()
textDF: org.apache.spark.sql.DataFrame = [_1: string, _2: string]

The shell auto-imports (I am using version 1.5), but you may need import sqlContext.implicits._ in an application.

A: I usually do this like the following:
Create a case class like this:
case class DataFrameRecord(property1: String, property2: String)

Then you can use map to convert into the new structure using the case class:
rdd.map(p => DataFrameRecord(prop1, prop2)).toDF()


Q: make cells mandatory to fill in google sheets with javascript I am new to programming. Is there a way of making a cell mandatory to be filled in google sheets or microsoft excel using javascript, where by a message pops up to remind users to fill in the cells.


Q: sum calculation for position in intervals in pandas dataframe I have a pandas dataframe with intervals (define by start and stop) :
df = pd.DataFrame(
    {
        'start': [1,1,1,2,2,2,2,3,3,3,3,3,3,3],
        'stop': [9,9,10,10,10,11,11,11,11,12,11,12,11,11],
        'percent' : [0.51,0.29,0.92,0.60,0.10,0.12,0.60,0.30,0.10,0.42,0.51,0.51,0.51,0.10],
        'order':[3,80,3,3,4,8,89,2,3,4,5,64,82,68]

    }
    )

Which look like :
start   stop    percent order
1   9   0.51    3
1   9   0.29    80
1   10  0.92    3
2   10  0.60    3
2   10  0.10    4
2   11  0.12    8
2   11  0.60    89
3   11  0.30    2
3   11  0.10    3
3   12  0.42    4
3   11  0.51    5
3   12  0.51    64
3   11  0.51    82
3   11  0.10    68

I want to calculate, for each position (by splitting intervals): total count, sum of value, sum of order
NB : original dataframe is not coordinate sorted in the example.
I want to end up with a dataframe :
pos count   sum_percent sum_order
1   3   1.72    86
2   7   3.14    190
3   14  5.59    418
4   14  5.59    418
5   14  5.59    418
6   14  5.59    418
7   14  5.59    418
8   14  5.59    418
9   14  5.59    418
10  12  4.79    335
11  9   3.17    325
12  2   0.93    68

I managed to have the result that i want for the count column like this :
max_pos=df[['start', 'stop']].values.max()
pos_range=np.arange(1, max_pos+1)
counts = ((df[['start']].values <= pos_range) & (pos_range <= df[['stop']].values)).sum(axis=0)
o = pd.DataFrame({'pos': pos_range, "counts": counts})

But for the sum of column, i didn't manage to do it.
Any help ?
Thanks in advance

A: Use the boolean variable used to count as an index:
import numpy as np
import pandas as pd
names=["start","stop","percent","order"]
vals=np.array([
  [1,9,0.51, 3],
  [1,9,0.29,80],
  [1,10,0.92, 3],
  [2,10,0.60, 3],
  [2,10,0.10, 4],
  [2,11,0.12, 8],
  [2,11,0.60,89],
  [3,11,0.30, 2],
  [3,11,0.10, 3],
  [3,12,0.42, 4],
  [3,11,0.51, 5],
  [3,12,0.51,64],
  [3,11,0.51,82],
  [3,11,0.10,68]
  ])

df = pd.DataFrame(vals, columns=names)
df
max_pos=df[['start', 'stop']].values.max()
pos_range=np.arange(1, max_pos+1)

_ix = ((df[['start']].values <= pos_range) & (pos_range <= df[['stop']].values))
counts = _ix.sum(axis=0)
sum_percent=[]
for i in _ix.T:
    sum_percent.append(df["percent"].values[i].sum())
sum_order = []
for i in _ix.T:
    sum_order.append(df["order"].values[i].sum())

o = pd.DataFrame({'pos': pos_range, "counts": counts, "sum_percent":sum_percent, "sum_order":sum_order})


Q: Annotate datatime calculations How could I cast datetime to seconds and perform calculation on that or directly perform calculation on datetime?
for example:
User.objects.annotate(min=Min('created'), max=Max('created'), perc=F('created') - min/(max - min))

User model
class User(AbstractUser):
    ...
    created = models.DateTimeField(auto_now_add=True)

How to get the value of perc for each user(I'm using postgres)?


Q: Help with jQuery's .live() method I have a function that dynamically creates links for a photo gallery. The function also produces a larger image as a background image of a div when and thumbnail is clicked on. What I want to do is have a third event, where if the user clicks the enlarged image in the div, the jQuery Fancybox loads an even bigger version of the image being displayed in the div. The problem is that the link for the anchor tag I'm using is created dynamically, and I know that Fancybox parses the HTML when the DOM is ready...unfortunately my function changes the DOM by appending the anchor tag for the full sized image. The help I need is using the Fancybox's options to specify the href attribute for the plugin. I'm sorry that was so long-winded...here's the code.
jQuery:
function gallery(picid, picnum){
var ext = 'jpg';
var fullSize = 'imgs/'+picid+'_full.'+ext;
$('#photolarge').css("background", 'url(imgs/'+picid+'_large.'+ext+') no-repeat');
$('#photolarge a').attr(
    {   href: fullSize
        //rel: 'lightbox',
    }
    );

$("#lightboxlink").click(function(){
    $('#lightboxlink').fancybox({
        'autoDimensions' : false,
        'width' : 'auto',
        'height' : 'auto',
        'href' : fullSize
        });

    });

return false;
}

HTML Snippet

CSS:
#photolarge {
width: 590px;
height: 400px;
margin-left: 7px;
border: 2px solid;
background: none;}

#phototable {
width: 590px;
height: 300px;
border: 2px solid;
margin: 10px 0 0 7px;}

#phototable img {
cursor: pointer;}

#phototable ul {
list-style: none;
display: inline;}

#phototable li {
padding-left: 10px;}

#lightboxlink {
display: block;
height: 100%;
width: 100%;}

Any help would be greatly appreciated!!!

A: Try this and see if it works,this is just fancy box bit though,the rest of your code seems fine
$("#lightboxlink").live('click', function(){

    $.fancybox({
        'autoDimensions'  : false,
        'width'           : 'auto',
        'height'          : 'auto',
        'href'            : $(this).attr('href')
    });
    return false;
});


Q: Inverse Cosine in Python Apologies if this is straight forward, but I have not found any help in the python manual or google.
I am trying to find the inverse cosine for a value using python.
i.e. cos⁻¹(x)
Does anyone know how to do this?
Thanks

A: To augment the correct answers to use math.acos, it is also worth knowing that there are math functions suitable for complex numbers in cmath:
>>> import cmath
>>> cmath.acos(1j)
(1.5707963267948966-0.88137358701954294j)

Stick with math.acos if you're only interested in real numbers,

A: The result of math.acos() is in radians. So you need to convert that to degrees.
Here is how you can do:
import math
res = math.degrees (math.acos (value))

A: We have the acos function, which returns the angle in radians.
>>> import math
>>> math.acos(0)
1.5707963267948966
>>> _ * 2 - math.pi
0.0

A: In response to using inverse cosine to find return angles via math.acos,  it's all fine and dandy so long as the angle is <=90*  once you go past that, python will have no way of differentiating which angle you wanted.
Observe.
>>> math.cos(5)
0.28366218546322625

Above, I asked python to fetch me the cosine of a 5 radian angle, and it gave me .28~ Great, below I'll ask python to give me the radian which has a .28~ cosine. Should be 5, right? It literally just told me it was.
>>> math.acos(0.28366218546322625)
1.2831853071795865

Wrong! Python returns 1.28~ radians. The reason is obvious when plotted visually, 1.28rad has the same cosine as 5rad, they're inverse angles. Every angle shares the same sine with another angle (and -sine with two others).
i.e. 5/175* share an equivalent sine. They share inversely proportional cosines .99~/-.99 respectively.  Their -sine cousins would be 185 and 355.  The relationship meme here is that all these angles share the same angular deflection from the horizontal axis. 5*.
The reason python returns 1.28 and not 5 is that all computers/calculators are based on an abacus-like data table of an angle/radian, its sine, cos, tan etc etc.  So when i math.acos(x), python asks the kernal to look through that data table for whichever angle has a cosine of x, and when it finds it, it returns the first entry it appears with. and then python gives that angle to me.
Due to this shared, proportional symmetry, sin/cos ratios repeat frequently. And you are likely to see the same figure, multiple times. There's no way for python, or the OS, to determine the difference of which of the two angles you actually require without doing additional logic that takes into account the -/+ value of the angle's sine.  Or, the angle's tangent.
1.28 Rad has  x cosine, y sine, z tan  (72*)
1.88 Rad has -x cosine, y sine, -z tan (108*)
4.39 Rad has -x cosine, -y sine, z tan (252*)
   5 Rad has  x cosine, -y sine, -z tan (288*)

or, viewed Cartesianly,
                       negX,posY | posX,posY
                            -----+-----
                       negX,negY |  posX,negY

1.88 Rad has -x cosine, y sine (108) | 1.28 Rad has  x cosine, y sine (72*)
                                -----+-----
4.39 Rad has -x cosine, -y sine (252)|    5 Rad has  x cosine, -y sine (288)

So if, for whatever reason, i need 5 radians to be chosen (say for a vector drawing or game to determine the various vectors enemies are from the player), i would have to do some type of if/then logic comparing the sines/tangents.

A: You're looking for the math.acos() function.

A: You may also use arccos from the module numpy
>>> import numpy
>>> numpy.arccos(0.5)
1.0471975511965979

WARNING: For scalars the numpy.arccos() function is much slower (~ 10x) than math.acos.  See post here
Nevertheless, the numpy.arccos() is suitable for sequences, while math.acos is not. :)
>>> numpy.arccos([0.5, 0.3])
array([ 1.04719755,  1.26610367])

but
>>> math.acos([0.5, 0.3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a float is required

A: or just write a function of your own for the taylor expansion of cos^{-1}
this would be more time consuming (and maybe slower to run) but is the more general approach


Q: How to use @HiltAndroidApp annotation but there's no Application class in the project? As Android documentation said:

All apps that use Hilt must contain an Application class that is annotated with @HiltAndroidApp

When I create an Android project from template (Tabs template of Android Studio) it seems not to provide any Application class but class MainActivity : AppCompatActivity() instead. So how can I use Hilt in this project?
I have tried this:
@HiltAndroidApp
class MainActivity : AppCompatActivity() {
    ...
}

But it didn't work :<

A: Your MainActivity is not the Application class.
For activities use the @AndroidEntryPoint. See more on https://dagger.dev/hilt/android-entry-point
The annotation @HiltAndroidApp is for the Application class. See more on https://dagger.dev/hilt/application


Q: How do I exclude multiple terms in Kibana 4 How can I exclude multiple search terms in Kibana 4? If I type in only one term, it excludes it...but how can I have more than one excluded term. For example, the term "not yet classified"

A: If I understand your question properly, you're trying to use the "Exclude Pattern" to exclude certain values from populating in the chart.
The "Exclude Pattern" and "Include Pattern" fields are for Regular Expressions and are documented here: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html.
If you want to exclude multiple fields, you could do something like this:
term1|term2|term3

A: The query field in Kibana uses Lucene syntax which has some info at http://www.lucenetutorial.com/lucene-query-syntax.html.
To exclude a term containing specific text, use

-field: "text"

to exclude different texts, I use

-field: ("text1" or "text2")

If it's two separate fields, try

-field1: "text1" -field2: "text2"

A: in newer version of kibana if you want to exclude some term use this:
not field : "text"

if you want to exclude a phrase use this:
not field : "some text phrase"

you can use other logical operation with not:
field: "should have phrase" and not field: "excluded phrase"

A: https://www.elastic.co/guide/en/kibana/master/kuery-query.html
To match documents where response is 200 but extension is not php or css.
response:200 and not (extension:php or extension:css)

A: So in the query above the visualization, you can use Lucene syntax to exclude the hits, once saved this will perform the same as an attempt of using regex or Lucene syntax in the Exclude Field of the Buckets advanced options.


Q: Multi-branching model currently I have a task about branching model I should use.
Right now I have master branch and I am branching release branches from time to time to release branches about new features. This is how it looks my branching model right now.
master
|
|---- release 1.0 branch
|   |
|   |
|   |
|   |----- *(1) needed branch
|   |    |
|   |    |
|   |    |
|   |    |
|----    |
|---------
|
|---- release 1.1
|   |
|   |----- needed branch
|   |    |
|   |    |
|   |

*(1) - Each time release branch is closed for features I make new feature branch and then merge this("needed branch") just before next
  release.

Few questions that might come up reading this.
I will edit this as questions are given so I can give the answers in the post

*

*Why you are closing release branch if you need more features? - The thing is I need to have stable branch(release) at any time after development is "over".

What I want to accomplish?
The problem with this branching model is that I might have a lot of features and each one of them for different client and many of the clients don't want to wait another 1 or 2 weeks until next deploy. I was thinking of making branch for every client and pushing features there and whenever client want to get given feature I can deploy from there without affecting other clients. Cause right now this is impossible. But this is really bad approach since as the clients grow the branches will too.
I want more elegant approach. I understand there will be a lot of questions in the comments so please ask them and lets see if I can answer them and come up with solution or at least an idea.

A: It sounds like your problem is not Git: your problem is people. Since these people are paying you, presumably, this seems like the right problem to have!
What I would do is this:
|
* tag:r1
|\______________________
|   \             \     \
|    * feature1   WIP2  WIP3
| __/              |
|/                 |
* tag:r2           * feature2
| ________________/
|/
* tag:r3
|
master

In words, I would do all my releases from master, and all my work on feature branches. When a feature is complete, tested, and a client wants it, only then would I merge to master, retest, and make another release. In this way, master is never in a development state; it's always "just released", or "just about to release" (or idle).
If WIP3 ("Work in progress 3") takes a long time to develop, the graph would evolve like this:
|
* tag:r1
|\__________
|           \
|           WIP3
* tag:r2     |
|\__________ |
|           \|
|            * merge
* tag:r3     |
|\__________ |
|           \|
|            * merge
|            |
|            * feature3
| __________/
|/
* tag:r4
|
master

(I've deleted the feature1 and feature2 branches, now they're merged, but you'd still see the multiple paths in the history.)
If you discover that a client wants a bug fix release to some old version (maybe they paid for support, but didn't pay for new features?), then you can always make a release branch from a tag:
|
* tag:r1
|
* tag:r2
|\_________
* tag:r3   \
|          * bugfix
* tag:r4   |
|          * tag:r2.1
master     |
           release2.x_branch


Q: Is iOS capable of accessing and manipulating files on a Windows network file share? I'm planning an app for work and venturing into potential features which I've not used before.
Essentially I need to be able to access files on a network share, read, write and delete files as well as amend the file names. As a pretty closed platform I'm not sure whether iOS is capable of such a thing and if it is, what features should I look for to begin researching?
My Google-Fu hasn't come up with anything thus far so hopefully looking for someone to point me in the right direction.
Thanks.

A: I know this isn't very secure, but I'd personally create an ASP.NET app on your target Windows Server, or a different Server on the domain. Create web services exposed, and make an iOS app with UIWebView. You can do RPC calls from the web service that do WMI/ADSI/File System manipulation. You can prompt for domain credentials, and do remote calls essentially is the gist.
You could expose the web app so that your app can access it from local network, or URL. If you were to access it from outside I'd suggest using some secure credentials in Windows/IIS.
Some years ago I created a "mobile-friendly" web app that allowed me to manage servers, perform RPC, and do basic Active Directory queries. Also allowed file listing and deletion/moving/copying with some creative scripting. It was essentially a ASP.NET/C# web app that loaded in a iPhone app. UIWebView in iOS was a able to load it, used AJAX and some other client side scripting that looked decent. You'd essentially have to make sure that your web app renders properly in Safari/UIWebView (which is bastardized safari).
Here's a link to a demo of what I created:
https://www.youtube.com/watch?v=czXmubijHwQ&t=12s
I ran it in a browser, but it'd run from my PSP, Android test devices, iPod Touch, Blackberry, etc.


Q: In google sheets, how do you use googlefinance to get the high price of a stock in a date range? I wrote the following formula, and it only returns the high of the starting date and not the high of the entire date range:  =INDEX(GoogleFinance(C7,"high", A7,B7,"DAILY"),2,2)
where C7 is the google sheet cell that contains the stock symbol and A7 contains the starting date and B7 contains the ending date.

A: The formula:
=MAX(INDEX(GOOGLEFINANCE(C7, "high", A7, B7), , 2))
…will return the stock's high price between the dates A7 and B7 in your example.1
How does it work?
Using the formula:
=GOOGLEFINANCE(<symbol>, "high", <StartDate>, <EndDate>) or
=GOOGLEFINANCE(C7, "high", A7, B7) (in your example),
…will return an array which looks something like this:

Using the INDEX() function, you can convert that array to a single column of the high values:
=INDEX(GOOGLEFINANCE(C7, "high", A7, B7), , 2)

Now you can pass that array into the MAX() function to get the highest value in a single cell:
=MAX(INDEX(GOOGLEFINANCE(C7, "high", A7, B7), , 2))

1 Important Note:
If you include a date range in GOOGLEFINANCE's "high" function, it will not include today's price during the current trading day — so if you need to include today's high price in your range, you will need to compare today's high price to the historical data explicitly.
E.g., the function =GOOGLEFINANCE(symbol, "high") gives you today's high price, so:
=MAX(GOOGLEFINANCE(C7, "high"), MAX(INDEX(GOOGLEFINANCE(C7, "high", TODAY()-30, TODAY()), , 2)))
…will give you the high price over the last 30 days, including today.
If there's a possibility that your date range might include today only (i.e. no historical data where A7 and B7 both equal today), unfortunately, the formula above will return #NA. I have the ultimate solution to generate the correct array even if it does not contain historical data.
The Bullet-Proof Solution
The formula below traps the #NA condition and builds the array to include today's high no matter what date range is specified:
=MAX(INDEX({IFNA(GOOGLEFINANCE(E7, "high", A7, TODAY()), {"Date", "High"}); NOW(), GOOGLEFINANCE(E7, "high")}, , 2))
I've been bitten by this quirk a few times and this solution seems to be cover all scenarios. Enjoy!

A: Please try:
=max(INDEX(GoogleFinance(C7,"high",A7,B7,"DAILY"),0,2))

0,2 rather than 2,2 at the end to return the range rather than a cell from it and MAX for the maximum.


Q: How to reference a method on the object itself In java I can write
Arrays.asList("test  ").stream().map(String::trim);

If I try this in groovy
Arrays.asList("test  ").stream().map(String.&trim)

I get
    Caught: groovy.lang.MissingMethodException: No signature of method: java.lang.String.trim() is applicable for argument types: (String) values: [test  ]
Possible solutions: trim(), wait(), grep(), wait(long), split(java.lang.String), print(java.io.PrintWriter)

What is the correct syntax or do I have to resort to
    Arrays.asList("test  ").stream().map({ x -> x.trim() })

?

A: you can use .map { it.trim() } too, but otherwise, groovy does not have method reference working like java one


Q: stripe.net - how to process subscriptionService.Get with no results The stripe.com API only returns active subscriptions. I want to verify when I delete a subscription.
So this is going to return an error. I am not sure how to code for it.
I would prefer to make this call based on the subscriptionId. Will this cause an exception or will it return an error code?
Retrieving a subscription
var subscriptionService = new StripeSubscriptionService();
StripeSubscription stripeSubscription = subscriptionService.Get(*subscriptionId*);

Another options which is somewhat of a hack is to return all the subscriptions for the given customer and test to see if the subscriptionId was returned.
List all subscriptions for a customer
var subscriptionService = new StripeSubscriptionService();
IEnumerable<StripeSubscription> responses = subscriptionService .List(*customerId*);
foreach( var response in responses )
{
     if (response.subscriptionId == subscriptionId)
     {
         // subscription exists and was not deleted
         exit;
     }
}

A: Per their documentation, https://stripe.com/docs/api they have 2 different APIs.  You're trying to use the RESTful API, which is for retrieving information on demand.
They also have a WebHooks API, which requires you have an endpoint listening on your site which can accept event notifications.  You configure these through your Dashboard with them.
The event type you're looking for specifically is probably the customer.subscription.deleted event, but there's a lot more you can do with them and I'd encourage you to explore all of those Webhooks.
I can't offer a code sample, as I don't use their service.

A: The strip.net example shows the subscriptionService.Cancel as a methed:
var subscriptionService = new StripeSubscriptionService();
subscriptionService.Cancel(*customerId*, *subscriptionId*);

But you can also use it as a function and it returns the subscription object.
var subscriptionService = new StripeSubscriptionService();
StripeSubscription stripeSubscription = subscriptionService.Cancel(*customerId*, *subscriptionId*);

If (stripeSubscription.Status != "canceled")
{
     //subscription not cancelled
     // take action
}

Per Stripe API docs:
Returns:
The canceled subscription object. Its subscription status will be set to "canceled" unless you've set at_period_end to true when canceling, in which case the status will remain "active" but the cancel_at_period_end attribute will change to true.One of the fiels is .status , witch is set to canceled.


Q: Which components do what when using Python with OpenCV? I'm quite puzzled about what to use or install, because there are a plethora of components old and new, and the relationship between them is quite unclear to me.
There is OpenCV, the C++ library that does the heavy lifting.
Then there are various packages that provide Python support, including:

*

*opencv-python - Python packages for OpenCV; also installs OpenCV itself. Available with import cv2.

*pyopencv - a very old library.

*python-opencv - a Debian package.

*libopencv, described in another question here as "only a metapackage", but its purpose remains unclear to me.

Possibly I have missed some...
For a modern Python 3 project, which of these components should be used?
Using import cv
I am trying to use OpenCV with a Django project, that expects to find the library with import cv.
That recommends installing python-opencv. It also mentions pyopencv which seems odd, given how old the latter is.
What package does make a cv module available?
System vs Python packages
It looks like python-opencv is a system-level package that also installs Python modules, whereas opencv-python is a Python package that also installs system-level modules.
Is that correct? In which case, am I right in thinking that one would install both system and Python libraries using one of these but not both?

A: in opencv3 the old cv or cv2.cv api was removed, to use opencv correctly in python is enough with import cv2.
another package would be opencv-contrib-python


Q: How to insert COUNT value of another table in column of a table Hey I have a two tables
Likes

And other table
Comments

I want to total likes  in comment table . How can i achieve this . I just write fake query in comments table just for understanding i want effect like that , any ideas please

A: INSERT INTO Destination(Col)
SELECT COUNT(1) FROM Source;

A: You can use triggers to automatically update comments tables based on likes table.
The following in an Insert After Trigger which will increment the value of total_likes of the corresponding comment_id by one in comments table when an insert in performed in likes table.
You have to give initial value of total_likes for comments as zero when inserting in comments table.
CREATE TRIGGER update_likes AFTER INSERT ON likes
FOR EACH ROW
  UPDATE comments
     SET total_likes = total_likes+1
   WHERE comment_id = NEW.comment_id;

A: If you want a query that resolve this.
I suggest some like this:
select comment_id,uploader,
(select count(*) from likes l where L.COMMENT_ID =CM.COMMENT_ID ) nlikes
from commments cm;


Q: C, Fast way to limit a number to <= 64 Which is the fastest way to limit a number to 64 inclusive (ie. <= 64)
len = len > 64 ? 64 : len; /* limit to 64 */

Thanks!

A: Don't bother. The compiler optimizes better than you could.
You might perhaps try
len = ((len - 1) & 0x3f) + 1;

(but when len is 0 -or 65, etc...- this might not give what you want)
If that is so important for you, benchmark!

A: I created a program
#include <stdio.h>

int main(void) {
    unsigned int len;
    scanf("%u", &len);
    len = len > 64 ? 64 : len;
    printf("%u\n", len);
}

and compiled with gcc -O3 and it generated this assembly:
cmpl    $64, 4(%rsp)
movl    $64, %edx
leaq    .LC1(%rip), %rsi
cmovbe  4(%rsp), %edx

the leaq there loads the "%u\n" string in between - I presume it is because the timing of the instructions. The generated code seems pretty efficient. There are no jumps, just a conditional move. No branch prediction failure.
So the best way to optimize your executable is to get a good compiler.