text:
Q: RDFLib or rdflib-sqlalchemy: graph.remove function fails silently I am in the process of building out a Django-based semantic application using rdflib-sqlalchemy to handle translation between triplestore and database logic. I can't really tell whether the issue is with rdflib-sqlalchemy or with RDFLib itself, but when I attempt to remove triples from within the Django application, there is no effect on the triples portion of the database, and the graph returns an identical count of triples before and after the delete attempt. If I try the same procedure from the Python console (same VirtualEnv, same base data, but different database), the graph.remove() function works as expected. I don't see anything on SO that even closely resembles this, but I could be missing something.
So, for instance, the following works as a means of deleting all the triples with https://url.to/scheme/MADAGASCAR as the subject:
>>> g
<Graph identifier=foo (<class 'rdflib.graph.ConjunctiveGraph'>)>
>>> g.store
<Partitioned SQL N3 Store>
>>> len(list(g.triples(('https://url.to/scheme/MADAGASCAR',None,None))))
11
>>> g.remove(('https://url.to/scheme/MADAGASCAR',None,None))
>>> len(list(g.triples(('https://url.to/scheme/MADAGASCAR',None,None))))
0

Similarly, I can use the same methods from inside my Django interactive console:
>>> from django.conf import settings
>>> from rdflib_sqlalchemy.SQLAlchemy import SQLAlchemy
>>> from semantic.models import Namespace, AssertionStatement, LiteralStatement, QuotedStatement, TypeStatement, Resource
>>> g = settings.GRAPH
>>> len(list(g.triples(('https://url.to/scheme/MADAGASCAR',None,None))))
11
>>> g.remove(('https://url.to/scheme/MADAGASCAR',None,None))
>>> len(list(g.triples(('https://url.to/scheme/MADAGASCAR',None,None))))
0

But when I call it from within a Signal, there is no effect. Before I post the Signal code, let me briefly describe my approach for managing triples, which are effectively compound keys (something for which Django lacks support). What I've done is created a single Django-managed model to list out Resources (e.g., anything that can be an owl:NamedIndividual, so neither predicates nor literals) and five unmanaged models that map to rdflib-sqlalchemy's database tables (which include id (pk) fields as of 4ee1791). Populating the store via a management command makes use of rdflib-sqlalchemy to put the data in the right unmanaged tables, after which I iterate through the TypeStatements and get the unique set of resources to populate the managed Resource table. This in turn drives a portion of the admin interface so that it's possible to manage Resources in a unified way as a workaround for the lack of compound key support.
Now, everything in my admin interface works for listing purposes. So I wanted to add a delete function that would mimic a cascade delete such that if you delete a Resource object, it deletes all triples with that Resource as subject and all triples with that Resources as object. My research on how to interject with additional functions attached to the object delete function led me to Signals. Below is the Signal I created for pre_delete of a Resource object. I have added console logging simply to aid in debugging; the output of that also follows.
from django.db.models.signals import pre_save, pre_delete, post_save, post_delete
from django.dispatch import receiver
from django.conf import settings
from semantic.models import Namespace, AssertionStatement, LiteralStatement, QuotedStatement, TypeStatement, Resource
from rdflib_sqlalchemy.SQLAlchemy import SQLAlchemy
from rdflib import ConjunctiveGraph, URIRef

graph = settings.GRAPH

# When something is deleted from the Resource table, we want to delete all of its associated inbound and outbound triples
@receiver(pre_delete, sender=Resource)
def model_pre_change(sender, **kwargs):
  print("Before delete, the graph has %s triples" % len(graph))
  print("There are %s " % len(list(graph.triples((kwargs['instance'].__str__(),None,None)))) + "triples associated with %s " % kwargs['instance'].__str__())

  # Not sure why graph.remove(triple_or_quad) doesn't seem to work...
  graph.remove((kwargs['instance'].__str__(),None,None))
  graph.remove((None,None,kwargs['instance'].__str__()))

@receiver(post_delete, sender=Resource)
def model_post_change(sender, **kwargs):
  # This is for debugging only.
  print("After delete, the graph has %s triples" % len(graph))
  print("There are %s " % len(list(graph.triples((kwargs['instance'].__str__(),None,None)))) + "triples associated with %s " % kwargs['instance'].__str__())

And the log output:
Before delete, the graph has 2178 triples
There are 11 triples associated with https://url.to/scheme/MADAGASCAR
After delete, the graph has 2178 triples
There are 11 triples associated with https://url.to/scheme/MADAGASCAR

The Resource model object gets deleted as expected, but the triples remain in the store.
So the question is how do I get this to actually work? Am I doing something wrong in my Signals?

A: I didn't think it mattered, but I was using sqlite for my database. With no error messages, it didn't occur to me that the database gets locked while the Django wsgi is running. This doesn't seem to happen under the Django interactive console, which is why the function worked there with no issue.
Anyway I switched to PostgreSQL and the logic works as expecetd now. I guess my setup relies on multiple simultaneous connections to the database, which is fine as long as rdflib-sqlalchemy is just going to read the store.


text:
Q: removing jPanel from another class Here's the scenario:
I created a function that can remove or hide the JPanel inside the main panel but if calling it from another class, it won't work.
The function was:
public void hideLoginPanel(){
    mainPanel.removeAll();
    mainPanel.repaint();
}

I can set anything like setting variable values here but removing the JPanel inside the mainPanel won't work.
Here's the code from another class where I'm calling the function:
public class logService{
    private MainFrame frame = new MainFrame();
    private static logService dataService;

    public static logService getService() {
        if (dataService == null) {
            dataService = new logService();
        }
        return dataService
    }

    public void removePanel(){
        frame.hideLoginPanel // here's where I called the function
    }
}

A: import javax.swing.*;

public class Test extends JFrame {
    private JPanel nPanel;
    private JLabel label;

    Test() {
        setSize(300,300);
        nPanel = new JPanel();
        label = new JLabel("Hello!");
        nPanel.add(label);
        add(nPanel);
    }

    public void clear(JPanel panel) {
        panel.removeAll();
        panel.repaint();
    }

    public static void main(String[] args) {
        Test t = new Test();
        t.setVisible(true);
        t.clear(t.nPanel); //if you comment this line, you will see label said "Hello" to you!
    }
}

A: By looking at your code i assume you have created a new object of
MainFrame by using code private MainFrame mainFrame = new MainFrame();
Instead you should pass this object to another class from where you are calling mehtod hideLoginPanel(). Object can be passed in constructor. Look at these two classes:
class MainFrame extends JFrame {
    public MainFrame() {
        this.setLayout(new BorderLayout());
        this.setBounds(50, 50, 200, 300);
        this.setVisible(true);
        JPanel jp = new JPanel();
        jp.setBackground(Color.BLUE);
        this.add(jp, BorderLayout.CENTER);
        LogService logService = new LogService(this); // This object should be used in your control where you want clear panel
        //logService.removePanel(); // Comment and uncomment this line to see the difference. Change in blue color
    }

    public void hideLoginPanel() {
        this.removeAll();
        this.repaint();
    }

    public static void main(String args[]) {
        new MainFrame();
    }
}

class LogService {
    private  MainFrame mainFrame;

    public LogService(MainFrame mainFrame) {
        this.mainFrame=mainFrame;
    }

    public void removePanel(){
        mainFrame.hideLoginPanel(); // here's where I called the function
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++, random number w/ range of 1-6 I was wondering what the way is to get a random number with a range of 1-6, using the rand() method. This is to simulate a dice roll needed for me to find the average of 3 dice rolls so the type will be double.

A: This is a simple example to generate randoms between 1 to 6, I think you can figure the rest
#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    srand(time(0));
    std::cout << (rand() % 6 + 1) <<std::endl;
    return 0;
}


text:
Q: Restlet - how to update authenticator verifier map after a new user is created? My quest to deal with a java restlet server continues.
I was able to set-up my routing as desired, in particular there is a User resource which can be created with a POST call on an URL. When this happens, a new user is created on the Database.
From this point on I'd like the new user to be able to authenticate. The problem is that the authenticator in the inbound-root loads the usernames and password once at the beginning. So, if a new user is created, he can't authenticate unless I restart the server.
There must be an easy way of dealing with this!
This is the Application:
public class APIServerApplication extends Application {

    @Override
    public Restlet createInboundRoot(){
          //some routers and filter..

          //here the verifier is initialized with the current users and passwords:
          MapVerifier verifier = new MapVerifier();

          //get users and pwd from DB
          HashMap<String,String> usrPwdMap = SomeDBClass.getVerifierMap();
          for(String uname : usrPwdMap.keySet()){
              verifier.getLocalSecrets().put(uname,   (usrPwdMap.get(uname)).toCharArray());
          }

          //..verifier is used to build the authenticator... etc

    }

The user resource looks something like:
 public class UserResource extends ServerResource{

