Q: Adding controls to a from C# 2015, this.Controls.Add(bla) method not found? public partial class MainWindow : Window
{
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        WebBrowser wb = new WebBrowser();
        this.Controls.Add(wb);
    }
}

This results in an error:

'MainWindow' does not contain a definition for 'Controls' and no extension method accepting a first argument of type 'MainWindow' could be found

Whats wrong here?
This is a WPF Application.
I'm new to C#.
I find it on internet that to add controls to the form the function is
this.Controls.Add(fdfdf)

But here this doesn't contain Controls.

A: In WPF it should be Children. In WPF you need to add items as Childrens of layout panels like your main Grid. For example if you have a Grid set it's name to grid1 and then in the code you can:
grid1.Children.Add(fdfdf)

A: You can add a component like your WebBrowser directly to the content of the Window.
In WPF you are doing it like this:
public partial class MainWindow : Window
{
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        WebBrowser wb = new WebBrowser();
        this.Content = wb;
    }
}

But I suggest to do this via the XAML.


Q: python - calculate the number of nodes in a Binary Tree I'm trying to write a function that uses recursion to find the number of nodes, i.e. the size of the binary tree. If the tree is empty there is no node. If it's not empty the number of nodes is 1 (the root) plus the number of nodes of the left subtree and the number of nodes of the right subtree.
I'm meant to use the binary tree class given to me to do this.
This is my Binary Tree class:
class BinaryTree:

    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

    def insert_left(self, new_data):
        if self.left == None:
            self.left = BinaryTree(new_data)
        else:
            t = BinaryTree(new_data)
            t.left = self.left
            self.left = t

    def insert_right(self, new_data):
        if self.right == None:
            self.right = BinaryTree(new_data)
        else:
            t = BinaryTree(new_data)
            t.right = self.right
            self.right = t

    def get_left(self):
        return self.left

    def get_right(self):
        return self.right

    def set_data(self, data):
        self.data = data

    def get_data(self):
        return self.data

and this is my recursive function to calculate the size:
def size(my_tree):
    count = 0
    if my_tree.get_data() is None:
        return 0
    else:
        count += 1 + size(my_tree.get_left()) + size(my_tree.get_right())
    return count

However, when I run it with this program:
 a = BinaryTree(1)
 a.insert_left(2)
 a.insert_right(3)
 print(size(a))

I get the following error:
Original exception was:
Traceback (most recent call last):
    File "prog.python3", line 57, in <module>
        print(size(a))
    File "prog.python3", line 41, in size
        count += 1 + size(my_tree.get_left()) + size(my_tree.get_right())
    File "prog.python3", line 38, in size
        if my_tree.get_data() is None:
AttributeError: 'NoneType' object has no attribute 'get_data'

when the output should be:
3

I simply don't understand what I'm doing wrong, but I'm pretty sure it must be something to do with the if statement.

A: Just modify your if statement to
if my_tree is None:
    return 0

The error arises since you are trying to access get_data property for a NULL data object on recursive call for leaf nodes of the binary tree.
Instead what you actually need to do is return 0 when you reach a NoneType node.

A: What happens if my_tree is None? Then you can't call get_data()...
Try this
if my_tree is None:
    return 0

Worth pointing out that you don't care about the node data to find the size of the tree
The more optimal method is to not recurse, and keep the size updated as you insert/remove elements

A: Assuming you pass in a valid root object and recursion occurs as expected, then at what point can you hit upon a NoneType error? Certainly, when my_tree is None, and you try to access an attribute of None. When can my_tree be None? At the leaves. In other words, your base case is malformed.
Note that testing the return value of get_data is completely redundant here, because self.data has nothing to do with the height of the node, or the node itself.
def size(my_tree):
    if not my_tree:
        return 0

    return 1 + size(my_tree.get_left()) + size(my_tree.get_right())

Further nitpicks:

*

*You don't need else; that's implied by control flow.

*You don't need an extra variable to store the count, because you don't do anything else besides return it.

A: You are getting this error because you are calling get_data() on non-existent object. So, you are calling get_data() on a NoneType object.
def size(my_tree):
    count = 0
    if my_tree is None:
        return 0
    count += 1 + size(my_tree.get_left()) + size(my_tree.get_right())
    return count

The else clause is not needed. Another suggestion to count the binary tree nodes is to have a attribute size on the class, and increase / decrease it as items are added / removed from the tree.


Q: Restrict list of components when linking in property editor in IDE I have created a new designtime component, which contains a published property Handler of type TComponent and registered it into the Tool Palette.
When i place a component of this type on my form, the property editor of the IDE shows me the property 'Handler' with a dropdown box that allows me to set this property at design time. The dropbox shows all available TComponents on the current form.
How can I restrict the list of components that is shown here (design time) to components of a certain type or with a certain property? i.e. Components that implement a certain (set of) interfaces.
I know that you can also use interface-properties, but also encountered several posts on the internet stating that this is very unstable and raises all kinds of problems.
Is there a method I can call for each of the proposed components where I can determine if they should appear in the list at design time?
Addition after the answer of @David:
Now that I've learned that TComponentProperty is what i was looking for, I also found a related question here: How to modify TComponentProperty to show only particular items on drop down list?

A: *

*Derive a sub class of TComponentProperty.

*Override its GetValues method to apply your filter.

*Register this TComponentProperty as the property editor for your property.

Here is a very simple example:
Component
unit uComponent;

interface

uses
  System.Classes;

type
  TMyComponent = class(TComponent)
  private
    FRef: TComponent;
  published
    property Ref: TComponent read FRef write FRef;
  end;

implementation

end.

Registration
unit uRegister;

interface

uses
  System.SysUtils, System.Classes, DesignIntf, DesignEditors, uComponent;

procedure Register;

implementation

type
  TRefEditor = class(TComponentProperty)
  private
    FGetValuesProc: TGetStrProc;
    procedure FilteredGetValuesProc(const S: string);
  public
    procedure GetValues(Proc: TGetStrProc); override;
  end;

procedure TRefEditor.FilteredGetValuesProc(const S: string);
begin
  if S.StartsWith('A') then
    FGetValuesProc(S);
end;

procedure TRefEditor.GetValues(Proc: TGetStrProc);
begin
  FGetValuesProc := Proc;
  try
    inherited GetValues(FilteredGetValuesProc);
  finally
    FGetValuesProc := nil;
  end;
end;

procedure Register;
begin
  RegisterComponents('Test', [TMyComponent]);
  RegisterPropertyEditor(TypeInfo(TComponent), nil, 'Ref', TRefEditor);
end;

end.

This rather useless property editor will only offer you components whose names begin with A. Despite its complete lack of utility, this does illustrate the ability to filter that you desire. You'll likely want to call Designer.GetComponent(...) passing a component name to obtain the component instance, and implement your filtering based on the type and state of that component instance.

A: As @TLama already pointed out you need to change the tpe of handler field/property.
Now in case if you want to ba able to assign specific type of component to this field/property then set this field type to the same type of that compomnent.
But if you want to be able to assign several different component types but not all components make sure that Handler field/property type is the type of the first common ancestor class/component of your desired components that you want to be able to assign to the Handler field/property.


Q: Copying from a set of cells from one column and paste them in consecutive columns in VBA Excel Macros I have got a set of values in Range 'A' and Range 'B'. I want to compare each consecutive row of Range 'A' and when the previous row is greater than the next row ; I want to copy then set of points below the compared points and paste them in the consecutive columns. for eg. C,G,J etc... I have got the compare  part  done ..Just the arranging part is taking my time. In my case I am trying to use DO Until and For Loop. But is there any better way ... PLs Advice...
 Range("H1").Select

 Do Until Range("H1", Range("H1").End(xlDown))

 If IsEmpty(ActiveCell) Then

 ActiveCell.Offset(1, 0).Select
 j = 2

 For i = 1 To Range("H1", Range("H1").End(xlDown)).Rows.Count

 Cells(i + 1, 8).Select
 Selection.Copy
 Cells(i + 1, 11 + j).Select
 ActiveSheet.Paste

 Cells(i + 1, 9).Select
 Selection.Copy
 Cells(i + 1, 12 + j).Select
 ActiveSheet.Paste

 Next i

ActiveCell.Offset(1, 0).Select

 Else

 j = 0
 For i = 1 To Range("H1", Range("H1").End(xlDown)).Rows.Count

 Cells(i + 1, 8).Select
 Selection.Copy
 Cells(i + 1, 11 + j).Select
 ActiveSheet.Paste

 Cells(i + 1, 9).Select
 Selection.Copy
 Cells(i + 1, 12 + j).Select
 ActiveSheet.Paste

 Next i

 ActiveCell.Offset(1, 0).Select

 End If

Loop


Q: CDash build ID not set (CTest, CMake) I have a CDash configured to accept posts for automatic builds and tests. However, when any system attempts to post results to the CDash, the following error is produced. The result is that each result gets posted four times (presumably the original posting attempt plus the three retries).
Can anyone give me a hint as to what sets this mysterious build ID? I found some code that seems to produce a similar error, but still no lead on what might be happening.

Build::GetNumberOfErrors(): BuildId not set
    Build::GetNumberOfWarnings(): BuildId not set
     Submit failed, waiting 5 seconds...
     Retry submission: Attempt 1 of 3
     Server Response:

A: The buildid for CDash is computed based on the site name, the build name and the build stamp of the submission. You should have a Build.xml file in a Testing/20110311-* directory in your build tree. Open that up and see if any of those fields (near the top) is empty. If so, you need to set BUILDNAME and SITE with -D args when configuring with CMake. Or, set CTEST_BUILD_NAME and CTEST_SITE in your ctest -S script.
If that's not it, then this is a mystery. I've not seen this error occur before...


Q: How do I prompt the user to give the name for the writing and reading serialized file? I am making an attempt to prompt the user to create the name for the writing and reading serialized file. E.g. could I do the following:
System.out.print("What would you like to name your file?");
String fileName = scanner.nextLine;

