text:
Q: Getting Variable does not exist erro when trying to use a picklist value in method I'm trying to pass a picklist value to a method if statement to change up the query based on what is selected form a picklist. When I try to use the if statement below I get a variable does not exist.
I'm using public String SearchField {get;set;} to bring in the picklist values to the controller. Is there a way to use the SearchField Value from the picklist in the method below?
method:
@RemoteAction
global static List<InnerClassAccount> getAccounts(String toQuery) {

    List<InnerClassAccount> ret = new List<InnerClassAccount>();
    List<Schema.FieldSetMember> fields = Schema.SObjectType.Account.fieldSets.Search_Businesses.getFields();
    List<Fields> fieldsInner = new List<Fields>();
    String query = 'SELECT ';
    String SearchField = 'd';

    for(Schema.FieldSetMember f : fields) {
        if(f.getFieldPath().contains('.')) {
            String [] split = f.getFieldPath().split('\\.');
            fieldsInner.add(new Fields(f.getFieldPath(),split[0] + ' '+f.label));
        }else {
            fieldsInner.add(new Fields(f.getFieldPath(),f.label));
        }

        if(f.getFieldPath()!= 'Id' &&  f.getFieldPath()!= 'Name'&& f.getFieldPath()!= 'ShippingAddress' && f.getFieldPath()!= 'BillingAddress'&& f.getFieldPath()!= 'OwnerID' ){
          query += f.getFieldPath() + ', ';
        }
    }

    if (SearchField = 'Name') {
        String filter = '%' + toQuery + '%';
    query += 'Id, Name,ShippingAddress,BillingAddress, OwnerID, TSGADX__MainParentId__c FROM Account WHERE Name LIKE :filter';

    if (SearchField = 'Phone') {
        String filter1 = '%' + toQuery + '%';
        query += 'Id, Name,ShippingAddress,BillingAddress, OwnerID, TSGADX__MainParentId__c FROM Account WHERE Phone LIKE :filter1';

    if (SearchField = 'Address') {
        String filter2 = '%' + toQuery + '%';
        query += 'Id, Name,ShippingAddress,BillingAddress, OwnerID, TSGADX__MainParentId__c FROM Account WHERE BillingAddress LIKE :filter2 or ShippingAddress like :filter2';
    }}}

A: = Is Not Equality
You need to use == instead:
if (SearchField == 'Name') {

Your Braces Are Tangled
Your braces should look like:
if (SearchField == 'Name') {
    String filter = '%' + toQuery + '%';
    query += 'Id, Name,ShippingAddress,BillingAddress, OwnerID, TSGADX__MainParentId__c FROM Account WHERE Name LIKE :filter';
}
if (SearchField == 'Phone') {
    String filter1 = '%' + toQuery + '%';
    query += 'Id, Name,ShippingAddress,BillingAddress, OwnerID, TSGADX__MainParentId__c FROM Account WHERE Phone LIKE :filter1';
}
if (SearchField == 'Address') {
    String filter2 = '%' + toQuery + '%';
    query += 'Id, Name,ShippingAddress,BillingAddress, OwnerID, TSGADX__MainParentId__c FROM Account WHERE BillingAddress LIKE :filter2 or ShippingAddress like :filter2';
}

You Cannot Access Instance Variables In Static Code
You need to pass in the SearchField parameter:
@RemoteAction
global static List<InnerClassAccount> getAccounts(String SearchField, String toQuery) {

A: Since the method is static, it can only work with parameters that you pass to it, and by default any controller instance variables are not visible (unless you pass the whole controller into the method).
Are you able to declare the method like so?
global static List getAccounts(String toQuery, String SearchField)


text:
Q: os.walk not parsing a few directories I am kinda new to python and right now I am trying out some stuff, specifically :
recurse through all the directories and files and print the file sizes using os.walk.
My problem is, that the program does not recurse through a few directories although files are present in those directories. An example in my machine would be the directory Python2.7. This is inside the /usr directory. When I give the top path as /usr, this directory is not parsed. But when I specifically mention the path to Python2.7 directory, then it does parse through it. Can anyone help me out by pointing what is wrong ?
Here is my code :
from os import walk, listdir, stat
from os.path import join, isdir, isfile, islink, getsize, abspath, dirname, realpath
from stat import ST_INO as st_ino
from sets import Set

def determine_parent_directory( root ):
     #print "parent-dirname : ", dirname( realpath( root ) )
     return stat( dirname( abspath( root ) ) ).st_ino

def determine_size( root, file ):
    size_type = ""
    file_size = getsize( abspath( ( join( root, file ) ) ) )
    if file_size < 1024:
        size_type = "bytes"
    else:
    if file_size > 1024:
        file_size /= 1024
        size_type = "Kb"
    if file_size > 1024:
        file_size /= 1024
        size_type = "Mb"
    if file_size > 1024:
        file_size /= 1024
        size_type = "Gb"
    if file_size > 1024:
        file_size /= 1024
        size_type = "Tb"

    return [file_size, size_type]

def walk_through( path ):
    total_size = 0
    for root, dirs, files in walk( path ):
        print root.split( "/" )[-1]
        print "\n"

        for file in files:
            if islink( abspath( join( root, file ) ) ):
                print "link"
                continue
            #total_size += determine_size( root, file )[0]
            file_size, size_type = determine_size( root, file )
            print "\t\t\t{0} -- {1} {2}".format ( file, file_size, size_type )
            #total_size += file_size
    print "\n"
    #print total_size

def get_path_user():
    default_path = "/usr"
    walk_through( default_path )

if __name__ == '__main__':
    get_path_user()

A: Is it a symbolic link?

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
By default, walk() will not walk down into symbolic links that resolve to directories. Set followlinks to True to visit directories pointed to by symlinks, on systems that support them.
Note: Be aware that setting followlinks to True can lead to infinite recursion if a link points to a parent directory of itself. walk() does not keep track of the directories it visited already.

A: Check the permissions on those directories - does the user account that the script is running under have rights to those directories?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show another window from mainwindow in QT Platform: QT, Windows XP
I am new to Qt. I want to show another window(what to do to open it as dialog) from mainwindow. I did "add New Item ->Qt Designer Form Class", named it say MyWindow. But how to show this MyWindow from mainwindow ?

A: *

*Implement a slot in your QMainWindow where you will open your new Window,

*Place a widget on your QMainWindow,

*Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:
MainWindow.h
// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp
// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.


text:
Q: angularjs where to start service I want to start a service in angularjs in function app.run like this:
app.run(function($rootScope, $location, $timeout, MessagesService) {
  if(!MessagesService.isRunning()){
    MessagesService.startService();
  }
}

the problem is that app.run is called twice, and even if messageservice was started already, it runs another instance of a service... service should be singleton so I don't understand what is happening. Or maybe this is a bad function to start a service in?
///edited
I paste whole app.run
app.run(function($rootScope, $location, $timeout, AuthenticationService, FlashService, MessagesService, ContactsService) {

  if(!MessagesService.isRunning()){
    MessagesService.startService();
  }

  if(!ContactsService.isRunning()){
    ContactsService.startService();
  }

  $rootScope.newContactReq = 0;
  $rootScope.newMsgCount = 0;
  var routesThatNotRequireAuth = ['/login','/register'];

  $rootScope.$on('$routeChangeStart', function(event, next, current) {
    if(!_(routesThatNotRequireAuth).contains($location.path())) {
      if(!AuthenticationService.isLoggedIn()){
        $location.path('/login');
        FlashService.show("Please log in to continue.");
      }
    }
  });

  $rootScope.$watch(function() {
    return $location.path();
  },
  function(a){
    if(!AuthenticationService.isLoggedIn()) {
      $rootScope.isUserAuth = 0;
    }
    else{
      $rootScope.isUserAuth = 1;
    }
  });

});

even when I do something like
if($rootScope.service === undefined)
$rootScope.service = 1;

it than runs the app.run for second time and $rootScope.service is undefined again...


text:
Q: MXE record on AWS Route53 Namecheap offers a handy external mail service in their Advanced DNS called MXE. You just put in the IP address of the account you have created elsewhere in cPanel and you can collect external email. Works great.
I am switching over to Route53 and hope to do the same, but there is no MXE option available in the list? How can I replicate this in Route53?

*

*CName points to Cloudfront in Route53 which in turn points to S3 website hosted bucket

*Mail hosted at 154.32.45.2, running on a cPanel

I tried adding an MX record with "10  155.94.234.2" but it doesn't seem to produce the same results as MXE on Namecheap
How can I replicate this in Route53?

A: So the correct answer was to add an mx record ( 0:mail.mydomain.com ) and create an A record for mail.mydomain.com that pointed to the ip address for the domain on cpanel.


text:
Q: What is the problem in my code how to style my code properly What is the problem in my code how to style my code properly I want that the frontend developer text and ReactJS website text move upside a little big I am a beginner I am learning from course, and they have given this exercise to do I have almost completed it just this text is not styling properly pls anyone tell how to style it properly you all can also check my code I will provide you

React file code
import React from 'react'
import './Info.css';
import About from './About';
import logo from './logo.jpg';
import Interest from './Interest';
import Socail from './Socail';

function Info() {
    return (
        <>

React learner

Frontend Developer

            reactjs.website

            <button className='e-button'>Email</button>

        <About/>
        <Interest/>
        <Socail/>
        </>
    )
}

export default Info

css file code
img {
    position: absolute;
    width: 317px;
    height: 317px;
    left: 116px;
    top: 44px;
    border-radius: 10px 10px 0px 0px;
}

.info-body {
    position: absolute;
    width: 317px;
    height: 399px;
    left: 116px;
    top: 361px;

    background: #1A1B21;

}

.name-text {
    width: 178.06px;
    height: 25.81px;
    top: 382px;
    font-style: normal;
    font-weight: 700;
    font-size: 25px;
    line-height: 30px;
    text-align: center;
    color: #FFFFFF;
    margin-left: 20%;
}

.pos {
    width: 178.06px;
    height: 14.19px;
    font-style: normal;
    font-weight: 400;
    font-size: 12.8px;
    line-height: 15px;
    text-align: center;
    margin-left: 20%;
    color: #F3BF99;
    margin-bottom: 10%;
}

small {
    font-style: normal;
    font-weight: 400;
    font-size: 11px;
    line-height: 150%;
    text-align: center;
    color: #F5F5F5;
    margin-left: 35%;
    margin-bottom: 90px;
}

.e-button{
 box-sizing: border-box;
/* Auto layout */
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
padding: 9px 13px 9px 11px;
gap: 8px;
width: 247px;
height: 34px;
left: 151px;
top: 469px;

/* white */

background: #FFFFFF;
/* gray/300 */

border: 1px solid #D1D5DB;
/* shadow/sm */

box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.05);
border-radius: 6px;
margin-left: 10%;
}

A: Here I created a little example for you that somewhat gives you what you need. Of course, you can still adjust a few things.
https://stackblitz.com/edit/react-ts-jamyyh
I only made changes inside Info.css, so just take a look at this file.


text:
Q: AngularJs http request concats my data into a JSON key Sometimes a behavior is so bizarre that I don't even know how to begin to google it. I'm fairly new at Angular, and I am trying to send POST data to my node server from the client. Here is the controller on the client side:
var app = angular.module("groomer", []);
app.controller("gCtrl", function($scope, $http) {
    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
    $scope.send = function() {
        $http({
            method : "POST",
            url : "/gUpdate",
            data: {
                gName:$scope.gName,
                gPhone:$scope.gPhone,
                gWebsite:$scope.gWebsite,
                gEmail:$scope.gEmail,
                gCustAcct:$scope.gCustAcct,
                gAddress:$scope.gAddress,
                gNotes:$scope.gNotes
            }
        }).then(function success(response) {
            alert(console.log('Success!'));
        }, function error(response) {
            alert(console.log('Booooooo'));
        });
    };
});

What I naively imagine ought to show up at the server is:
    req.body = {
        gName:'a',
        gPhone:'b',
        gWebsite:'c',
        gEmail:'d',
        gCustAcct:'e',
        gAddress:'f',
        gNotes:'g'
    }

But things get weird. What actually shows up at the server as the request body is:
{"{\"gName\":\"a\",\"gPhone\":\"b\",\"gWebsite\":\"c\",\"gEmail\":\"d\",\"gCustAcct\":\"e\",\"gAddress\":\"f\",\"gNotes\":\"g\"}":""}

In case it takes you a second to see what's happening here, that's all of my JSON keys and data in an object, double-quoted, escaped, concatenated as a string, and passed to the server inside an object as a JSON key corresponding to an empty value.
//so
var lifeMakesSense = {gName:'a',gPhone:'b',gWebsite:'c',gEmail:'d',gCustAcct:'e',gAddress:'f',gNotes:'g'}
//becomes
var waitNo = "{\"gName\":\"a\",\"gPhone\":\"b\",\"gWebsite\":\"c\",\"gEmail\":\"d\",\"gCustAcct\":\"e\",\"gAddress\":\"f\",\"gNotes\":\"g\"}"
//then
var whatEven = {waitNo:""} // nailed it

Thoughts?


text:
Q: mouseover animation weird behaviour I'm creating a simple animation with jquery.
The animation consists on a div being slided left when the mouse hovers it.
This is my html:

            Some useful content

This is the js:
function over(element) {
    $(element).stop().animate({left: "-250"}, 500);
}

function out(element) {
    $(element).stop().animate({left: "0"}, 500);
}

This is the css:
.item {
    position: relative;
    width: 300px;
    height: 107px;
    overflow:hidden;
}

.item .content {
    position: absolute;
    top:0;
    left:0;
    width: 600px;
    height: 107px;
}

.item .content .image {
    position:absolute;
    top: 0;
    left: 0;
}
.item .content .text{
    position:absolute;
    top: 0;
    left: 300px;
    width: 250px
}

.item {
    border: 1px solid black;
}

The animation works properly, but I noticed that if you move the cursor over the left border of the .image div while the animation is running, it pauses for a moment and then resumes.
I don't know how to explain this better, so here you can find a JSFiddle, and here you can find a video that demonstrates the behaviour
My question is: Why is the animation behaving like this? How can I make the animation continue without pausing?

A: Use mouseenter and mouseleave instead

DEMO

A: Your jsfiddle is working for me. Also, its better for you to use the $(el).hover() function jQuery provides, for example:
$('.content').hover(function() {
    // Mouseover
}, function() {
    // Mouseout
});

A: Well, you can use your hover event on the parent element (in this case .item) and animate the child element (.content). If you're using jQuery, just use .hover () instead of those two mouse events.

A: When you move the cursor out of the image div then a mouseout event fires - you move out of the image - and the out function is called, making the animation stop. Right after that the mouseover event fires - you move over the text - and the over function is called.
You attached the event handlers to the content div, i.e. they are called whenever the event fires on itself, but also when the event fires on one of it's descendants.
The reason why it's working with mousenter and mouseleave is that those events are handled differently by the browser. But be aware that they are not supported by all browsers.


text:
Q: Custom Smarty functions In Smarty i want to be able to write {widget 15} or {widget id=15} , so the output will be the return value of PHP function
function widget($id){
    echo 'hi '.$id;
}

is it possible ?

A: Smarty allows you to create such custom functions easily: see the official reference.


text:
Q: Pass argument to controller on submit So, i started learning MVC, and i need to pass an email to a controller. (Trying to make a standard email signup)
Therefore i have an input and a button which (should) pass the input to an argument accepting controller and then redirect to another view.
I have the following controllers:
public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(string mail)
{
    person = new EmailSignup{Email = mail};
    return RedirectToAction("details");
}

public ActionResult details()
{
    return View(person);
}

This is what i have in my View:
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    <form class="col-md-12">

            Sign up for newsletter
            <input type="Email" class="form-control" style="display:inline-block; max-width:200px" id="mail" placeholder="Example@Example.com" />
            <button type="submit" class="btn btn-default" style="display:inline-block" id="emailSignup">Signup</button>

    </form>
}

It redirects to my "details" view, but my email is not showing.
Furthermore, is this best practice? would i want to do it like this?

A: @using (Html.BeginForm("Index", "Home", FormMethod.Post)) renders a form, you don't need a second one inside it (if you need to add the class, you can use an overload of Html.BeginForm). Your input contains an id property, but not a name property. name is what's used when an action happens inside a form.


text:
Q: Sql query to get the GrandFather name by doing a self join Can any one please give me the query to get the child name and his grand fathers name For eg - if i have a table Relationships in the i have childid and fatherid columns so how will i get the grandfather,
i can easily get the father name by using a join but for grandfather i need to do joins 2 times so can any one help me with this
D.Mahesh

A: Just add an additional join similar to the one you already have.
 select grandparent.name, child.name
 from Relationships child
 inner join Relationships parent
  on child.parentid = parent.id
 inner join Relationships grandparent
  on parent.parentid = grandparent.id

A: I think its possible with single join as below-
select t2.fatherid as grandfather
from table1 as t1
inner join table1 as t2 on t1.fatherid=t2.childid
where t1.childid='grandson_id';


text:
Q: Removing a 'non-gap' gap from a polygon that straddles +/- 180 longitude; looking for an R-based, code solution I am working with a set of polygons from here: http://lme.edc.uri.edu/index.php/digital-data.  In the artic, there are several polygons that straddle the +/- 180 longitude line.
These are single polygons (only one entry in attribute table), yet they have overlapping edges along this boundary.  (i.e., if I look at a 1:1 scale, there is no gap; I assume there are repeated vertices).  These internal gaps in the polygons are causing some issues with reprojection (e.g., to Mollweide, where the polygons wrap across the globe) and area calculations, and I don't think moving the center of the map around will help.

I may have missed a good solution, but most people are solving slightly different: a) overlapping different polygons that they need to snap together, or b) a 'true' gap/slice out of a polygon that they want to mend.
My goal is the following:
1) identify polygons that have this kind of internal 'non-gap'
2) remove the 'non-gaps' from the polygons, creating a single set of non-overlapping vertices
I would like to know if there is a way to achieve this in R.  I have enough facility with R to import of shapefiles, change projections, and make area calculations, but I have cobbled this together from R documentation and stackexchange.  I do not need you to write the code out for me (though I would not object), but I am hoping you can point to a plausible approach, perhaps with some psuedocode or at least identification of useful tools/packages.