       @Post
   public Representation acceptItem(Representation entity) {
             //get the data from the form
             //insert the new user in the db

             /* TODO: I think i should add something here
                to refresh the verifier map!
              */
       }
 }

How can I refresh the verifier map?

A: This is AN INCORRECT way of doing things in a production application. NEVER load the usernames/password combinations in memory. It would be too much of an overkill.
In fact, please modify your application to check the username/password against the one stored in the DB for that user on EVERY http request. That is the restful way of doing things. If you think that's not a good way of doing things I suggest you read the answers for this question: RESTful authentication - resulting poor performance on high load?


text:
Q: Transform rows into columns in sql server wrong result I have table:
ID  platform
1   IOS
2   Android
3   Windows
4   IOS
5   IOS
6   IOS
7   IOS
8   Windows
9   Windows
10  Android

I want to get for platform = 'Android' and platform = 'IOS' the number of appearance.
This i did by:
select  top 2  platform, max(platformNumber) as count
from(
select ROW_NUMBER() over (partition by platform order by platform ) as platformNumber, B.* from B) temp
group by platform

The result I am getting:
platform count
Android 2
IOS 5

Now i want to be able to transform the columns to show:
IOS Android
5     2

For this i tried this script:
select platform,  'platform' + cast(ROW_NUMBER() over (partition by platform order by platform ) as varchar(10)) columnsqu
from
(
select  top 2  platform, max(platformNumber) as count
from(
select ROW_NUMBER() over (partition by platform order by platform ) as platformNumber, B.* from B) temp
group by platform) Temp2
PIVOT
(
MAX(count) FOR columnsqu IN (IOS,Android)
)PIV

I am getting error...

A: I think you just want a pivot query here:
SELECT
    COUNT(CASE WHEN platform = 'IOS' THEN 1 END) AS IOS,
    COUNT(CASE WHEN platform = 'Android' THEN 1 END) AS Android
FROM B
WHERE
    platform IN ('IOS', 'Android')
GROUP BY
    platform;


text:
Q: Xcode 7.3  &  file not found I am running project since long time.Suddenly it start giving error. I have just update Xcode to 7.3 create certificates and upload App at iTunes for Test flight. Now When I run project, it gives error "CoreTelephony/CTCallCenter.h file not found".
I have removed these files and run again, This time it gives "CoreBluetooth/CoreBluetooth.h file not found".

Framework already exist in App

*

*I have clean and rebuild project, restart xcode, restart pc.

*I have added "$(OBJROOT)/UninstalledProducts/$(PLATFORM_NAME)/include" line to "Header Search Paths".
But nothing has worked, So how to solve this error?

A: CoreBluetooth and CoreTelephony don't exist on Watch OS 2.x. Here is my tips for this:

*

*Define your preprocessor macro on project setting. In my case is APPLE_WATCH=1

*Your code now should be something like this

#ifndef APPLE_WATCH
   // YOUR CODE HERE
#endif


text:
Q: Bold/Unbold button I'm currently working with an online text editor as part of a project, and to say the least, I'm having a small issue with my bold button.
Here is my button in HTML:
 <button id="b" onclick="bold()">Bold</button>

And here is my function in JavaScript:
    function bold() {
      var ban = document.getElementById("b");

      if (ban == true) {
        document.getElementById("texto").style.fontWeight = 'bold';
      } else {
        document.getElementById("texto").style.fontWeight = 'normal';
      }
    }

If I take away everything and just leave it as:
     function bold() {
       document.getElementById("texto").style.fontWeight = 'bold';
     }

It makes my text bold, but my goal is to be able to unbold the text inside my <textarea> when I click the button a second time.
What am I doing wrong?

A: Try this:
function Bold()
{
    var text = document.getElementById("texto");
    var weight = text.style.fontWeight;
    if(weight == 'bold')
    {
        text.style.fontWeight = 'normal';

    }
    else
    {
        text.style.fontWeight = 'bold';
    }
}

A: Use external JavaScript, so it's cached, for quicker load times, and because you should separate your HTML from JavaScript as a best practice. But really, your problem is that you are redefining your var ban each time your function is getting called. Watch and learn:
//<![CDATA[
// change the pre var on any page using this onload technique
var pre = onload, doc, bod, htm, E, boldToggle; // higher scope in case other onloads need access
onload = function(){ // same as window.onload - note that window is implicit
if(pre)pre(); // execute previous onload

doc = document, bod = doc.body, htm = doc.documentElement;
E = function(id){
  return doc.getElementById(id);
}
boldToggle = (function(){ // Anonymous function executes and scopes off var b before returning an unexecuted function
  var b = 0;
  return function(e){ // e is for Element here - this is function that is returned unexecuted
    var s = e.style;
    if(b){ // test if bold
      s.fontWeight = 'normal'; b = 0;
    }
    else{
      s.fontWeight = 'bold'; b = 1;
    }
  }
})();
E('b').onclick = function(){
  boldToggle(this); // this within Event refers to Element id='b' in this case
}

} // end onload
//]]>

Oh, if using <button> that would be a submit button, so do this:
<button type='button' id='b'>Bold</button>

I prefer:
<input type='button' id='b' value='Bold' />

It's more clear, since many a Browser cannot access .innerHTML on <button> because it's really an input, so the <button> tag may be misleading. I learned this when I corrected some code here, where the user had nested other Elements within <button>. That won't work on some Browsers, so I just prefer <input type='button' />. If you ever work on large projects this can prevent others from trying to throw Elements in there that don't belong.

A:

function Bold()
{

   var  ban =document.getElementById("texto").style.fontWeight ;

 if(ban == 'normal')
    {
        document.getElementById("texto").style.fontWeight = 'bold';
    }
 else
    {
        document.getElementById("texto").style.fontWeight = 'normal';
    }
}
<button id="b"   onclick="Bold()">Bold</button>

Hi

A: Use classes to manage CSS styling.

function bold() { document.getElementById('b').classList.toggle('bold'); }
.bold { font-weight: bold; }
<button id="b" onclick="bold()">Bold</button>


text:
Q: How to use function defined in a groovy script using the "evaluate" method from Java I just discover Groovy call from Java and have problem with this case :
I have a groovy file : "test.groovy"
a = 1.0
def mul2( x ) { 2.0 * x }

And I want to use it from Java code like this
GroovyShell gs = new GroovyShell();
gs.parse( new File( ".../test.groovy" ) ).run();

System.out.printf( "a = %s%n", gs.evaluate("a") ); // ok
System.out.printf( "mul2(a) = %s%n", gs.evaluate( "mul2(a)" ) ); // error

The error is :
groovy.lang.MissingMethodException: No signature of method: Script1.mul2() is applicable for argument types: (BigDecimal) values: [1.0]

What I have to do to have access to function defined in groovy script, using evaluate() method ?
I need to use "evaluate" method because I want finally to evaluate something like Math.sin( a * mul2(Math.Pi) ).

Now I have 4 solutions (the forth is what I searched for) :

*

*use closure as in answer of 'Szymon Stepniak'

*use import static as in answer of 'daggett'

*extends the script that contains Java functions with the script that evaluate the expression :

...the class (in Java, not Groovy)...
  public static abstract class ScriptClass extends Script
  {
    double mul2( double x )
    {
      return x * 2;
    }
  }

...the code...
  CompilerConfiguration config = new CompilerConfiguration();
  config.setScriptBaseClass(ScriptClass.class.getName());

  GroovyShell gs = new GroovyShell(config);

  System.out.printf( "result = %s%n", gs.evaluate("mul2(5.05)") );

That works but the code is in Java, not what I want, but I note it here for ones need to do that

*And finally extends groovy script :

the groovy file :
double mul2( x ) { x * 2 }
a=mul2(3.33)

the java code that use it
GroovyClassLoader gcl = new GroovyClassLoader();
Class<?> r = gcl.parseClass( resourceToFile("/testx.groovy") );
CompilerConfiguration config = new CompilerConfiguration();
config.setScriptBaseClass(r.getName());
GroovyShell gs = new GroovyShell(gcl, config);

System.out.printf( "mul2(5.05) = %s%n", gs.evaluate("mul2(5.05)") );

// WARNING : call super.run() in evaluate expression to have access to variables defined in script
System.out.printf( "result = %s%n", gs.evaluate("super.run(); mul2(a) / 123.0") );

It's exactly what I wanted :-)

A: There are two things worth explaining to understand what is happening here. There are two different scopes in the script you have provided.
The variable a gets stored in GroovyShell binding object and that is why it is available in every gs.evaluate() call. Take a look at this example:
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;

final class ExecuteGroovyScriptExample {

    public static void main(String[] args) {
        final String script = "a = 1.0 \n" +
                "def mul2(x) { 2.0 * x }\n";

        final Binding binding = new Binding();

        final GroovyShell gs = new GroovyShell(binding);
        final Script sc = gs.parse(script);
        sc.run();

        System.out.printf("binding.getVariable(\"a\") == %s\n", binding.getVariable("a"));
    }
}

Running this example produces following output:
binding.getVariable("a") == 1.0

The second thing is that every gs.evaluate() call generates a new groovy.lang.Script class which has a completely different context. This is why calling:
gs.evaluate("mul2(a)")

throws something like this:
Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: Script2.mul2() is applicable for argument types: (BigDecimal) values: [1.0]

because the script class that gets generated from gs.evaluate("mul2(a)") invocation does not contain mul2(x) method. The class that gets generated by this call looks something like this:
class Script2 extends groovy.lang.Script {
    void run() {
        mul2(a)
    }
}

However, the script class returned from gs.parse(script) contains mul2(x) method, so you can invoke it, but not as gs.evaluate() call, but Script.invokeMethod(name, args) instead. Something like this:
import groovy.lang.GroovyShell;
import groovy.lang.Script;

final class ExecuteGroovyScriptExample {

    public static void main(String[] args) {
        final String script = "a = 1.0 \n" +
                "def mul2(x) { 2.0 * x }\n";

        final GroovyShell gs = new GroovyShell();
        final Script sc = gs.parse(script);
        sc.run();

        System.out.printf("mul2(a) = %s%n", sc.invokeMethod("mul2", gs.evaluate("a")));
    }
}

This example produces following output:
mul2(a) = 2.00

Take a look how mul2(x) method got invoked. Firstly, we store script returned by gs.parse(script) in sc variable and it allows us to invoke method defined in this script by following call:
sc.invokeMethod("mul2", gs.evaluate("a"));

In this example we take value of a variable simply by gs.evaluate("a"), but you can also use binding object from the first example as well. And keep in mind that if a variable was defined like:
def a = 1.0

or
@groovy.transform.Field
def a = 1.0

it would not get stored in the binding object anymore and in the first case it defines script's local variable a and in the second case it defines script class field a.

Alternatively, if you want to execute following invocation:
gs.evaluate("mul2(a)")

or even
gs.evaluate("Math.sin( a * mul2(Math.PI))")

you would have to modify input Groovy script file and replace function mul2(x) definition with a closure in the same scope as the a variable, so it gets stored in the binding object:
a = 1.0
mul2 = { x -> 2.0 * x }

A: let you have /my/groovy/classes/Test.groovy:
static mul2( x ) { 2.0 * x }
def    mul3( x ) { 3.0 * x }

then you can use class loader to load it as a class and use this class in expressions:
GroovyShell gs = new GroovyShell();
gs.getClassLoader().addClasspath("/my/groovy/classes");

System.out.println( gs.evaluate( "import static Test.*; mul2(5)" ) );
System.out.println( gs.evaluate( "new Test().mul3(6)" ) );


text:
Q: Castle windsor Adding conditional dependency I have 2 implementations of the same interface and want to use implementation1 if the user is logged in or implementation2 if the user is not logged in.  How can I configure this with castle windsor?

A: You could add a handler selector, which would be able to select between available implementations depending on e.g. whether Thread.CurrentPrincipal was set (or HttpContext.Current.Request.IsAuthenticated in ASP.NET/MVC if I remember correctly).
The handler selector would probably look somewhat like this:
public class MyAuthHandlerSelector : IHandlerSelector
{
    public bool HasOpinionAbout(string key, Type service)
    {
        return service == typeof(ITheServiceICareAbout);
    }

    public IHandler SelectHandler(string key, Type service, IHandler[] handlers)
    {
        return IsAuthenticated
            ? FindHandlerForAuthenticatedUser(handlers)
            : FindGuestHandler(handlers);
    }

    bool IsAuthenticated
    {
        get { return Thread.CurrentPrincipal != null; }
    }
    // ....
}

Only downside of handler selectors is that they're not pulled from the container - i.e. they're added as an instance to the container at registration time, so they don't get to have dependencies injected, lifestyle managed, etc., but there are ways to mitigate that - take a look at F.T.Windsor if you're interested in seeing how that can be done.

A: One way to solve this would be, Register the service with key and then resolve as you need.
public interface ISample
{
    int Calculate(int a, int b);
}

class SampleB : ISample
{
    public int Calculate(int a, int b)
    {
        return a + b + 10;
    }
}

class SampleA : ISample
{
    public int Calculate(int a, int b)
    {
        return a + b;
    }
}

The registration:
        container.Register(Component.For<ISample>().ImplementedBy<SampleA>().Named("SampleA").LifeStyle.Transient);
        container.Register(Component.For<ISample>().ImplementedBy<SampleB>().Named("SampleB").LifeStyle.Transient);

// Resolve when SampleA needed.
var sampleA = container.Resolve<ISample>("SampleA");

// Resolve when SampleB needed.
var sampleB = container.Resolve<ISample>("SampleB");


text:
Q: Python - Loading Zip Codes into a DataFrame as Strings? I'm using Pandas to load an Excel spreadsheet which contains zip code (e.g. 32771). The zip codes are stored as 5 digit strings in spreadsheet. When they are pulled into a DataFrame using the command...
xls = pd.ExcelFile("5-Digit-Zip-Codes.xlsx")
dfz = xls.parse('Zip Codes')

they are converted into numbers. So '00501' becomes 501.
So my questions are, how do I:
a. Load the DataFrame and keep the string type of the zip codes stored in the Excel file?
b. Convert the numbers in the DataFrame into a five digit string e.g. "501" becomes "00501"?

A: As a workaround, you could convert the ints to 0-padded strings of length 5 using Series.str.zfill:
df['zipcode'] = df['zipcode'].astype(str).str.zfill(5)

Demo:
import pandas as pd
df = pd.DataFrame({'zipcode':['00501']})
df.to_excel('/tmp/out.xlsx')
xl = pd.ExcelFile('/tmp/out.xlsx')
df = xl.parse('Sheet1')
df['zipcode'] = df['zipcode'].astype(str).str.zfill(5)
print(df)

yields
  zipcode
0   00501

A: You can avoid panda's type inference with a custom converter, e.g. if 'zipcode' was the header of the column with zipcodes:
dfz = xls.parse('Zip Codes', converters={'zipcode': lambda x:x})

This is arguably a bug since the column was originally string encoded, made an issue here

A: str(my_zip).zfill(5)

or
print("{0:>05s}".format(str(my_zip)))

are 2 of many many ways to do this

A: The previous answers have correctly suggested using zfill(5). However, if your zipcodes are already in float datatype for some reason (I recently encountered data like this), you first need to convert it to int. Then you can use zfill(5).
df = pd.DataFrame({'zipcode':[11.0, 11013.0]})