try{
 ObjectOutput ostream = new ObjectOutputStream(new FileOutputStream(fileName)) // Would this create a file with the name inputted by the user? If so what would be the extension for the file?

 ostream.writeObject(//whatever I want to put in here)

 //close

//catch

try{

 ObjectInputStream = new ObjectInputStream(new FileInputStream(fileName))

//catch

A: If you want to prompt the user for something from the terminal, the easiest way is probably to use java.io.Console, in particular one of its readLine() methods:
import java.io.Console;

...

Console console = System.console();
if (console == null) {
  throw new IllegalStateException("No console to read input from!");
}

String fileName = console.readLine("What would you like to name your file? ");
// Whatever the user inputed is now in fileName

See http://docs.oracle.com/javase/7/docs/api/java/io/Console.html.


Q: Braces around Java method I just noticed recently, while coding, that surrounding code with braces without any condition (or anything else) lets the code running correctly. For example, the following snippet:
public static void main(String[] args) {
{
    System.out.println("Hello world !");
    {
        System.out.println("Hello subworld !");
        {
            System.out.println("Hello sub-subworld !");
        }
    }
}
}

Gives the following output:
Hello world !
Hello subworld !
Hello sub-subworld !

I would like to know: are there any consequences, deeper into execution, of this kind of practice ? And, is it used in any case and proven to be useful ?


Q: Recursively reversing a string in C? I have to reverse a string in a recursive function, but I cannot use loops or strlen to find where the end of the string is. Then I have to pass the reversed string back to main and copy it to a new file. Here's what I have so far:
int reverse(char *str, char *strnew, int p)
{
    char temp=str[p];
    if(temp=='\0' || temp=='\n')
    {
            strnew=str;
            return p;
    }
    else
    {
            reverse(str++, strnew, ++p);
            p--;
            strnew[p]=str[p];
            printf("strnew: %c\n",  strnew[p]);
            return 0;
    }
}

int main(int argc, char *argv[])
{
    FILE *fp;
    char buffer[100];
    char newstr[100];
    int pointer=0;
    fp=fopen("lab8.txt", "r");
    if(fp==NULL)
    {
            printf("Error opening file\n");
            return 0;
    }
    (fgets(buffer, 100, fp));
    reverse(buffer, newstr, pointer);
    printf("newstr: %s\n", newstr);
    FILE *fp2=fopen("lab8.2.txt", "w");
    fputs(newstr, fp2);
    fclose(fp);
    fclose(fp2);

    return 0;
}

I cannot wrap my head around how to reverse the string. I've found where the null character is using p, but how do I copy the string backwards onto a new string?

A: #include <stdio.h>

int reverse(char *str, int pos){
    char ch = str[pos];
    return (ch == '\0')? 0 : ((str[pos=reverse(str, ++pos)]=ch), ++pos);
}

int main(){
    char buffer[100];

    scanf("%99[^\n]", buffer);
    reverse(buffer, 0);
    fprintf(stdout, "%s\n", buffer);
    return 0;
}

A: Since this is obviously homework, no complete solution, only ideas.
First, you don't need to limit yourself to one recursive function. You can have several, and a resursive implementation of strlen is trivial enough. my_strlen(char *p) evaluates to 0 if *p = 0, and to 1 + my_strlen(p+1) otherwise.
You can probably do it in a single recursion loop, too, but you don't have to.
One more thing: as you recurse, you can run your code both on the front end of recursion and on the back end. A recursion is like a loop; but after the nested call to self returns, you have a chance to perform another loop, this one backwards. See if you can leverage that.

A: It is quite simple.  When you enter the string, you save the character at the position you are are.  Call the method recursively more character to the right.  When you get to the end of the string, you will have N stack frames, each holding one character of an N character string.  As you return, write the characters back out, but increment the pointer as you return, so that the characters are written in the opposite order.

A: I'll try to be nice and give you a little sample code. With some explanation.
The beauty of recursion is that you don't need to know the length of the string, however the string must be null terminated. Otherwise you can add a parameter for the string length.
What you need to think is that the last input character is your first output character, therefore you can recurse all the way to the end until you hit the end of the string. As soon as you hit the end of the string you start appending the current character to the output string (initially set to nulls) and returning control to the caller which will subsequently append the previous character to the output string.
void reverse(char *input, char *output) {
    int i;
    if(*input) /* Checks if end of string */
        reverse(input+1,output); /* keep recursing */
    for(i=0;output[i];i++); /* set i to point to the location of null terminator */
    output[i]=*input; /* Append the current character */
output[i+1]=0; /* Append null terminator */
} /* end of reverse function and return control to caller */

Finally, lets test the function.
int main(argc, argv) {
    char a[]="hello world";
    char b[12]="\0";
    reverse(a,b);
    printf("The string '%s' in reverse is '%s'\n", a, b);
}

Output
The string 'hello world' in reverse is 'dlrow olleh'


Q: How to programmatically grant the "draw over other apps" permission in android? How can I programmatically grant the permission in Settings -> Apps -> Draw over other apps in Android? I want to use system alert window but unable to in Android Marshmallow without forcing the user to go through the Settings app and grant the permission first.

A: Here's the code for automatic granting the SYSTEM_ALERT_WINDOW permission to the package. To run this code, your Android application must be system (signed by platform keys).
This method is based on the following Android source code files: AppOpsManager.java and DrawOverlayDetails.java, see the method DrawOverlayDetails.setCanDrawOverlay(boolean newState).
@TargetApi(Build.VERSION_CODES.KITKAT)
public static void autoSetOverlayPermission(Context context, String packageName) {
    PackageManager packageManager = context.getPackageManager();
    int uid = 0;
    try {
        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
        uid = applicationInfo.uid;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return;
    }

    AppOpsManager appOpsManager = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
    final int OP_SYSTEM_ALERT_WINDOW = 24;
    try {
        Class clazz = AppOpsManager.class;
        Method method = clazz.getDeclaredMethod("setMode", int.class, int.class, String.class, int.class);
        method.invoke(appOpsManager, OP_SYSTEM_ALERT_WINDOW, uid, packageName, AppOpsManager.MODE_ALLOWED);
        Log.d(Const.LOG_TAG, "Overlay permission granted to " + packageName);
    } catch (Exception e) {
        Log.e(Const.LOG_TAG, Log.getStackTraceString(e));
    }
}

}
The code has been tested in Headwind MDM project, it successfully grants "Draw over other apps" permission without any user consent to the Headwind Remote application (disclaimer: I'm the project owner of Headwind MDM and Headwind Remote), when Headwind MDM application is signed by platform keys. The code has been tested on Android 10 (LineageOS 17).

A: You can check and ask for overlay permission to draw over other apps using this
if (!Settings.canDrawOverlays(this)) {
    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
    startActivityForResult(intent, 0);
}

A: if (!Settings.canDrawOverlays(this)) {
    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
    Uri.parse("package:" + getPackageName()));
    startActivityForResult(intent, 0);
}

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

A: Check this question and the answer:
SYSTEM_ALERT_WINDOW - How to get this permission automatically on Android 6.0 and targetSdkVersion 23
"Every app that requests the SYSTEM_ALERT_WINDOW permission and that is installed through the Play Store (version 6.0.5 or higher is required), will have granted the permission automatically."


Q: Django - assign m2m relationship in admin In the app I'm building some users have the role "Coder" and are assigned to "Assignments".
What I can't seem to get working is the process of an Admin assigning Coders to Assignments.
Here is the Model-Code I have so far (probably totally wrong):
class Coder(models.Model):
"""Every user can be a coder. Coders are assigned to Assignments"""
user = models.OneToOneField(User)

class Admin:
    list_display = ('',)
    search_fields = ('',)

def __unicode__(self):
    return u"Coders"

class Assignment(models.Model):
"""(Assignment description)"""
title = models.CharField(blank=True, max_length=100)
start_year = models.IntegerField(blank=True, null=True)
end_year = models.IntegerField(blank=True, null=True)
country = models.IntegerField(blank=True, null=True)
coders = models.ManyToManyField(Coder)

class Admin:
    list_display = ('',)
    search_fields = ('',)

def __unicode__(self):
    return u"Assignment"

And this is the admin-code:
class AssignmentCoderInline(admin.StackedInline):
model = Assignment.coders.through
can_delete = False
verbose_name_plural = 'coder'

class AssignmentAdmin(admin.ModelAdmin):
fieldsets = [
    ('Assignment', {'fields': ['title', 'start_year', 'end_year']})
]
inlines = (AssignmentCoderInline,)

class CoderInline(admin.StackedInline):
model = Coder
can_delete = False
verbose_name_plural = 'coder'

Now, when i'm in the admin, I want to create an assignment and add coders to it.
Yet all I see when trying to do so is this:

How can I add one coder/user to an assignment, so I can later show him in a view all the assignments he has?
This is probably a really dumb question, but please answer anyways, I greatly appreciate any help :)

A: If I'm not mistaken, it looks like you want to call a coder to a view, and then show all the assignments for an a user.
First, I might start by assigning a related_name to the coder and assignment models relationships with each other, so you can easily reference them later.
class Assignment(models.Model):
    coders = models.ManyToManyField(Coder, related_name='assignments')

class Coder(models.Model):
    user = models.OneToOneField(User, related_name="coder")

I'd then reference the user in a template as such using the one to one relationship:
    {% for assignment in user.coder.assignments.all %}

Also, looks like the problem is how you've got yout models setup. After reviewing the django.db.models.base for the "models.Model" class and "ModelBase" class, it looks like there is no "Admin" subclass. You'll probably want to remove those to start with.
Next, the __unicode__ field shows the default visible value which represents the object on the screen. In this case, you've forced it to be "Coders". If you had 5 coders to an assignment, you'd see "Coders, Coders, Coders, Coders, Coders" instead of "admin, user1, bob22, harry8, stadm1in", etc. Let's override the unicode to show something more meaningful. Since the coders field only has the user field, let's reference that by self.user.username. We'll change Assignment()'s unicode to self.title as well.
ModelForm doesn't have an 'Admin' subclass either, so let's remove that.
MODELS:

class Coder(models.Model):
    """Every user can be a coder. Coders are assigned to Assignments"""
    user = models.OneToOneField(User, related_name='coder')

    def __unicode__(self):
        return self.user.username

class Assignment(models.Model):
    """(Assignment description)"""
    title = models.CharField(blank=True, max_length=100)
    start_year = models.IntegerField(blank=True, null=True)
    end_year = models.IntegerField(blank=True, null=True)
    country = models.IntegerField(blank=True, null=True)
    coders = models.ManyToManyField(Coder, related_name='assignments')

    def __unicode__(self):
        return self.title

ADMIN:

class AssignmentCoderInline(admin.StackedInline):
    model = Assignment.coders.through
    can_delete = False
 #   verbose_name_plural = 'coder'

class AssignmentAdmin(admin.ModelAdmin):
    fieldsets = [
        ('Assignment', {'fields': ['title', 'start_year', 'end_year']})
    ]
    inlines = (AssignmentCoderInline,)


Q: Using JSP to paint a part of page other wise painted by Servlet I am updating an age old application that paints its page using a Servlet. I want to add something to that page and really want to stop adding to that Servlet file.
Is there a way I could paint a part of a page using JSP and all other using Servlet.

A: Yes of course, you can use the
`<jsp:include page="content.jsp">`  or
`<%@include file="content.jsp"%>`
If your content is static(copy and paste), you can use `<%@include file="content.jsp"%>`
The `<%@include file="content.jsp">` directive is similiar to "#include" in C programming, including the all contents of the included file and then compiling it like it is part of the including file. Also the included file can be any type (including HTML or text).


Q: Starting and stopping Apache Camel routes from admin UI I have a Apache Camel context which is part of a large Spring application. The application has a web based admin UI. I'd like to be able to stop/start/suspend/resume the camel routes from within this UI. How can I achieve this?
Currently my Camel context is defined in a Spring context file and autostarts when the Spring application is deployed. My routes are defined in Java classes which extend SpringRouteBuilder.
I have:
camel-context.xml:
<beans>

    <!--bootstrap camel context-->
    <camelContext xmlns="http://camel.apache.org/schema/spring">
        <package>com.package</package>
    </camelContext>

</beans>

which is imported in the main Spring context. I then have classes which extend SpringRouteBuilder in com.package
Is there a better way of doing this so that I can programatically control the Camel context when there is an event in the UI?

A: You can also do like we do in hawtio (http://hawt.io/) where we use REST calls to remote manage Camel applications, so we can control routes, see statistic, view routes, and much more. All this is made easier by using an excellent library called jolokia (http://jolokia.org/) that makes JMX exposed as REST services. Each JMX operation/attribute is easily callable as an URI template over REST. And data is in json format.
That what you can build UI consoles that just use REST for communication, and are not tied into the Java or JMX world etc.
Also the Java API on CamelContext allows you to control routes. And there is also the control-bus EIP that has more details: http://camel.apache.org/controlbus


Q: Detect activity level of microphone in flex I have to detect avtivityLevel of microphone in Flex. I am using the activityLevel property of Microphone class but as I found out it always return -1 even if I have done Microphone.getMicrophone().
To detect activity level we have to set microphone.setLoopback = true;
Does anybody know how to do this without using loop back as I do not want to hear my sound back just monitor the activity level
Thanks

A: The microphone won't show any activity until it is attached to a NetStream connection. You can use a MockNetStream to fake the connection using OSMF - see my answer here.


Q: php docker how to use file_get_contents to fetch self domain's result I have a project need to server migration, the new server deployed by docker. but in docker, the file_get_contents() cannot fetch the result from self domain. and I can't use others way (for example reqire_once) to load this file ( this project is too old and code is... you know ).
code:
$json = file_get_content("http://this.site.com/xxx/yyy/get_result.php?params=xxx&params2=yyy")

If I use it, will get a warning connect refuese, if I replace the domain to http://127.0.0.1 or http://localhost, will get the same warning, or replace to http://nginx ( nginx is another container's name ) will get content, but not my site's content ( it will get contents the same by using 127.0.0.1 in the broswer, not using http://this.site.com )
So it

A: Your code is running with a docker on another instance so is 127.0.0.1 address is different from your computer's address.
You must enter the external IP address of the container

A: Try using host.docker.internal...


Q: Keep selected row in table highlighted during fireTableDataChanged is there chance to keep the selected row in a JTable higlithed druing fireTableDataChanged?
Thank you


Q: Prism 7 throws and exception when working with nested views I posted similar question few months ago Working with nested views using Prism with IsNavigationTarget which can return false, I'm still not sure what is the proper way to do it.
Imagine you have a view A, in this view A you have declared a region A, then you injected a view B into this region A. Similarly, in View B you have registered region B, and then you injected a view C into this region B. As it shown on the following picture:

In the ViewModelA for ViewA, I have a method SetUpSubViews() where I call:
_regionManager.RequestNavigate("regionA", "ViewB", NavigationCallback);

ViewModelB for View B implements INavigationAware. So that in OnNavigatedTo() method I call:
_regionManager.RequestNavigate("regionB", "ViewC", NavigationCallback);

ViewModelC for View C implements INavigationAware too.
Now, I have in both ViewModelB and ViewModelC in IsNavigationTarget() method:
public bool IsNavigationTarget(NavigationContext navigationContext)
    {
        return false;
    }

It means I want to create new view everytime this view is navigated.
Both ViewB and ViewC implement IRegionMemberLifetime interface, where I set:
#region IRegionMemberLifetime

public bool KeepAlive => false;

#endregion

It means that I don't want to reuse view and I want it to be disposed.
And regions in the view are declared like this:
<ContentControl prism:RegionManager.RegionName="{x:Static localRegions:LocalRegions.RegionB}" />

Now, first time when I call SetUpSubViews() method on ViewModelA all is good. Second time when I call it I see the exception:

Region with the given name is already registered
...

What I need is to have a way to recreate view<->viewmodel pair from scratch everytime when I need. It seems when view is disposed, prism doesn't remove region that was declared in removed view. Question to community and prism developers, how to do it in proper way?
The current solution doesn't make happy, here is what I do:
Step 1 - I set in ViewModelB and ViewModelC in INavigationAware part
    public bool IsNavigationTarget(NavigationContext navigationContext)
    {
        return true;
    }

that signals to prism to do not create new views and probably it also means that if any region is found in the view to do not register it in the region manager.
Step 2 - When i need to inject view to region, i remove manually old view and create new one. So my SetUpSubViews() method looks like this:
protected void SetUpSubViews(){
            //get region by name
            var region = _regionManager.Regions["regionA"];
            // push to remove all views from the region
            region.RemoveAll();
            // navigate to view
           _regionManager.RequestNavigate("regionA", "ViewB", NavigationCallback);}

Similarly I have to remove ViewC from region regionB on ViewB. (here is region.RemoveAll() is a key line.)
Step3 - I don't implement IRegionMemberLifetime interface on viewB and viewC.
It works, but it doesn't look correct.
P.S. I also tried scoped manager, but i don't know how to propagate new created scoped manager to the viewmodels, cause they are created automatically, and if i resolve it via constructor I get main global manager instead of scoped.
Thanks.

A: This is quite a troublesome problem. I recommend videos from Brian Lagunas himself where he provides a solution and explanation. For example this one.
https://app.pluralsight.com/library/courses/prism-problems-solutions/table-of-contents
If you can watch it. If not I will try to explain.
The problem I believe is that IRegionManager from the container is a singleton and whenever you use it it is the same instance, so when you are trying to inject a region in an already injected region it will not work and you need to have a separate RegionManager for nested views.
This should fix it.
Create two interfaces
public interface ICreateRegionManagerScope
{
    bool CreateRegionManagerScope { get; }
}
public interface IRegionManagerAware
{
    IRegionManager RegionManager { get; set; }
}

Create a RegionManagerAwareBehaviour
public class RegionManagerAwareBehaviour : RegionBehavior
{
    public const string BehaviorKey = "RegionManagerAwareBehavior";

    protected override void OnAttach()
    {
        Region.Views.CollectionChanged += Views_CollectionChanged;
    }

    void Views_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Add)
        {
            foreach (var item in e.NewItems)
            {
                IRegionManager regionManager = Region.RegionManager;

                // If the view was created with a scoped region manager, the behavior uses that region manager instead.
                if (item is FrameworkElement element)
                {
                    if (element.GetValue(RegionManager.RegionManagerProperty) is IRegionManager scopedRegionManager)
                    {
                        regionManager = scopedRegionManager;
                    }
                }

                InvokeOnRegionManagerAwareElement(item, x => x.RegionManager = regionManager);
            }
        }
        else if (e.Action == NotifyCollectionChangedAction.Remove)
        {
            foreach (var item in e.OldItems)
            {
                InvokeOnRegionManagerAwareElement(item, x => x.RegionManager = null);
            }
        }
    }

    private static void InvokeOnRegionManagerAwareElement(object item, Action<IRegionManagerAware> invocation)
    {
        if (item is IRegionManagerAware regionManagerAwareItem)
        {
            invocation(regionManagerAwareItem);
        }

        if (item is FrameworkElement frameworkElement)
        {
            if (frameworkElement.DataContext is IRegionManagerAware regionManagerAwareDataContext)
            {
                // If a view doesn't have a data context (view model) it will inherit the data context from the parent view.
                // The following check is done to avoid setting the RegionManager property in the view model of the parent view by mistake.
                if (frameworkElement.Parent is FrameworkElement frameworkElementParent)
                {
                    if (frameworkElementParent.DataContext is IRegionManagerAware regionManagerAwareDataContextParent)
                    {
                        if (regionManagerAwareDataContext == regionManagerAwareDataContextParent)
                        {
                            // If all of the previous conditions are true, it means that this view doesn't have a view model
                            // and is using the view model of its visual parent.
                            return;
                        }
                    }
                }

                invocation(regionManagerAwareDataContext);
            }
        }
    }
}