text:
Q: Pig 0.12 Nested Foreach not working properly I've been trying to do this for a while and can't seem to figure it out and it's a bit hard to look for a fix for my problem.
I have a relation that I previously grouped by user_id and listing_id and after generating and flattened the output I got this:
    test: {user_id: bytearray,listing_id: bytearray,hotness: long}

So my next step is to group by user, order by hotness and limit the amount of listings per user to 20.
grped = GROUP test BY user_id;
grped_sorted = FOREACH grped {
    sorted = order test BY hotness desc;
    top1   = limit sorted 20;
    listings = FOREACH top1 GENERATE FLATTEN((bytearray)top1.listing_id) as listing_id;
         GENERATE group as user_id, FLATTEN(listings.($0)) as listing_ids;
   };

But this seems to be getting me the error, with information that was previously stripped from the listings details:
Scalar has more than one row in the output.

Please, I need help on this.
Is there a way to do this? Can I use some UDF from DataFu?
Creating my own UDF is out of the question.
Thanks in advance.

A: I think it should work if the code looks like this
grped = GROUP test BY user_id;
grped_sorted = FOREACH grped {
    sorted = order test BY hotness desc;
    top1   = limit sorted 20;
    GENERATE group as user_id, top1.listing_id as listing_ids;
};

Output of this would be something like
grped_sorted: {user_id: bytearray,listing_ids: {(listing_id: bytearray)}}

Not sure if this is what you want though.


text:
Q: Edit distance with varying dictionaries My question is similar to Algorithm to transform one word to another through valid words
But with is a major difference. I have one fixed word say "JAMES" and varying dictionaries as i/p. Ofcourse, I can't preprocess dictionary now.
So I have to find the minimum cost for processing "JAMES" to "JOHNY" with different dictionaries as input.
Is there anyway I could preprocess the word "JAMES" so that I need to perform minimum number of edit distance calculations at run time? What do you guys suggest?