    zipcode
0   11.0
1   11013.0

df['zipcode'] = df['zipcode'].astype(int).astype(str).str.zfill(5)

    zipcode
0   00011
1   11013


text:
Q: How do you prove the transitiveness of xRy if 2 divides x + y The relation I have is
xRy iff 2 | x + y on the set of positive integers (Z+)
I intrinsically know that it is transitive, but I can't think of a way to mathematically prove it. Any thoughts?

A: assume that you have $xRy$ and $yRz$, and then prove that you also have $xRz$.
because $xRy$ and $yRz$ then its says that $2 |(x+y)$ and also $2 |(y+z)$, then exists integers $m,k \in \Bbb Z^+$ s.t $$x+y = 2k\rightarrow x= 2k -y$$ and $$y+z=2m\rightarrow z=2m-y.$$ now, you can write that $$x+z = (2k - y) + (2m - y)= 2(k+m-y),$$ which implies that $2|(x+z)$ and therefore you have also $xRz$

A: Suppose $x,y,z\in\Bbb Z_+$ with  $x\mathrel Ry$ and $y\mathrel Rz$, i.e., $2\mid x+y$ and $2\mid y+z$, say $x+y=2r$ and $y+z=2x$ with $r,s\in\Bbb Z$. Then $x+z=(x+y)+(y+z)-2y=2r+2s-2y=2(r+s-y)$ with $r+s-y\in\Bbb Z$, i.e., $2\mid x+z$, in other words $x\mathrel R z$.

A: Well $2|x+y$ if and only if $x$ and $y$ are of the same parity (both odd or both even).
Thus, $xRy$ ($x$ and $y$ the same parity) and $yRz$ ($y$ and $z$ the same parity) implies $x$ and $z$ are the same parity (i.e. $xRz$).


text:
Q: Show decimals only if the cell has while showing custom text in Excel I have a row of cells with numeric values. I'd like to produce the following effect:
---------------------------
|Cell value | Cell result |
---------------------------
|2          | 2 kg        |
|1.43       | 1.43 kg     |
|9.5764     | 9.58 kg     |
|3.2        | 3.2 kg      |
---------------------------

Basically,

*

*I want them to always show "kg" after the value that is entered.

*Any decimal value entered need to be rounded up to 2 decimal places; if there are no decimal places, it's going to show the whole number.

I've formatted cells to 0" kg"so it always show  the kilograms.
As for showing only decimals if necessary, I've used the formula =ROUND(X, 2) on each cell to only show two decimals (X being the value I introduce).
Question: However when I type =ROUND(2.5, 2) it displays 3 kg instead of 2.5 kg. Why is it? Do you have other possible solutions?
Edit 1
I've changed the cell formatting to 0.##" kg" and it works just like I want. Now the problem is if I use =ROUND(10, 2) it displays 10. kg with that additional point right after the number.

A: One possible solution based on what I understand your requirement.  Use FIXED function to first round it to 2 decimals and check for last three digits, if .00 use only integer portion and concatenate with 'kg' if last digit is zero round to only 1 decimal else round to two decimals.
Assuming your data is in column B, try this formula in column C
=IF(RIGHT(FIXED(B1,2),3)=".00",CONCATENATE(INT(B1)," kg"),IF(RIGHT(FIXED(B1,2),1)="0",CONCATENATE(FIXED(B1,1)," kg"),CONCATENATE(FIXED(B1,2)," kg")))

A: With the numbers in column A, use the Round() function in column B and then format with Custom format "General k\g". See screenshot


text:
Q: Collapse and expand all I am trying to implement expand/collapse all functionality.
I have a list of expandable items, with a button in the top right which allows the users to expand and collapse everything.
Currently, my code works if everything is expanded/collapsed together, but does not work properly when the user expands a few (and not all) of the elements. It simply switches the collapsed/expanded elements. JSFiddle
Here is my jQuery code that is being run:
$('div.srcprojects').hide();
$('.projectscontainer').on("click", "span.destproject", function (){
    $(this).siblings('.srcprojects').toggle().end().siblings('div.destarrow').toggleClass("arrow-right arrow-down");
}).on("click", "div.destarrow", function (){
    $(this).parent().find("span.destproject").trigger("click");
});

$('body').on("click", "span#expandcollapse", function (){
    $(this).text(function(i, currentText){
        return currentText === 'Expand All' ? 'Collapse All' : 'Expand All';
    });
    $('body').find("span.destproject").trigger("click");
});

How I can make it so my #expandcollapse actually expands all/collapses all?

A: Without disecting your code completely, I will just point out that jQuery's toggle method simply switches the visibility from show to hide and vice-versa.  If you just want to toggle in one direction, you can do:
.toggle(true) to show and
.toggle(false) to hide
http://api.jquery.com/toggle/#toggle-showOrHide

A: Using toggle will do that.
I'm not sure I understand exactly what you're looking for, but hopefully this little example could get you on your way there:
$('#expandcollapse').click(function () {
    $('.projectscontainer').each(function () {
        //Code to manipulate the elements here, like .show()/.hide()
    });
});

A: I believe that you can simply do
$("#expandcollapse").on("click",function(e) {
    $(".projectscontainer").find(".srcprojects").toggleSlide();
});

This will also give you a nice slideUp/Down animation when the slides are toggled.


text:
Q: Drawing cubes with stacked matrix I am trying to understand some parts of OpenGL. I have to create a robot, which is made from a few part. At start I want to draw 3 cubes in a row. At first I want to draw a cube in the middle, and after that the rest two.
Can you tell me what I did wrong?
void drawScene(GLFWwindow* window) {
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

    mat4 P=perspective(50.0f*PI/180.0f,aspect,1.0f,50.0f);
    mat4 V=lookAt(
                  vec3(0.0f,0.0f,-15.0f),
                  vec3(0.0f,0.0f,0.0f),
                  vec3(0.0f,1.0f,0.0f));
    glMatrixMode(GL_PROJECTION);
    glLoadMatrixf(value_ptr(P));
    glMatrixMode(GL_MODELVIEW);

    mat4 M=mat4(1.0f);
    glLoadMatrixf(value_ptr(V*M));

    glPushMatrix();                         //create matrix 1 on the top
    Models::cube.drawSolid();               //draw cube on 0,0,0 coords
    glTranslatef(3.0, 0.0, 0.0);            //apply translation to matrix 1
    Models::cube.drawSolid();               //draw cube on 3,0,0 coords
    glPopMatrix();
    glRotatef(180*PI/180, 1.0, 0.0, 0.0);
    glTranslatef(3.0, 0.0, 0.0);
    Models::cube.drawSolid();

    glfwSwapBuffers(window);
}

And another example which is giving me the same wrong results:
void drawScene(GLFWwindow* window) {
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

    mat4 P=perspective(50.0f*PI/180.0f,aspect,1.0f,50.0f);
    mat4 V=lookAt(
                  vec3(0.0f,0.0f,-15.0f),
                  vec3(0.0f,0.0f,0.0f),
                  vec3(0.0f,1.0f,0.0f));
    glMatrixMode(GL_PROJECTION);
    glLoadMatrixf(value_ptr(P));
    glMatrixMode(GL_MODELVIEW);

    mat4 M=mat4(1.0f);
    glLoadMatrixf(value_ptr(V*M));

    glPushMatrix(); //Matrix 1 on the top
    glPushMatrix(); //Matrix 2 on the top
    Models::cube.drawSolid(); //Draw cube on matrix 2
    glTranslatef(3.0, 0.0, 0.0); //Apply translation on matrix 2
    glPushMatrix(); //Matrix 3 on the top
    Models::cube.drawSolid(); //Draw cube on matrix 3
    glPopMatrix(); //Matrix 2 on the top
    glPopMatrix(); //Matrix 1 on the top
    glRotatef(180*PI/180, 1.0, 0.0, 0.0); //Apply translation on matrix 1
    glTranslatef(3.0, 0.0, 0.0); //Apply translation on matrix 1
    Models::cube.drawSolid(); //Draw cube on matrix 1

    glfwSwapBuffers(window);
}

In both cases I have to translate last cube for 6.0 instead of 3.0. I dont really understand why. It seems to me that after backing to matrix 1 I apply effect on them.
To be clear, I want to do something like this:
Draw Cube in 0,0,0
    []
go to 3,0,0
Draw Cube
    []  []
Go back to 0,0,0
Rotate in 180 degrees
Go to -3,0,0
Draw Cube
[]  []  []

A: You want to draw a cube in the center, a second cube translated to the right and a third cube translated to the left (along the X-axis).
This can be done in different ways:

You can draw the cube in the center, go one step to the right and draw the next cube and finally go two steps to the left an draw the third cube:
float step = 3.0f;

Models::cube.drawSolid();
glTranslatef( 1.0f * step, 0.0f, 0.0f );
Models::cube.drawSolid();
glTranslatef( -2.0f * step, 0.0f, 0.0f );
Models::cube.drawSolid();

You can draw the cube in the center and save (push) the model matirx, go one step to the right and draw the next cube and finally restore (pop) the model matrix, go one steps to the left an draw the third cube:
glPushMatrix();
Models::cube.drawSolid();
glTranslatef( 1.0f * step, 0.0f, 0.0f );
Models::cube.drawSolid();
glPopMatrix();
glTranslatef( -1.0f * step, 0.0f, 0.0f );
Models::cube.drawSolid();

Finally what you desided to do.
Draw the cube in the center and save (push) the model matirx, go one step to the right and draw the next cube and finally restore (pop) the model matrix, turn around 180° degrees, go one steps to the right an draw the third cube. But you have to rotate around the up vector, which is (0, 1, 0) in your case, and not around the X-axis:

glPushMatrix();
Models::cube.drawSolid();
glTranslatef( 1.0f * step, 0.0f, 0.0f );
Models::cube.drawSolid();
glPopMatrix();
glRotatef( 180*PI/180, 0.0, 1.0f, 0.0f ); // rotate around the up vector
glTranslatef( 1.0f * step, 0.0f, 0.0f );
Models::cube.drawSolid();

By the way, in your 2nd example you push 3 matrices onto the stack, but you pop only 2 matrices. Each matrix which is put on the stack should also be taken down again. This means the number of glPushMatrix and glPopMatrixshould always be equal. Else you would either stack up without an end, or you would try to take something from the empty stack.


text:
Q: Parse a Ruby Variable inside YML file I have a yml file here where I took a part of my ruby code and make it a hash:
answer: "The answer is: #{result}"

The result variable is from my ruby code where I initiated here:
require 'yaml'
MESSAGES = YAML.load_file('mymessages.yml')

result = case operator
           when '1'
             number1.to_i() + number2.to_i()
           when '2'
             number1.to_i() - number2.to_i()
           when '3'
             number1.to_i() * number2.to_i()
           else
             number1.to_f() / number2.to_f()
           end