Create ScopedRegionNavigationContentLoader
public class ScopedRegionNavigationContentLoader : IRegionNavigationContentLoader
{
    private readonly IServiceLocator serviceLocator;

    /// <summary>
    /// Initializes a new instance of the <see cref="RegionNavigationContentLoader"/> class with a service locator.
    /// </summary>
    /// <param name="serviceLocator">The service locator.</param>
    public ScopedRegionNavigationContentLoader(IServiceLocator serviceLocator)
    {
        this.serviceLocator = serviceLocator;
    }

    /// <summary>
    /// Gets the view to which the navigation request represented by <paramref name="navigationContext"/> applies.
    /// </summary>
    /// <param name="region">The region.</param>
    /// <param name="navigationContext">The context representing the navigation request.</param>
    /// <returns>
    /// The view to be the target of the navigation request.
    /// </returns>
    /// <remarks>
    /// If none of the views in the region can be the target of the navigation request, a new view
    /// is created and added to the region.
    /// </remarks>
    /// <exception cref="ArgumentException">when a new view cannot be created for the navigation request.</exception>
    public object LoadContent(IRegion region, NavigationContext navigationContext)
    {
        if (region == null) throw new ArgumentNullException("region");
        if (navigationContext == null) throw new ArgumentNullException("navigationContext");