A: I am assuming the rules are similar to the question you cited i.e. only single edit is allowed at a time, and each intermediate word should be present in the given dictionary.

*

*Create single edit versions of source string to destination string. for eg:
JOMES
JAHES
JAMNS
JAMEY

Recurse for each of these words and keep creating nodes for every unique word.  Just create edges if the node is already is created.  This completes the preprocessing.
Now given a dictionary, find all the first level words in dictionary.  For all matches, further find all the second level words and so on, till you reach destination word.

A: First, you need to properly define your rules - is an "edit" allowed to add or delete multiple characters, substitute one character etc.?
Anyway - I'd just start with the obvious - create a graph where each word links to all those it can be directly edited into.  Then, use recursion with a depth limit, marking visited elements as "dirty" to avoid cycles, then see if there's a one-edit solution, two-edit solution etc. until you find a solution or all paths are dirty at that depth.  (If you record the depth being attempted in the "dirty" member, you don't have to worry about cleaning them out each time you increment the depth limit.  You could also mark all-dirty sub-trees to avoid recursing into them again.)


text:
Q: How to group by the partial value of the column in pandas? I have some data in the pandas data frame as following where I converted the currency and the value earlier to the USD from CYN (Chinese Yuan)
      currency   port  supplier_id     value
0         USD  CNAQG           35  118.8344
1         USD  CNAQG           19  121.0082
2         USD  CNAQG           49   86.9520
3         USD  CNAQG           54  112.3130
4         USD  CNAQG          113  113.7622
5         USD  CNAQG            5  114.4868
6         USD  CNAQG           55  111.5884
7         USD  CNAQG           81  117.3852
8         USD  CNAQG            2  111.5884
6651      USD  USTPA           14  420.0000
6652      USD  USTPA           56  420.0000
6653      USD  USTPA          113  420.0000
6654      USD  USTPA            5  500.0000
6655      USD  USTPA           55  500.0000
6656      USD  USTPA          193  390.0000
6657      USD  USTPA           74  450.0000
6658      USD  USTPA           35  420.0000
6659      USD  USTPA           54  420.0000
6660      USD  USTPA          231  450.0000

The df.info() prints the following,
<class 'pandas.core.frame.DataFrame'>
Int64Index: 6652 entries, 0 to 6660
Data columns (total 4 columns):
currency       6652 non-null object
port           6652 non-null object
supplier_id    6652 non-null int64
value          6652 non-null float64
dtypes: float64(1), int64(1), object(2)
memory usage: 259.8+ KB
None

The first 2 letter of the port indicates country and I have a map for that,
COUNTRIES = {
    "CN": "CHINA",
    "US": "USA"
}

I would like to group the data based on the country where the port is situated and
the intention will be to visualize the list of values per country in a meaningful way. I appreciate any suggestion of what kind of graph would be appropriate for the job done.

A: You can filter and select values from a dataframe using pandas boolean indexing and pandas.Series.str.startswith. For example following line gives you rows that starts with "US". Which you can store however you want.
df.loc[df['port'].str.startswith('US')]

This should give you a dictionary of dataframes per country in your COUNTRIES dict.
country_values = {}
for key in countries:
    country_values[key] = df.loc[df['port'].str.startswith(key, na=False)]

A: I think you need pivot and then plot by plot.bar or plot:
df1 = pd.pivot(index=df['supplier_id'],
               columns = df['port'].str[:2].map(COUNTRIES),
               values=df['value']).fillna(0)
print (df1)
port            CHINA    USA
supplier_id
2            111.5884    0.0
5            114.4868  500.0
14             0.0000  420.0
19           121.0082    0.0
35           118.8344  420.0
49            86.9520    0.0
54           112.3130  420.0
55           111.5884  500.0
56             0.0000  420.0
74             0.0000  450.0
81           117.3852    0.0
113          113.7622  420.0
193            0.0000  390.0
231            0.0000  450.0

df1.plot.bar()

df1.plot()

But if error:

ValueError: Index contains duplicate entries, cannot reshape

then need pivot_table with some aggregate function mean, sum... (default function is 'mean'):
print (df)
     currency   port  supplier_id     value
0         USD  CNAQG           35  118.8344
1         USD  CNAQG           19  121.0082
2         USD  CNAQG           49   86.9520
3         USD  CNAQG           54  112.3130
4         USD  CNAQG          113  113.7622
5         USD  CNAQG            5  114.4868
6         USD  CNAQG           55  111.5884
7         USD  CNAQG           81  117.3852
8         USD  CNAQG            2  111.5884
6651      USD  USTPA           14  420.0000
6652      USD  USTPA           56  420.0000
6653      USD  USTPA          113  420.0000
6654      USD  USTPA            5  500.0000
6655      USD  USTPA           55  500.0000
6656      USD  USTPA          193  390.0000
6657      USD  USTPA           74  450.0000
6658      USD  USTPA           35  420.0000
6659      USD  USTPA           54  420.0000
6660      USD  USTPA          231  450.0000 <-duplicates for USTPA, 231
6660      USD  USTPA          231  800.0000 <-duplicates for USTPA, 231

COUNTRIES = {
    "CN": "CHINA",
    "US": "USA"
}

df1 = pd.pivot_table(df,
                     index='supplier_id',
                     columns = df['port'].str[:2].map(COUNTRIES),
                     values='value',
                     aggfunc=np.mean,
                     fill_value=0)
print (df1)
port            CHINA  USA
supplier_id
2            111.5884    0
5            114.4868  500
14             0.0000  420
19           121.0082    0
35           118.8344  420
49            86.9520    0
54           112.3130  420
55           111.5884  500
56             0.0000  420
74             0.0000  450
81           117.3852    0
113          113.7622  420
193            0.0000  390
231            0.0000  625 <-mean (450 + 800) /2

df1.plot.bar()

Alternative solution with groupby and mean:
df1 = df.groupby(['supplier_id', df['port'].str[:2].map(COUNTRIES)])['value']
        .mean()
        .unstack(fill_value=0)
print (df1)
port            CHINA    USA
supplier_id
2            111.5884    0.0
5            114.4868  500.0
14             0.0000  420.0
19           121.0082    0.0
35           118.8344  420.0
49            86.9520    0.0
54           112.3130  420.0
55           111.5884  500.0
56             0.0000  420.0
74             0.0000  450.0
81           117.3852    0.0
113          113.7622  420.0
193            0.0000  390.0
231            0.0000  625.0


text:
Q: Android Studio - XML image buttons and text won't fit the size So, I am creating a workout app and getting problems with imageButtons and text.
Screen-1
content_app_layout_main.xml
<?xml version="1.0" encoding="utf-8"?>

<ScrollView android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android" >

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="hr.app.liftme.liftmehr.AppLayoutMain"
        android:orientation="vertical"
        tools:showIn="@layout/activity_app_layout_main"
    android:weightSum="1">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/gornjiLayoutIkone"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="50dp">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="110dp"
            android:id="@+id/imageButtonVjezbe"
            android:background="@drawable/ikona_vjezbe"
            android:layout_weight="1"
            android:layout_marginRight="8dp" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="110dp"
            android:id="@+id/imageButtonProgramiTreninga"
            android:background="@drawable/ikona_programi"
            android:layout_weight="1"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:onClick="ProgramiTreninga"/>

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="110dp"
            android:id="@+id/imageButtonPopisTeretana"
            android:background="@drawable/ikona_popisteretana"
            android:layout_weight="1"
            android:layout_marginLeft="8dp" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/gornjiLayoutIkone"
        android:id="@+id/gornjiLayoutImena"
        android:layout_marginBottom="5dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Vježbe"
            android:id="@+id/textViewVjezbe"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:textColor="#000000" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Programi \n treninga"
            android:id="@+id/textViewProgramiTreninga"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:textColor="#000000" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Popis \n teretana"
            android:id="@+id/textViewPopisTeretana"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:textColor="#000000" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/gornjiLayoutImena"
        android:id="@+id/srednjiLayoutIkone"
        android:layout_marginBottom="5dp">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="110dp"
            android:id="@+id/imageButtonPrehrana"
            android:layout_weight="1"
            android:layout_marginRight="8dp"
            android:background="@drawable/ikona_prehrana" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="110dp"
            android:id="@+id/imageButtonDodaciPrehrani"
            android:layout_weight="1"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:background="@drawable/ikona_dodaciprehrani" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="110dp"
            android:id="@+id/imageButtonTrgovineSportskomPrehranom"
            android:layout_weight="1"
            android:layout_marginLeft="8dp"
            android:background="@drawable/ikona_popistrgovina" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/srednjiLayoutIkone"
        android:layout_marginBottom="5dp"
        android:id="@+id/srednjiLayoutImena">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Prehrana"
            android:id="@+id/textViewPrehrana"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:textColor="#000000" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Dodaci \n prehrani"
            android:id="@+id/textViewDodaciPrehrani"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:textColor="#000000" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Trgovine \n sportskom \n prehranom"
            android:id="@+id/textViewTrgovineSportskomPrehranom"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:textColor="#000000" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/srednjiLayoutImena"
        android:id="@+id/donjiLayoutIkone"
        android:layout_marginBottom="5dp">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="110dp"
            android:id="@+id/imageButtonSavjeti"
            android:layout_weight="1"
            android:layout_marginRight="8dp"
            android:background="@drawable/ikona_savjeti"
            android:onClick="Savjeti"/>

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="110dp"
            android:id="@+id/imageButtonKalkulatori"
            android:layout_weight="1"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:background="@drawable/ikona_kalkulatori" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="110dp"
            android:id="@+id/imageButtonKontakt"
            android:layout_weight="1"
            android:layout_marginLeft="8dp"
            android:background="@drawable/ikona_kontakt"
            android:onClick="Kontakt"/>
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/donjiLayoutIkone"
        android:id="@+id/donjiLayoutImena">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Savjeti"
            android:id="@+id/textViewSavjeti"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:textColor="#000000" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Kalkulatori"
            android:id="@+id/textViewKalkulatori"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:textColor="#000000" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Kontakt"
            android:id="@+id/textViewKontakt"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:textColor="#000000" />
    </LinearLayout>

</LinearLayout>
</ScrollView>

As you can see, main layout icons are OK, only text is not alligned properly. I don't know should I use layout:margin to align them, I think that won't be good because various screen sizes. Icons look good when there are exacly 3 in a row.
Screen-2
content_programi_treninga.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="hr.app.liftme.liftmehr.ProgramiTreninga"
    tools:showIn="@layout/activity_programi_treninga">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="110dp"
            android:id="@+id/imageButtonProgramiBodybuilding"
            android:background="@drawable/ikona_programi_bodybuilding"
            android:layout_weight="1"
            android:adjustViewBounds="false"
            android:layout_marginRight="15dp"
            android:onClick="ProgramiBodybuilding"/>

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="110dp"
            android:id="@+id/imageButtonProgramiPowerlifting"
            android:background="@drawable/ikona_programi_powerlifting"
            android:layout_weight="1"
            android:adjustViewBounds="false"
            android:layout_marginLeft="15dp"
            android:onClick="ProgramiPowerlifting"
            />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayout"
        android:id="@+id/linearLayout2">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Bodybuilding"
            android:id="@+id/textViewProgramiBodybuilding"
            android:textColor="#000000"
            android:gravity="center_horizontal"
            android:layout_weight="1"
            android:layout_marginTop="5dp"
            android:onClick="ProgramiBodybuilding"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Powerlifting"
            android:id="@+id/textView8"
            android:textColor="#000000"
            android:gravity="center_horizontal"
            android:layout_weight="1"
            android:layout_marginTop="5dp"
            android:onClick="ProgramiPowerlifting"/>
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayout2"
        android:gravity="center_horizontal"
        android:layout_marginBottom="5dp"
        android:id="@+id/linearLayout3">

        <ImageButton
            android:layout_width="115dp"
            android:layout_height="115dp"
            android:id="@+id/imageButtonPowerbuilding"
            android:background="@drawable/ikona_programi_powerbuilding"
            android:layout_weight="0"
            android:layout_marginTop="10dp"
            android:onClick="ProgramiPowerBuilding"/>
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/linearLayout3"
        android:gravity="center_horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Power \nBuilding"
            android:id="@+id/textView7"
            android:textColor="#000000"
            android:gravity="center" />
    </LinearLayout>
</RelativeLayout>

As you can see, it doesn't look good with 2 in a row.
I created various icon sizes, from ldpi screen to xxxhdpi screen and when I add them on my layout editor, they are so small so I am using layout:height to correct that. But I don't think that's a good idea because of different screen sizes.
So my question is, what should I do to fix this so it would be perfectly alligned and imageButtons big and in 1:1 ratio?
If you need me to upload some code, just tell me what code and I'll upload it ASAP!
Thanks!


text:
Q: Adding a new column to existing JQ GRID I am working on AbanteCart in which there is use of JQgrid to show the order related information in tabular form. Now , I want to add a new column to this table. The code I have tried till now goes as follow:
    $grid_settings['colNames'] = array(
        $this->language->get('column_order'),
        $this->language->get('column_name'),

        $this->language->get('column_status'),
        $this->language->get('column_mode'),//Column Name that I added
        $this->language->get('column_date_added'),
        $this->language->get('column_total'),
    );
    $grid_settings['colModel'] = array(
        array('name' => 'order_id',
            'index' => 'order_id',
            'align' => 'center',),
        array('name' => 'name',
            'index' => 'name',
            'align' => 'center'),
        array('name' => 'status',
            'index' => 'status',
            'align' => 'center',
            'search' => false),
            array('name' => 'payment',//Column data that I added
            'index' => 'payment',
            'align' => 'center',
            'search' => false),
        array('name' => 'date_added',
            'index' => 'date_added',
            'align' => 'center',
            'search' => false),
        array('name' => 'total',
            'index' => 'total',
            'align' => 'center'),
    );

These are the two changes I made up . But it only shows the column name in grid but is not showing related data to that column. Is there something else where I need to change code for showing changes in JQgrid??
name,status,payment etc variables are from database.
Thanks in advance for any help.

A: It's important to understand that jqGrid creates the grid with all internal structures once. jqGrid don't provide a method which allows to add new column. So you have the following alternatives:

*

*use GridUnload to "destroy" the grid back to empty <table> and recreate the grid with new columns (see the answer)

*create grid with additional hidden columns and make hidden column visible using showCol when you need to add new column. In the way you will have the same effect as by adding the column.

By the way if you load named property of data in the grid (your JSON input data looks like {"order_id":"123", "name": "abc" , "status": "OK"...}) you can define colModel as
colModel: [
    {name: "c1", key: true, jsonmap: "order_id"},
    {name: "c2", jsonmap: "name"},
    {name: "c3", jsonmap: "status"},
    ...
]

using generic names c1 c2, c3, ... for the columns. In the way you can easy modify the value of jsonmap at the runtime. You can set hidden: true property or remove it etc. The answer shows how to use beforeProcessing to modify colModel based on the server response. In the way you can makes jqGrid full dynamical.


text:
Q: Указание в rsync абсолютного пути с использованием ~ связанный вопрос: Подстановка переменной пути в rsync

Задаю NEW_FILE_PATH через read:
read -a NEW_FILE_PATH

Ввожу ~/gb/174_3/
rsync -avzP --rsh="sshpass -p $password ssh -l ts -o StrictHostKeyChecking=no" stalin@box:/home/jaime/test.txt ${NEW_FILE_PATH}

receiving incremental file list
rsync: ERROR: cannot stat destination "/home/jaime/bash/~/gb/174_3/": Not a directory (20)
rsync error: errors selecting input/output files, dirs (code 3) at main.c(652) [Receiver=3.1.1]

Я ожидаю, что копирование произойдёт в ~/gb/174_3/, а происходит в /home/jaime/bash/~/gb/174_3/.
Как дать понять rsync, что указан абсолютный путь, т.е. чтобы копирование происходило в ~/gb/174_3/?

A: тут возникает некоторое количество «подводных камней».
во-первых, процесс, запрашивающий ввод от пользователя икс, может выполняться от имени пользователя игрек. соответственно, домашние каталоги «с точки зрения» скрипта и с точки зрения пользователя икс — будут совершенно разными.
во-вторых, встаёт вопрос безопасности.
ведь решение «в лоб«
eval NEW_FILE_PATH=$NEW_FILE_PATH

может привести к весьма «интересным» последствиям. например, если пользователь введёт что-нибудь вроде ;rm -rf *.
более безопасным будет что-нибудь вроде:
NEW_FILE_PATH="${NEW_FILE_PATH/#\~/$HOME}"


text:
Q: quotient group inheritance of some properties from original group Let us say that there is the group with addition modulo 6:
$G = \{0,1,2,3,4,5\}$ and let $N = \{0,3 \}$.
Then the quotient group $G/N$ would be $G/N = \{ \{0,3\}, \{1,4 \}, \{2,5\} \}$.
According to my sources, they say that as $N$ is normal subgroup, $G/N$ must be also group.
As the group $G$ is abelian, according to my sources (Wikipedia and textbook), they say that $G/N$ must be abelian group.
The question is, by quotient group $G/N$ being group, is group operation done by assuming that in the example, $0$ and $3$ are treated same, $1$ and $4$ are treated same and $2$ and $5$ are treated same? And abelian-ness can be checked by adding $(3+4) \pmod 6 = (4+3) \pmod 6 = 1 = 4?$
Or is this something else?

A: This is something else: in the quotient you have equivalence classes which you will multiply (sum) according to the rules you were surely told. There are no more mere elements as in the mother group, yet it is always possible to pick up some representative from each class andwork with it...
This subject is better understood in calss, with a decent blackboard and some chalk, and doing many examples, but in your case we can say, for example, that
$$\{1,4\}+\{2,5\}=\{0,3\}\iff \bar 1+\bar 2=\bar 0$$
where the bar above means that we'reworking the equiv. class, not merely with the bare elements.


text:
Q: Could not find the main class: org.netbeans.modules.web.project.ant.JspCSingle. Program will exit I have tried again my jsp coding with taglid.  This time round, everything seems to work except when I run it, the following error appears:
java.lang.NoClassDefFoundError: org/netbeans/modules/web/project/ant/JspCSingle
Caused by: java.lang.ClassNotFoundException: org.netbeans.modules.web.project.ant.JspCSingle
        at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
Could not find the main class: org.netbeans.modules.web.project.ant.JspCSingle.  Program will exit.

What's wrong?

A: I had a similar problem trying to run a single jsp file in netbeans 6.9
How to solve the prob: Go to librairies manager(tools>libraries) and locate the "Jsp Compilation" library. Use  "Add Jar/Folder" to add the path to your jspCSingle.java file to the library classpath. And that's it.  Note that the "jsp compilation" library is necessary to compile/run single jsp files. So must either have it in your project library or netbeans set of libraries.
Emmanuel


text:
Q: Cannot recover key I published the first version of my app in Play Store two days ago. I used a key with a known alias and password.
Then, I changed the name of my app in eclipse, just changed one letter. Now, I want to export version 2 in eclipse, try use the key from the first time and enter alias and passwort. I´m sure they are correct!!
On the last step, Eclipse tells me "Cannot recover key". I tried it with a new one but then the Play Store shows an error. What can I do??
EDIT:

Like you see in the second image abobe, it MUST be the right password because otherwise the alias would not be in the dropdownbox. Also the second password is correct, it´s a copy from the first. I only have one alias!
Destination APK file-link in the last picture doesn´t matter right?

A: Changing App Name doesn't create any problem while you signing the application. you might have entered a wrong password or keystore-alias.
And you cannot create a new keystore to sign the application. If you done so then it is another application and you cannot updated the currently existing application.
Try re-sign the app with First Keystore with proper keystore-alias and password. It may be hard for you but if you fail to re-sign with the first keystore file then you cannot update the app with second version.

A: If you have special characters in you passwords use this tool to change it:
http://keystore-explorer.org/
I've tried the commands on Windows and it didn't work(probably because of the special characters).

A: Solution: The KeyStore password and The Key password should be the same.
Changing both passwords using keytool
Change KeyStore password
keytool -storepasswd -new %newpassword% -keystore %YourKeyStore%.jks

replace %newpassword% with your actual password, same with YourKeyStore
Change Alias key Password
keytool -keypasswd -alias %MyKeyAlias% -new %newpassword% -keystore KeyStore.jks

Note: supply old passwords for both keystore and alias when asked for them
(quoted from http://karim-ouda.blogspot.com/2010/07/errors-solutions-5.html)

A: In my case the error was due a special character in the password: Ç.


text: Q: hp envy 15 installed windows 7 .no drivers I had windows 8 by default which i get rid of by installing windows 7.at the moment it didnt pick up any drivers,cant access usb,network to communicate with any external source to download install drivers,any idea welcomes


text:
Q: How to store images into files using SQL? <?php

    if(isset($_POST['hour'])&&isset($_POST['day'])){

        //the path to store the uploaded image.
        $target = "images/".basename($_FILES['image']['name']);

        $db = mysqli_connect("localhost","root","","a_database");

        $image = $_FILES['image']['name'];
        $carmodel = $_POST['carmodel'];
        $cartype = $_POST['cartype'];
        $hour = $_POST['hour'];
        $day = $_POST['day'];

        $query = "INSERT INTO `cardetails` (`image`, `carmodel`, `cartype`, `hour`, `day`) VALUES ('".$image."', '".$carmodel."', '".$cartype."', '".$hour."', '".$day."')";
        mysqli_query($db,$query);//stores the data

        //move uploaded image into the folder.
        if(move_uploaded_file($_FILES['image']['tmp_name'],$target)){
             header('Location:upload_success.php');
        }else{

             header('Location:upload_fail.php');
        }

    }else{
            echo ' ';
    }

?>

    <form method="POST" action="upload.php" enctype="multipart/form-data">
    <input type="hidden" name="size" value="1000000">

        <input type="file" name="image">

         Car Model
        <select name="carmodel" class="form-control" >
        <option value="Myvi">Myvi</option>
        <option value="Vios">Vios</option>
        <option value="Lambo">Lambo</option>
        </select>

     Car Type
        <input type="radio" name="cartype" value="Auto">Auto
        <input type="radio" name="cartype" value="Manual"> Manual

        <input type="text" name="hour" placeholder="$/hour">

        <input type="text" name="day" placeholder="$/day">

        <button type="submit">Upload</button>

</form>

I've successfully insert the data into database with the image name but the image doesn't seems to upload into my images file, what could be wrong? Based on the code above, upload_fail.php is called. If isset with $_POST['image'], nothing happens.

A: I think, you don't have sufficient permissions for writing to images directory. Does exist images directory itself?
If you want to know what's wrong, you can enable error reporting on beginning of your php file like:
<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    ...


text:
Q: Why The assembly is not permitted to be used by an ObjectDataSource component when exporting Telerik Report from C# An error has occurred while processing Table 'table2': The assembly "AssemblyName.Context, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" is not permitted to be used by an ObjectDataSource component. Please include it in an AssemblyReferences element in the Telerik.Reporting configuration section of your application configuration file.
I am using below code for export report in pdf.
 public static System.IO.Stream GerRep(List<EquipmentSearchResult> list)
        {
            EquipmentExportReportT report = new EquipmentExportReportT();

            report.ReportParameters["BaseLocationName"].Value = "MyTest";
            //report.DataSource = list;

            ReportProcessor reportProcessor = new ReportProcessor();

            // set any deviceInfo settings if necessary
            System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable();

            Telerik.Reporting.TypeReportSource typeReportSource = new Telerik.Reporting.TypeReportSource();

            // reportName is the Assembly Qualified Name of the report
            typeReportSource.TypeName = typeof(EquipmentExportReportT).AssemblyQualifiedName;

            RenderingResult result = reportProcessor.RenderReport("XLS", typeReportSource, deviceInfo);

            string fileName = result.DocumentName + "." + result.Extension;
            string path = System.IO.Path.GetTempPath();
            string filePath = System.IO.Path.Combine(path, fileName);

            using (FileStream fs = new FileStream(filePath, System.IO.FileMode.Create))
            {
                fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);
            }

            MemoryStream ms = new MemoryStream(result.DocumentBytes);
            ms.Position = 0;

            return ms;
        }

A: This is the configuration issue, you need to apply some setting on the web.config file.
In this case the application configuration file needs to be modified and the name of the assembly needs to be added in a new node within the AssemblyReferences element contents in the following manner:
<configuration>

  <configSections>
    <section name="Telerik.Reporting" type="Telerik.Reporting.Configuration.ReportingConfigurationSection, Telerik.Reporting" allowLocation="true" allowDefinition="Everywhere" />
  </configSections>

  <Telerik.Reporting>
    <assemblyReferences>
      <add name="yourAssemblyName"/>
    </assemblyReferences>
  </Telerik.Reporting>

</configuration>

I hope this will resolve your problem. Cheers :)