  prompt('answer')

When I initiated this, it's just displaying the whole text as a string but the result variable was not displayed w/c is suppose to be an addition or subtraction etc. of 2 numbers.
Do you know how to fix this?
Thanks!

A: YAML and Ruby are two different languages. You can't use Ruby string interpolation in YAML, because YAML is YAML, not Ruby. You can only use Ruby string interpolation in Ruby.

A: You need to extract the piece of code you have a problem with in a separate script that you can test or publish on its own, here an example of what I made of your code, I must guess at the contents of your Yaml file since you didn't provide that.
require 'yaml'

MESSAGES = YAML.load_file('./mymessages.yml')
p MESSAGES # poor mans debug
operator = MESSAGES["operator"].to_f #supposing in your yaml it is a Hash with key "operator"
#operator = '1' # for testing without the yaml
number1, number2 = 4.0, 5.0

result = case operator
when '1'
  number1 + number2
when '2'
  number1 - number2
when '3'
  number1 * number2
else
  number1 / number2
end

puts result # 9.0
prompt = "The answer is: #{result}".sub(/\.0$/,'') #remove unwanted traling .0
puts prompt # The answer is: 9

You see I use variables that I can check wit a puts or p, real testing would be better but I don't have time to explain all that, but you should learn it.
If you do things more than once like the .to_i conversion try to save that in a variable.
Also I don't see the need to work with both integers ands floats, if one is float, treat them all like float and if you don't want the traling zero remove it with the sub method or chaneg the type once like this
result = result.to_i if result == result.to_i


text:
Q: VBA filtering based on multiple criteria I have an Excel workbook where a user inputs up to four keywords from a drop-down list in cells C4:C7 of sheet "Report generator", and my VBA code then takes these keywords, does a filtering on another sheet called "Data", copies the filtered rows and pastes them in a Word file as a report. The code works for up to two keywords at the same time, but for some reason fails when having three or four and I cannot understand why. Specifically, when having three or four keywords the filtering returns 0 rows so there is nothing to copy. This is not an issue if I try to do it manually in Excel so it's not a problem of the data.
Below is the part of the code that does the filtering. As you can see, the if loop checks sequentially whether each keyword is blank starting from the last one, and applies the filled-in keywords to the filtering. The loop finishes successfully every time, but for some reason the filtering command in cases of 3 or 4 keywords returns 0 rows. Could you please help me to understand why this happens? Thank you!
    'Filter data based on keywords selected
Sheets("Data").Select

'If user inputs 1 keyword
If IsEmpty(Sheets("Report generator").Range("C7")) = True And IsEmpty(Sheets("Report generator").Range("C6")) = True And IsEmpty(Sheets("Report generator").Range("C5")) = True Then

    ActiveSheet.Range("$A$1:$F$1").AutoFilter Field:=5, Criteria1:= _
        Array("*" & Sheets("Report generator").Range("C4").Value & "*"), _
    Operator:=xlFilterValues

'If user inputs 2 keywords
ElseIf IsEmpty(Sheets("Report generator").Range("C7")) = True And IsEmpty(Sheets("Report generator").Range("C6")) = True Then

    ActiveSheet.Range("$A$1:$F$1").AutoFilter Field:=5, Criteria1:= _
        Array("*" & Sheets("Report generator").Range("C4").Value & "*", _
        "*" & Sheets("Report generator").Range("C5").Value & "*"), _
    Operator:=xlFilterValues

'If user inputs 3 keywords
ElseIf IsEmpty(Sheets("Report generator").Range("C7")) = True Then

    ActiveSheet.Range("$A$1:$F$1").AutoFilter Field:=5, Criteria1:= _
        Array("*" & Sheets("Report generator").Range("C4").Value & "*", _
        "*" & Sheets("Report generator").Range("C5").Value & "*", _
        "*" & Sheets("Report generator").Range("C6").Value & "*"), _
    Operator:=xlFilterValues

'If user inputs 4 keywords
ElseIf IsEmpty(Sheets("Report generator").Range("C7")) = False And IsEmpty(Sheets("Report generator").Range("C6")) = False And IsEmpty(Sheets("Report generator").Range("C5")) = False And IsEmpty(Sheets("Report generator").Range("C4")) = False Then

    ActiveSheet.Range("$A$1:$F$1").AutoFilter Field:=5, Criteria1:= _
        Array("*" & Sheets("Report generator").Range("C4").Value & "*", _
        "*" & Sheets("Report generator").Range("C5").Value & "*", _
        "*" & Sheets("Report generator").Range("C6").Value & "*", _
        "*" & Sheets("Report generator").Range("C7").Value & "*"), _
    Operator:=xlFilterValues

End If

A: Copy Filtered Data

*

*The main issue is that you cannot use more than two elements containing wild characters in the Criteria1 array.

*The following will copy the filtered data to a third worksheet (Report). You could then export it to Word.

Option Explicit

Sub CopyFilteredData()

    Const lName As String = "Report Generator"
    Const lrgAddress As String = "C4:C7"

    Const sName As String = "Data"
    Const sCols As String = "A:F"
    Const sfField As Long = 5

    Const dName As String = "Report"
    Const dFirst As String = "A1"

    Const doCopyHeaders As Boolean = True ' e.g. if dFirst = "A2" then 'False'

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    ' Write the criterias to a dictionary.

    Dim lws As Worksheet: Set lws = wb.Worksheets(lName)
    Dim lrg As Range: Set lrg = lws.Range(lrgAddress)

    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    dict.CompareMode = vbTextCompare

    Dim lCell As Range
    Dim lString As String

    For Each lCell In lrg.Cells
        lString = CStr(lCell.Value)
        If Len(lString) > 0 Then
            dict("*" & lString & "*") = Empty
        End If
    Next lCell

    Dim dCount As Long: dCount = dict.Count
    If dCount = 0 Then Exit Sub ' no criterias

    Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
    If sws.AutoFilterMode Then
        sws.AutoFilterMode = False
    End If

    ' Source Table Range
    Dim strg As Range: Set strg = sws.Range("A1").CurrentRegion.Columns(sCols)
    ' Source Data Range ('strg' without headers)
    Dim sdrg As Range: Set sdrg = strg.Resize(strg.Rows.Count - 1).Offset(1)

    Dim srg As Range

    Select Case dCount

    Case Is < 3 ' up to two criteria with wild characters

        strg.AutoFilter sfField, dict.Keys, xlFilterValues
        Set srg = sdrg.SpecialCells(xlCellTypeVisible)
        sws.AutoFilterMode = False

    Case Else ' more criteria with wild characters

        Dim fpCount As Long: fpCount = Int(dCount / 2)
        Dim UB As Long: UB = 1
        Dim arr As Variant: ReDim arr(0 To 1)

        Dim sfdrg As Range
        Dim fp As Long
        Dim n As Long

        ' For each filter pair...
        For fp = 0 To fpCount
            If fp = fpCount Then ' last loop only
                If dCount Mod 2 = 1 Then ' count is odd: needs to loop once more
                    UB = 0
                    ReDim arr(0 To 0)
                Else ' count is even: no need to loop anymore
                    UB = -1
                End If
            End If
            If UB > -1 Then
                ' Write criteria pair to an array.
                For n = 0 To UB
                    arr(n) = dict.Keys()(n + fp * 2)
                Next n
                ' Filter Source Data Range.
                sdrg.AutoFilter sfField, arr, xlFilterValues
                ' Combine filtered range into Source Range.
                On Error Resume Next
                Set sfdrg = sdrg.SpecialCells(xlCellTypeVisible)
                On Error GoTo 0
                sws.AutoFilterMode = False
                If Not sfdrg Is Nothing Then
                    If srg Is Nothing Then
                        Set srg = sfdrg
                    Else
                        Set srg = Union(srg, sfdrg)
                    End If
                    Set sfdrg = Nothing
                End If
            End If
        Next fp

    End Select

    If srg Is Nothing Then Exit Sub

    If doCopyHeaders Then
        Set srg = Union(strg.Rows(1), srg)
    End If
    Debug.Print srg.Address(0, 0)