        string candidateTargetContract = this.GetContractFromNavigationContext(navigationContext);

        var candidates = this.GetCandidatesFromRegion(region, candidateTargetContract);

        var acceptingCandidates =
            candidates.Where(
                v =>
                {
                    var navigationAware = v as INavigationAware;
                    if (navigationAware != null && !navigationAware.IsNavigationTarget(navigationContext))
                    {
                        return false;
                    }

                    var frameworkElement = v as FrameworkElement;
                    if (frameworkElement == null)
                    {
                        return true;
                    }

                    navigationAware = frameworkElement.DataContext as INavigationAware;
                    return navigationAware == null || navigationAware.IsNavigationTarget(navigationContext);
                });

        var view = acceptingCandidates.FirstOrDefault();

        if (view != null)
        {
            return view;
        }

        view = this.CreateNewRegionItem(candidateTargetContract);

        region.Add(view, null, CreateRegionManagerScope(view));

        return view;
    }

    private bool CreateRegionManagerScope(object view)
    {
        bool createRegionManagerScope = false;

        if (view is ICreateRegionManagerScope viewHasScopedRegions)
            createRegionManagerScope = viewHasScopedRegions.CreateRegionManagerScope;

        return createRegionManagerScope;
    }

    /// <summary>
    /// Provides a new item for the region based on the supplied candidate target contract name.
    /// </summary>
    /// <param name="candidateTargetContract">The target contract to build.</param>
    /// <returns>An instance of an item to put into the <see cref="IRegion"/>.</returns>
    protected virtual object CreateNewRegionItem(string candidateTargetContract)
    {
        object newRegionItem;
        try
        {
            newRegionItem = this.serviceLocator.GetInstance<object>(candidateTargetContract);
        }
        catch (ActivationException e)
        {
            throw new InvalidOperationException(
                string.Format(CultureInfo.CurrentCulture, "Cannot create navigation target", candidateTargetContract),
                e);
        }
        return newRegionItem;
    }

    /// <summary>
    /// Returns the candidate TargetContract based on the <see cref="NavigationContext"/>.
    /// </summary>
    /// <param name="navigationContext">The navigation contract.</param>
    /// <returns>The candidate contract to seek within the <see cref="IRegion"/> and to use, if not found, when resolving from the container.</returns>
    protected virtual string GetContractFromNavigationContext(NavigationContext navigationContext)
    {
        if (navigationContext == null) throw new ArgumentNullException(nameof(navigationContext));

        var candidateTargetContract = UriParsingHelper.GetAbsolutePath(navigationContext.Uri);
        candidateTargetContract = candidateTargetContract.TrimStart('/');
        return candidateTargetContract;
    }

    /// <summary>
    /// Returns the set of candidates that may satisfiy this navigation request.
    /// </summary>
    /// <param name="region">The region containing items that may satisfy the navigation request.</param>
    /// <param name="candidateNavigationContract">The candidate navigation target as determined by <see cref="GetContractFromNavigationContext"/></param>
    /// <returns>An enumerable of candidate objects from the <see cref="IRegion"/></returns>
    protected virtual IEnumerable<object> GetCandidatesFromRegion(IRegion region, string candidateNavigationContract)
    {
        if (region == null) throw new ArgumentNullException(nameof(region));
        return region.Views.Where(v =>
            string.Equals(v.GetType().Name, candidateNavigationContract, StringComparison.Ordinal) ||
            string.Equals(v.GetType().FullName, candidateNavigationContract, StringComparison.Ordinal));
    }
}

In your App.xaml
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
 containerRegistry.RegisterSingleton<IRegionNavigationContentLoader,ScopedRegionNavigationContentLoader>();

}

protected override void ConfigureDefaultRegionBehaviors(IRegionBehaviorFactory regionBehaviors)
    {
       base.ConfigureDefaultRegionBehaviors(regionBehaviors);

       regionBehaviors.AddIfMissing(RegionManagerAwareBehaviour.BehaviorKey, typeof(RegionManagerAwareBehaviour));
    }

Coming to the finish.
Now in your ViewModelB implement IRegionManagerAware and have it as a normal property
public IRegionManager RegionManager { get; set; }

Then at your ViewB implement ICreateRegionManagerScope and have it as a get property
public bool CreateRegionManagerScope => true;

Now it should work.
Again I truly recommend the videos at Pluralsight from Brian on Prism. He has a couple of videos that help a lot when you are starting with a Prism.


Q: CSRF PHP Prevention Mechanism I have read many articles about CSRF, almost all of them have the same solution which is hidden tokens, so i wrote a code to prevent CSRF and i tried hacking my own page afterwards but it didn't work, i would like to know if my code is CSRF bulletproof, and if there is anyway around it.
i have four pages that has forms in them so in each page i would write the following:
            if (isset($_POST['submit'])){

            // Check for CSRF token
            if ($_SESSION['token'] === $_POST['token']){

                // write to db

            }else{
                 // CSRF attack has been detected
                 die("CSRF :
1: $_SESSION[token]
 2: $_POST[token]");

            }

        }else{
            // assign CSRF prevention token
            $form_token = md5((rand(1,89412) * 256 / 4).$date.time());
            $_SESSION['token'] = $form_token;
        }
        ?>
        <form action='' method='post'>
        <input type='hidden' name='token' value='<?echo $form_token;?>'>

would this method be enough to stop attackers from using CSRF on my website ?
Thanks alot.

A: I'll show you my code for CSRF prevention:
config.php
Configuration file should be auto-loaded in every page using require or include functions.
Best practice would be to write a configuration class (I'll just write down functions in order to simplify my code).
session_start();

if(empty($_SESSION['CSRF'])){
        $_SESSION['CSRF'] = secureRandomToken();
    }

post.php
This is just an example. In every "post" page you should check if CSRF token is set. Please submit your forms with POST method! I'd also recommend you to take a look at Slim Framework or  Laravel Lumen, they provide an excellent routing system which is gonna let you to accept POST requests only on your "post.php" page very easily (they also will automatically add a CSRF token in every form).
if (!empty($_POST['CSRF'])) {
    if (!hash_equals($_SESSION['CSRF'], $_POST['CSRF'])) {
        die('CSRF detected.');
    }
}else{
    die('CSRF detected.');
}

view.php
Now you just have to put an hidden input with your CSRF session value in it.
<input type="hidden" name="CSRF" value="<?= $_SESSION['CSRF'] ?>">

I hope that this quick explanation may help you :)


Q: youku search JS API in english I need the youku (China youtube) API in English or an explanation how to use it.
This is the code from youtube I want to write with youku:
url: 'https://www.googleapis.com/youtube/v3/search',
data: {
       'part': 'snippet',
       'q': this.searchBox.val(),
       'type': 'video',
       'key': '***key***'
       },

Thank you!
Edit:
This topic was for everyone who wants to work with youku API.
I edited my question and I provided the correct answer.
You have to work with translator (no English version) and this is the correct path:
http://doc.open.youku.com/?docid=318
Please ready the Developer agreement as well:
http://doc.open.youku.com/?docid=312
Good luck.

A: EDIT: I found the correct link, and you can use the browser to translate to english.  http://doc.open.youku.com/
The closest thing I can find to help you out this this thread, which contains a link that appears to go to Youku API documentation. I cannot get that link to open however. I hope this helps.


Q: Ideas to upgrade Excel Income and Expense tracker Sorry for the overly lengthy explanation below but I thought it'll be helpful in getting your ideas:
A few years ago I helped a friend keep track of the income and expenses of his family run guest house (around 10 rooms). The way it works is that his guest house is managed by staff who provide my fiend with regular updates on income and expenses (eg. rooms occupied, income, types and amounts of expenses, referral sources etc).
I built a quick and simple system in Excel with a user form, which the guest house manager uses to log the information. This info gets saved in the same workbook on another sheet. Since my friend lives in another city, the manager then emails the workbook to him on a monthly basis. My friend has a master copy of the same workbook and every time he receives his monthly update, he copies and pastes (appends) the data into his master copy.
The master workbook also has some dashboards built into it which work off the back of some pivots, formulas or the data directly; and provide my friend with key information like monthly profit figures, expense types, most commonly occupied rooms, avg length of stay etc.
All worked well but now, since the dataset has increased hugely, the workbook has started crashing. He has asked me to fix it, but I think it's time to change the underlying technology which would better suit the purpose. He doesn't want to approach a professional developer as the profits don't justify the costs. I can develop something but I'm not sure which is the best way to do it:
I'm good with SQL and Excel. My VBA knowledge is intermediate and I've just started learning Python. My initial thoughts are:
I could host a webpage on my friend's machine which his manager can remotely access to fill in information which then gets stored in the SQL server - Again, I've only got very limited knowledge around web page development and hosting. There could be an Excel file (or Tableau once I've learnt it) linked to it
and serve as a dashboarding platform. Essentially, instead of storing data in Excel it'll be stored in a SQL database.
If any of you could suggest a better/simpler way of implementing this that'll be greatly appreciated.
Many Thanks


Q: python time vs datetime The following comparison does not work, is there any way to get number of seconds passed (w.r.t localtime) since epoch from time module?
(datetime.datetime.now() - datetime.datetime.utcfromtimestamp(0)).total_seconds() - time.mktime(time.localtime()) => 3600.9646549224854

OR
(datetime.datetime.now() - datetime.datetime.utcfromtimestamp(0)).total_seconds() - time.time() => 3599.9999861717224

Thanks

A: datetime.now() returns a local datetime, while datetime.utcfromtimestamp() returns a UTC datetime. So of course you will have the difference of your timezone accounted for in your calculation. In order to avoid that, either always use local time, or always use universal time.
>>> (datetime.datetime.utcnow() - datetime.datetime.utcfromtimestamp(0)).total_seconds() - time.time()
0.0

A: Epoch is in GMT, so the number of seconds that have passed since Epoch is the same no matter what timezone you are in. Hence, the correct answer to your question:

is there any way to get number of seconds passed (w.r.t localtime) since epoch from time module?

is
>>> import time
>>> time.time()
1442482454.94842


Q: How to read a LinkedHashMap written in file? I want to read a particular value from LinkedHashMap written in a .txt file, but is showing "java.io.StreamCorruptedException: invalid stream header: 7B495020"
For writing in LinkedHashMap i tried the method;
public void WriteBasicInfo(String name, String pass) throws IOException, ParseException {
    Map<String, String> m;
        try {
            m = new LinkedHashMap<String, String>();
            m.put("Name", name);
            m.put("Password", pass);

            BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_NAME, false));
            bw.write(m.toString());
            bw.flush();
            bw.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

And it successfully writes in file. But when Iam trying to read the above hashmap using this method
public void readBasicInfo() throws IOException, ParseException, InvocationTargetException, ClassNotFoundException
{
        ObjectInputStream is = new ObjectInputStream(new FileInputStream(FILE_NAME));
        Map<String, String> myMap=(LinkedHashMap<String, String>) is.readObject();

        for(Map.Entry<String,String> m :myMap.entrySet()){
                 System.out.println(m.getKey()+" : "+m.getValue());
        //  String val1=m.get("Name");
        }
     ois.close();
    }

it is showing "java.io.StreamCorruptedException: invalid stream header: 7B495020" , and no data is read
I tried to read all the entries written in hashmap, to check whether it is reading or not; but actually I just want read only "name" entry stored in hashmap.

A: You are simply: writing as string, but reading back expecting a binary serialized object!
You know, that is like: you put an egg in a box, and then you expect you can open that box and pour milk from it into a glass! That wont work.
Here:
bw.write(m.toString());

You write the map into that file as raw string. This means that your file now contains human readable strings!
But then you do:
Map<String, String> myMap=(LinkedHashMap<String, String>) is.readObject();

Which expects that the file contains serialized objects.
Long story short, these are your options:

*

*keep writing these strings, but then you need to implement your own parser that reads such text files, and turns them back into objects within maps

*instead of writing raw text strings, use a library such as gson or jackson and serialize your map as JSON string (which requires that all keys/values can be serialized as JSON)

*instead of writing raw text or JSON, use the default Java serialization mechanism and serialize to binary content which requires that all keys/values implement the Serializable interface. See here for a nice tutorial how to do that in detail.

My recommendation: go for option 2, or 3. 2 adds a dependency to a 3rd party library, but I think it is the more "common" practice these days.

A: You need to serialize/deserialize the object, not just reading/writing its toString representation to file.
See: https://javahungry.blogspot.com/2017/11/how-to-serialize-hashmap-in-java-with-example.html


Q: Permission error [winerror 5] access is denied-Selenium chrome webdriver I'm following a tutorial on using selenium and I'm having trouble getting started. Namely, when I try to run the code below, I get the error below. I have seen other users with the same problem, I have tried their solutions, they did not work.
These solutions include:

*

*running pycharm as administrator,

*setting permissions for all

*group/usernames of subprocess.py and service.py

*site-package(and pretty much every file/folder within) to full
access.

from selenium import webdriver
driver = webdriver.Chrome(r"C:\Users\User\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\selenium\webdriver\chrome")
driver.get("http://python.org")

Here is the full error message:

Traceback (most recent call last):   File
"C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\common\service.py",
line 76, in start
stdin=PIPE)   File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py",
line 775, in init
restore_signals, start_new_session)   File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py",
line 1178, in _execute_child
startupinfo) PermissionError: [WinError 5] Access is denied

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File
"C:/Users/User/PycharmProjects/PythonProject/DataCollection", line 2,
in
driver = webdriver.Chrome(r"C:\Users\User\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\selenium\webdriver\chrome")
File
"C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py",
line 73, in init
self.service.start()   File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\common\service.py",
line 88, in start
os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'chrome'
executable may have wrong permissions. Please see
https://sites.google.com/a/chromium.org/chromedriver/home