text:
Q: pyglet script works in windows but not in osx I am working in a pyglet script which displays an animation, it works as expected in Windows, but when I execute it in osx I only get a blank screen.
I know it works because I've put print statements in on_draw() and other functions and those are shown in the terminal, but the pyglet window does not display anything.
I am forcing the execution of the 32 bit python with the command defaults write com.apple.versioner.python Prefer-32-Bit -bool yes, and I have executed without a problem another pyglet script which also displayed an animation.
I do not understand the problem, because this script, as I said, works in Windows. The code is the following:
import pyglet
from pyglet.gl import *
from pyglet.window import mouse, key
import math
import time
import ConfigParser
import numpy as np # for randomize the trials
import sys # debuging purposes
import os

## Create pyglet window
# Get screens
screens = pyglet.window.get_platform().get_default_display().get_screens()
allowstencil = pyglet.gl.Config(stencil_size=8)

# Create window (not visible at start)
myWindow = pyglet.window.Window(config=allowstencil,fullscreen=False,screen=screens[0], visible = 0)

## Functions definition

def create_filename():

    ## Create output data file name

    # Get subject and time information
    exp_name = 'pythonMigration'
    time_string = time.strftime("%y.%m.%d_%H.%M.%S", time.localtime())
    subject_name = "Name"

    textfilename = (exp_name + '_' + subject_name + '_' + time_string + '.txt')

    # Save output file in the folder "data"
    out_file_name = os.path.join('data', textfilename)

    return out_file_name