    ' Copy to the Destination worksheet.
    Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
    dws.Cells.Clear
    Dim dfCell As Range: Set dfCell = dws.Range(dFirst)
    srg.Copy dfCell

End Sub


text:
Q: ImageMagick: use multiple cores with convert and montage on macOSX? I am using montage and convert utilities in my bash scripts to convert, process or combine images in the following fashion:
for file in "${vizu_temp}"/*.png; do
    convert ${some+options} $file $file
  done

how could I improve my bash workflow in order that I could use multiple cores available on my Imac to speed up such post-processing ?
In particularly I am using '-distort BarrelInverse 2:20' option as the pre-processing filter that takes a lot of time for a big image ..


text:
Q: ¿Como establezco el fragmento predeterminado al iniciar mi aplicacion Estoy usando un BottomNavigationView, tengo 3 fragmentos en un container y al iniciar siempre aparece el fragmento del icono de la izquierda por defecto, quisiera que al iniciar me salga predeterminado otro ítem, el del centro, la verdad no se como hacerlo, agradecia de la ayuda de alguien
bottom.setOnNavigationItemSelectedListener(new
BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem)
{
        switch (menuItem.getItemId()) {
               case R.id.home:
                    HomeFragment homeFragment =new HomeFragment();

      getSupportFragmentManager().beginTransaction().replace(R.id.container,
      homeFragment)

     .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
                            .addToBackStack(null).commit();
                    return true;
                case R.id.searc:
                    SearchFragment searchFragment = new SearchFragment();

getSupportFragmentManager().beginTransaction().replace(R.id.container,
searchFragment)

.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
                            .addToBackStack(null).commit();
                    return true;
                case R.id.profile:
                    ProfileFragment profileFragment =new ProfileFragment();

getSupportFragmentManager().beginTransaction().replace(R.id.container,
profileFragment)

.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
                            .addToBackStack(null).commit();
                    return true;
            }
            return false;
        }
    });

A: Veras, la lógica es la siguiente, espero que te pueda servir.
Debes inicializar el fragmento que quieres que sea el que inicie primero en el MainActivity, en el método onCreate()
Lo inicializas de la misma manera que lo estas realizando en el Listener:
 getSupportFragmentManager().beginTransaction().replace(R.id.container,
  TU FRAGMENT)

 .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
                        .addToBackStack(null).commit();

De esta manera aparecerá como principal este fragment.
Espero que sea de ayuda.
Saludos


text:
Q: How do I start up remote debugging with PyCharm? I'm trying to get debugging up between PyCharm (on windows host) and a debian virtual host running my django application.  The instructions say to install the egg, add the import, and then invoke a command. I assume these things need to be done on the debian host?
Ok, then, in what file should I put these two lines?
from pydev import pydevd
pydevd.settrace('not.local', port=21000, stdoutToServer=True, stderrToServer=True)

I tried putting it into the settings.py but got this kind of thing...
File "/django/conf/__init__.py", line 87, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
File "/django/utils/importlib.py", line 35, in import_module
    __import__(name)
File "/settings.py", line 10, in <module>
    pydevd.settrace('dan.local', port=21000, stdoutToServer=True, stderrToServer=True)
File "/pycharm-debug.egg/pydev/pydevd.py", line 1079, in settrace
    debugger.connect(host, port)
File "/pycharm-debug.egg/pydev/pydevd.py", line 241, in connect
    s = StartClient(host, port)
File "/pycharm-debug.egg/pydev/pydevd_comm.py", line 362, in StartClient
    sys.exit(1)
SystemExit: 1

Whilst pycharm just sat there "waiting for connection"

A: PyCharm (or your ide of choice) acts as the "server" and your application is the "client"; so you start the server first - tell the IDE to 'debug' - then run the client - which is some code with the settrace statement in it. When your python code hits the settrace it connects to the server - pycharm - and starts feeding it the debug data.
To make this happen:
1. copy the pydev library to the remote machine
So I had to copy the file from C:\Program Files\JetBrains\PyCharm 1.5.3\pycharm-debug.egg to my linux machine. I put it at /home/john/api-dependancies/pycharm-debug.egg
2. Put the egg in the PYTHONPATH
Hopefully you appreciate that you're not going to be able to use the egg unless python can find it. I guess most people use easy_install but in my instance I added it explicitly by putting this:
   import sys
   sys.path.append('/home/john/app-dependancies/pycharm-debug.egg')

This is only necessary because I've still had no success installing an egg. This is my workaround.
3. setup the debug server config
In PyCharm you can configure the debug server via:

*

*Run-> Edit Configurations: opens the 'Run/Debug Configurations' dialog

*Defaults -> "Python Remote Debug": is the template to use

*fill out the local host name and port and you'll probably want to 'use path mapping' but more on all this below...

*"OK"
Local host name: means the name of the server - that's the windows host machine in my case - or actually the IP Address of the windows host machine since the hostname is not known to my remote machine. So the virtual (remote) machine has to be able to reach the host.  ping and netstat are good for this.
Port: can be any vacant non-priviledged port you like. eg: 21000 is unlikely to be in use.
Don't worry about the path mappings for now.
4. Start the debug server

*

*Run-> Debug : start the debug server - choose the configuration you just created.

The debug console tab will appear and you should get
 Starting debug server at port 21000

in the console which means that the ide debug server is waiting for your code to open a connection to it.
5. Insert the code
This works inside a unit test:
from django.test import TestCase
class APITestCase(TestCase):
    def test_remote_debug(self):
        import sys
        sys.path.append('/home/john/dependancies/pycharm-debug.egg')
        from pydev import pydevd
        pydevd.settrace('192.168.33.1', port=21000, suspend=False)

        print "foo"

And in a django web application it's a bit finicky about where you put it - seems to work only after everything else is done:
if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

    sys.path.append('/vagrant/pycharm-debug.egg')
    import pydevd
    pydevd.settrace('192.168.33.1', port=21000, suspend=False)

Again that the IP address is the box where you're running Pycharm on; you should be able to ping that ip address from the box running your code/website.  The port is your choice, just make sure you've told pycharm to listen on the same port.  And I found the suspend=False less problematic than the defaults of, not only immediately halting so you're not sure if it's working, but also trying to stream to stdin/out which might give you grief also.
6. Open the firewall
Windows 7 firewall will, by default, block your incoming connection. Using netstat on the remote host you'll be able to see that SYN_SENT never becomes ESTABLISHED, at least not until you add an exception to the windows firewall for the application 'pycharm'.
OS/X and Ubuntu do not have firewalls to punch threw (by default, someone may have applied one later).
7. Set a breakpoint and run the code
After all that, when everything goes to plan, you can set a breakpoint - somewhere after the settrace has run - and pycharm console will show
Connected to pydev debugger (build 107.386)

and under the 'Debugger' tab the variables stack will start working and you can step through the code.
8. Mappings
Mapping tell pycharm where it can find the source code. So when the debugger says "i'm running line 393 of file /foo/bar/nang.py, Pycharm can translate that remote absolute path into an absolute local path... and show you the source code.
/Users/john/code/app/    /opt/bestprice/app/
/Users/john/code/master/lib    /opt/bestprice/lib/python2.7/site-packages

Done.

A: It  is just  a note ,  actually  ,  but  contains some info  that  may save hours.

*

*Right  now pip  install pydevd  worked for me on both ubuntu and centos 6

*If you  want to  really   debug  remote server  which is behind firewals and stuff,  you  can  use the  following  trick:
ssh -R  8081:localhost:8081 user@remote-server.com

This allows  remote code to  connect  to  your machine  listening  on  localhost:8081

*If remote debugger does not  want to  start,  saying  it  can't  find socket port, check  your firewall rules. Note that rule  with  127.0.0.1 is not  the  same as localhost.

A: It seems that for some reason debugger couldn't connect to your windows host with PyCharm. Haven't you got any other messages in stderr? If you have not, try to run it one more time, but with sterrToServer=false. That may show real reason why it doesn't connect.


text:
Q: Iterating a singly linked list not working drivers I'm trying to code a driver that implements a singly linked list for md5 hashes.
The code I have so far is:
Signature.h
#ifndef SIGNATURE_H
#define SIGNATURE_H

typedef struct {
    char hash[33]; // last byte for null terminator
    SINGLE_LIST_ENTRY next;
} SIGNATURE, *PSIGNATURE;

#endif

SignatureList.h
#define CopyCharArrays(src, dest, len)      \
do {                                    \
    for (int i = 0; i < len; i++)       \
        dest[i] = src[i];               \
    dest[len] = '\0';                   \
} while(0)

/* Return TRUE if strings are equal */
static BOOLEAN IsEqual(char* str1, char* str2, int len)
{
    for (int i = 0; i < len; i++)
        if (str1[i] != str2[i])
            return FALSE;

    return TRUE;
}
SINGLE_LIST_ENTRY Head;

static void AddToSignatureList(char hash[32]) {
    PSIGNATURE Sig = ExAllocatePool(NonPagedPoolNx, sizeof(SIGNATURE)); // allocate memory to store a SIGNATURE node

    CopyCharArrays(hash, Sig->hash, 32); // place the hash in our new allocated node (puts null terminator at position 33)

    DbgPrintEx(0, DPFLTR_ERROR_LEVEL, "Hash: %s\n", Sig->hash);
    PushEntryList(&Head, &Sig->next); // insert the new node in our list
}

/*Returns TRUE if the hash is in the library*/
static BOOLEAN SignatureScan(char hash[32])
{
    if (IsListEmpty(Head)) { // if there is no signature in the index
        return FALSE;
    }
    else {
        PSINGLE_LIST_ENTRY pSig = Head; // this is the pointer we will use to iterate
        PSIGNATURE Sig;

        do {
            Sig = CONTAINING_RECORD(pSig, SIGNATURE, next); // get the PSIGNATURE on the current pointer

            DbgPrintEx(0, DPFLTR_ERROR_LEVEL, "%s - %s\n", Sig->hash, hash);
            if (!IsEqual(Sig->hash, hash, 32)) {
                return TRUE;
            }

            pSig = &Sig->next; // go to the next node
        } while (pSig != Head);

        return FALSE;
    }
}

Main.c
AddToSignatureList("2d75cc1bf8e57872781f9cd04a529256");
AddToSignatureList("00f538c3d410822e241486ca061a57ee");
AddToSignatureList("3f066dd1f1da052248aed5abc4a0c6a1");
AddToSignatureList("781770fda3bd3236d0ab8274577dddde");
AddToSignatureList("86b6c59aa48a69e16d3313d982791398");

DbgPrintEx(0, DPFLTR_ERROR_LEVEL, "Should return TRUE: %d\n", SignatureScan("3f066dd1f1da052248aed5abc4a0c6a1"));
DbgPrintEx(0, DPFLTR_ERROR_LEVEL, "Should return FALSE: %d\n", SignatureScan("3f066dd1f1da052248aed5abc4a0c6a2"));
DbgPrintEx(0, DPFLTR_ERROR_LEVEL, "Should return FALSE: %d\n", SignatureScan("526ae1b5f10eccfa069f4fd1c8b18097"));

I can't really figure out.. It doesn't crash and the WinDBG output is:

I have read this blog post and this msdn article but I still don't know what is wrong in my driver

A: I see several likely issues.

*

*Your loop isn't being initialized correctly.
PSINGLE_LIST_ENTRY pSig = Head;
PSIGNATURE Sig;

do {
    Sig = CONTAINING_RECORD(pSig, SIGNATURE, next);

The first time through this loop, pSig is pointing at Head which is not part of a SIGNATURE structure, so the call to CONTAINING_RECORD results in a meaningless pointer.

*

*You're not exiting the loop correctly either.  The end of a singly-linked list is represented by a null pointer, not by a pointer to the header.

*And, going for the triple, you aren't incrementing the list properly either:
pSig = &Sig->next; // go to the next node

Sig->next points to the current node, not the next node.

*

*IsListEmpty is for doubly-linked lists, not singly-linked lists.  That code shouldn't even compile.

*The choice of PSINGLE_LIST_ENTRY rather than SINGLE_LIST_ENTRY for Head is odd, and the code that initializes Head is missing.

*The argument hash is declared as a 32-character array, it should be 33 characters to allow for the null terminator.
I think the function should look more like this:
SINGLE_LIST_ENTRY Head = {NULL};

static BOOLEAN SignatureScan(char hash[33])
{
    PSINGLE_LIST_ENTRY pSig = Head->Next;
    PSIGNATURE Sig;

    while (pSig != NULL)
    {
        Sig = CONTAINING_RECORD(pSig, SIGNATURE, next);

        DbgPrintEx(0, DPFLTR_ERROR_LEVEL, "%s - %s\n", Sig->hash, hash);

        if (!strcmp(Sig->hash, hash)) return TRUE;

        pSig = pSig->Next;
    }

    return FALSE;
}

Also, note that it is more usual for the SINGLE_LINKED_LIST to be the first element of the structure, and that calling it next is misleading.  Something like this might be preferable:
typedef struct {
    SINGLE_LIST_ENTRY list_node;
    char hash[33]; // last byte for null terminator
} SIGNATURE, *PSIGNATURE;


text:
Q: Octave - sawtooth function I would like to plot a sawtooth function in Octave. I know that I can use the command "sawtooth(t)" but I don't have the package so I created the following function.
function x = pieceWise2bis(t)
x = zeros (size (t));

ind1 = t >= 10 & t < 13;
x(ind1) = +20;

ind2=t >= 13 & t < 16;
x(ind2) = -20;

ind3=t >= 16 & t < 19;
x(ind3) = +20;

ind4=t >= 19 & t < 22;
x(ind4) = -20;
endfunction

When I plot this function I don't get the result I'm looking for because I want a real sawtooth function and not a periodic function with crenels like that.
COuld someone tell me how I could adapt my code ?
Thank you

A: It appears that the usual way to load sawtooth, by installing signal which requires control....  is not working, in any case you are  way better off writing this yourself.  Here's one of many ways to do it:
clear; %% this line tells octave the remainder is more than just a func.
## usage: ST = sawtooth (time)
function ST = sawtooth (time)
  ST=rem(time,2*pi)/2/pi;
endfunction

time=linspace(0,20,101); % second line of main program (clear is 1st)
PriSawtooth=sawtooth(time);
plot(time,PriSawtooth,'linewidth',1)


text:
Q: Django 1.11 - Can't edit my model in Admin panel Please could tell me why I can't modify my model in the admin panel of Django ?
models.py :
from django.db import models

# Create your models here.
class Games(models.Model):
    guid = models.CharField(max_length=100, unique=True, null=False, verbose_name="GUID")
    title = models.CharField(max_length=100, null=False, verbose_name="Titre")
    logo = models.CharField(max_length=100, null=True, blank=True, verbose_name="Logo")
    date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création")
    update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification")

admin.py
from django.contrib import admin
from .models import Games

# Register your models here.

class GamesAdmin(admin.ModelAdmin):
    list_display = ('logo', 'title', 'guid', 'date', 'update')
    list_filter = ('title', 'guid')
    date_hierarchy = 'update'
    ordering = ('date', )
    search_field = ('guid', 'title')

admin.site.register(Games, GamesAdmin)

When I'm going to the admin panel, I see all the field of my model, I can also add a new field. But when I want to edit the field, there is no link clickable...
Thanks !

A: Just swap the places of 'logo' and 'title' or 'logo' with any other non-empty column.
list_display = ('logo', 'title', 'guid', 'date', 'update')

A: By default, the first column should be clickable and take you to the view to change the object. Even if the column is empty, Django will add a clickable non-breaking space ( ), although you might not spot it until you hover over it and the cursor changes.
You can set link_display_links and include a field that is not empty.
class GamesAdmin(admin.ModelAdmin):
    list_display = ('logo', 'title', 'guid', 'date', 'update')
    list_display_links = ('title',)

Alternatively, you could reorder list_display so that the first column is not empty.
To make all columns clickable, you would set list_display_links = list_display.


text:
Q: How can i calculate the field of view of the camera of a phone? I need to know the field of view of the camera of the phone to make an augmented reality app, for calculate where i have to write on the camera view the name of a gps located Point of interest of a city on the correct coordinates of the screen, pointing the point of interest.
for example:
distance 5 meters: 6 meters (from left to right FOV)
distance 10 meters: 12 meters (from left to right FOV)
How to calculate it?

A: I think you will never match the FOV definition for every device. (Compare this answer for iPhone.)
Every device is different when using android. Take your device, do the math (or take the results from anywhere else) and decide yourself to choose a reasonable FOV angle.
Maybe you could take account of Camera.Parameters.getSupportedPictureSizes() for getting the camera ratio, but that should be all you can do.


text:
Q: How to install Selenium in a conda environment? I'm trying to install Selenium in a conda environment in Windows 10 with
conda install --name myenv selenium

but this returns the error
PackageNotFoundError: Package missing in current win-64 channels:
  - selenium

How can I complete this package installation?

A: Conda uses different channels to search for packages. You need find the package which supports Win 64
You can do that by going to below link
https://anaconda.org/search?q=selenium&sort=ndownloads&sort_order=-1&reverse=true
And you will find that this is most downloaded one
https://anaconda.org/conda-forge/selenium
So execute below
conda install -c conda-forge --name myenv selenium

A: If you are using Anaconda just use:

*

*go to anaconda command prompt

*just type pip install selenium

A: *

*launch jupyter notebook

*write command conda install selenium in the cell and run it

*once installation is done restart the kernel


text:
Q: Merge Ruby Hash values with same key Is this possible to achieve with selected keys:
Eg
h = [
  {a: 1, b: "Hello", c: "Test1"},
  {a: 2, b: "Hey", c: "Test1"},
  {a: 3, b: "Hi", c: "Test2"}
]

Expected Output
[
  {a: 1, b: "Hello, Hey", c: "Test1"}, # See here, I don't want key 'a' to be merged
  {a: 3, b: "Hi", c: "Test2"}
]

My Try
g = h.group_by{|k| k[:c]}.values
OUTPUT =>
  [
    [
      {:a=>1, :b=>"Hello", :c=>"Test1"},
      {:a=>2, :b=>"Hey", :c=>"Test1"}
    ], [
      {:a=>3, :b=>"Hi", :c=>"Test2"}
    ]
  ]

g.each do |v|
  if v.length > 1
    c = v.reduce({}) do |s, l|
      s.merge(l) { |_, a, b| [a, b].uniq.join(", ") }
    end
  end

  p c #{:a=>"1, 2", :b=>"Hello, Hey", :c=>"Test1"}
end

So, the output I get is
{:a=>"1, 2", :b=>"Hello, Hey", :c=>"Test1"}

But, I needed
{a: 1, b: "Hello, Hey", c: "Test1"}

NOTE: This is just a test array of HASH I have taken to put my question. But, the actual hash has a lots of keys. So, please don't reply with key comparison answers
I need a less complex solution

A: I can't see a simpler version of your code. To make it fully work, you can use the first argument in the merge block instead of dismissing it to differentiate when you need to merge a and b or when you just use a. Your line becomes:
s.merge(l) { |key, a, b| key == :a ? a : [a, b].uniq.join(", ") }

A: Maybe you can consider this option, but I don't know if it is less complex:
h.group_by { |h| h[:c] }.values.map { |tmp| tmp[0].merge(*tmp[1..]) { |key, oldval, newval| key == :b ? [oldval, newval].join(' ') : oldval } }
#=> [{:a=>1, :b=>"Hello Hey", :c=>"Test1"}, {:a=>3, :b=>"Hi", :c=>"Test2"}]

The first part groups the hashes by :c
h.group_by { |h| h[:c] }.values #=> [[{:a=>1, :b=>"Hello", :c=>"Test1"}, {:a=>2, :b=>"Hey", :c=>"Test1"}], [{:a=>3, :b=>"Hi", :c=>"Test2"}]]

Then it maps to merge the first elements with others using Hash#merge

A: h.each_with_object({}) do |g,h|
  h.update(g[:c]=>g) { |_,o,n| o.merge(b: "#{o[:b]}, #{n[:b]}") }
end.values
  #=> [{:a=>1, :b=>"Hello, Hey", :c=>"Test1"},
  #    {:a=>3, :b=>"Hi", :c=>"Test2"}]

This uses the form of Hash#update that employs a block (here { |_,o,n| o.merge(b: "#{o[:b]}, #{n[:b]}") }) to determine the values of keys that are present in both hashes being merged. The first block variable holds the common key. I've used an underscore for that variable mainly to signal to the reader that it is not used in the block calculation. See the doc for definitions of the other two block variables.
Note that the receiver of values equals the following.
h.each_with_object({}) do |g,h|
  h.update(g[:c]=>g) { |_,o,n| o.merge(b: "#{o[:b]}, #{n[:b]}") }
end
  #=> { "Test1"=>{:a=>1, :b=>"Hello, Hey", :c=>"Test1"},
  #     "Test2=>{:a=>3, :b=>"Hi", :c=>"Test2"} }


text:
Q: Generate delegate methods for a visible property of a parent class In Eclipse there is the handy command
Source -> Generate Delegate Methods …

Unfortunately this works only for properties of the current class, not for visible properties of one of its parent class.
Do you know a workaround with which I can create delegate methods automatically for a property inherited from a parent class?

A: Generate them in the parent class and then use cut&paste to move them to the right place.


text:
Q: A CLR function equivalent to string.Format in C# I was looking for a CLR function that will do the same thing as String.Format in C#. As an example, I would like to do the following through a CLR function:
String.Format("My name is {0}, and I live in {1}",myName, cityName)

I would like to be able to pass variable number of parameters after the first parameter, which would be as many place holders are specified in the first parameter to this CLR function. Anyone has any idea on what would be the C# code for such a CLR function?

A: I'm looking for the same thing. I came across these two sites: http://www.fotia.co.uk/fotia/Blog/2009/05/indispensable-sql-clr-functions.html & http://stringformat-in-sql.blogspot.com/.
The first uses a CLR function, the other uses a stored procedure.
In the first post, the writer says that UDF parameters aren't optional so you can't have variable number of params (at least the way he is doing it). He just creates a different function with the number or args he will need.
[SqlFunction(DataAccess = DataAccessKind.None)]
public static SqlString FormatString1(SqlString format, object arg0, object arg1)
{
   return format.IsNull ? SqlString.Null :
       string.Format(format.Value, SqlTypeToNetType(arg0, arg1));
}

EDIT :  This is how I solved this problem for me.

Using the stored procedure from the second article, I created this function to format the text for me using a pivot table. Our database is setup with a table dbo.[Rules] that has a column [Description] that has a string that needs to be formatted such as: "NET INCOME MARGINAL (${0} TO BELOW ${1})". We then have a 1-many table dbo.[RuleParameters] with a row for each value that needs to be substituted. The column dbo.[SortOrder] specifies which order the arguments go in. This function will work for AT MOST 4 arguments which is the most that we have.

CREATE FUNCTION [dbo].[GetRuleDescriptionWithParameters]
(
    @Code VARCHAR(3)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @Result NVARCHAR(400)

    SELECT
        @Result =
            dbo.FormatString([Description],
                ISNULL([1], '') + ',' +
                ISNULL([2], '') + ',' +
                ISNULL([3], '') + ',' +
                ISNULL([4], '')
                )
    FROM
    (
        SELECT
        r.[Description]
        ,rp.Value
        ,rp.SortOrder

        FROM
            [Rules] r
        LEFT OUTER JOIN [RuleParameters] rp
            ON r.Id = rp.RuleId

        WHERE r.Code = @Code

    ) AS SourceTable
    PIVOT
    (
        MAX(Value)
        FOR SortOrder IN ([1], [2], [3], [4])
    ) AS PivotTable;

    RETURN @Result
END

EDIT #2: Adding more examples
Format string function:
CREATE FUNCTION [dbo].[FormatString]
(
    @Format NVARCHAR(4000) ,
    @Parameters NVARCHAR(4000)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @Message NVARCHAR(400),
@Delimiter CHAR(1)
DECLARE @ParamTable TABLE ( ID INT IDENTITY(0,1), Paramter VARCHAR(1000) )
SELECT @Message = @Format, @Delimiter = ','
;WITH CTE (StartPos, EndPos) AS
(
    SELECT 1, CHARINDEX(@Delimiter, @Parameters)
    UNION ALL
    SELECT EndPos + (LEN(@Delimiter)), CHARINDEX(@Delimiter,@Parameters, EndPos + (LEN(@Delimiter)))
FROM CTE
WHERE EndPos > 0
)
INSERT INTO @ParamTable ( Paramter )
SELECT
[ID] = SUBSTRING ( @Parameters, StartPos, CASE WHENEndPos > 0 THEN EndPos - StartPos ELSE 4000 END )
FROM CTE
UPDATE @ParamTable SET @Message = REPLACE ( @Message, '{'+CONVERT(VARCHAR,ID) + '}',     Paramter )
RETURN @Message
END
GO

Here is how I call the stored procedure:
SELECT r.[Id]
        ,[Code]
        ,[Description]
        ,dbo.GetRuleDescriptionWithParameters([Code])
        ,rp.[Value]
        ,rp.SortOrder
FROM [Rules] r
INNER JOIN [RuleParameters] rp
    ON r.Id = rp.RuleId

Now I can just call the function like this to get everything formatted nicely for me! Here is sample usage with the results:
Id  Code    Description                     (No column name)          Value     SortOrder
1   1       NOT THE MINIMUM AGE             NOT THE MINIMUM AGE       18        1
3   8       NET INCOME (BELOW ${0})      NET INCOME (BELOW $400)   400    1
4   9       NET (${0} TO BELOW ${1})          NET ($400 TO BELOW $600)  400         1
4   9       NET (${0} TO BELOW ${1})          NET ($400 TO BELOW $600)  600         2

Normally when calling this, I wouldn't join on the [RuleParameters] table, but I did in this case so that you can see the data before and after in one data set.


text:
Q: What's the best way to launch a view after device is unlocked? I'm trying to display a view that the user must dismiss each time they unlock their phone (it's intended to be annoying). It should be able to take a small amount of keyboard input, save it, then return to the previously open activity. I tried having a BroadcastReceiver listen for ACTION_USER_PRESENT and launch my own activity, but then I found out we can no longer listen for implicit intents, or have background services launch activities.
I'm not an Android developer (just trying to build something for my phone), but I did some looking, and I see a few options:

*

*Display a full-screen intent. I think something like scheduling a job to raise a notification whenever the phone is locked, so that the notification appears first thing when they unlock the phone.

*Use SYSTEM_ALERT_WINDOW and draw my view as an overlay whenever the phone is unlocked. My only concern with this is how apps like Twilight (which I believe draws an overlay to redden the screen) might interact with it. In those cases, I'd like my overlay to appear at the very bottom.
Are either of those options viable or recommended? Any other suggestions or approaches for how I could accomplish this would be greatly appreciated too. I'm just looking for some guidance on what direction I should pursue.


text:
Q: AmbiguousMatchException: "Mehrdeutige Übereinstimmung gefunden" on Bindinglistview I am going crazy on this:
I have in information class, which contains some information about software instances in the network. It looks like this:
public class cInstances
{
    public enum eStatus
    {
        UNKNOWN = 0x00,
        TO_BE_UPDATED = 0x01,
        UPDATE_FINISHED = 0x02
    }

    public string id { get; set; }
    public string AppName { get; set; }
    public string IP { get; set; }
    public string version { get; set; }
    //public string machine { get; set; }
    public eStatus status { get; set; }
    public DateTime? lastAlive { get; set; }
    public DateTime? lastUpdate { get; set; }

    public cInfoHW info_HW { get; set; }
    public List<cInfoHDD> info_HDD { get; set; }

    [JsonIgnore]
    public UDPconnection connection { get; set; }

    public cInstances()
    {
        try
        {
            info_HW = new cInfoHW();
            info_HDD = new List<cInfoHDD>();
        }
        catch (Exception ex)
        {
            Log log = new Log(null, null);
            log.Write(LogLevel.LOG_ERROR, ex.ToString());
        }
    }
}

Now in my program I want to make this data visible in a Data grid and decided to use Equin BindinglistView.
global = AppData.GetInstance();
public BindingListView<cInstances> BiLiVi;
BiLiVi = new BindingListView<cInstances>(global.Instances);
dgv_data.DataSource = BiLiVi;

Here occurs the exception:
On new BindingListView(...) I receive a AmbiguousMatchException: "Mehrdeutige Übereinstimmung gefunden."
When I remove the getter and setter methods in the following line, it works fine. But I do really need them!
public List<cInfoHDD> info_HDD { get; set; }

Here is the HDD info class:
public class cInfoHDD
{
    public string Name { get; set; }
    public string DriveFormat { get; set; }
    public string AvailableFreeSpace { get; set; }
    public string TotalFreeSpace { get; set; }
    public string TotalSize { get; set; }
    public DateTime timestamp { get; set; }
    public cInfoHDD()
    {
        timestamp = DateTime.Now;
    }
}

Please help me. I do not see, where I am going wrong.
Thank you,
Lama


text:
Q: How can I correct the mutate and filter errors in my R function I have function that takes a dataframe and two other variables (horse and race_date) as inputs.  The horse and race_date are utilized to filter the dataframe passed the function and then a summarise function is applied to calculate the desired output.  When I test the function stand-alone and outside of the pipes everything works fine but when I try to run the function from within a mutate function and the pipes I get the following error message:
Error: Problem with `mutate()` input `split_Lt`.
x Problem with `filter()` input `..1`.
x Input `..1` must be of size 1, not size 18.
i Input `..1` is `Horse == horse & NewSplit == "LT Races" & race_date < date`.
i The error occurred in group 2: split = "A BIT OF BOTH_var106_Track: CD".
i Input `split_Lt` is `getsplit_LT(splits, horse, race_date)`.
i The error occurred in group 2: split = "A BIT OF BOTH_var106_Track: CD".

Here is the function:
getsplit_LT <- function(df, horse, date){

  kpi <- df %>%
    filter(Horse == horse & NewSplit == "LT Races" & race_date < date) %>%
    group_by(split) %>%
    summarise_if(is.numeric, sum) %>%
    mutate(TopAvgB = ((E + 3.439) /(R+3.439 + 25.69))) %>%
    select(TopAvgB)

  x = if(is.data.frame(kpi) && nrow(kpi)==0){0}else{kpi[[1]]}

  return(x)

}

Here's the code I tried to run:
df <- df %>%
  mutate(split_Lt = getsplit_LT(splits, horse, race_date))

Here is the dput data:
structure(list(horse = c("A BIT OF BOTH", "A BIT OF BOTH", "A BIT OF BOTH",
"A BIT OF BOTH", "A BIT OF BOTH", "A BIT OF BOTH", "A BIT OF BOTH",
"A BIT OF BOTH", "A BIT OF BOTH", "A BIT OF BOTH", "A BIT OF BOTH",
"A BIT OF BOTH", "A BIT OF BOTH", "A BIT OF BOTH", "A BIT OF BOTH",
"A BIT OF BOTH", "A BIT OF BOTH", "A BIT OF BOTH"), race_date = structure(c(17802,
17906, 17941, 17969, 18006, 18062, 18091, 18183, 18183, 18226,
18244, 18286, 18454, 18502, 18546, 18581, 18601, 18664), class = "Date")), row.names = c(NA,
-18L), groups = structure(list(horse = "A BIT OF BOTH", .rows = structure(list(
    1:18), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr",
"list"))), row.names = 1L, class = c("tbl_df", "tbl", "data.frame"
), .drop = TRUE), class = c("grouped_df", "tbl_df", "tbl", "data.frame"
))

structure(list(split = c("A BIT OF BOTH_var102B_LifeTime: Life",
"A BIT OF BOTH_var102B_LifeTime: Life", "A BIT OF BOTH_var102B_LifeTime: Life",
"A BIT OF BOTH_var102B_LifeTime: Life", "A BIT OF BOTH_var102B_LifeTime: Life",
"A BIT OF BOTH_var102B_LifeTime: Life", "A BIT OF BOTH_var102B_LifeTime: Life",
"A BIT OF BOTH_var102B_LifeTime: Life", "A BIT OF BOTH_var102B_LifeTime: Life",
"A BIT OF BOTH_var102B_LifeTime: Life", "A BIT OF BOTH_var102B_LifeTime: Life",
"A BIT OF BOTH_var102B_LifeTime: Life", "A BIT OF BOTH_var102B_LifeTime: Life",
"A BIT OF BOTH_var102B_LifeTime: Life", "A BIT OF BOTH_var102B_LifeTime: Life",
"A BIT OF BOTH_var102B_LifeTime: Life", "A BIT OF BOTH_var102B_LifeTime: Life",
"A BIT OF BOTH_var102B_LifeTime: Life", "A BIT OF BOTH_var106_Track: CD",
"A BIT OF BOTH_var106_Track: CT", "A BIT OF BOTH_var106_Track: DE",
"A BIT OF BOTH_var106_Track: FG", "A BIT OF BOTH_var106_Track: GP",
"A BIT OF BOTH_var106_Track: GP", "A BIT OF BOTH_var106_Track: GP",
"A BIT OF BOTH_var106_Track: GP", "A BIT OF BOTH_var106_Track: GP",
"A BIT OF BOTH_var106_Track: GP", "A BIT OF BOTH_var106_Track: GP",
"A BIT OF BOTH_var106_Track: GP", "A BIT OF BOTH_var106_Track: KE",
"A BIT OF BOTH_var106_Track: MT", "A BIT OF BOTH_var106_Track: MT",
"A BIT OF BOTH_var106_Track: OT", "A BIT OF BOTH_var106_Track: PX",
"A BIT OF BOTH_var106_Track: PX", "A BIT OF BOTH_var107_Surface: Dirt",
"A BIT OF BOTH_var107_Surface: Dirt", "A BIT OF BOTH_var107_Surface: Dirt",
"A BIT OF BOTH_var107_Surface: Dirt", "A BIT OF BOTH_var107_Surface: Dirt",
"A BIT OF BOTH_var107_Surface: Dirt", "A BIT OF BOTH_var107_Surface: Dirt",
"A BIT OF BOTH_var107_Surface: Dirt", "A BIT OF BOTH_var107_Surface: Dirt",
"A BIT OF BOTH_var107_Surface: Dirt", "A BIT OF BOTH_var107_Surface: Dirt",
"A BIT OF BOTH_var107_Surface: Dirt", "A BIT OF BOTH_var107_Surface: Dirt",
"A BIT OF BOTH_var107_Surface: Synth", "A BIT OF BOTH_var107_Surface: Turf",
"A BIT OF BOTH_var107_Surface: Turf", "A BIT OF BOTH_var107_Surface: Turf"

A: One approach is with the purrr::pmap function which applies a function on a data.frame rowwise.
library(tidyverse)
pmap(df, ~ getsplit_LT(splits, horse = .x, date = .y))
[[1]]
[1] 0.2156712

[[2]]
[1] 0

[[3]]
[1] 0.1070373

[[4]]
[1] 0.1339914

[[5]]
[1] 0.1593659
...

Or back with the original data.frame:
bind_cols(df,kpi = pmap_dbl(df, ~ getsplit_LT(splits, horse = .x, date = .y)))
# A tibble: 18 x 3
   horse         race_date    kpi
   <chr>         <date>     <dbl>
 1 A BIT OF BOTH 2020-09-28 0.216
 2 A BIT OF BOTH 2020-01-10 0
 3 A BIT OF BOTH 2020-02-14 0.107
 4 A BIT OF BOTH 2020-03-14 0.134
 5 A BIT OF BOTH 2020-04-20 0.159
 6 A BIT OF BOTH 2020-06-15 0.183
 7 A BIT OF BOTH 2020-07-14 0.227
...

Data:
splits <- read_csv("https://raw.githubusercontent.com/Handicappr/Rstudio_test_project/main/splits.csv")
df <- read_csv("https://raw.githubusercontent.com/Handicappr/Rstudio_test_project/main/df.csv")
splits %>% mutate(race_date = as.Date(race_date,"%m/%d/%y")) -> splits
df %>% mutate(race_date = as.Date(race_date,"%m/%d/%y")) -> df


text:
Q: Draw 2 textures on a single quad directx He,
I have a quad and I want to draw the same texture twice on it. When the texture is set I do a pixelshader that will distort the image. I have a Flexible Vertex Format with D3DFVF_TEX2. When I make my quad I give it 2 texture coördinates.
But what now? How can I draw the texture twice on the same quad with the same coordinates?
#define CustomFVF (D3DFVF_XYZ | D3DFVF_TEX2)

This is my quad.
CustomVertex vertices[4] = {
    { -width - 0.5f, height + 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, //top left
    { width - 0.5f, height + 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f }, // top right
    { -width - 0.5f, -height + 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f }, //bottom left
    { width - 0.5f, -height + 0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f } // bottom right
};


text:
Q: how to load data based on id using Vue js and Laravel? I have a table called candidate_profiles with the following columns:
'user_id', 'photo_id', 'resume_id', 'video_one_id', 'video_two_id',
'video_three_id', 'date_of_birth', 'employment_type', 'experience','skills'

I have a page /employer/search that displays all of the profiles from that table. I'm using paginate to display 5 records per page. At the bottom I have a 'Load More' button, when clicked another 5 (or less) profiles appear. If there are anymore you will still see the 'Load More' button otherwise it will disappear.
This is how I'm fetching the data.
EmployerSearchController.php file:
public function search()
{
    $candidateProfile = CandidateProfile::orderBy('created_at', 'asc')->paginate(5);

    $user = User::all()->where('id', $candidateProfile->first()->user_id);

    $videoOne = Video::all()->where('id', $candidateProfile->first()->video_one_id);
    $videoTwo = Video::all()->where('id', $candidateProfile->first()->video_two_id);
    $videoThree = Video::all()->where('id', $candidateProfile->first()->video_three_id);
    $resumes = Resume::all()->where('id', $candidateProfile->first()->resume_id);
    $photos = Photo::all()->where('id', $candidateProfile->first()->photo_id);

    return response()->json(array($candidateProfile, $videoOne, $videoTwo, $videoThree, $resumes, $photos, $user), 200);

}

And this is how I'm assigning the data into variable and creating the Load More feature in my front end Vue js code:
methods: {
        loadCandidateProfileData: async function() {
            try {
                const response = await employerService.loadCandidateProfileData();
                this.resumes = response.data[4];
                this.video_one = response.data[1];
                this.video_two = response.data[2];
                this.video_three = response.data[3];
                this.photos = response.data[5];
                this.users = response.data[6];

                this.candidateProfiles = response.data[0].data;

                if (response.data[0].current_page < response.data[0].last_page) {
                    this.moreExists = true;
                    this.nextPage = response.data[0].current_page + 1;
                } else {
                    this.moreExists = false;
                }

                // console.log(JSON.stringify(response.data, undefined, 4));

            } catch (error) {
                this.$toast.error("Some error occurred, please refresh!");
            }
        },

The problem is this because I'm fetching the Videos, resume and photo from their own respective tables, I'm not getting the right information because it's not querying the right id.
If all of the data was coming from 1 table I wouldn't have this problem, but I'm fetching data from multiple tables.
How can I get the right data for each candidate_profile record in this way?

A: You can use a relationship on the CandidateProfile model. See here https://laravel.com/docs/7.x/eloquent-relationships. So for example with user you can have in you CandidateProfile  model
public function user()
{
    // You can choose the relationship that best suits your need for the users table
    return $this->belongsTo(User::class);
}

and when querying you can get that relationship by
 $candidateProfile = CandidateProfile::with('users')->orderBy('created_at', 'asc')->paginate(5);

then you can access those users by
$candidateProfile->users

The same can be applied to your other table relations (video, resumes, photos).
Then you can just pass $candidateProfile back through to your vue js


text:
Q: NameError issue when trying to call a class method Specifically having issues with using a class and calling it.
Its a highest-sum-path of a triangle program.. but I am having issues with my class and calling functions.
specifically..
class TriArray():
     triangle = read_input("inputt.txt")
     def get_data(node):
         return triangle[node.row][node.col]
def main():
      triangle = TriArray()

node = triangle.get_root()         #*added these to the question
path_sum = triangle.get_data()

def read_input(filename):           #*so you can see
  triangle = []
  with open(filename, 'r') as fin:
      rows = fin.readline()
      for line in fin:
          for word in rows.split():
              triangle.append([int(i) for i in line.split()])
              print(triangle)

error is saying triangle is not defined.
where might my mistake be? There are plenty more functions in this class. But this is the current error I am on, Thanks.
list is like
[[1],
[1 2],
[1 2 3]]

if its relevant..

A: You have some issues in your code.

*

*You should define triangle like triangle = TriArray()

*get_data needs node parameter but you are not sending.

*You are missing self parameter.

*read_input is not defined.

You can fix like this,
class TriArray():
   triangle = None

   def read_input(self):
     with open('inputt.txt', 'r') as f:
        self.triangle = f.read()

   def get_data(self, node):
     self.read_input()
     return self.triangle[node.row][node.col]

triangle = TriArray()
# you have to define and sent node parameter
# node = ??
path_sum = triangle.get_data(node)

A: class TriArray():
     triangle = read_input("inputt.txt")
     def get_data(node):
         return triangle[node.row][node.col]

triangle = TriArray()
path_sum = triangle.get_data()

Try this

A: In order to call a class method you must instantiate it first:
path_sum = TriArray().get_data(node)

A: You have not created an instance of the class. The class part of your code only defines a class, but does not instantiate it.
Create an instance by inserting
triangle = TriArray()

before the last line.
Edit: in your revised code you create an instance in the main function. However, that instance is not visiblke outside the main function. You must create the instance at the same scope as where you use it.

A: You can define a class like this, that's fine. But without an actual instance of the class, triangle will remain an internal value that is not defined outside. That's why there is a NameError.
Based on your edits, we see that there is an instantiation. But this takes place inside a main function; the other lines outside this function still don't see it.
One way is to put the path_sum inside the main function, as shown here:
class TriArray():

    def get_data(node):
        return triangle[node.row][node.col]

    def read_input(filename):
        triangle = []
        with open(filename, 'r') as fin:
            rows = fin.readline()
            for line in fin:
                for word in rows.split():
                    triangle.append([int(i) for i in line.split()])
                    print(triangle)

    triangle = read_input("inputt.txt")

def main():
    # let's assume node is defined and node.row = 0, node.col = 1
    triangle = TriArray()
    path_sum = triangle.get_data(node) # brought in from the cold

This means, of course, that for anything to happen, you'd need to actually invoke the main function. You'll also notice that I've shifted read_input into the class and before it is invoked, so that there will not be a NameError when trying to invoke read_input.


text:
Q: How to fetch and navigate to url provided by API using TypeScript I have a website manager that will return to me a different url for the server that my client should connect too.
So what I would like to do in my typescript function is resolve the first url, read the text, and then open that in a new window. Right now I can only open website manager window with the bellow code.
            var aWindow = window.open("http://azureredirect.net/home/workspace/" + this.workspace.id, "Window", "");
            if (aWindow) {
                aWindow.focus();
            }

What I really want is something like the following but the WebClient line does not work(this is the C# version of what I would do)
            var url = WebClient.open("http://azurejupyterredirect.net/home/workspace/" + this.workspace.id").toString();
            var aWindow = window.open(url, "JuPy", "");
            if (aWindow) {
                aWindow.focus();
            }

A: here's an example of how you could do this:

$(document).ready(function() {

  var workspaceId = '2';

  $.ajax('http://azurejupyterredirect.net/home/workspace/' + workspaceId)
    .then(
      function(url) {
        window.open(url);
      });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


text:
Q: get the last function call in the continuous calling (chain of function calls) - Python Imagine that I have the following code (This is just an example for demonstrating the thing that I want to achieve):
class Foo:

    def __init__(self, name):
        self.name = name

    def update_something(self, number):
        """
        This method is responsible for updating the object state, and it will be called hundreds of times at the same time
        So updating its state last call will be enough.
        """
        if number != 100:
            print(f"This method has been called for: ({number}) of times ---> [{self.name}]")
        else:
            print(f"This is the Final call ---> [{self.name}]")

if __name__ == '__main__':
    obj1 = Foo("obj1")
    obj2 = Foo("obj2")
    obj3 = Foo("obj3")
    obj4 = Foo("obj4")
    #  .
    #  .
    #  .
    # I have many objects
    list_of_objects = [obj1, obj2, obj3, obj4]

    # for example Let's imagine we have the following code
    for i in range(100):
        print("---")
        for obj in list_of_objects:
            obj.update_something(i)

The results for sure will be:
This method has been called for: (0) of times ---> [obj1]
This method has been called for: (0) of times ---> [obj2]
This method has been called for: (0) of times ---> [obj3]
This method has been called for: (0) of times ---> [obj4]
...
This method has been called for: (100) of times AND This is the Final call ---> [obj1]
This method has been called for: (100) of times AND This is the Final call ---> [obj2]
This method has been called for: (100) of times AND This is the Final call ---> [obj3]
This method has been called for: (100) of times AND This is the Final call ---> [obj4]

Instead, since it is performance-consuming, I want to take the last call in that "chain". so the update method will be called only once if they are repeatedly calling in a very very short time.
This is the Final call ---> [obj1]
This is the Final call ---> [obj2]
This is the Final call ---> [obj3]
This is the Final call ---> [obj4]


text:
Q: Dynamically create checkbox and store value in a record field I am trying to dynamically create a checkbox component and then store its value in a record's field.  I have a standard checkbox component that works.  I can't figure out how to dynamically create the same component & store the value of the checkbox.  I think my problem is related to the onCheck call.  I have onCheck in the controller of the component that is creating the dynamic checklist.  I can't seem to get to onCheck.  I am not sure if my syntax is create for trying to call onCheck dynamically.  Do I need to dynamically create onCheck, etc.?
                $A.createComponent(
                "ui:inputCheckbox",
                {
                    "change" : "{!c.onCheck}",
                    "value" : component.getReference("v.EventRSVP."+ fieldAPIName),
                    "aura:id": "findableAuraId",
                    "label": fieldLabel
                },

Here is the component and controller that I have that work - not being created dynamically.
Component
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes">
<aura:attribute name="myBool" type="Boolean" default="false"/>
<ui:inputCheckbox aura:id="checkbox" label="Select?"  change="{!c.onCheck}"/>

Selected:

<ui:outputText class="result" aura:id="checkResult" value="false" />

The following checkbox uses a component attribute to bind its value.

<ui:outputCheckbox aura:id="output" value="{!v.myBool}"/>

Controller
({
onCheck: function(cmp, evt) {
    var checkCmp = cmp.find("checkbox");
    var resultCmp = cmp.find("checkResult");
    resultCmp.set("v.value", ""+checkCmp.get("v.value"));
    cmp.set("v.myBool", checkCmp.get("v.value"));
}

})

A: I just figured out my problem.  I needed the line in the dynamically created component to call onCheck by using the following code instead of what I had:
                        "change" : component.getReference("{!c.onCheck}"),


text:
Q: Redirection of a url when clicking on menu
<a href="<%=
UTIL.getServletPath("/SetupPage?PG=setupusersettings") %>">
Settings

public String getServletPath(String fileName)
    {
        if(!fileName.startsWith("/"))
            fileName = "/" + fileName;
        return getContextPath() + fileName;
    }

public String getContextPath()
    {
        try
        {
            return request != null ? request.getContextPath() : "";
        }
        catch(Exception ex)
        {
            DBGlobals.Error(ex);
            return "";
        }
    }

public interface HttpServletRequest extends javax.servlet.ServletRequest {

 java.lang.String getContextPath();

I have a few questions..

*

*What does getServletPath do?

*What does getContextPath do?

*Canyone explain me the flow?

A: original derived from Oracle's specs:
http://download.oracle.com/javaee/1.2.1/api/javax/servlet/http/HttpServletRequest.html
getServletPath
public java.lang.String getServletPath()
Returns the part of this request's URL that calls the servlet. This includes either the servlet name or a path to the servlet, but does not include any extra path information or a query string. Same as the value of the CGI variable SCRIPT_NAME.
getContextPath
public java.lang.String getContextPath()
Returns the portion of the request URI that indicates the context of the request. The context path always comes first in a request URI. The path starts with a "/" character but does not end with a "/" character. For servlets in the default (root) context, this method returns "".
Returns:
a String specifying the portion of the request URI that indicates the context of the request
I think that the spec is descriptive enough.
Regards.


text:
Q: Good PCI-e wireless card for Windows7? I've just build a 64-bit Windows 7 PC but am unhappy with the piddly performance of the Linksys USB wireless dingle I've used. What is a good PCIe alternative that will be stronger for the connection and maybe faster. I don't see why my desktop should show a weaker performance on wireless than my laptop when it's sat next to it or even my Palm Pre for that matter.
Any thoughts?
UK based, max around £60ish.

A: What about the D-Link DWA-556 available for £45 ?


text:
Q: JQueryUI DatePicker inside html iFrame doesn't expand past the frame I have an ASP.net aspx page that's composed of 3 iframes. One for the header, one for the side menu and one for the main content area. The header frame has 2 date fields that will apply some kind of filter on the data in the main area.
I have to change the date fields to something more user friendly, so I figured I would use some jquery datepickers.
The problem I have is that the height of iframe is smaller than the height of the datepicker selection window. Instead of appearing on top of the other frames, the date picker is not displayed entirely (stops at the end of the iframe).
I tried a lot of z-index fiddling, but it seems to me like all this only applies to the page inside the iframe, and does not affect how it's displayed on the main page.
Any suggestions? Is what I'm trying to do even possible?
Thanks!

A: What you're trying to achieve is not possible. An iframe is a self-contained document, like a page in a different browser window. As long as you're using iframes any content in them will end at the iframe's border.
You will also find that it's a load of trouble getting the scripts in the different iframes to communicate with each other, especially in older browsers and intranet viewers (also called Internet Explorer).
In short: If there is no reason to use an iframe, don't use one. Having three of them on a page is like having four web pages open in the browser at the same time and is generally a waste of resources. Using an iframe makes sense when you need to load content eg. from a different domain and you want it isolated from the content on your page.

A: I know its late but it might help someone :
You can increase and decrease the row of frameset dynamically :
$("#fromdate, #todate").click(function () {
        $('frameset', top.document).eq(2).attr('rows', '300,*');
    });