A: first, replace all \ with /
and then add the executable filename in the file location:
driver = webdriver.Chrome(r'C:/Users/User/AppData/Local/Programs/Python/Python37-32/Lib/site-packages/selenium/webdriver/chrome/chromedriver.exe')


Q: Separate two html buttons and remove the fist button green animation There are two HTML buttons in the code below.

*

*Currently they are stuck together. I need to introduce a gap between them

*When you hover the mouse over the first (top) button, there is a green colour animation would show up around the button. I need to remove that.

Please advise me on how to make the proposed changes.

Escolha o seu tamanho!

            <button class="yp">36</button>
            <button class="no">No</button>
            <button class="tsete">37</button>
            <button class="toito">38</button>
            <button class="tnove">39</button>
            <button class="qzero">40</button>
            <button class="qum">41</button>
            <button class="qdois">42</button>
            <button class="qtres">43</button>

Azul

    <form action="b_657272">
  <button class="button">COMPRAR AGORA</button>


Q: Text mining with PHP I'm doing a project for a college class I'm taking.
I'm using PHP to build a simple web app that classify tweets as "positive" (or happy) and "negative" (or sad) based on a set of dictionaries. The algorithm I'm thinking of right now is Naive Bayes classifier or decision tree.
However, I can't find any PHP library that helps me do some serious language processing. Python has NLTK (http://www.nltk.org). Is there anything like that for PHP?
I'm planning to use WEKA as the back end of the web app (by calling Weka in command line from within PHP), but it doesn't seem that efficient.
Do you have any idea what I should use for this project? Or should I just switch to Python?
Thanks

A: If you're going to be using a Naive Bayes classifier, you don't really need a whole ton of NL processing. All you'll need is an algorithm to stem the words in the tweets and if you want, remove stop words.
Stemming algorithms abound and aren't difficult to code. Removing stop words is just a matter of searching a hash map or something similar. I don't see a justification to switch your development platform to accomodate the NLTK, although it is a very nice tool.

A: I did a very similar project a while ago - only classifying RSS news items instead of twitter - also using PHP for the front-end and WEKA for the back-end. I used PHP/Java Bridge which was relatively simple to use - a couple of lines added to your Java (WEKA) code and it allows your PHP to call its methods. Here's an example of the PHP-side code from their website:
<?php
require_once("http://localhost:8087/JavaBridge/java/Java.inc");

$world = new java("HelloWorld");
echo $world->hello(array("from PHP"));
?>

Then (as someone has already mentioned), you just need to filter out the stop words. Keeping a txt file for this is pretty handy for adding new words (they tend to pile up when you start filtering out irrelevant words and account for typos).
The naive-bayes model has strong independent-feature assumptions, i.e. it doesn't account for words that are commonly paired (such as an idiom or phrase) - just taking each word as an independent occurrence. However, it can outperform some of the more complex methods (such as word-stemming, IIRC) and should be perfect for a college class without making it needlessly complex.

A: You can also use the uClassify API to do something similar to Naive Bayes.  You basically train a classifier as you would with any algorithm (except here you're doing it via the web interface or by sending xml documents to the API).  Then whenever you get a new tweet (or batch of tweets), you call the API to have it classify them.  It's fast and you don't have to worry about tuning it.  Of course, that means you lose the flexibility you get by controlling the classifier yourself, but that also means less work for you if that in itself is not the goal of the class project.

A: Try open calais - http://viewer.opencalais.com/ . It has api, PHP classes and many more. Also, LingPipe for this task - http://alias-i.com/lingpipe/index.html

A: you can check this library https://github.com/Dachande663/PHP-Classifier very straight forward

A: you can also use thrift or gearman to deal with nltk


Q: Second Spinner not receiving the proper info based on the first Spinner's selection I know there are about a million topics on this already, but hear me out.
The title says it all, when i select an item in spinner 1, spinner 2 gets a specific list of choices to pick from (which will then be used to show info). It's essentially a small contacts book.
*UPDATE**
All fixed and working, and an EXTRA special thank you to user FishTruck for helping out(i.e making it work!)
package com.your.package.name;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class Contact extends Activity{

        public Spinner spinner1, spinner2;
        public Button btnSubmit;//not needed yet

        @Override
        public void onCreate(Bundle savedInstanceState){
                super.onCreate(savedInstanceState);

                setContentView(R.layout.contact);
                findViews();
                addItemsOnSpinner1();
                addItemsOnSpinner2(0);
        }

        private void findViews(){
                spinner1 = (Spinner) findViewById(R.id.spinner1);
                spinner2 = (Spinner) findViewById(R.id.spinner2);
        }

        private void addItemsOnSpinner1() {
                List<String> list = new ArrayList<String>();

                list.add("Please Select");
                list.add("Choice 1");
                list.add("choice 2");

                ArrayAdapter<String> name = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);

                name.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                spinner1.setAdapter(name);
                spinner1.setOnItemSelectedListener(new OnItemSelectedListener(){
                        @Override
                        public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
                                if(arg2>0)
                                addItemsOnSpinner2(arg2);
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> arg0) {
                                addItemsOnSpinner2(0);
                        }}
                );
        }

        private void addItemsOnSpinner2(int selectedIndex) {

                int positionTop = selectedIndex;

                if(positionTop==0){
                        List<String> list = new ArrayList<String>();
                        list.add("Please Select");
                        ArrayAdapter<String> name0 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
                        name0.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinner2.setAdapter(name0);
                }else if(positionTop==1){
                        List<String> list1 = new ArrayList<String>();
                        list1.add("Please Select");
                        list1.add("item 1");
                        list1.add("item 2");
                        ArrayAdapter<String> name1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list1);
                        name1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinner2.setAdapter(name1);
                }else if(positionTop==2){
                        List<String> list2 = new ArrayList<String>();
                        list2.add("Please Select");
                        list2.add("item 3");
                        list2.add("item 4");
                        ArrayAdapter<String> name2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list2);
                        name2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinner2.setAdapter(name2);
                }
        }

}

Hope this helps!

A: You need to call the addItemsOnSpinner2() function when the first spinner item has got selected.
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
    long arg3) {
addItemsOnSpinner2();}

A: you are setting both spinner at the beginning of the code ( in onCreate). You should populate the second spinner after the spinner1 data is changed

A: yes as the gentlemen before me said.
In order for the second spinner to get the correct index to set the list,
you need to populate it after the first spinner is clicked.
/* wrong answer deleted */
if this is my code i would change addItemsOnSpinner2() into:
private void addItemsOnSpinner2(int selectedIndex){
    int positionTop = selectedIndex;
    //rest is the same
    /* ... */
}

and again insert these into addItemsOnSpinner1():
spinner1.setOnItemSelectedListener(new OnItemSelectedListener(){
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
            if(arg2>0)
            addItemsOnSpinner2(arg2);
        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            addItemsOnSpinner2(0);
        }}
    );