def ConfigFileToStruct(configfilename):
    # ConfigFileToStruct receives the string of the name of the configuration file to be read.
    # It will return a dict variable with the configuration parameters and values

    # config_struct will be the dict struture where all the configuration parameters will be stored
    config_struct = {}

    # Initialize configParser
    config = ConfigParser.RawConfigParser()

    # Read file named configfilename
    config.read(configfilename)

    # Read sections of configuration file
    sectionlist = config.sections()

    # Read options of each section
    # optionlist will be an AxB array, where A is not defined and B is the len(sectionlist)
    optionlist = [[] for x in range(len(sectionlist))]

    for i in range(len(sectionlist)):
        # Read variables (options) from configuration file
        optionlist[i] = config.options(sectionlist[i])

        # Fill structure with sections
        config_struct[sectionlist[i]] = {}

        # Fill sections of structure with variables and values
        for j in range(len(optionlist[i])):
            config_struct[sectionlist[i]][optionlist[i][j]] = config.getfloat(sectionlist[i], optionlist[i][j])

    return(config_struct) #end of readconfigFile function

def load_trial_parameters(trialsfile,trial):
    # trialsfile is the struct previously loaded by ConfigFileToStruct()
    # trial is the number of the trial to load parameters from
    global mylambda1, duty_cycle1, orientation1, speed1
    global mylambda2, duty_cycle2, orientation2, speed2
    global timeCurrentTrial

    ## GRATING PARAMETERS

    mylambda1 = trialsfile[str(trial)]["wavelength1"]
    duty_cycle1 = trialsfile[str(trial)]["duty_cycle1"]
    orientation1 = trialsfile[str(trial)]["orientation1"]
    speed_pix = trialsfile[str(trial)]["speed1"]
    speed1 = speed_pix / math.cos(math.radians(orientation1))

    #grating2

    mylambda2 = trialsfile[str(trial)]["wavelength2"]
    duty_cycle2 = trialsfile[str(trial)]["duty_cycle2"]
    orientation2 = trialsfile[str(trial)]["orientation2"]
    speed_pix = trialsfile[str(trial)]["speed2"]
    speed2 = speed_pix / math.cos(math.radians(orientation2))

    # other parameters
    timeCurrentTrial = trialsfile[str(trial)]["time"]

def load_config_parameters(config):
    # config is the struct previously loaded by ConfigFileToStruct()

    # Declare variables, all are global, this function if for clearity purposes
    global x0_pix, y0_pix
    global ysize_cm, aperture_color, numTheta, deltaTheta, x1, y1, apertRad_pix
    global x2, y2
    global red_color, cyan_color
    global stereo1, stereo2
    global fixp_color, surrp_color
    global time_fixp

    # calculate x, y center coordinates in pixels
    x0_myW = 0 # note that we consider center of screen to be 0,0 in My World Coordinates
    y0_myW = 0
    x0_pix = ((x0_myW/0.5) + 1)/2 * myWindow.width # center of screen; assuming myW width max == 0.5; this equation derived with Nava
    y0_pix = ((y0_myW/0.5) + 1)/2 * myWindow.height # center of screen # assuming myW height max == 0.5

    # calculate radius; we want an aperture with a 13 deg diameter or 6.5 deg radius @ view dist of 57cm
#     ysize_cm = config["screen_parameters"]["ysize_cm"] #@@ TO-DO this will be set as a config param @@ and will change depending on monitor!!
#     apertDiam_cm = config["radius"]["aperture"]
#     apertRad_myW = (apertDiam_cm/ysize_cm) / 2 # determine radius value in My World with reference to 0,0 center
#     apertRad_pix = (((apertRad_myW/0.5) + 1)/2 * myWindow.height) - y0_pix
    apertureDiv = config["aperture_size"]["proportion"]
    apertRad_pix = myWindow.height / apertureDiv

    ## APERTURE PARAMETERS
        # Calculate circle for aperture
    aperture_color = (config["aperture_color"]["red"], config["aperture_color"]["green"], config["aperture_color"]["blue"])
    numTheta = int(config["radius"]["numtheta"])
    deltaTheta = 2 * math.pi / numTheta # == 0.0698
#
    ## GRATING PARAMETERS
    #grating1
    x1 = x0_pix - apertRad_pix
    y1 = y0_pix - apertRad_pix
    stereo1 = config["stereo"]["grating1"]

    #grating2
    x2 = x0_pix + apertRad_pix
    y2 = y0_pix + apertRad_pix
    stereo2 = config["stereo"]["grating2"]

    ## COLOR PARAMETERS
    red_color   = (config["red_color"]["red"], config["red_color"]["green"], config["red_color"]["blue"])
    cyan_color  = (config["cyan_color"]["red"], config["cyan_color"]["green"], config["cyan_color"]["blue"])

    # fixation point color
    fixp_color  = (config["fixp_color"]["red"], config["fixp_color"]["green"], config["fixp_color"]["blue"])
    surrp_color = (config["surrp_color"]["red"], config["surrp_color"]["green"], config["surrp_color"]["blue"])

    # fixation point time beginning trials
    time_fixp = config["time"]["time_fixp"]

@myWindow.event
def on_mouse_press(x, y, button, modifiers):
#     On_mouse_press will be executed each time a mouse button is pressed
    global count, datatime, dataclick, datatrial
    global show_stim, show_trial_menu, trial, clockTrial, show_welcome

    global show_trial_menu_release, show_welcome_release

    timeNow = time.clock() - clockTrial

    if show_stim:

        if button == mouse.LEFT:
            datatrial[count] = trials_array[trial_counter]
            dataclick[count] = '-1'
            datatime[count] = timeNow - time_fixp

        if button == mouse.RIGHT:
            datatrial[count] = trials_array[trial_counter]
            dataclick[count] = '1'
            datatime[count] = timeNow - time_fixp

        count += 1

    elif show_trial_menu:
        show_trial_menu_release = 1

    elif show_welcome:
        show_welcome_release = 1

@myWindow.event
def on_mouse_release(x, y, button, modifiers):
#     On_mouse_release will be executed each time a mouse button is release
    global count, dataclick, datatime, datatrial
    global show_stim, show_trial_menu, trial, clockTrial, show_welcome, trial_counter
    global show_trial_menu_release, show_welcome_release

    timeNow = time.clock() - clockTrial

    if show_stim:
        if button == mouse.LEFT:
            datatrial[count] = trials_array[trial_counter]
            dataclick[count] = '-2'
            datatime[count] = timeNow - time_fixp

        if button == mouse.RIGHT:
            datatrial[count] = trials_array[trial_counter]
            dataclick[count] = '2'
            datatime[count] = timeNow - time_fixp

        count += 1

    elif show_trial_menu & show_trial_menu_release:

        show_trial_menu_release = 0

        show_stim = 1
        show_trial_menu = 0
        trial = trial + 1
        trial_counter = trial_counter + 1
        clockTrial = time.clock()

    elif show_welcome & show_welcome_release:

        show_welcome_release = 0
        show_welcome = 0
        show_stim = 1

        clockTrial = time.clock()

@myWindow.event
def on_close():
    #on_close is executed when mywindow is closed
    close_nicely()

def close_nicely():
    #Write data to text file
    for i in range(count):
        with open(out_file_name, 'a') as txtfile:
            txtfile.write(str(i) +'\t'+ str(datatime[i]) +'\t'+ str(dataclick[i]) +'\t'+ str(datatrial[i]) + '\n')

    print("closed nicely :)")

    myWindow.clear()
    myWindow.close()

def drawCircle(radius, circle_color, x, y):
    global numTheta, deltaTheta

    glColor3f( circle_color[0] , circle_color[1], circle_color[2])

    for i in range (0, numTheta):
        cx1 = x + radius * math.sin(deltaTheta * i)
        cy1 = y + radius * math.cos(deltaTheta * i)
        cx2 = x + radius * math.sin(deltaTheta * (i+1))
        cy2 = y + radius * math.cos(deltaTheta * (i+1))

        glBegin( GL_TRIANGLES )
        glVertex2f(x, y )
        glVertex2f(cx1 , cy1 )
        glVertex2f(cx2 , cy2 )
        glEnd()

def drawAperture():
    global aperture_color, numTheta, deltaTheta, x0_pix, y0_pix, apertRad_pix

    # Do we need the stencil commands in here? It does not change if I delete them
    # Enable stencil
    glClearStencil(0x0)
    glEnable(GL_STENCIL_TEST)

    #define the region where the stencil is 1
    glClear(GL_STENCIL_BUFFER_BIT)
    glStencilFunc(GL_ALWAYS, 0x1, 0x1) #Always pass stencil functions test
    glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE) #Replace stencil value with reference value

    drawCircle(apertRad_pix, aperture_color, x0_pix, y0_pix)

def drawGrating(x, y, fill_color, orientation, mylambda, duty_cycle):

    bar_length = 1500

    radio_aux = (2 * apertRad_pix) + mylambda #diameter
    num_bars = int(1 + math.floor(radio_aux / mylambda))+3

    glStencilFunc (GL_EQUAL, 0x1, 0x1)
    glStencilOp (GL_KEEP, GL_KEEP, GL_KEEP)

    glLoadIdentity() #replace current matrix with the identity matrix
    glTranslatef(x, y, 0)
    glRotatef(orientation,0,0,1)
    glTranslatef(-x, -y, 0)

    glColor3f( fill_color[0] , fill_color[1], fill_color[2] )

    glBlendFunc(GL_ZERO, GL_SRC_COLOR)

    for i in range(num_bars):

        x1 = mylambda * i + x
        x2 = (duty_cycle * mylambda) + (mylambda * i + x)

        glBegin(GL_QUADS)

        glVertex2f(x1, y - bar_length)
        glVertex2f(x1, y + bar_length)
        glVertex2f(x2, y + bar_length)
        glVertex2f(x2, y - bar_length)

        glEnd()

#     glRotatef(-orientation, 0, 0, 1)#Is it necessary?
    glBlendFunc(GL_ONE, GL_ZERO)
    glLoadIdentity()

def update_frames(dt):
    global x1, x2, timetrial, clockTrial, trial, show_stim, show_trial_menu

    timeNow = time.clock()

    if (show_stim) & ((timeNow-clockTrial) < (timeCurrentTrial + time_fixp)):
        # Load trial parameters
        load_trial_parameters(trialsfile,trials_array[trial_counter])

        motion_cycle1 = mylambda1/(math.cos(math.radians(orientation1)))
        motion_cycle2 = mylambda2/(math.cos(math.radians(orientation2)))

        initialpos1 = myWindow.width/2 - apertRad_pix - mylambda1/2
        initialpos2 = myWindow.width/2 - apertRad_pix + mylambda2/2

        # update position of grating 1:
        x1 = initialpos1 + math.fmod(speed1*(timeNow-clockTrial), motion_cycle1)

        # update position of grating 2:
        x2 = initialpos2 + math.fmod(speed2*(timeNow-clockTrial), motion_cycle2)

    elif ((show_stim) & (trial_counter < numtrials)):
        show_stim = 0
        show_trial_menu = 1

    elif ((show_stim == 0) & (trial_counter == numtrials-1)):
        close_nicely()
        pass

@myWindow.event
def on_draw():
    print "on draw"
    if show_stim:
        # For each frame of the stimulus:

        # clear the window
        myWindow.clear()

        load_trial_parameters(trialsfile, trials_array[trial_counter])

        # Enable blending
        glEnable(GL_BLEND)
        pyglet.gl.glClearColor( 0.6, 0.6, 0.6, 0 )

        # Enable stencil
        glClearStencil(0x0)
        glEnable(GL_STENCIL_TEST)

        # define the region where the stencil is 1
        glClear(GL_STENCIL_BUFFER_BIT)
        glStencilFunc(GL_ALWAYS, 0x1, 0x1) #Always pass stencil functions test
        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE) #Replace stencil value with reference value

        # draw Aperture
        drawCircle(apertRad_pix, aperture_color, x0_pix, y0_pix)

        # draw Fixation point and fixation surround
        drawCircle(apertRad_pix/15, fixp_color,  x0_pix, y0_pix)
        drawCircle(apertRad_pix/80, surrp_color, x0_pix, y0_pix)

        if (time.clock()-clockTrial)>time_fixp:
            # draw gratings

            Red  = red_color
            Cyan = cyan_color

            drawGrating(x1 + stereo1, y1, Cyan, orientation1, mylambda1, duty_cycle1)
            drawGrating(x1 - stereo1, y1, Red,  orientation1, mylambda1, duty_cycle1)

            drawGrating(x2 + stereo2, y2, Red,  orientation2, mylambda2, duty_cycle2)
            drawGrating(x2 - stereo2, y2, Cyan, orientation2, mylambda2, duty_cycle2)

            glBlendFunc(GL_ONE, GL_ZERO)

    elif show_trial_menu:
        # For each frame of the in-between trials window

        myWindow.clear()

        #define the region where the stencil is 1
        glClear(GL_STENCIL_BUFFER_BIT)
        glStencilFunc(GL_ALWAYS, 0x1, 0x1) #Always pass stencil functions test
        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE) #Replace stencil value with reference value

        labelInterval.draw()

    elif show_welcome:
        # For each frame of the welcome window

        myWindow.clear()

        glEnable(GL_BLEND)
        pyglet.gl.glClearColor( 0.6, 0.6, 0.6, 0 )

        labelWelcome.draw()

################################################################################################
## Main
################################################################################################