that is just how i would do it
i think many ways works here though
edit2:oh and edit the addItemsOnSpinner2() in onCreate() into addItemsOnSpinner2(0)
edit3:you need to call addItemsOnSpinner2() in onCreate(), otherwise your spinner is empty!
edit4:sorry guys, i made a huge mistake into thinking onItemClickListener could be applied here, shame on me :((
btw, if you want to keep the index (under situation like change of screen orientation or back to foreground ) , it needs more complicated work
but here is a much simpler method:
1.set a global static variable: int selectedIndex;
2.in onCreate, set selectedIndex to 0 if savedInstanceState is null
3.in onCreate, after savedInstanceState is nullcheckd, call addItemsOnSpinner2(selectedIndex)
4.in spinner1's listener, set selectedIndex to selected index.
not guarranteed to work on every machine though:(


Q: how to make the vim plugin "Project" and "Mini Buffer Explorer" work together? As the title says, I need to make these plugins work together well. The mini buffer explorer just automatically opens after I open the second file(press Enter in project plugin window), then Mini Buffer Explorer opens as the third window on the top of my screen.
But after I switch back to project plugin window and press Enter to open the third file, a fourth window opened! It seems project plugin can't overwrite the second file's window.
Project plugin 1.4.1
Mini Buffer Explorer plugin 6.4.0


Q: Make NUnit not stop at first failure I'm running a NUnit test over a list of numbers.
My code goes something like this:
numbers = GetListOfNumbers()
foreach number in numbers
      Assert.IsTrue(TestNumber(number))

My problem is that NUnit will stop the test on the first number it encounters that doesn't pass the test.
Is there anyway to make NUnit still fail the test if any numbers don't pass, but give me the list of all numbers that don't pass?

A: As a workaround, instead of using an Assert.IsTrue like that, you could try something like:
numbers = GetListOfNumbers()
List<number> fails = numbers.Where(currentNum=>!TestNumber(curentNum))
if (fails.Count > 0)
    Assert.Fail(/*Do whatever with list of fails*/)

A: NUnit 2.5 has data-driven testing; this will do exactly what you need.  It'll iterate over all of your data and generate individual test cases for each number.
Link

A: This can be done in MBUnit using a "RowTest" test method.  I'm not aware of a way of doing this in NUnit, however.


Q: How to stop NSTimer with another NSTimer? Note: I am using swift for this project.
I am currently working on my first project and I am trying to stop (invalidate) an NSTimer if a button was not pressed after a certain amount of time. I have found other ways of stopping my NSTimer but none saying how to stop it after a certain amount of time, with that time being reset if the button actually is pressed. Read everything to understand more clearly.
Here is my code now;
@IBOutlet var Text: UILabel!
var timer: NSTimer!
var countdown: Int = 0

@IBAction func StartGame(sender: AnyObject) {
self.countdown = 20
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: "updateCountdown", userInfo: nil, repeats: true)
}

func updateCountdown() {

    self.countdown--

    if self.countdown == 0 {
        self.timer.invalidate()
        self.timer = nil
    }

    let texts: NSArray = ["Test", "Testing"]
    let range: UInt32 = UInt32(texts.count)
    let randomNumber = Int(arc4random_uniform(range))
    let textstring = texts.objectAtIndex(randomNumber)

    self.ColorText.text = textstring as? String
}

@IBAction func PlayerbuttonPRESSED(sender: AnyObject) {
if Text.text == "Test" {
//Something happens
}
if Text.text == "Testing" {
//Something happens
}

What I am dying to know is how I make something else happen if the button was not pressed before ColorText.text was changed! (If the button was not pressed before changing the text after 1.5 seconds).
Ps. Sorry for the long code, I think it is necessary. :-)

A: There are different ways of doing this. One way, you could set bool value to true when the button is pressed then in updateCountdown check to the boolean.
For example:
func updateCountdown() {

     self.countdown--

    if self.countdown == 0 && YOUR_BUTTON_BOOL {
        self.timer.invalidate()
        self.timer = nil
    }

    let texts: NSArray = ["Test", "Testing"]
    let range: UInt32 = UInt32(texts.count)
    let randomNumber = Int(arc4random_uniform(range))
    let textstring = texts.objectAtIndex(randomNumber)

    self.ColorText.text = textstring as? String
}

However, using NSTimer in this fashion where you have it trigger in a short period of time like 1.5 seconds can become inaccurate. After the timer triggers 20 times the time past will be greater than 30 seconds. If accuracy is important you might be better off setting a second timer for 30 seconds. If the button is pressed it invalidates the 30 second timer if the 30 second timer fires it invalidates the 1.5 second timer.


Q: React + GraphQL: dataArray.map is not a function I Just started learning graphQL and Apollo.
Below is the sample client side code using Apollo client.
I am providing data from nodemon express server.
console.log(data) shows the output from the server.
However i was trying to display the query result using the apollo client but i was unbale to do so. I am stuck in this , any help will be appreciated.

import React from "react"
import { Query } from "react-apollo";
import gql from "graphql-tag";

export const ExchangeRates = () => (
    <Query
        query={gql`
      {
        counterparty {
         name
       }
      }
    `}
    >
        {({ loading, error, data }) => {
            if (loading) return
Loading...
;
            if (error) return
Error :(
;

            console.log(data)   // Works fine as expected
            var a= data.map(x=>{
                return x.name
            })

            return
 Data {a}
 // stuck here ..how to display data
        }}

    </Query>
);

The following codes gives an error and says
TypeError: data.map is not a function

However the console.log(data) works fine and the following output:-

A: Your are doing wrong here... your array is inside data.counterparty...
try this
var a= data.counterparty.map(x=>{
                return x.name
            })


Q: doPostback() not refreshing some elements on page correctly Having the following problem:
I have an HTML button which causes a __doPostBack(button.ClientID,'texthere').
Dim button As HtmlButton
button = CType(Me.btnButton, HtmlButton)
button.Attributes.Add("onclick", "__doPostBack('" & btnButton.ClientID & "', 'btnBBHistory');return false;")

In my page_load I have the following:
Dim control_postback = Request("__EVENTARGUMENT")
    If control_postback = "texthere"
            Page.ClientScript.RegisterStartupScript(Me.GetType(), "Script", "ShowWindow();",
    End If

The ShowWindow(); javascript function is displayed using showModalDialog.
  Dim s As New StringBuilder
        s.Append("<script type=""text/javaScript"">")
        s.Append("function ShowWindow() {" & ControlChars.CrLf)
        '  s.Append("var result = window.showModalDialog('" & url & "','','dialogWidth:1200px;dialogHeight:450px;resizable:yes');" & ControlChars.CrLf)
        s.Append("var result = window.showModalDialog('" & url & "','','dialogWidth:1100px;dialogHeight:500px;resizable:yes;help:no;');" & ControlChars.CrLf)
        s.Append("if (result) { " & ControlChars.CrLf)
        ' s.Append("document.getElementById('" & lblwhatever.ClientID & "').innerHTML=result.fullline;" & ControlChars.CrLf)
        s.Append("if (result.text.length || result.quantity.length) { " & ControlChars.CrLf)
        s.Append("document.getElementById('" & txtwhatever.ClientID & "').value=result.text.concat(result.quantity);" & ControlChars.CrLf)
        s.Append("document.getElementById('" & txtqty.ClientID & "').value=result.quantity;" & ControlChars.CrLf)

        s.Append("__doPostBack()" & ControlChars.CrLf)
        s.Append("}" & ControlChars.CrLf)
        s.Append("}" & ControlChars.CrLf)
        s.Append("return false;" & ControlChars.CrLf)
        s.Append("}" & ControlChars.CrLf)
        s.Append("</script>")
        If Not ClientScript.IsClientScriptBlockRegistered("ShowWindow") Then
            ClientScript.RegisterClientScriptBlock(Me.GetType(), "ShowWindow", s.ToString())
        End If

This all works fine and the dialog box with the generated URL is displayed. However, on the originating webpage (the one where the button is initially clicked to produce this dialog box), there is an image (.djvu format). Whenever my code is run, the originating page is refreshed because of the __doPostBack() but in certain version of IE (IE8 and 9 so far) the image does not reload. Is there a chance that the showModalDialog is preventing any further rendering of the page in the background on these versions of IE or that the doPostBack() is not actually doing a complete postback in some way and the image is breaking?
Thanks for any help you might be able to give

A: Fixed: I needed to use window.open instead of showmodaldialog as when using showmodaldialog, the parent/calling page was (i believe) pausing/halting/breaking execution of the parent page until the child page was closed


Q: VB.NET table.sort with multiple columns I have the following but need to add more columns to filter by. I am getting errors with the syntax I am trying.
Dim ldv1 As System.Data.DataView
ldv1 = tbl1.DefaultView
ldv1.Sort = (tbl1.Columns(0).ColumnName) & " Asc" <-- I want to add to this

I am trying to do something like this but failing:
ldv1.Sort = (tbl1.Columns(0).ColumnName) & " Asc",(tbl1.Columns(1).ColumnName) & " Asc"

OR
ldv1.Sort = (tbl1.Columns(0).ColumnName), (tbl1.Columns(1).ColumnName) & " Asc"

Neither seems to be the correct way. How do I sort by more columns?

A: Add a , inside the string after the first Asc.
ldv1.Sort = tbl1.Columns(0).ColumnName + " Asc, " + tbl1.Columns(1).ColumnName + " Asc"


Q: Temporary captured-variables in lambda functions - C++11 I was trying out something like this to pre-populate a map using a vector-list of strings.
The code is self-explanatory:
Constructor(const vector<string>& names) {
  for_each(names.begin(), names.end(),
                     [this, counter = 1](const String& choice) mutable {
                            nameMapping.emplace(choice, counter++);
                        }
  );
}

Something I didnt really understand is how does counter work?
FYI: counter is no-where declared outside of the lambda function.
But yet, I am able to create a local-variable in class-scope and modify it in a mutable lambda fn?
Can someone please help me understand whats going on.

A: When you set counter = 1 you're declaring a new temporary counter equal to 1. The compiler does the work of determining the type. This temporary object is deduced to type int by default, and lives while the lambda is alive.
By setting mutable you can both modify counter and this
Aside: since it appears that you're inserting into a map/unordered map, you're probably better off with the following:
#include <algorithm> // For transform
#include <iterator>  // For inserter

Constructor(const vector<string>& names) {
    auto const example = [counter = 1](const string& item) mutable {
        return {item, counter++};
    };
    std::transform(names.begin(), names.end(),
                   std::inserter(nameMapping, nameMapping.end()), example);
}

By moving the nameMapping call outside of the lambda, you don't have to confuse yourself with what is in scope and what is not.
Also, you can avoid unnecessary captures, and anything else that might confuse yourself or other readers in the future.

A:
But yet, I am able to create a local-variable in class-scope and modify it in a mutable lambda fn?
Can someone please help me understand whats going on.

It's exactly as you said.
Possibly confusing because there's no type given in this particular kind of declaration. Personally I think that was an awful design decision, but there we go.
Imagine it says auto counter = 1 instead; the auto is done for you. The variable then becomes a "member" of the lambda object, giving it state.
The code's not great, because the lambda isn't guaranteed to be applied to the container elements in order. A simple for loop would arguably be much simpler, clearer and predictable:
Constructor(const vector<string>& names)
{
   int counter = 1;
   for (const string& name : names)
      nameMapping.emplace(name, counter++);
}

There's really no reason to complicate matters just for the sake of using "fancy" standard algorithms.


Q: Postgresql - Postgis - how to filter content? I have imported a shapefile that consists of POINT data.
Here is the query:
SELECT a.name,
       ST_Distance(ST_GeographyFromText(ST_AsText(a.geom)),
                   ST_GeographyFromText(ST_AsText(b.geom)))/1000 AS distance
FROM places a, places b
WHERE b.name='Mumbai';

This query displays distances (in KM) of places from 'Mumbai'.
Giving the output:
                       name                       |     distance
--------------------------------------------------+------------------
 Mumbai                                           |                0
 New Delhi                                        | 1159.26223973831
 Pune                                             |  117.86639722221
 Vittalpuram                                      | 1058.49956760668
 Kadapakkam                                       |  1064.4166204267
 Chellampatty                                     | 1136.24329302432
 Srirampur                                        |  205.27117214342
 Bhorvadi                                         |  213.69790081481
 Vaduj                                            |  227.66082105079
 Pushkar                                          |   853.0369297591
 Orcha                                            |  927.67801469371
 Phillaur                                         | 1369.21450470719
 Goraya                                           |  1381.0316667358
 Phagwara                                         | 1390.76210842565
 Ludhiana                                         | 1358.93226658828
 Mohali                                           | 1361.88704243237
 Morinda                                          | 1362.40782426879
 Kurali                                           | 1368.92321753998
 Rupnagar                                         | 1382.46666378301
 Moga                                             | 1335.85239784081
 Pahalgām                                         | 1689.72733587196
 Ambala                                           | 1327.24107571448
 Doraha                                           | 1351.41408180716
 Entrance of Ranjeet Avenue                       | 1351.43744476875
 Shaheed Jasdev Singh Nagar                       | 1353.19967929777
 Jagbir House                                     | 1357.58692404013
 Rania                                            | 1350.48320804851
 Pawa                                             | 1354.30374843403
 Sreenh                                           | 1347.01369530847
 Kaind                                            | 1345.76155280418
 Dharour                                          | 1352.71636605571
 TIBBA                                            | 1350.96268614694
 NAAT                                             |   1351.965780883
 Harnampura                                       | 1350.90891035291
 Nandpur                                          | 1354.12810806732
 Umadpur                                          | 1350.92919575633
 Dugri                                            | 1350.23846455405
 Dehlon intersection                              | 1341.15103218979
 Alwarpet                                         | 1029.21518660807
 Teynampet                                        | 1028.07582220005
 Gopalapuram                                      | 1028.37800837912
 Nandanam                                         | 1028.41251498301
 Raja Annamalai Puram                             | 1029.83876612634
 Abhiramapuram                                    | 1029.72834342923
 CIT Colony                                       | 1029.16938386861
 Sriperumbudur                                    | 1009.05941189302
 Poonamallee                                      | 1015.86523604896

Now I intend to filter out the results so as to view places where distance <= 500. How can I achieve this?

A: Use your query as a subselect:
SELECT *
FROM (SELECT a.name ...) dummy
WHERE distance < 500.0;


Q: HANA Query: CASE WHEN, without SELECT Statment I want to understand the CASE WHEN Statment in SAP HANA Query.
It is now to write a Value in a Column, only if there is a Value in the Column before.
"$[$3.U_chsBestNr2.0]" is the Column before (i get the value of this Column with this Statement).
CASE WHEN $[$3.U_chsBestNr2.0] <> '' THEN
SELECT T1."Name"
FROM OPOR T0
LEFT JOIN "@CHS_BEL_BELEGTYP" T1 ON T0."U_chsBelTyp" = T1."Code"
WHERE T0."DocEntry" = $[$3.U_chsBestNr2.0] AND T0."DocStatus" = 'O'
END CASE

The Error appear always as follow:
...257 sql error: incorrect syntax near "CASE"..


Q: Django; 2 model/class/tables pass into one template Forgive me if I ask something foolish, I very new to coding industry
I been working on Django project to create dashboards to show case monitoring of an hydroponics greenhouse.
So I create two model;
class tank_system(models.Model):
PH = models.DecimalField(default=7.5,max_digits=3, decimal_places=1)
EC = models.DecimalField(default=13.3,max_digits=3, decimal_places=1)
Winlet = models.DecimalField(default=20.1, max_digits=3, decimal_places=1)
Woutlet = models.DecimalField(default=20.3,max_digits=3, decimal_places=1)
WaterLevel = models.IntegerField(default=500)
TempWater = models.IntegerField(default=25)
tanks = models.IntegerField(default=1)
datetime = models.DateTimeField(default=timezone.now())

class ambient (models.Model):
TempRoom = models.IntegerField(default=25)
CO2 = models.DecimalField(default=20.0, max_digits=3, decimal_places=1)
O2 = models.DecimalField(default=20.0,max_digits=3, decimal_places=1)
Humdity = models.IntegerField(default=25)
Room = models.IntegerField(default=1)
datetime = models.DateTimeField(default=timezone.now())

and I render the data of two model into one single template
here my views;
from django.shortcuts import render, get_object_or_404
from CGI.models import tank_system, ambient

def index(request):
    tank = tank_system.objects.all()
    room = ambient.objects.all()
    return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank},{'room': room})

when I try this I only got data form 1 table
Here my html template;
{% extends "base.html" %}
 {% block content %}
{%load staticfiles%}
 {% load static %}

Camera

Ambinet

                <video id="livestream" width="550" height="350" autoplay></video>
                 <canvas class = "my-4 chartjs-render-monitor" id="live_vid" height="1"></canvas>

                    <picture>

                    </picture>

                    {% for ambient in room %}
                         {% if forloop.first %}
                         {{  ambient.Humdity }}
                         {% endif %}
                         {% endfor %}
                    %

                    <picture>

                    </picture>

                    {% for ambient in room %}
                         {% if forloop.first %}
                         {{  ambient.TempRoom }}
                         {% endif %}
                         {% endfor %}
                    C

                    <picture>

                    </picture>

                    {% for ambient in room %}
                         {% if forloop.first %}
                         {{  ambient.CO2 }}
                         {% endif %}
                         {% endfor %}

Water tank

                        <picture>

                        </picture>

                    {% for tank_system in tank %}
                         {% if forloop.first %}
                         {{ tank_system.PH }}
                         {% endif %}
                         {% endfor %}

                        <picture>

                        </picture>

                    {% for tank_system in tank %}
                         {% if forloop.first %}
                         {{ tank_system.EC }}
                         {% endif %}
                         {% endfor %}
                    %

                        <picture>

                        </picture>

                    {% for tank_system in tank %}
                         {% if forloop.first %}
                         {{ tank_system.TempWater }}
                         {% endif %}
                         {% endfor %}
                    C

                        <picture>

                        </picture>

                    {% for tank_system in tank %}
                         {% if forloop.first %}
                         {{ tank_system.Winlet }}
                         {% endif %}
                         {% endfor %}
                    ml/hr

                        <picture>

                        </picture>

                    {% for tank_system in tank %}
                         {% if forloop.first %}
                         {{ tank_system.Woutlet }}
                         {% endif %}
                         {% endfor %}
                    ml/hr

                        <picture>

                        </picture>

                    {% for tank_system in tank %}
                         {% if forloop.first %}
                         {{ tank_system.tanks }}
                         {% endif %}
                         {% endfor %}
                    L

Water data

Room data

here picture better understanding;

If you could help I, really appreciated

A: You have 4 arguments in your render of which 2 is context. It needs only one dictionary with context or you can make a context dictionary variable and pass it as argument in render.
Try this:
from django.shortcuts import render, get_object_or_404
from CGI.models import tank_system, ambient

def index(request):
    tank = tank_system.objects.all()
    room = ambient.objects.all()
    return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank,'room': room})