if __name__ == "__main__":

    ## Check command-line arguments
    if len(sys.argv)>1:
        confignamefile = sys.argv[1]
        trialsnamefile = sys.argv[2]
        print("input received")
    else:
        print("no input received")
        confignamefile = "cfgfile.txt"
        trialsnamefile = "trialsfile.txt"

    # Load configuration parameters
    config = ConfigFileToStruct(confignamefile)
    if not config:
        print("CONFIG FILE EMPTY")
    else:
        print("CONFIG FILE LOADED")

    # Load trials file parameters
    trialsfile = ConfigFileToStruct(trialsnamefile)
    if not trialsfile:
        print("TRIALS FILE EMPTY")
        sys.exit()
    else:
        print("TRIALS FILE LOADED")
        numtrials = len(trialsfile)

    ## Initialize states of on_draw()
    show_welcome = 1
    show_stim = 0
    show_start_menu = 0
    show_trial_menu = 0

    show_trial_menu_release = 0

    ## Load parameters
    randomize_trials = 1

    if randomize_trials:
        trials_array = np.random.permutation(numtrials) # goes from 0 to numtrials in random order
    else:
        trials_array = range(numtrials) # no random

    trial = 0
    trial_counter = 0

    load_config_parameters(config)
    load_trial_parameters(trialsfile,trials_array[trial_counter])

    ## Create output data file name
    out_file_name = create_filename()

    # Necessary variables for the data file
    count = 0
    dataclick   = [0]*15000
    datatime    = [0]*15000
    datatrial   = [0]*15000

    ## Message that will be shown between trials
    labelInterval = pyglet.text.Label("Click the mouse to start the next trial", font_name = 'Arial',
                                  font_size = 20, x = myWindow.width/2, y = myWindow.height/2,
                                  anchor_x = "center", anchor_y = "center")

    ## Message that will be shown at startup
    textWelcome = "\t\t\t\tWelcome\n RIGHT click: Grating to the right is in front\n LEFT click: Grating to the left is in front\n\n LEFT click to start"
    labelWelcome = pyglet.text.Label(textWelcome,
                                font_name = 'Arial', font_size = 20, x = myWindow.width/2, y = myWindow.height/2,
                                multiline = True, width=600, anchor_x = "center", anchor_y = "center")

    ## Run stimulus

    # Set stimulus window to visible and mouse not visible
    myWindow.set_visible(1)
    myWindow.set_mouse_visible(0)

    # initialize clock
    clockTrial = time.clock() # this clock will be reset for each trial

    framerate = 1/60.0

    pyglet.clock.schedule_interval(update_frames,framerate)

    pyglet.app.run()

Could anybody help me to find out what am I doing wrong in this code?

A: This is a (working) example code where flip is utilized:
import pyglet
from pyglet.gl import *
from math import radians, cos, sin, degrees, atan2
from time import time
from os.path import abspath

glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_LINE_SMOOTH)
glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE)
pyglet.options['audio'] = ('alsa', 'openal', 'silent')
key = pyglet.window.key

class BasicObject(pyglet.sprite.Sprite):
    def __init__(*args, **dictWars):
        if type(args) == tuple and len(args) == 2 and len(dictWars) == 0 and type(args[1]) == dict:
            args, dictWars = args

        self = args[0]
        self.name = args[1]
        self.render = True
        self.anchor = 'center'

        self.last_update = time()

        self.texture = pyglet.image.load(abspath(dictWars['texture']))
        super(BasicObject, self).__init__(self.texture)

        self.x, self.y = 0, 0
        self.rotation = 0

        if 'x' in dictWars:
            self.x = dictWars['x']
        if 'y' in dictWars:
            self.y = dictWars['y']

    def swap_image(self, image, filePath=True):
        if filePath:
            self.texture = pyglet.image.load(abspath(image))
        else:
            self.texture = image
        self.image = self.texture

    def draw_line(self, xy, dxy, color=(0.2, 0.2, 0.2, 1)):
        glColor4f(color[0], color[1], color[2], color[3])
        glBegin(GL_LINES)
        glVertex2f(xy[0], xy[1])
        glVertex2f(dxy[0], dxy[1])
        glEnd()

    def rotate(self, deg):
        self.image.anchor_x = self.image.width / 2
        self.image.anchor_y = self.image.height / 2
        self.rotation = self.rotation+deg
        if self.anchor != 'center':
            self.image.anchor_x = 0
            self.image.anchor_y = 0

    def click(self):
        print('Clicked:',self.name)

    def work(self, *args):
        if time() - self.last_update > 0.1:
            self.rotate(10)

    def click_check(self, x, y):
        if x > self.x and x < (self.x + self.width):
            if y > self.y and y < (self.y + self.height):
                return self

    def _draw(self):
        self.work()
        # self.draw_line((x,y), (dx, dy))
        self.draw()

class GUI(pyglet.window.Window):
    def __init__(self):
        super(GUI, self).__init__(640,340, caption='My app')
        self.alive = True
        self.keys_down = {}

        self.myImage = BasicObject('TestImage', texture='/path/to/texture.png')

    def render(self, *args):
        pyglet.gl.glClearColor(1, 1, 1, 1)
        self.clear()
        # .. This is where you draw your objects, for instance
        self.myImage._draw()
        self.flip()

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = False

    def on_key_press(self, symbol, modkey):
        self.keys_down[symbol] = time()

    def on_key_release(self, symbol, modkey):
        if symbol in self.keys_down:
            del(self.keys_down[symbol])

    def on_mouse_release(self, x, y, button, modifiers):
        pass

    def on_mouse_press(self, x, y, button, modifiers):
        print(button,'pressed',(x,y))

    def on_mouse_motion(self, x, y, dx, dy):
        pass

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        pass

    def run(self):
        while self.alive:
            event = self.dispatch_events()

            for symbol in self.keys_down:
                if symbol == key.ESCAPE:
                    self.alive = None
                    break
                elif symbol == key.LEFT:
                    pass #Arrowkey Left
                elif symbol == key.RIGHT:
                    pass #Arrowkey Right
                elif symbol == key.UP:
                    pass #Arrowkey Up
                elif symbol == key.DOWN:
                    pass #Arrowkey Down
                elif symbol == 65515:
                    pass # Win key
                else:
                    print(symbol)
            self.render()

if __name__ == '__main__':
    x = GUI()
    pyglet.clock.set_fps_limit(120)
    x.run()

This is also the code i use in all my projects, something that's been evolving to fit my needs but also something that's proved to be working in most scenarios.


text:
Q: Need to incorporate some features from Excel. Is that possible? I know one of the main principles of Software Engineering is DRY(Don't Repeat Yourself), that's why I don't want write another implementation of something I already know exists in Excel.
I was wondering if it is possible to take a feature from an existing program, and use it?
The feature I'm particularly interested in is in the Data section in Excel, there is ability to import a text with data.  It opens a wizard that makes the user describe his datafile, and then Excel tries it's best to import it into Excel.
What I want to do is to make another version of this data text importer, except with more specific options. Would I have to make another instance of Excel's importer?


text:
Q: Automatic Layout Constraints in NSScrollView I'm creating an NSTableView inside a NSScrollView programmatically, but when I try to set the frame to the scroll view I'm getting a constraint error.
Unable to simultaneously satisfy constraints:
(
    "<NSAutoresizingMaskLayoutConstraint:0x107d4ec50 h=--& v=--& V:[NSScrollView:0x10068c570(372.5)]>",
    "<NSAutoresizingMaskLayoutConstraint:0x107d4d020 h=-&- v=-&- V:[NSClipView:0x10068d7f0]-(673)-|   (Names: '|':NSScrollView:0x10068c570 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x107d4cfc0 h=-&- v=-&- V:|-(2)-[NSClipView:0x10068d7f0]   (Names: '|':NSScrollView:0x10068c570 )>"
)

Will attempt to recover by breaking constraint
<NSAutoresizingMaskLayoutConstraint:0x107d4d020 h=-&- v=-&- V:[NSClipView:0x10068d7f0]-(673)-|   (Names: '|':NSScrollView:0x10068c570 )>

Set the NSUserDefault NSConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints to YES to have -[NSWindow visualizeConstraints:] automatically called when this happens.  And/or, break on objc_exception_throw to catch this in the debugger.

It seems like they are being created automatically.
This is my creation code (using arc) I'm subclassing NSView
-(void)addColumnsToTable{
    NSTableColumn *col = [[NSTableColumn alloc]initWithIdentifier:@"priority"];
    [col.headerCell setStringValue:@"priority"];
    [col setWidth:10];
    [col setMinWidth:1];
    [col setMaxWidth:10];
    [self.tableView addTableColumn:col];

   // col = [[NSTableColumn alloc]initWithIdentifier:@"name"];
   // [self.tableView addTableColumn:col];
}

-(void)createTable{
    NSTableView *tableView = [[NSTableView alloc]initWithFrame:NSZeroRect];

    [tableView setDelegate:self];
    [tableView setDataSource:self];

    NSScrollView *scrollView = [[NSScrollView alloc]initWithFrame:self.bounds];
    [scrollView setBorderType:NSGrooveBorder];

    [self addSubview:scrollView];
    [scrollView setDocumentView:tableView];
    [scrollView setHasVerticalScroller:YES];
    [scrollView setAutohidesScrollers:YES];

    self.tableView = tableView;
    self.scrollView = scrollView;

    [self addColumnsToTable];

}

Here is where it is breaking:
-(void)setFrame:(NSRect)frameRect{
    [super setFrame:frameRect];
    [self.scrollView setFrame:self.bounds];

}

Is there a way to turn off these automatic constraints?

A: Got it, the problem is that automatic constraints are being created based on the view's automatic resize mask. To deactivate this behaviour:
[scrollView setTranslatesAutoresizingMaskIntoConstraints:NO];

where scrollView is a subview of NSView

A: I also got the exact same problem when setting the frame of an NSScrollView, within the DrawRect method of a NSView subclass.  The above solution of setting the TranslatesAutoresizingMaskIntoConstraints to NO gets rid of the exception.  But in my situation, I have a dynamic window.  Indeed, my tableview didn't follow the new frame size I am calculating and setting up to the NSScrollView anymore.
Working around for a while, I finally came up with the right solution.  It appear that the problem was not about the NSScrollView autoresizing setup, but setting up the AutoresizesSubviews of my NSView subclass is the right solution for an dynamic custom view.
- (void)awakeFromNib
{

[super awakeFromNib];
[self setAutoresizesSubviews:NO];   // <- Here is the solution

    // …
}

- (void)drawRect:(NSRect)dirtyRect
{

[super drawRect:dirtyRect];

    // From DirtyRect (dimensions of the my subclass NSView)
    // Calculate the rectangle allowable for MyScrollView
    // and setting local NSRect mRect..

    [MyScrollView setFrame:mRect];      // no more 'exception' here
}

I also have to create other NSView subclass programmatically, which also had NSScrollView and frame setting needs.  Since those objects have no awakeFromNib method… simply set it elsewhere… like in an Init method of the NSView subclass.
- (id)init:(NSInteger)aSpecialTag
{

[self setAutoresizesSubviews:NO];   // <- Here is the solution

    _mTag = aSpecialTag;

    // …
}


text:
Q: Java ThreadLocal static? Setting a value in Thread Local:
//Class A holds the static ThreadLocal variable.

    Class A{

    public static ThreadLocal<X> myThreadLocal = new ThreadLocal<X>();
    ....
    }

//A Class B method sets value in A's static ThreadLocal variable
    class B{
    {
         public void someBmethod(){
             X x = new X();
             A.myThreadLocal.set(x);
         }
    }

//Class C retrieves the value set in A's Thread Local variable.

    Class C {

    public void someCMethod(){
         X x = A.myThreadLocal.get();
    }
    ...
    }

Quesiton:
Now assuming this is a web-application, and threads execute: B.someBMethod, C.someCMethod in that order.
Multiple threads executing B's someBMethod, will end up updating the SAME A's static ThreadLocal variable myThreadLocal, thereby beating the very purpose of ThreadLocal variable. (Using static for ThreadLocal is what is recommended as per documentation.)
The C's someCMethod, while retrieving value from ThreadLocal may not get the value set by the 'current' thread.
What am i missing here?

A: As per the definition of ThreadLocal class

This class provides thread-local variables. These variables differ
from their normal counterparts in that each thread that accesses one
(via its get or set method) has its own, independently initialized
copy of the variable. ThreadLocal instances are typically private
static fields in classes that wish to associate state with a thread
(e.g., a user ID or Transaction ID).

That means say 2 threads t1 & t2 executes someBMethod() and they end up setting x1 & x2(Instances of X) respectively. Now when t1 comes and executes someCMethod() it gets x1 (which is set by itself earlier) and t2 gets x2.
In other words, its safe to have a single static instance of ThreadLocal, because internally it does something like this when you invoke set
set(currentThread, value) //setting value against that particular thread

and when you invoke get
get(currentThread) //getting value for the thread

A:
Multiple threads executing B's someBMethod, will end up updating the SAME A's static ThreadLocal variable myThreadLocal

Yes, they operate on the same object. However, it is important to realize that the way ThreadLocal works is that each thread has its own, separate value. Thus if you have ten threads writing to myThreadLocal and then reading from myThreadLocal, each will see the correct (i.e. their own) value.
To put it another way, it does not matter which class or object writes to an instance of ThreadLocal. What matters is the thread in whose context the operation is performed.

A: No they won't, thats the point. Javadoc :

These variables differ from their normal counterparts in that each
  thread that accesses one (via its get or set method) has its own,
  independently initialized copy of the variable. ThreadLocal instances
  are typically private static fields in classes that wish to associate
  state with a thread (e.g., a user ID or Transaction ID).

A: I study the java source code,

*

*java.lang.Thread Class contains a instance variable as below.
ThreadLocal.ThreadLocalMap threadLocals = null;
Because threadLocals variable is non-static, Every thread in a application (i.e., every instance of Thread Class) will have it's own copy of threadLocals map.

*Key for this map is, current ThreadLocal instance, and value is the value which you pass as argument to ThreadLocal.set().

*When you try to fetch value as ThreadLocal.get() , internally, it will fetch from the ThreadLocalMap of Current Thread.
In simple terms, you are getting & setting values from/to your current Thread Object, not from/to your ThreadLocal object.

A:
Multiple threads executing B's someBMethod, will end up updating the SAME A's static ThreadLocal variable myThreadLocal

No they won't. Every thread has its own instance of the contained variable of type X.

thereby beating the very purpose of ThreadLocal variable

No.
Have another look at the Javadoc.


text:
Q: My Grandparent is not re-rendering the Query with new variables and displaying new data, after the state changes through useState() So, I am running into this problem where I am making filters while using the one graphql query. There's a child, parent & grandparent(these are different components). Now my query uses variables inside it, initially on load I set the variables in useState and it's working fine. Now when I click on a checkbox(which is insinde Child component) it passed its data(which is variable for new query) to the Grandparent and I am getting that, so I pass that data into the query variable. But it's not re-redering the query again with new variable. So my filters are not working.
Grand Parent
// handling all the product grid actions and data
function ProductGrid() {

  const [queryVariables, setQueryVariables] = useState({first: 20});
  console.log(queryVariables);
  // get the variable object

  const { loading, error, data, fetchMore} = useQuery(QUERY, {
    variables: queryVariables
  });

  if (loading) return
Loading...
;
  if (error) return (

    {console.log(error)}

  );

  let productEdges = data.products.edges;
  return(

      {/* <PriceFilter/> */}
      <TypeFilter getFilters={queryVariables => setQueryVariables(queryVariables)} />
      {/* test button */}

        {productEdges.map((element, index) => {

          // formatting the price
          let tempPrice = Math.floor(element.node.priceRange.minVariantPrice.amount);
          let productPrice = new Intl.NumberFormat().format(tempPrice);

          return(

{element.node.title}

{element.node.priceRange.minVariantPrice.currencyCode}. {productPrice}

          )
        })}

      {/* load more products button */}
      <button
        className="load-more"
        onClick={()=>{
          const endCursor = data.products.edges[data.products.edges.length - 1].cursor;

          fetchMore({
            variables: {
              after: endCursor,
              queryVariables
            }
          })
        }}>
          Load More
        </button>

  )
}

// graphql query for products fetching
const QUERY = gql`
query productFetch($first:Int, $after:String, $query:String){
  products(first:$first, after: $after, query:$query){
    edges{
      node{
        priceRange{
          minVariantPrice{
            amount
            currencyCode
          }
        }
        title
        images(first:1){
          edges{
            node{
              transformedSrc(maxWidth: 300)
            }
          }
        }

      }
      cursor
    }
    pageInfo{
      hasNextPage
    }
  }
}

`

Parent
// ************** Parent ***************
function TypeFilter(props) {
  // assume other code is here for a modal pop and
     accordion inside here

  // passing the prop to checkbox component here and
     getting back new state which we use as a callback for
     it's parent
  <TypeCheckBox getCheckState={queryVariables =>
  props.getFilters(queryVariables)} />
}

Child
// ************** Child *****************
let result = "";
let variables =
  {
    first: 28,
    query: ""
  };
function TypeCheckBox(props){
  // below function returns variables for apollo query
    const handleCheckChange = (event) => {
        setState({ ...state, [event.target.name]: event.target.checked });
        if(event.target.checked){
            // pass this value into the productGrid component
            if(counter > 1){
              result += "&";
            }
            result = `${result}product_type:${event.target.value}`;
            counter++;
            // setting filter type to result
            console.log(result);
            variables.query = result;
            console.log(variables);
            return props.getCheckState(variables);
        }else{

          result = result.replace(`product_type:${event.target.value}`, "");
          result = removeLast(result, "&");
          counter--;
          // setting filter type to result
          console.log(`in else ${result}`);
          variables.query = result;
          console.log(variables);
          return props.getCheckState(variables);
        }
    };

}
  return (
            <FormGroup column>
              <FormControlLabel
                control={<Checkbox checked={state.checkedBridal} value="Bridal" onChange={handleCheckChange} name="checkedBridal" />}
                label="Bridals"
              />
  )
}

I tried using useEffect on useQuery in GrandParent, but then the returned constants don't have access outside, like
    useEffect(() => {
    const { loading, error, data, fetchMore} = useQuery(QUERY, {
        variables: queryVariables
      });
  }, [queryVariables])

Thanks you soo much for your answers ^^

A: So, I figured out a solution since no one answered it so I am gonna answer it.
first, you need to add refetch and fetch-policy in useQuery hook as
const { loading, error, data, fetchMore, refetch, networkStatus } = useQuery(
QUERY,
{
  variables: queryVariables,
  // notifyOnNetworkStatusChange: true,
  fetchPolicy: "network-only"
}
);

Then you need to make a separate function with the same name as your props that you're passing to your children and use the spread operator with queryVariables to expand and refetch the query with new variables as
const getFilters = queryVariables => {
 setQueryVariables({ ...queryVariables });
 refetch();
};

Hope this is helpful to someone ^^


text:
Q: nwj.s change webview http referrer i have moved from electronjs to nwjs, and i want to change the http referer but does not work, i already did it in electronjs.. here is example..
<webview
id="ref"
src="https://whatsmyreferer.com/"
httpreferrer="http://google.com"
useragent="Custom user agent"
</webview>

In nw.js, I don't see httpreferrer and useragent parameters in webview, how can I do that in nw.js, I'm new on nwjs, please help?
thanks in advance..


text:
Q: Doctrine DBAL type boolean for SQLite I've problems using type boolean in SQLite. The error-message is:

Fatal error: Uncaught exception 'Doctrine\DBAL\DBALException' with
  message 'Unknown database type bool requested,
  Doctrine\DBAL\Platforms\SqlitePlatform may not support it.'

The error happens on connecting to SQLite database. The database-schema is just the default from here: https://doc.powerdns.com/md/authoritative/backend-generic-sqlite/
How can I solve this? I didn't find something on Google/Stackoverflow.

A: You're using Doctrine, so you should also use it to set up the database structure for you. So instead of running these "Create table" statements yourself, use the solution below, which applies to your use case.
If you're using Doctrine ORM set up your entity classes as described here: Basic Mapping
If you're using Doctrine DBAL without the ORM, you should set up the database structure like this:
Schema-Representation

A: According to Doctrine\DBAL\Platforms\SqlitePlatform API, boolean type is defined as 'BOOLEAN' (I am sure it is case insensitive) not 'bool'.