OR
from django.shortcuts import render, get_object_or_404
from CGI.models import tank_system, ambient

def index(request):
    tank = tank_system.objects.all()
    room = ambient.objects.all()
    context = {
           'tank': tank,
           'room': room
       }
    return render(request, 'CGI/Pages/DashBoard.html',context)

A: You can pass data using two different ways
def index(request):
    tank = tank_system.objects.all()
    room = ambient.objects.all()
    return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank,'room': room})
                  or
    return render(request, 'CGI/Pages/DashBoard.html', locals())
locals() stands for get all local variable/objects and pass to the html as context

A: In your index method, make changes as:
def index(request):
    tank = tank_system.objects.all()
    room = ambient.objects.all()
    return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank, 'room': room})


Q: how to filter join query with Flask and SQLAlchemy Hello I'm trying to query something like this in SQLAlcehmy, Flask and Graphene
select d."name", e."name"
from departments d
join employees e on e.department_id = d.id
where e."name" like '%M%' and d."name" = 'IT'

so, it would return all employee with name contains 'M' in department 'IT'
here's my query in python using sqlalchemy
find_department = graphene.List(Department, name = graphene.String(), employee = graphene.String())
def resolve_find_department(self, info, name, employee):
  like_query = '%{0}%'.format(employee)
  department = (Department.get_query(info)
                          .join(EmployeeModel)
                          .filter(DepartmentModel.name == name)
                          .filter(EmployeeModel.name.ilike(like_query)))

  return department

and in my graphql
{
  findDepartment(name:"IT", employee:"M"){
    name
    employees{
      edges{
        node{
          name
        }
      }
    }
  }
}

and the result is it returns all employee instead of 1 with name contains 'M'
{
  "data": {
    "findDepartment": [
      {
        "name": "IT",
        "employees": {
          "edges": [
            {
              "node": {
                "name": "Chris"
              }
            },
            {
              "node": {
                "name": "Dori"
              }
            },
            {
              "node": {
                "name": "Mario"
              }
            }
          ]
        }
      }
    ]
  }
}

why is that happening? how to show only 1 just like the SQL query returns?
thanks
UPDATE:
the query from SQLAlchemy was fine
SELECT departments.id AS departments_id, departments.name AS departments_name
FROM departments JOIN employees ON departments.id = employees.department_id
WHERE departments.name = 'IT' AND employees.name ILIKE '%M%'

but somehow when it's called using graphql, with query above, it returns all employee instead of the filtered one
how to return only the filtered Employee?

A: I think you need to use an "and_" filter to make sure sqlalchemy returns only rows which fulfil all the requirements (rather than at least one of the filters):
from sqlalchemy import and_
department = (Department.get_query(info)
                      .join(EmployeeModel)
                      .filter(and_(DepartmentModel.name == name, EmployeeModel.name.ilike(like_query)))

not 100% sure if this works with graphene or whatever (i think this is unrelated in this case...). Also check this link: sqlalchemy tutorial
Give it a try!


Q: spring boot rest webservice, how to improve a clean code? i started a project on spring boot using a rest a webservice, when i shared  it between my team they puted some comments :

*

*get method need to be grouped Ex : get/users & get/users/{id} will be get/users/{id}

*remove put method & just use post Ex: post/users/0 add | post/users/{id} update

*make a helper class for Jdbc Template and call it in the repository classes to centralize the code

pls guys help me to solve this i'm so confused, and thank you

A:
get method need to be grouped Ex : get/users & get/users/{id} will be
  get/users/{id}

I do not agree with this. /get/users will be returning List<User> and get/users/{id} will return User that matches with {id}

remove put method & just use post Ex: post/users/0 add |
  post/users/{id} update

Post should be used when you create a new resource. POST is not idempotent. Each time you call a post a new resource will be created.
e.g. Calling POST /Users will create a new User every-time.
PUT on other hands works like upsert. Create if the resource is not present and update/replace if present. Put is idempotent and doesn't change the resource's state even if it's called multiple times.

make a helper class for Jdbc Template and call it in the repository
  classes to centralize the code

Helper classes help to separate the concerns and achieve single responsibility.
However, JdbcTemplate is a ready to use abstraction of JDBC. I don't see any point in creating Helper. You can create a DataAccessObject (DAO) or Repository which has-a JdbcTemplate. Like the two Dao shown below
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public User findUserById(String id){}

    public void addUser(User user){}
}

//    -------
public class BooksDao{
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Book> getAllBooksByType(String type){}

    public void Book getBookByName(String name){}
}

Now, your Dao objects can be called from Controller or if you need to modify data before/after DB operation, best is to have a Service layer between Controller and Dao.
Don't bother too much about recommendations or rules. Stick to the basic OOPS concepts. Those are really easy to understand and implement.
Always:

*

*Encapsulate data variables and methods working on those variables together

*Make sure your class has a Single Responsibility

*Write smaller and testable methods (if you can't write tests to cover your method, then something is wrong with your method)

*Always keep the concerns separate

*Make sure your objects are loosely coupled. (You are already using spring so just use the spring's auto-wiring)


Q: How to override routes in ng-admin? I want to change url in ng-admin state. For example, I need to add a trailing / at the URL for getting a list of users. (http://localhost/api/v1/users/ instead of http://localhost/api/v1/users)

A: The Entity and View classes offer a baseUrl() method, so it's probably not very hard. Just follow the directions from the documentation:

*

*https://github.com/marmelab/ng-admin/blob/master/doc/Configuration-reference.md#entity-configuration

*https://github.com/marmelab/ng-admin/blob/master/doc/Configuration-reference.md#entity-configuration

*https://github.com/marmelab/ng-admin/blob/master/doc/API-mapping.md


Q: how to remove a specific factor level to missing value in r? I got a factor data set df that looks like this:
df <- data.frame(attend = c("yes", "no", "no", "iap", "yes", "yes", "iap"),
           sex = c("male", "female", "female", "male", "female", "male", "female"))

df$attend <- as.factor(df$attend)
df$sex <- as.factor(df$sex)

df

attend
sex

yes
male

no
female

no
female

iap
male

yes
female

yes
male

iap
female

I want to remove only the iap level from the attend variable.(I don't want to remove the entire row, what I'm looking for is to remove the level iap, so that it becomes a missing value under variable attend)
I tried the below code to remove it but it occurs an error saying:
Error in UseMethod("droplevels") :
no applicable method for 'droplevels' applied to an object of class "character".
df$attend <- droplevels(levels(df$attend)[4])

Much appreciated it if someone can help.

A: You can change the levels of the variable -
levels(df$attend)[levels(df$attend) == 'iap'] <- NA
df

#  attend    sex
#1    yes   male
#2     no female
#3     no female
#4   <NA>   male
#5    yes female
#6    yes   male
#7   <NA> female

This will also automatically drop the 'iap' as level.
levels(df$attend)
#[1] "no"  "yes"

Here we can also use forcats::fct_recode to turn specific values to NA.
df$attend <- forcats::fct_recode(df$attend, NULL = 'iap')

A: Another base R solution would be using exclude:
df$attend <- factor(df$attend, exclude = "iap")

  attend    sex
1    yes   male
2     no female
3     no female
4   <NA>   male
5    yes female
6    yes   male
7   <NA> female


Q: string-splitting and arrays In this program for storing high scores I want the user to input a player's name and high score in a single line, for example "eric 87".
After the user enters the last player's name and score, it should then list all at once the scores that were entered. I don't know how to do this when splitting strings like "eric 97". Thanks very much for any help!
const int MAX = 20;
static void Main()
{
    string[ ] player = new string[MAX];
    int index = 0;

    Console.WriteLine("High Scores ");
    Console.WriteLine("Enter each player's name followed by his or her high score.");
    Console.WriteLine("Press enter without input when finished.");

    do {
        Console.Write("Player name and score: ", index + 1);
        string playerScore = Console.ReadLine();
        if (playerScore == "")
            break;
        string[] splitStrings = playerScore.Split();
        string n = splitStrings[0];
        string m = splitStrings[1];

    } while (index < MAX);

    Console.WriteLine("The scores of the player are: ");
    Console.WriteLine("player \t Score \t");

  //  Console.WriteLine(name + " \t" + score);
    // scores would appear here like:
    // george 67
    // wendy 93
    // jared 14

A: Looking at your code you didn't put your player array to use.
However, I would suggest a more object oriented approach.
public class PlayerScoreModel
{
    public int Score{get;set;}

    public string Name {get;set;}
}

Store the player and scores in a List<PlayerScoreModel>.
And when the last user and score has been entered.. simply iterate through the list.
 do {
        Console.Write("Player name and score: ", index + 1);
        string playerScore = Console.ReadLine();
        if (playerScore == "")
            break;
        string[] splitStrings = playerScore.Split();
        PlayerScoreModel playerScoreModel = new PlayerScoreModel() ;

        playerScoreModel.Name = splitStrings[0];
        playerScoreModel.Score = int.Parse(splitStrings[1]);
        playerScoreModels.Add(playerScoreModel) ;

    } while (somecondition);

   foreach(var playerScoreModel in playerScoreModels)
   {
      Console.WriteLine(playerScoreModel.Name +" " playerScoreModel.Score) ;
    }

Provide error checking as necessary.


Q: TypeError: super() takes at least 1 argument (0 given) With this code: https://github.com/SmBe19/praw-OAuth2Util
It's receiving this error:
Traceback (most recent call last):
  File "update_sidebar.py", line 6, in <module>
    o = OAuth2Util.OAuth2Util(r)
  File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 162, in __init__
    self.refresh()
  File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 364, in refresh
    self._get_new_access_information()
  File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 254, in _get_new_access_information
    self._start_webserver(url)
  File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 229, in _start_webserver
    self.server = OAuth2UtilServer(server_address, OAuth2UtilRequestHandler, authorize_url)
  File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 58, in __init__
    super().__init__(server_adress, handler_class, bind_and_activate)
TypeError: super() takes at least 1 argument (0 given)

By doing:
import praw
import OAuth2Util

user_agent = "sidebar helper"
r = praw.Reddit(user_agent=user_agent)
o = OAuth2Util.OAuth2Util(r)

Is the code missing something?

A: According to @Ryan, your problem is that you are running it in Python 2 instead of Python 3. Running it in Python 3 should fix it.


Q: CSS responsive design using em for the layout I have to design a (responsive) website, using only HTML5, CSS3, elastic design, and em as unit measurement. I dont know how to apply em on the width and height properties to make the margins of the main wrapper (i.e. div #page) equal on all sides in relation to the actual screen size.
I have tried the width and height properties with different em-values, but that leads to the margins not being equal. I have tried to find some sort of conversion between em and %, but since em is based on font size it's always the percentage of the font size. I have also tried to instead apply the position property to other containers and elements inside #page.

#page {
    position: relative;
    width: 90%;
    height: 90%;
    top: 1em;
    right: 1em;
    bottom: 1em;
    left: 1em;
}

I want to be able to only use em as measurement unit and have the margins of #page equal in relation to the actual screen size, but the width either becomes longer than the screen size, or the right margin is not equal to the other margins.
Here is a link to JSFiddle with my entire code:
https://jsfiddle.net/binaryglot/8dkn96g0/

A: you can just using margin:0em auto for making the div page stay on the center. But unfortunately you can't make teh height on the center. Here the fiddle for making width and stay on center.
#page {
  position: relative;
  width: 90%;
  height: 90%;
  top: 1em;
  margin:0em auto;
  bottom: 1em;
}

JSfiddle
You can adjust the height using padding--but you can't make it responsive for the height... so far i know.

A:     #page {
    position: fixed;
    width: 90%;
    height: 90%;
    top: 1em;
    right: 1em;
    bottom: 1em;
    left: 1em;
    margin: auto;
    }

Using combination of fixed position and auto margin did the trick. Hope this helps!