text:
Q: Updating MySQL Field Using Volley POST Request With Shared Preferences As Parameter My app opens with a Login Acitivity where after logging in, the email and password are stored into shared preferences. Then the user is brought to a second activity where they must press a button that "checks" them in , meaning they are available for work.
Using volley, I'm trying to send the email address and the String "available" as parameters to update a field in my SQL database.
So I have a couple constants defined in a separate class:
Config.java
//Currently logged in employee
public static final String EMAIL_SHARED_PREF = "employee_email";

//URL to PHP file that updates the field
public static final String EMPLOYEE_STATUS_URL = "http://localhost/android/employeestatus.php";

I have a method in my activity that makes the POST request to update the SQL field:
CheckinActivity.java
private void checkin() {

    SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
    final String employee_email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF,"Not Available");
    final String employee_status = "available";

    StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.EMPLOYEE_STATUS_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(CheckinActivity.this, response, Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(CheckinActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("employee_status", employee_status);
            params.put("employee_email", employee_email);
            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
}

And finally the PHP file that handles the request:
employeestatus.php
<?php

 if($_SERVER['REQUEST_METHOD']=='POST'){

 $employee_email = $_POST['employee_email'];
 $employee_status = $_POST['employee_status'];

//importing database connection script
 require_once('dbConnect.php');

 //Creating sql query
 $sql = "UPDATE employees
            SET employee_status = '$employee_status'
          WHERE employee_email = '$employee_email'";

 //Updating database table
 if (mysqli_query($conn,$sql)) {
 echo 'Status Updated';
 }
 else {
 echo 'Status Not Updated';
 }

 //closing connection
 mysqli_close($conn);
 }

{ print_r($_POST); return; }

As it is now, ALL the column fields update to show available instead of just the employee who is logged into the app. Any ideas?
EDIT
My original attempt was obviously wrong, the part where I was trying to post the email address. I only need to update my employee_status field but need the shared preference email from the app to be the WHERE in my SQL UPDATE.
I thought I could append the email to the url and assign it as a GET value but that didn't work. Hmmm still working on it...

A: Finally got it working! Made many mistakes:

*

*I didn't properly get the sharedPreferences email value

*I had my params backwards in the volley request

*I incorrectly named my POST values in the php file

*I forgot some apostrophes in the SQL query

Adding in { print_r($_POST); return; } to the php file really helped out seeing what was being sent, and displaying it in the toast. All the above code is working now.
So now, I plan to make a checkOut method which does the exact opposite when the employee checks out :)
Hopefully someone finds this useful.


text:
Q: Nullable string property/column in nHibernate + Fluent I'm new to nHibernate universe, so this question can be idiot ..
I have a table with a nullable nvarchar column.
In the mapping i use this Map(c => c.Genero, "genero").Nullable();
In the property i use trim to set the value, so i have a private string and a public virtual string.
When i do an select in this table i receive an runtime error in the setter of this property.
I tryed to pass this property to Nullable, but i receive a compile-time error saying The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'.
How can i do this ?
Thanks for everyone !
UPDATE
If i use just the property with { get; set; } works normally, but i need to trim.

A: The problem may be that you can't trim a null string. Try:
public string Genero
{
    get { return _genero; }
    set { _genero = string.IsNullOrEmpty(value) ? value : value.Trim(); }
}

Depending on your mapping, this may cause the trimmed string to be written to the database when the session is flushed. It might be better to map the string as a private field and trim it in the getter.

redpajama_set_name: RedPajamaStackExchange


text:
Q: django-background-tasks indefinite run The docs says,
In Django Background Task, all tasks are implemented as functions (or any other callable).
There are two parts to using background tasks:
creating the task functions and registering them with the scheduler
setup a cron task (or long running process) to execute the tasks

It appears there is no way to run django-background-tasks indefinitely and periodically, is that correct?

A: If I am understood correctly then You want to execute your tasks periodically without using cron.
You can do using django celery(https://github.com/celery/django-celery) or Task Master (https://github.com/dcramer/taskmaster)
Hope you are wanting this.

A: you can run the task indefinitely with the repeat like this.
task_method(repeat=300)

this task will repeat every 300 secconds
you can check the docs here https://django-background-tasks.readthedocs.io/en/latest/#repeating-tasks


text:
Q: Pig javascript does not fire I have copied the following JavaScript from Pig Latin site and created firstJS.js file
helloworld.outputSchema = "(word:chararray)"
function helloworld() {
    return 'Hello, World';
}

The script is Registered as follows:
register '/cloudera/examples/javascripts/firstJS.js' using javascript as myfuncs;

The JavaScript is called in Pig as follows:
//Loading the data
student = LOAD '/cloudera/examples/Students.csv' USING PigStorage(',') AS (name:chararray);

//Calling the JavaScript function in Pig Statement
B = foreach student generate myfuncs.helloworld();

//ERROR Received
 ERROR 1070: Could not resolve myfuncs.helloworld using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]

Question:
What am I doing wrong? Can somebody give me a working, complete and small example of using JavaScript with Pig. I am not sure what is missing. I am learning Pig and have just started to move little on the advance topic.


text:
Q: select data using 'IN' in MySQL using joins on multiple tables There are many questions like this but didn't helped me I have multiple tables that contain different data.
There is an institutes table that contains multiple institutes
institutes

id
name

1
A

2
B

I'm using the id of institutes in the courses table
courses

id
course
inst_id

1
A
1,2

2
B
1

Now i want to select institute name based on courses.inst_id, it return B when courses.id = 2 that's good but when id = 1 it returns only one institute name but inst_id contains on 1,2 so it should be returned both values A and B is there is any way to do that?
Here is my try
$match = '1,2';
    $stmt = $db->prepare("SELECT courses.*, teachers.name,i.name as institute FROM courses
    JOIN teachers ON teachers.id =  courses.teacher_id JOIN institutes i WHERE i.id IN
    ($match) AND courses.id = :id ");
    $stmt->execute([':id' => $id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);

A: Save inst_id as a string such as '1','2'
Check this query
SELECT courses.*, teachers.name,i.name as institute
FROM courses
JOIN teachers ON teachers.id =  courses.teacher_id JOIN institutes i WHERE i.id IN
(SELECT data_set.inst_id FROM (select inst_id from courses) AS data_set) AND courses.id = :id

Make necessary changes the query where needed.


text:
Q: Index will be removed I'm trying to simply change the length of a column within a table through SQL Server Management Studio, but receive a 'Validation Warning':
'MyTable' table
-Warning: The following schema-bound objects will be modified:
 -View 'dbo.MyViewName': indexes and schema binding will be removed.

I remember from experience that if I actually go through with this, the binding will not be readded. In the past I've had to manually write a script to re-add the view. This doesn't seem right - why would it just remove it without re-adding it at the end of the operation?
It makes me think I don't have something set up correctly, or am going about this the wrong way - am I? Or is it 'correct' procedure to have to manually re-add things in this way after table changes are made?

A: Creating a view with WITH SCHEMABINDING locks the underlying tables and prevents any changes that may change the table schema.
To change the base table you need to remove the SCHEMABINDING option from the objects or drop and recreate these objects once the table has been altered.
To find out if the view is schema bound use below tsql:
select objectproperty(object_id('view_name'), 'IsSchemaBound') as SchemaBound

To remove the with schemabinding option, just alter the view defination :
alter view schemaname.tablename
-- with schemabinding (remove it )
as
select some_column_name
from schema_name.table_name

Then make changes to the table and then alter the view again now with schemabinding
alter view schemaname.tablename
with schemabinding --(adding back )
as
select some_column_name
from schema_name.table_name

from BOL :

SCHEMABINDING :
Binds the view to the schema of the underlying table or tables. When SCHEMABINDING is specified, the base table or tables cannot be modified in a way that would affect the view definition. The view definition itself must first be modified or dropped to remove dependencies on the table that is to be modified. When you use SCHEMABINDING, the select_statement must include the two-part names (schema.object) of tables, views, or user-defined functions that are referenced. All referenced objects must be in the same database.
Views or tables that participate in a view created with the SCHEMABINDING clause cannot be dropped unless that view is dropped or changed so that it no longer has schema binding. Otherwise, the Database Engine raises an error. Also, executing ALTER TABLE statements on tables that participate in views that have schema binding fail when these statements affect the view definition.


text:
Q: Losing control of GUI upon playing a wav file I can't understand why I am loosing control of my GUI even though I am implementing a thread to play a .wav file. Can someone pin point what is incorrect?
    #!/usr/bin/env python

import wx, pyaudio, wave, easygui, thread, time, os, sys, traceback, threading
import wx.lib.delayedresult as inbg

isPaused = False
isStopped = False

class Frame(wx.Frame):
 def __init__(self):
            print 'Frame'
            wx.Frame.__init__(self, parent=None, id=-1, title="Jasmine", size=(720, 300))

            #initialize panel
            panel = wx.Panel(self, -1)

            #initialize grid bag
            sizer = wx.GridBagSizer(hgap=20, vgap=20)

            #initialize buttons
            exitButton = wx.Button(panel, wx.ID_ANY, "Exit")
            pauseButton = wx.Button(panel, wx.ID_ANY, 'Pause')
            prevButton = wx.Button(panel, wx.ID_ANY, 'Prev')
            nextButton = wx.Button(panel, wx.ID_ANY, 'Next')
            stopButton = wx.Button(panel, wx.ID_ANY, 'Stop')

            #add widgets to sizer
            sizer.Add(pauseButton, pos=(1,10))
            sizer.Add(prevButton, pos=(1,11))
            sizer.Add(nextButton, pos=(1,12))
            sizer.Add(stopButton, pos=(1,13))
            sizer.Add(exitButton, pos=(5,13))

            #initialize song time gauge
            #timeGauge = wx.Gauge(panel, 20)
            #sizer.Add(timeGauge, pos=(3,10), span=(0, 0))

            #initialize menuFile widget
            menuFile = wx.Menu()
            menuFile.Append(0, "L&oad")
            menuFile.Append(1, "E&xit")
            menuBar = wx.MenuBar()
            menuBar.Append(menuFile, "&File")
            menuAbout = wx.Menu()
            menuAbout.Append(2, "A&bout...")
            menuAbout.AppendSeparator()
            menuBar.Append(menuAbout, "Help")
            self.SetMenuBar(menuBar)
            self.CreateStatusBar()
            self.SetStatusText("Welcome to Jasime!")

            #place sizer on panel
            panel.SetSizer(sizer)

            #initialize icon
            self.cd_image = wx.Image('cd_icon.png', wx.BITMAP_TYPE_PNG)
            self.temp = self.cd_image.ConvertToBitmap()
            self.size = self.temp.GetWidth(), self.temp.GetHeight()
            wx.StaticBitmap(parent=panel, bitmap=self.temp)

  #set binding
            self.Bind(wx.EVT_BUTTON, self.OnQuit, id=exitButton.GetId())
            self.Bind(wx.EVT_BUTTON, self.pause, id=pauseButton.GetId())
            self.Bind(wx.EVT_BUTTON, self.stop, id=stopButton.GetId())
            self.Bind(wx.EVT_MENU, self.loadFile, id=0)
            self.Bind(wx.EVT_MENU, self.OnQuit, id=1)
            self.Bind(wx.EVT_MENU, self.OnAbout, id=2)

 #Load file using FileDialog, and create a thread for user control while running the file
 def loadFile(self, event):

  foo = wx.FileDialog(self, message="Open a .wav file...", defaultDir=os.getcwd(), defaultFile="", style=wx.FD_MULTIPLE)
  foo.ShowModal()

  self.queue = foo.GetPaths()
  self.threadID = 1

  while len(self.queue) != 0:
   self.song = myThread(self.threadID, self.queue[0])
   self.song.start()
   while self.song.isAlive():
    time.sleep(2)
   self.queue.pop(0)
                self.threadID += 1

 def OnQuit(self, event):
  self.Close()

 def OnAbout(self, event):
  wx.MessageBox("This is a great cup of tea.", "About Jasmine", wx.OK | wx.ICON_INFORMATION, self)

 def pause(self, event):
  global isPaused
  isPaused = not isPaused

 def stop(self, event):
  global isStopped
  isStopped = not isStopped

class myThread (threading.Thread):
  def __init__(self, threadID, wf):
   self.threadID = threadID
   self.wf = wf
   threading.Thread.__init__(self)
  def run(self):
   global isPaused
   global isStopped

   self.waveFile = wave.open(self.wf, 'rb')

   #initialize stream
   self.p = pyaudio.PyAudio()
   self.stream = self.p.open(format = self.p.get_format_from_width(self.waveFile.getsampwidth()), channels = self.waveFile.getnchannels(), rate = self.waveFile.getframerate(), output = True)
   self.data = self.waveFile.readframes(1024)

   isPaused = False
   isStopped = False
   #main play loop, with pause event checking
   while self.data != '':
   # while isPaused != True:
   #  if isStopped == False:
     self.stream.write(self.data)
     self.data = self.waveFile.readframes(1024)
   #  elif isStopped == True:
   #   self.stream.close()
   #   self.p.terminate()

   self.stream.close()
   self.p.terminate()

class App(wx.App):

 def OnInit(self):
  self.frame = Frame()
  self.frame.Show()
  self.SetTopWindow(self.frame)
  return True

def main():
 app = App()
 app.MainLoop()

if __name__=='__main__':
 main()

A: Your loadFile method, quite independently of the fact that it delegates song-playing to many threads (which it waits for in strange ways, but, that's another issue), is still monopolizing the wx event loop until it returns.  Where you currently have a time.sleep, try adding app.Yield(True) (of course you need to make app visible at that point in your code: simplest though inelegant is to add a global app at the start of main.
Event-driven systems typically serve the event loop only when your various event handler methods return: if you have a long-running event handler, you need to explicitly yield control to the event loop once in a while.  Various event systems offer different ways to do it: in wx, it's the Yield method which I just recommended you try.  See the brief description un the docs.


text:
Q: After switching brackets [] to list, would this be considered to be the same? I commented out the list containing the odd numbers and added my_odds = list(range(1, 60, 2))
print(my_odds). I was wondering whats the difference between the list and the []? are they technically the same?
def first_code_from_headfirst():

   # odds = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55,
     #       57, 59]

    my_odds = list(range(1, 60, 2))
    print(my_odds)

    for el in range(5):
        right_this_minute = datetime.today().minute

        if right_this_minute in my_odds:
            print("this minute seems a little odd")

        else:
            print('not an odd minute.')

A: The difference between [] and list is that one is syntactic construct and the other is function call. Which means:
import dis

def func():
    a = []

dis.dis(func)

  1           0 BUILD_LIST               0
              3 STORE_FAST               0 (a)
              6 LOAD_CONST               0 (None)
              9 RETURN_VALUE

whereas:
def func():
    a = list()

dis.dis(func)

  1           0 LOAD_GLOBAL              0 (list)
              3 CALL_FUNCTION            0
              6 STORE_FAST               0 (a)
              9 LOAD_CONST               0 (None)
             12 RETURN_VALUE

So the former should be tiny bit faster as it does not have to search for the global name list. (This is for CPython 2.7.10)


text:
Q: Matching Google Cloud Storage ID to a user email address I'm looking for a way to determine who uploaded a file to a Cloud Storage bucket. All of the users with access to write to the bucket are authenticated users in the same G Suite domain.
The object ACL in Cloud Storage shows an owner identifier string which looks like the following:
{
  "entity": "user-84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46",
  "entityId": "84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46",
  "role": "OWNER"
}

However, it does not appear that there is an easy way to map this ID back to a user's email address (or to determine the Cloud Storage ID for a user whose email I know, except by using that user account to upload a file and querying the object ACL).
Is this true? Or am I just not seeing the way to do this?
Thank you for the help!

A: Although I can't give you an specific timeline, we're actively working on deprecating canonical ids.  This should no longer be a problem in the near future.
In the meanwhile, there are.. options.
First: A user can find their canonical ID on this page (Unfortunately it is going to make you pick a project, since the page also shows the canonical ids for the project roles).
https://console.cloud.google.com/storage/settings
However, if you really need to find out the email address for a random canonical id you should be able to do this somewhat ugly workaround.
1) Add the user to a bucket policy via the ACL API
    gsutil acl ch -u <canonical_id>:READ gs://<bucket>

2) Fetch the bucket IAM policy
    gsutil iam get gs://<bucket>

The entry should show up as an email address.
{
  "bindings": [
    {
      "members": [
        "projectOwner:<project-id>",
        "projectEditor:<project-id>",
      ],
      "role": "roles/storage.legacyBucketOwner"
    },
    {
      "members": [
        "projectViewer:<project-id>",
        "user:<user email here>"
      ],
      "role": "roles/storage.legacyBucketReader"
    }
  ],
  "etag": "CAI="
}

A: Try getting the ACLs again. I just tried today 07/05/2017 and the returned ACLs included email address. It would appear Google has updated the API, replacing the old Google Cloud Storage ID with the user's email address.
{
  "email": "email@domain.com",
  "entity": "user-email@domain.com",
  "role": "OWNER"
}


text:
Q: Prime Factor JAVA program not printing out the write number of "Sets Factored" At the very bottom of my code I have a System.out.print  printing the wrong sets of numbers. In the output terminal it says it is factoring 13 numbers, but as you can see it is a lot more numbers than just 13.
Here is my code:
import java.io.*;
import java.util.Scanner;
public class Project4
{
    public static void main(String[] args)
    throws FileNotFoundException
    {
        Scanner in = new Scanner(new File("data4.txt"));
        System.out.println("Tanner Triggs  CM111 Lecture   Project #4    Due Friday Oct 18");
        int ctr= 0;
        int x = in.nextInt();
        while (x != -999)
        {
            int y = x;
            int z = 2;
            System.out.printf("\r\n For the number %9d the prime factors are",x);
            ctr++;
            while (z< y)
            {
                int remainder = x%z;
                if (remainder == 0)
                {
                    System.out.print(","+z);
                    x= x/z;
                }
                else
                {
                    z++;
                }
            }
            if (x==y)
            {
                System.out.print("  "+x);
            }
            x = in.nextInt();
        }
        System.out.printf("\n\n %9d Sets of numbers factored",ctr);
    }
}

This is my data4.txt file:
459
120
340
379217
56
457
315
548153764
1001
240652872
123456789
32159
456
-999

A: You increase ctr for every line you read from your file, so you end up with a correct 13. If you want to count how many prime factors are processed, you should move the incrementing into the inner while loop.


text:
Q: grant only specific IP access to network drive how to grant a specific IP on my LAN permission to my network drive running on Win7. this machine can't see my ubuntu, and I want only this ubuntu to have access to the drive. so is there any option to give acces only for the specific IP i.e. 192.168.0.xxx ?
I can mount this drive, and I have it already, but now I want to give access only to one machine. I can make password access but can I just specify concrete IP address instead?

A: Password protection (network authentication) is significantly easier and less error prone.  Password protection also allows you to restrict access per share rather than restricting all access to all shares on the system.
It can be done via IPSec, but (at least historically) IPSec on Windows is ridiculously complex and is generally considered a tremendous waste of time for the benefits you get.  I've never seen anybody actually use IPSec before except on production servers.
You can also configure the firewall, but this is only slightly less cumbersome.  Open Control Panel --> System and Security --> Windows Firewall --> Advanced Settings.  Make sure Inbound connections are default blocked (this is the default setting).  Then, click on Inbound rules.  Scroll down until you see "File and Printer Sharing".  The ones that should do what you want are NB-Datagram-In, NB-Name-In, NB-Session-In, and SMB-In.  I don't believe the others are used for file sharing.  For each of those, double click the rule to open the Properties Window.  On the Scope tab, add the IP Address in question to the list of allowed clients.  This should prohibit any other IP from accessing all file shares on this computer, but you should test it.


text:
Q: Conditionally format a table based on average of dataset, but adhering to slicer selections I have a simple CSV data set such as this.
ID,MainCategory,SubCategory,Type,Value
1,E,E1,Demo,5
2,N,N3,Install,2
3,E,E1,Demo,4
4,E,E2,Install,7
5,D,D1,Install,3
6,S,S2,PM,4
7,N,N2,Install,7
8,N,N2,Demo,1
9,E,E2,Demo,2
10,D,D2,Install,6
11,D,D3,PM,4
12,S,S1,PM,8
13,N,N1,Install,5
14,S,S3,Install,8
15,S,S1,Demo,9
16,E,E3,Demo,5
17,N,N2,Install,3
18,E,E2,PM,6
19,D,D2,PM,6
20,N,N3,Demo,6
21,S,S2,Demo,7
22,E,E3,Install,2
23,S,S1,Install,4
24,S,S2,PM,8
25,D,D1,Install,5

In my Power BI Desktop, I'd like to load this into a table, and conditionally format the Value column based on whether the value in each row is greater than or less than the average for the currently selected data set.
For instance, the average of Value considering the entire table is 5.08, so if there are no filters applied (as in, all my slicers are set to select nothing), I'd like all rows whose Value is 6 or more to be background colored in one color, and the others in another color. For this, I created two measures like so:

*

*AvgOfVal = DIVIDE( SUM(G2G[Value]), COUNTA(G2G[ID]) )

*BGColor = IF(SUM(G2G[Value]) > [AvgOfVal], "Light Pink", "Light Blue")
Then I tried to apply the BGColor measure for conditionally formatting the background, but this doesn't work as expected, and instead produces the result below.

I realize that this is due to the fact that the measure is calculated per row, so when conditional formatting is applied, as seen in the AvgOfVal column in the table, it calculates average per row instead of for the entire data set. How can I calculate a measure that takes into account the entire data set (considering slicers), and do the conditional formatting as I need.
Please keep in mind that if a user were to select a slicer filter (say, MainCategory = D), then I want the conditional formatting to reflect this. So in this case, given that AvgOfVal = 4.80 for MainCategory = D entries, I'd like all rows whose Value >= 5 to be in one color, and others in another color.

A:
I realize that this is due to the fact that the measure is calculated per row

Yes.  The key is understanding how that happens.  When the measure is calculated a "context transition" happens and the current row is added to the filter context.
So what you want is a calculation that removes the row filter that was added in the context transition.  So you need ALLSELECTED(), which does precisely that. eg
AvgOvVAl = CALCULATE( AVERAGE('data'[Value]), ALLSELECTED() )

Removing the "innermost" filter which in this case is the filter on the row, but leaving all other filters, ie filters added on the report, page, visual, or filters coming from interactions with other visuals like slicers.


text:
Q: Spring integration - SpelParseException in gateway I'm working on some app with spring integration, and I'm gettion Exception
Property 'expressionString' threw exception; nested exception is org.springframework.expression.spel.SpelParseException: EL1046E:(pos 24): Cannot find terminating  for string [Sanitized]

my gateway:
<int:channel id="getProductsReq"/>
<int:channel id="getProductsResp"/>

<int:chain input-channel="getProductsReq" output-channel="getProductsResp" id="getProductsChain">
    <int:header-enricher>
        <int:header name="Content-Type" value="application/json"/>
        <int:header name="Authorization" expression="@httpSessionService.getToken()"/>
    </int:header-enricher>
    <int:service-activator expression="@chainLogger.log(#root, 'FO req for getProductsInfo)"/>
    <int-http:outbound-gateway url="${getProducts.url}"
                               http-method="GET" mapped-request-headers="Authorization,Content-Type"
                               expected-response-type="com.app.GenericResponse">
        <int-http:uri-variable name="code" expression="payload.getCode()"/>
        <int-http:request-handler-advice-chain>
            <beans:ref bean="integrationLoggingAdvice" />
        </int-http:request-handler-advice-chain>
    </int-http:outbound-gateway>
</int:chain>

Yup, GenericResponse is a Generic type. I have no idea what is wrong.


text:
Q: rcharts: nPlot Formating x-axis with dates I have a data.frame with dates and integers:
  df <- data.frame(date=seq.Date(from=as.Date("2012/01/01"), to=as.Date("2012/02/28"), by="1 day"), y=1:59)

I want to plot the data.frame with rCharts nPlot:
  n <- nPlot(y ~ date, group = "team", data = df, type = "lineChart")
  n$xAxis(
    tickFormat =   "#!
      function(d) {return d3.time.format('%Y-%M-%d')(new Date(d));}
    !#",
    rotateLabels = -90
  )
  n

But the x-axis isn't formatted correctly.

So how do I format the dates correctly?

A: In R as.numeric(someDate) is days since origin. Here we need milliseconds from origin.
So it should be
  df <- data.frame(date=seq.Date(from=as.Date("2012/01/01", origin="1970-01-01"), to=as.Date("2012/02/28", origin="1970-01-01"), by="1 day"), y=1:59)

  n <- nPlot(y ~ date, group = "team", data = df, type = "lineChart")
  n$xAxis(
    tickFormat =   "#!
      function(d) {return d3.time.format('%Y-%m-%d')(new Date(d*1000*3600*24));}
    !#",
    rotateLabels = -90
  )
  n

A: %M is minute, what you want is %m which will get you months:
 n <- nPlot(y ~ date, group = "team", data = df, type = "lineChart")
  n$xAxis(
    tickFormat =   "#!
      function(d) {return d3.time.format('%Y-%m-%d')(new Date(d));}
    !#",
    rotateLabels = -90
  )
  n


text:
Q: Memory issue while Animating many images I have about 272 layer of images for animating my view background. Below is a sample code on how I animate the images. But doing like this I'm getting memory issue and app crashes. Any advice?
NSMutableArray *imagesArray = [NSMutableArray array];

for (int i = 272; i >=1; i--)
{
    NSString *imageName = [NSString stringWithFormat:@"layer-%d.jpg", i];
    UIImage *bgImage =[UIImage imageNamed:imageName];

    [imagesArray addObject:bgImage];
}

[self.bgImageView setAnimationDuration:7.0f];
[self.bgImageView  setAnimationImages:imagesArray];
[self.bgImageView  startAnimating];

A: Using [UIImage imageNamed:] cache the image in memory, try using [UIImage imageWithContentOfFile:]. Check this answer

A: Try release object of uiimage after adding to to array:
NSMutableArray *imagesArray = [NSMutableArray array];
for (int i = 272; i >=1; i--)
{
    NSString *imageName = [NSString stringWithFormat:@"layer-%d.jpg", i];
    UIImage *bgImage =[UIImage imageNamed:imageName];
    [imagesArray addObject:bgImage];
    bgImage=nil;
    imageName=nil;
 }
    [self.bgImageView setAnimationDuration:7.0f];
    [self.bgImageView  setAnimationImages:imagesArray];
    [self.bgImageView  startAnimating];

Or try to declare uiimage outside loop and reuse it in each loop:
NSMutableArray *imagesArray = [NSMutableArray array];
UIImage  *bgImage;
NSString *imageName;
for (int i = 272; i >=1; i--)
{
    imageName = [NSString stringWithFormat:@"layer-%d.jpg", i];
    bgImage =[UIImage imageNamed:imageName];
    [imagesArray addObject:bgImage];
 }
    [self.bgImageView setAnimationDuration:7.0f];
    [self.bgImageView  setAnimationImages:imagesArray];
    [self.bgImageView  startAnimating];


text:
Q: How do I track down a golang stack overflow? I have a stack overflow in my code somewhere that's most likely caused by a (deliberately) recursive structure being printed (I don't actually want to print it). I want to track down which print call in my code is leading to the stack overflow, but all I get is the top 100 entries of the stack, and then one entry from the bottom:
fmt.(*pp).printValue(0xc000088a90, 0x609680, 0xc00015cde0, 0x97, 0xc000000076, 0x115ab4)
    /usr/local/go/src/fmt/print.go:869 +0x516 fp=0xc0204b98a8 sp=0xc0204b96d0 pc=0x4cd066
fmt.(*pp).printValue(0xc000088a90, 0x61d300, 0xc000149400, 0x194, 0x76, 0x115ab3)
    /usr/local/go/src/fmt/print.go:823 +0x1883 fp=0xc0204b9a80 sp=0xc0204b98a8 pc=0x4ce3d3
...additional frames elided...
created by testing.(*T).Run
    /usr/local/go/src/testing/testing.go:960 +0x350

... which is completely opposite to what you need to track down a SO. Is there a way to get the useful part of the stack trace (the first 100 entries rather than the last 100 entries)?


text:
Q: Java: Class Not Found: net.sf.cglib.proxy.MethodInterceptor So I have this old app and I am currently getting this error when trying to run some scheduled tasks (see Exception).
I experienced sort of the same issue before and I solved it by excluding cglib from jersey (see pom.xml). However, now it seems that this affected some other part of the app.
Any ideas?
UPDATE: The project uses java 1.6
Exception:
ERROR at org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler.handleError(:95) Unexpected error occurred in scheduled task.
    java.lang.NoClassDefFoundError: net/sf/cglib/proxy/MethodInterceptor
            at org.jvnet.hk2.external.generator.ServiceLocatorGeneratorImpl.initialize(ServiceLocatorGeneratorImpl.java:71)
            at org.jvnet.hk2.external.generator.ServiceLocatorGeneratorImpl.create(ServiceLocatorGeneratorImpl.java:96)
            at org.glassfish.hk2.internal.ServiceLocatorFactoryImpl.internalCreate(ServiceLocatorFactoryImpl.java:251)
            at org.glassfish.hk2.internal.ServiceLocatorFactoryImpl.create(ServiceLocatorFactoryImpl.java:228)
            at org.glassfish.jersey.internal.inject.Injections._createLocator(Injections.java:142)
            at org.glassfish.jersey.internal.inject.Injections.createLocator(Injections.java:113)
            at org.glassfish.jersey.internal.RuntimeDelegateImpl.<init>(RuntimeDelegateImpl.java:60)
            at sun.reflect.GeneratedConstructorAccessor439.newInstance(Unknown Source)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:534)
            at java.lang.Class.newInstance(Class.java:379)
            at javax.ws.rs.ext.FactoryFinder.newInstance(FactoryFinder.java:117)
            at javax.ws.rs.ext.FactoryFinder.find(FactoryFinder.java:207)
            at javax.ws.rs.ext.RuntimeDelegate.findDelegate(RuntimeDelegate.java:135)
            at javax.ws.rs.ext.RuntimeDelegate.getInstance(RuntimeDelegate.java:120)
            at javax.ws.rs.core.UriBuilder.newInstance(UriBuilder.java:95)
            at javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:119)
            at org.glassfish.jersey.client.JerseyWebTarget.<init>(JerseyWebTarget.java:72)
            at org.glassfish.jersey.client.JerseyClient.target(JerseyClient.java:180)
            at org.glassfish.jersey.client.JerseyClient.target(JerseyClient.java:69)
            [Some app method calling a REST service]..
            at sun.reflect.GeneratedMethodAccessor998.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:622)
            at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:64)
            at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:53)
            at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
            at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351)
            at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178)
            at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:165)
            at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:267)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1146)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
            at java.lang.Thread.run(Thread.java:701)
    Caused by: java.lang.ClassNotFoundException: net.sf.cglib.proxy.MethodInterceptor
            at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1858)
            at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1701)
            ... 35 more

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    ....
    <modules>
        ....
    </modules>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-idea-plugin</artifactId>
                    <version>2.2-fixed</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-idea-plugin</artifactId>
                <version>2.2</version>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <useFile>false</useFile>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <repositories>
        ...

        <repository>
            <id>official1</id>
            <name>Official Maven Repository Mirror 1</name>
            <url>http://repo1.maven.org/maven2</url>
            <releases>
                <!--<checksumPolicy>false</checksumPolicy>-->
                <updatePolicy>never</updatePolicy>
            </releases>
        </repository>

        <repository>
            <id>official2</id>
            <name>Official Maven Repository Mirror 2</name>
            <url>http://repo2.maven.org/maven2</url>
            <releases>
                <!--<checksumPolicy>false</checksumPolicy>-->
                <updatePolicy>never</updatePolicy>
            </releases>
        </repository>
    </repositories>

    <pluginRepositories>
        ...
        ...
    </pluginRepositories>

    <properties>
        <spring.version>3.2.14.RELEASE</spring.version>
        <org.spring.security.version>3.2.8.RELEASE</org.spring.security.version>
        <cxf.version>2.1</cxf.version>
        <gwtVersion>1.5.3</gwtVersion>
        <project.build.sourceEncoding>ISO-8859-1</project.build.sourceEncoding>
    </properties>

    <dependencyManagement>
        <dependencies>
            ...
            <!-- END internal modules -->

            <dependency>
                <groupId>org.apache.ws.commons.axiom</groupId>
                <artifactId>axiom-impl</artifactId>
                <version>1.2.7</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.apache.geronimo.specs</groupId>
                        <artifactId>geronimo-javamail_1.4_spec</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>org.apache.geronimo.specs</groupId>
                        <artifactId>geronimo-activation_1.1_spec</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>jaxen</groupId>
                        <artifactId>jaxen</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.apache.ws.commons.axiom</groupId>
                <artifactId>axiom-api</artifactId>
                <version>1.2.7</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.apache.geronimo.specs</groupId>
                        <artifactId>geronimo-javamail_1.4_spec</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>org.apache.geronimo.specs</groupId>
                        <artifactId>geronimo-activation_1.1_spec</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>jaxen</groupId>
                        <artifactId>jaxen</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>

            <!-- Spring Framework -->
            <dependency>
                <groupId>aopalliance</groupId>
                <artifactId>aopalliance</artifactId>
                <version>1.0</version>
            </dependency>

            <dependency>
                <groupId>org.apache.xmlbeans</groupId>
                <artifactId>xmlbeans</artifactId>
                <version>2.4.0</version>
            </dependency>

            <dependency>
                <groupId>wsdl4j</groupId>
                <artifactId>wsdl4j</artifactId>
                <version>1.6.1</version>
            </dependency>

            <dependency>
                <groupId>org.apache.axis2</groupId>
                <artifactId>axis2</artifactId>
                <version>1.3</version>
            </dependency>

            <dependency>
                <groupId>org.apache.axis2</groupId>
                <artifactId>axis2-wsdl2code-maven-plugin</artifactId>
                <version>1.3</version>
            </dependency>

            <dependency>
                <groupId>org.apache.ws.commons.schema</groupId>
                <artifactId>XmlSchema</artifactId>
                <version>1.4.5</version>
            </dependency>

            <dependency>
                <groupId>backport-util-concurrent</groupId>
                <artifactId>backport-util-concurrent</artifactId>
                <version>3.1</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
                <scope>test</scope>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <!-- Apache CXF -->
            <dependency>
                <groupId>javax.xml.bind</groupId>
                <artifactId>jaxb-api</artifactId>
                <version>2.1</version>
            </dependency>

            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-core</artifactId>
                <version>${cxf.version}</version>
            </dependency>

            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-frontend-jaxws</artifactId>
                <version>${cxf.version}</version>
            </dependency>

            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-databinding-jaxb</artifactId>
                <version>${cxf.version}</version>
            </dependency>

            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-transports-http</artifactId>
                <version>${cxf.version}</version>
            </dependency>

            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-management</artifactId>
                <version>${cxf.version}</version>
            </dependency>

            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-common-utilities</artifactId>
                <version>${cxf.version}</version>
            </dependency>

            <!-- JSP Libraries -->
            <dependency>
                <groupId>org.ajaxtags</groupId>
                <artifactId>ajaxtags</artifactId>
                <version>1.3-beta-rc7</version>
                <exclusions>
                    <exclusion>
                        <groupId>taglibs</groupId>
                        <artifactId>standard</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>

            <dependency>
                <groupId>org.apache.xmlgraphics</groupId>
                <artifactId>fop</artifactId>
                <version>0.95</version>
            </dependency>

            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.1.2</version>
            </dependency>

            <dependency>
                <groupId>taglibs</groupId>
                <artifactId>standard</artifactId>
                <version>1.1.2</version>
            </dependency>

            <!-- Java Mail -->
            <dependency>
                <groupId>javax.mail</groupId>
                <artifactId>mail</artifactId>
                <version>1.4</version>
            </dependency>

            <!-- Apache Commons -->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-httpclient</artifactId>
                <version>3.0-beta1</version>
            </dependency>

            <dependency>
                <groupId>commons-httpclient</groupId>
                <artifactId>commons-httpclient</artifactId>
                <version>3.1</version>
            </dependency>

            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>3.2-FINAL</version>
            </dependency>

            <!-- XML Serialization -->
            <dependency>
                <groupId>com.thoughtworks.xstream</groupId>
                <artifactId>xstream</artifactId>
                <version>1.3.1</version>
            </dependency>

            <!-- JPA Persistence Annotations -->
            <dependency>
                <groupId>javax.persistence</groupId>
                <artifactId>ejb</artifactId>
                <version>3.0-public-draft-20060502</version>
            </dependency>

            <!-- GeoIP -->
            <dependency>
                <groupId>net.sf</groupId>
                <artifactId>javainetlocator</artifactId>
                <version>1.0</version>
            </dependency>

            <!-- MySQL JDBC Connector -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.36</version>
            </dependency>

            <!-- Servlet API -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.4</version>
            </dependency>

            <!-- Logging -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.14</version>
            </dependency>

            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>1.4.2</version>
            </dependency>

            <!-- Unit testing -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
                <scope>test</scope>
            </dependency>

            <dependency>
                <groupId>org.jmock</groupId>
                <artifactId>jmock</artifactId>
                <version>2.5.1</version>
            </dependency>

            <dependency>
                <groupId>org.jmock</groupId>
                <artifactId>jmock-parent</artifactId>
                <version>2.5.1</version>
            </dependency>

            <dependency>
                <groupId>org.jmock</groupId>
                <artifactId>jmock-junit4</artifactId>
                <version>2.4.0</version>
            </dependency>

            <dependency>
                <groupId>com.oreilly</groupId>
                <artifactId>fileupload</artifactId>
                <version>1.0</version>
            </dependency>
             <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging-api</artifactId>
                <version>1.0.4</version>
            </dependency>
            <dependency>
                <groupId>commons-codec</groupId>
                <artifactId>commons-codec</artifactId>
                <version>1.3</version>
            </dependency>

            <dependency>
                <groupId>org.antlr</groupId>
                <artifactId>stringtemplate</artifactId>
                <version>3.2</version>
            </dependency>

            <!--  GWT deps  -->
            <dependency>
                <groupId>com.google.gwt</groupId>
                <artifactId>gwt-servlet</artifactId>
                <version>${gwtVersion}</version>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>com.google.gwt</groupId>
                <artifactId>gwt-user</artifactId>
                <version>${gwtVersion}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>com.google.gwt</groupId>
                <artifactId>gwt-dev</artifactId>
                <version>${gwtVersion}</version>
                <classifier>${platform}-libs</classifier>
                <type>zip</type>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>com.google.gwt</groupId>
                <artifactId>gwt-dev</artifactId>
                <version>${gwtVersion}</version>
                <classifier>${platform}</classifier>
                <scope>provided</scope>
            </dependency>

            <dependency>
                <groupId>javax.media</groupId>
                <artifactId>jai_core</artifactId>
                <version>1.1.2_01</version>
            </dependency>

            <dependency>
                <groupId>com.sun.media</groupId>
                <artifactId>jai_codec</artifactId>
                <version>1.1.2_01</version>
            </dependency>

            <dependency>
                <groupId>xstream</groupId>
                <artifactId>xstream</artifactId>
                <version>1.2</version>
            </dependency>

            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
                <version>1.1.2</version>
            </dependency>

            <dependency>
                <groupId>net.sourceforge.jtds</groupId>
                <artifactId>jtds</artifactId>
                <version>1.2.2</version>
            </dependency>

            <dependency>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
                <version>18.0</version>
            </dependency>

            <dependency>
                <groupId>org.glassfish.jersey.core</groupId>
                <artifactId>jersey-client</artifactId>
                <version>2.4.1</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.glassfish.hk2.external</groupId>
                        <artifactId>cglib</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.glassfish.jersey.media</groupId>
                <artifactId>jersey-media-moxy</artifactId>
                <version>2.4.1</version>
            </dependency>
            <dependency>
                <groupId>org.codehaus.jettison</groupId>
                <artifactId>jettison</artifactId>
                <version>1.3.7</version>
            </dependency>

            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-core</artifactId>
                <version>${org.spring.security.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-web</artifactId>
                <version>${org.spring.security.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-config</artifactId>
                <version>${org.spring.security.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-acl</artifactId>
                <version>${org.spring.security.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-taglibs</artifactId>
                <version>${org.spring.security.version}</version>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <!--  profiles (with activation per platform) -->
    <profiles>
        <profile>
            <id>gwt-dev-windows</id>
            <properties>
                <platform>windows</platform>
            </properties>
            <activation>
                <activeByDefault>false</activeByDefault>
                <os>
                    <family>windows</family>
                </os>
            </activation>
        </profile>
        <profile>
            <id>gwt-dev-mac</id>
            <properties>
                <platform>mac</platform>
            </properties>
            <activation>
                <activeByDefault>false</activeByDefault>
                <os>
                    <family>mac</family>
                </os>
            </activation>
        </profile>
        <profile>
            <id>gwt-dev-linux</id>
            <properties>
                <platform>linux</platform>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
                <os>
                    <name>linux</name>
                </os>
            </activation>
        </profile>
    </profiles>
</project>

A: To fix

ClassNotFoundException: net.sf.cglib.proxy.MethodInterceptor

you need to add cglib:cglib dependency:
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>2.2</version>
</dependency>

This cglib:cglib was transitively picked up through org.glassfish.hk2.external:cglib, but is now missing since you excluded it.
which cglib version to use
With @SteveC's suggestion (to use version 2.2 instead of 3.2.4), I checked which version was used by jersey-client:2.4.1.  It's cglib:cglib:2.2.0-b21.
Now, looking on https://mvnrepository.com/artifact/cglib/cglib, this is not available (probably a private repackaging of 2.2 done for org.glassfish). I think it's fair to say 2.2 is the best match.

A: Simply add .jar "com.springsource.net.sf.cglib-2.2.0" for Page Factory


text:
Q: Passed JSON collection not picked up by controller I have the following javascript snippet:
$.ajax({
            url: self.LoadCirculationListUrl,
            cache: false,
            async: false,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: [ { "ColumnName":"France","Comparitor":"=","Value":"1"},{"ColumnName":"Germany","Comparitor":">","Value":"3"}]
        });

Here is the controllre which is accessed from the above ajax call:
public ActionResult LoadCirculationData(IList<CirculationListFilter> filters)
{
}

Here is the CirculationListFilter class
public sealed class CirculationListFilter
{
    public string ColumnName { get; set; }

    public string Comparitor { get; set; }

    public string Value { get; set; }
}

Now when I run the code, the controller does not get the JSON collection passed to it; filters is always null. However, if I do this:
$.ajax({
            url: self.LoadCirculationListUrl,
            cache: false,
            async: false,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: { "ColumnName":"Germany","Comparitor":">","Value":"3"}
        });

and the contoller is like this:
public ActionResult LoadCirculationData(CirculationListFilter filters)
{
}

The data is passed fine. Why can't the controller bind a collection of JSON items?
EDIT:
I changed the AJAX call to use this:
data: { filters: [{ "ColumnName": "France", "Comparitor": "=", "Value": "1" }, { "ColumnName": "Germany", "Comparitor": ">", "Value": "3" }]},

and the ActionResult:
public ActionResult LoadCirculationData(List<CirculationListFilter> filters)

Now filters has 2 items inside of it, but each of the CirculationListFilter classes are populated with NULL data in their properties. So I'm getting closer, but the actual values are not being binded.

A: The problem is in the .ajax() call.
.ajax() doesn't convert the data into JSON string.
The reason why it works for one item is because .ajax() was able to convert the data into a query string which MVC happily accepted.
The solution is to convert the JSON into string first:
$.ajax({
            url: self.LoadCirculationListUrl,
            cache: false,
            async: false,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify([ { "ColumnName":"France","Comparitor":"=","Value":"1"},{"ColumnName":"Germany","Comparitor":">","Value":"3"}])
        });

A: I've found another solution:
Ajax call:
data: { 'json': '[{ "ColumnName": "France", "Comparitor": "=", "Value": "1" }, { "ColumnName": "Germany", "Comparitor": ">", "Value": "3" }]' },

Controller:
public ActionResult LoadCirculationData(string json)
{
    JavaScriptSerializer js = new JavaScriptSerializer();

    var obj = js.Deserialize<List<CirculationListFilter>>(json);
}

The above gives me the items that I need. Really not sure why the JSON binder doesn't do this by default.

A: If you want to recieve in this format
public ActionResult LoadCirculationData(IList<CirculationListFilter> filters)
{
}

You need to post it in next format data: {
{
"ColumnName[0]":"Germany","Comparitor[0]":">","Value[0]":"3",
"ColumnName[1]":"Germany","Comparitor[1]":">","Value[1]":"3",
"ColumnName[2]":"Germany","Comparitor[2]":">","Value[2]":"3",
"ColumnName[3]":"Germany","Comparitor[3]":">","Value[3]":"3",
"ColumnName[4]":"Germany","Comparitor[4]":">","Value[4]":"3",
}


text:
Q: Check if serial port is listening I have an Arduino sending and receiving instructions with a Python script via a serial port.
The Arduino takes a button state and when it is pushed, it will send a message via the serial port to a Python script and await a response. (via Serial.available()). It works well enough.
However, if the Python script has crashed for whatever reason (ideally it will run in the background, so it can't be easily checked), the Arduino will wait forever and will be unavailable even on a script restart.
Is there a way for my Arduino to check if there is something listening on the serial port? (and alert me with flashing lights, etc. if not) or is this not how serial works? Worst case I guess I could use a timeout, although that is not ideal.

A: You have a limited ability to detect if there is something listening on the other side by using the DSR/DTR pins.
When you open the serial port on the machine your scripts runs on, it should raise its DTR pin (or you should be able to convince it to do so: the documentation of the library you use to drive the COM port should tell you how).
Then, on your Arduino, you can check its DSR pin (assuming null-modem wiring with handshaking, where the PC DTR pin is wired to DSR+CD on the Arduino) at regular intervals, and handle the 'nobody connected' scenario in any way you see fit.
One problem with this approach is that your PC script may not close the serial port when it crashes/stops responding, leaving the DTR pin enabled as if everything is still OK. Also, your script may simply miss the message from the Arduino due to errors on the serial line.
For that reason, you should always implement a timeout in your receive routines: even if there is a party listening at the other end, there is no guarantee it has received your message (or that its response will reach you intact).
Re-sending the message at least once (assuming DSR is raised) if a timeout occurs makes your protocol more reliable.

A: The Arduino doesn't use the DSR line or any other handshaking line, so you can't do what you suggest.

A: I agree with mdb that timeouts are necessary, but would also add that you might want to implement simple challenge/response system that periodically  checks if anyone is listening. (I like ircd's Ping-Pong analogy).


text:
Q: RoutedCommands propagation strategy I'm a newby of WPF, and 'm trying to unserstund RoutedCommands.
RoutedCommands starts from command source, than event is propagated vua bubbling and tunneling.
But can i stop the process? for example i would like set CanExecute = false and than stop event propagation.
Thanks for any help!

A: I suppose you try to stop a RoutedCommand to bubbling up the visual tree when your CanExecute-Handler sets CanExecute to false? If yes, try the following:
Set e.Handled = true. Make sure that the CommandTarget is set correct so that your CanExecute-Handler really is called.
This is important, if you place your command in a ContextMenu. If no CommandTarget is specified, WPF will take the focused element and your CanExecute-Handler will not always be called and therefore possibly interpreted by another handler.
Something like the following will do the job:
 <ContextMenu>
  <MenuItem Command="DesiredCommand" CommandTarget="{Binding PlacementTarget,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}}" .../>
  ...
 </ContextMenu/>


text:
Q: Use "zero" timestamp in a MySQL JDBC prepared statement (in WHERE clause) My problem is that I don't know how to make a java.sql.Timestamp object representing a '0000-00-00 00:00:00' datetime.
I have a database with a field declared like:
`a_field_name` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'

I want to make a prepared statement deleting an entry with zero datetime.
Example:
String sql = "DELETE from `table` WHERE a_field_name = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setTimestamp(1, zeroTimestamp);

The zeroTimestamp object is the problem. :)

A: A JDBC Timestamp object cannot represent the special all-zeros date of MySQL. You can use a string though:
String sql = "DELETE from `table` WHERE a_field_name = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, "0000-00-00 00:00:00");

You'll also have to add the connection property noDatetimeStringSync=true if you want to recover these values; otherwise the driver will throw an exception when obtaining values from the database.
See the full detail in the "Datetimes" section here:
https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-installing-upgrading-3-0-to-3-1.html


text:
Q: How can I tell if an RF transmitter is transmitting? In my project, I use a use an RF transmitter and receiver.
One of the RF components seemed to fail because the connection between my Arduinos no longer works. I cannot determine whether the RF receiver or transmitter works.
I want to see if my RF transmitter gives an output, but I do not own an oscilloscope to view it's waves.
I've seen this answer, but it only shows if the Arduino is sending data to the RF transmitter. Is there any alternative way to check if the RF transmitter works or not?

A: Build a simple detector with some diodes:

simulate this circuit – Schematic created using CircuitLab
If you just want to know if there is some signal, and aren't concerned with accurately measuring its strength, or demodulating it, you can throw this together with just about any components and it will work. Ideally the diodes have a low forward voltage, so they are Schottky diodes, like 1N60, or 1N5711, or a germanium diode. If you don't have any of those, probably an ordinary 1N4148 works too. Use whatever you have.
The capacitor is also not terribly critical. A cheap ceramic disk capacitor will work fine; whatever value you have.
The antenna is just a piece of wire. Connect the ground to something else, like your Arduino's ground, or the case, or another piece of wire. Not especially critical.
The hardest part is probably the ammeter. This needs to be a very sensitive meter -- on the order of microamps. Ideally, an analog meter, since it will be easier to see the changes in signal strength. A digital meter will work also, if it has a low enough range. It will just be harder to read.
Test the circuit by putting the antenna near a source of noise, like a computer monitor, or a motor, or your wireless access point, or your laptop's WiFi antenna, or any other radio transmitter you have that you know works.
Then, put it near your RF transmitter. Try transmitting something. If the ammeter moves, it's transmitting something.


text:
Q: Redirect from ActionFilterAttribute to Custom Error Page I have a login system, which means if an unauthorized user (not logged in) is trying to visit an authorized page an 401 error (Unauthorized) should be displayed, but it redirects to an incorrect error page I also have which is 404 NotFound.
It shows "NotFound" when it should "Unauthorized".
UserAuthenticationFilter
public class UserAuthenticationFilter : ActionFilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            // Check session is empty then set as result is HttpUnauthorizedResult
            if (string.IsNullOrEmpty(Convert.ToString(filterContext.HttpContext.Session["UserId"])))
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "Unauthorized"
                };
            }
        }

    }

ErrorController
[HandleError]
    public class ErrorController : Controller
    {
        public ActionResult Error()
        {
            return View();
        }
        public ActionResult NotFound()
        {
            return View();
        }
        public ActionResult Unauthorized()
        {
            return View();
        }
    }

Web.config
<system.web>
    <customErrors mode="On">
      <error statusCode="401" redirect="~/Error/Unauthorized"/>
      <error statusCode="404" redirect="~/Error/NotFound"/>
    </customErrors>
    <authentication mode="Forms">
      <forms timeout="2800"></forms>
    </authentication>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <globalization uiCulture="en-US" />
  </system.web>


text:
Q: How to convert Strings to numbers and then perform addition on them I am trying to find a way to take a String from a NumberPicker, and then perform addition on it. If the user selects 5 on the NumberPicker, I want to do (5 + 10), then display the results in a TextView. I'm looking for examples of how to do this.  I cannot seem to find a easy way to get this done.
Here is some code I'm using.
  np5.setOnValueChangedListener(new OnValueChangeListener()
        {
            public void onValueChange(NumberPicker picker, int oldVal,
                                      int newVal)
            {
                current_weight_view.setText(String.valueOf(newVal));
            }
        });

A: Update:

However I need to make it so when the user selects
  1 it adds 10, not 11 and when the user select 2 it equals 20. and so
  on.

How about multiplying?
 np5.setOnValueChangedListener(new OnValueChangeListener()
        {
            public void onValueChange(NumberPicker picker, int oldVal,
                int newVal)
            {
             //10 * 0 = 0;
             //10 * 1 = 10;
             //10 * 2 = 20;
             //etc
                current_weight_view.setText("" + (newVal * 10));
            }
        });

And silly me forgetting the brackets earlier:I

A: You want to add a number to the number selected in NumberPicker then
np5.setOnValueChangedListener(new OnValueChangeListener()
        {
            public void onValueChange(NumberPicker picker, int oldVal,
                int newVal)
            {
                current_weight_view.setText("" + (newVal + 10));
            }
        });

A: String.valueOf(Integer.parseInt(str)+Integer.parseInt(str2))

…should add the 2 numbers.


text:
Q: Cannot set parameters or run program in visual studio 2022 I recently installed visual studio 2022 to use as a secondary IDE for monogame specifically, but I cannot run the project nor set which CPU to use
Here is an image of what I can see when I'm in visual studio, is this simply a missing part of my visual studio installation or is it more complex?
In case it helps, I'm not signed in.


text:
Q: sqlstate[23000]: integrity constraint violation: 1062 duplicate entry '1827' for key 'primary' My webhost is siteground and they asked me to reduce my SQL size as it has exceeded the limit. I done so, following their instructions and now my website is broken. I emptied the visitors log, and url logs in phpMyAdmin as they were taking up most of the space and now my website is not working and siteground want me to pay them to restore my website back to a working date even though it is their instructions on how to empty the files that broke my site for a second time. Below is the error I am getting. I have not upgraded my site since July 2014 with the new files that have come out since, and there has been quite a few from the template provider, and have not upgraded my magento, so I am still using 1.9.0.
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1827' for key 'PRIMARY'

A: this error occurs when database user has a access problem.
if you give full access (full permission) to db user then your problem is solve.


text:
Q: Line Cross then give signal once only and not repeat I am looking for pine script coding with condition when pivot line here blue color of price 179.85 when any candle cross with green (close>open) then give signal, but only once.
If in case again same situation come then avoid repeating signal.
Thanks in advance...
enter image description here

A: You should use the crossover function from pinescript (v5):
alreadycrossed = false
numberofalert = 0
numbermaxofalert = 1

if ta.crossover(close, pivotline)
    alreadycrossed := true

if alreadycrossed and numberofalert < numbermaxofalert
    alert("my alert")
    numberofalert := numberofalert + 1

This way, you will have an alert only the first time the price cross above your pivotline.
Be carefull, in this code, the pivotline must be a serie of float (cf the pinescript manual : https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}crossover)


text:
Q: ReportViewer returns blank even if there exists data My reportviewer returns blank when deployed. I have tried setting AsyncRendering="false" and ShowParameterPrompts="true".
While setting AsyncRendering the report is loading but not properly,the control lost its width and no scroll appears, even the menu can't be seen.


text:
Q: Accessing redux-persist state without window.localStorage.getitem() I have been working on a login system for my react-redux app. The login should in essence do the following: allow the user to log in, access certain pages only after login, use the token/authentication from the user to make calls to the server using axios. For persisting the state of the redux store, I use redux persist. The state is indeed persisted and stored in the local storage. For accessing the different pages after the user logged in (without having to log in again), redux persist works great.
I had however trouble using the user authentication (in further development to change for a token) as the default authorization header in axios (see here and here for further explanation about default headers). Although the state of the redux store (where the authentication header of the user is stored at the moment of successful login) is indeed persisted (I can see it in the redux development tool and the local storage), axios was unable to use the persisted state. I managed to get it working in the end by calling the window.localStorage.getitem() (see code below). This seems however an extra complication.
Question 1: Although everything is working fine, I was wondering if there are better ways to get this working?
The flow is currently this. When the user logs in successfully, the authentication details (in the future to change for a token) are store in the redux state using the following steps:
handleLogin.js:
import axios from "axios";
import {store} from '../store'
import { loginRequest, loginSucces, loginFailure } from './loginActions';
import refreshPage from "../handlerefresh/handleRefresh";

const path = process.env.REACT_APP_Path; //stil to change for a default header in axios. cf supra.

export const handleLogin = content => {

  var credentials = btoa(content.username + ':' + content.password);
  var basicAuth = 'Basic ' + credentials;

  return dispatch => {
    dispatch(loginRequest(basicAuth));
    axios
      .get( `${path}/_security/_authenticate`,
            {headers: {'Authorization': basicAuth}},
      )
      .then(res => {
        console.log(res);
        dispatch(loginSucces(res));
        axios.defaults.headers.common['Authorization'] = store.getState().loginAPI.authentication; //function sets the default header of axios to the current users login information. this might be redundant (?)
        // console.log("this should be the authorization " + axios.defaults.headers.common['Authorization'])
        refreshPage()
      })
      .catch(error => {
        dispatch(loginFailure(error.message))
        console.log(error);
      });
  };
};

These actions are defined in: loginActions.js.
import {LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE } from './loginTypes'

export const loginRequest = (request) => {
  return{
    type: LOGIN_REQUEST,
    payload: request
  }
}

export const loginSucces = response => {
  return{
    type: LOGIN_SUCCESS,
    payload: response
  }
}

export const loginFailure = error => {
  return{
    type: LOGIN_FAILURE,
    payload: error
  }
}

With the following reducer: loginReducer.js

import {LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE } from './loginTypes';

import {LOGOUT_REQUEST, LOGOUT_SUCCESS, LOGOUT_FAILURE } from './logoutTypes';

const initialLoginState = {
  loading: false,
  loggedIn: false,
  user: '',
  error: '',
  authentication: 'undefined',
}

const loginAPIReducer = (state = initialLoginState, action) => {
  console.log(action.type)
  switch(action.type){
    case LOGIN_REQUEST:
      return{
        ...state,
        loading: true,
        authentication: action.payload
      }
    case LOGIN_SUCCESS:
      return{
        ...state,
        loading: false,
        user: action.payload,
        error: '',
        loggedIn: true
      }
    case LOGIN_FAILURE:
      return{
        loading: false,
        user: '',
        loggedIn: false,
        error: action.payload
      }
    case LOGOUT_REQUEST:
      return{
        ...state,
        loading: true
      }
    case LOGOUT_SUCCESS:
      return{
        loading: false,
        user: '',
        loggedIn: false,
        error: '',
        authentication: action.payload
      }
    case LOGOUT_FAILURE:
      return{
        loading: false,
        error: action.payload
      }
    default:
      return state;
  }
}

export default loginAPIReducer;

Because I was unable to get the persisted state from redux persist to be used as an authorization header for all the axios requests, I wrote the following function, which gets the authorization header from the local storage:
provideUserAuth.js
function provideUserAuth(){
    // I split in these comments the authentication into smaller steps for clarity.
    // var state = window.localStorage.getItem('reduxState');
    // var JSONstate = JSON.parse(state);
    // var authentication = JSONstate.loginAPI.authentication;
    // return authentication;
    var authentication = JSON.parse(window.localStorage.getItem('reduxState')).loginAPI.authentication;
    return authentication
}

export default provideUserAuth;

This function is called in the index.js file, to set the default header for all the axios requests.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import { PersistGate } from 'redux-persist/integration/react';
import { store, persistedStore } from '../src/redux/store';
import Loader from './components/loader/loader';

import { fetchRVVBCases } from './redux/raadvoorvergunningsbetwistingen/rvvbReducer';
import { fetchBURGCases } from './redux/burgerlijkehovenenrechtbanken/burgReducer';
import {fetchREVIEWCases} from './redux/review/reviewReducer';

import provideUserAuth from './redux/auth/provideUserAuth';

const axios = require('axios');

axios.interceptors.request.use(async function (config) {
  const token = provideUserAuth();
  console.log("this is the " + token);
  config.headers.Authorization =  token;

  return config;
});

axios.interceptors.request.use(request => {
    console.log("current axios request: " + JSON.stringify(request, null, 2));
    // Edit request config
    return request;
}, error => {
    console.log(error);
    return Promise.reject(error);
});

axios.interceptors.response.use(response => {
    console.log(response);
    // Edit response config
    return response;
}, error => {
    console.log(error);
    return Promise.reject(error);
});

store.dispatch(fetchRVVBCases());
store.dispatch(fetchBURGCases());
store.dispatch(fetchREVIEWCases());

ReactDOM.render(
  <Provider store={store}>
    <PersistGate loading={<Loader />} persistor={persistedStore}>
      <App />
    </PersistGate>
  </Provider>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: <omit>;

It works fine but it seems an extra complication.
Second question: Secondly, I was wondering whether this way of working is secure. The authorization will be changed for a token, but this token still persists in the local storage, even after logging out. Should I add a function localstorage.removeItem() or even .clear() to clean up the local storage after logging out or closing the browser?
Thank you for your time and have a nice weekend!


text:
Q: Redshift : Syntax Check Utilities If you know any good sql syntax check tool for Redshift, could you kindly advise me?
So far, I use SQLWorkbenchJ and AginityRedshiftWorkbench as connection tool, and SCT as migration tool. They actually help me a lot though, just I'm wondering if there are any other good utilities for syntax or intelligence check purpose.
Other useful conection tool would be also appreciated.
Thank you.


text:
Q: Get current route name in Ember I need to get the current route name in my ember application; I tried this:
Ember App.Router.router.currentState undefined
but it doesn't work for me (there is probablig something i'm missimg...) I use Ember rc6 and I have a multilingual app; in the applicationRoute I detect the browser's language and I redirect to the correct page with:
this.transitionTo(userLang);
but I would like this to be executed only when user are on the home page, so something like this:
if (currentRoute == 'home'){
  this.transitionTo(userLang)
}

A: Currently as of Ember 1.7.0 you can get the current route from within a route by calling this.routeName.

A: The Ember namespace API now has a getOwner method, which is very useful for looking up the currentRouteName, or, other route properties.
  const owner        = Ember.getOwner(this);
  const currentRoute = owner.lookup('router:main').currentRouteName;
  const routeInfo    = owner.lookup(`route:${currentRoute}`).get('info');
  // etc.

I've created an Ember Twiddle example to demonstrate. Use the text input above the "Output" pane to hit other routes like /blue, /green, or /red.

A: NOTE: as of Ember 3.16, the original answer is not only recommended, but observers are strongly discouraged.
To get the current route name, you can utilize the Router Service: https://api.emberjs.com/ember/3.18/classes/RouterService/properties/currentRouteName?anchor=currentRouteName
export default class MyComponent extends Component {
  @service router;

  get activeRoute() {
    return this.router.currentRouteName;
  }
}

Original answer below

You could observe the application's currentPath and set it to the current route accordingly when it changes:
App = Ember.Application.create({
  currentPath: '',
});

App.ApplicationController = Ember.Controller.extend({
  updateCurrentPath: function() {
    App.set('currentPath', this.get('currentPath'));
  }.observes('currentPath')
}),

This way you have access to the currentPath when ever you want with App.get('currentPath');
E.g.
if (App.get('currentPath') == 'home'){
  this.transitionTo(userLang);
}

Hope it helps.

A: This worked for me on 1.3.0-beta (and a quick glance at the source for 1.1.2 suggests it would work there too):
App.__container__.lookup('router:main').location.lastSetURL

Note that the documentation states:

At present, it relies on a hashchange event existing in the browser.

However, I believe it's strongly suggested that App.__container__ not be used in production code. A more acceptable alternative would be to use App.Router.router.currentHandlerInfos, which provides information on the current Ember route.
Yet another option is currentRouteName on the ApplicationController. You can add needs: ['application'] to your controller, then access the route name with controllers.application.currentRouteName. This will return something like posts.index.

A: Ember has a RouterService since 2.15. It provides the name of the current route as currentRouteName property. A polyfill exists for Ember 2.4 - 2.14 if you are still on such an old version.
import Component from '@ember/component';

export default Component.extend({
  router: service(),

  isHomeRoute: computed('router.currentRouteName', function() {
    return this.router.currentRouteName === 'home';
  }),
});

All other solutions mentioned here are relying on private API that might already be deprecated / removed. Using RouterService is working at least up the current version, which is 3.12 at the time of writing this.
Please note that the "home" is not /. The root URL is called "index".

A: With the shift to components, it is harder to get route name.  The best way is to add an initializer such as
ember g initializer router

(from command line), and
export function initialize(application) {
  application.inject('route', 'router', 'router:main');
  application.inject('component', 'router', 'router:main');
}

export default {
  name: 'router',
  initialize
};

in a initializers/router.js.  You can also inject into controller if you need to.  Then just do simply
this.get('router.currentRouteName');

in JS, or
{{router.currentRouteName}}

in template.
This is the only way I have found to get it reliably, and observable in Ember 2.4

A: If you want to get current route in your component or controller you can inject routing service (routing: Ember.inject.service('-routing'))
(for more) and use:
this.get('routing.currentRouteName') or this.get('routing.currentPath')
Example with component and computed property:
import Ember from 'ember';

export default Ember.Component.extend({
  routing: Ember.inject.service('-routing'),

  checkMyRouteName: Ember.computed('routing.currentRouteName',  function() {
    return this.get('routing.currentRouteName');
  })
})

Example with controller and computed property:
import Ember from 'ember';

export default Ember.Controller.extend({
  routing: Ember.inject.service('-routing'),

  checkMyRouteName: Ember.computed('routing.currentRouteName', function() {
    return this.get('routing.currentRouteName');
  })
})

Current route in your route you just need this.routeName
Example with route:
import Ember from 'ember';

export default Ember.Route.extend({
  checkMyRouteName() {
    return this.routeName;
  }
})

A: Just as an update, in Ember 1.8.1, we can get the routeName inside an Ember.Route object by doing this.routeName.

A: I had the same problem for a while. then i started exploring router. It always have a state object which can be obtained from any route using
var route = this;
var handlerInfos = route.get("router.router.state.handlerInfos");
var currRouteHandlerInfo = handlerInfos[handlerInfos.length-1];
var currRouteName = currRouteHandlerInfo.name; //"home"

that's it. Now you have the current route name!
if you want the current route params,
var routerParams = this.get("router.router.state.params");
var currRouteParams = routerParams[currRouteName]; //{ homeId : "1" }

A: You can simple parse the current URL. This way you can use your full url for example:
http://127.0.0.1:8000/index.html/#/home

and extract from this string the suffix:
/home

which is the current route name.
A simple JS function (that works regardless to your Ember version) will be:
function getCurrentRoute()
{
    var currentRoute;
    var currentUrl = window.location.href; // 'http://127.0.0.1:8000/index.html/#/home'

    var indexOfHash = currentUrl.indexOf('#');
    if ((indexOfHash == -1) ||
        (indexOfHash == currentUrl.length - 1))
    {
        currentRoute = '/';
    }
    else
    {
        currentRoute = currentUrl.slice(indexOfHash + 1); // '/home'
    }

    return currentRoute;
}

Example of use:
if (getCurrentRoute() == '/home')
{
// ...
}


text:
Q: TFS Git build breaks after updating build definition Our TFS build has broken following updating the XAML build definition. Changes included modifying the template and a few parameters. The trace is below
TF215097: An error occurred while initializing a build for build definition [REDACTED]:
Exception Message: Cannot set unknown member 'Microsoft.TeamFoundation.Build.Activities.Git.GitPull.CheckoutSubmodules'. (type XamlObjectWriterException)
Exception Stack Trace:    at System.Xaml.XamlObjectWriter.WriteStartMember(XamlMember property)
   at System.Xaml.XamlServices.Transform(XamlReader xamlReader, XamlWriter xamlWriter, Boolean closeWriter)
   at System.Activities.XamlIntegration.FuncFactory`1.Evaluate()
   at System.Activities.DynamicActivity.OnInternalCacheMetadata(Boolean createEmptyBindings)
   at System.Activities.Activity.InternalCacheMetadata(Boolean createEmptyBindings, IList`1& validationErrors)
   at System.Activities.ActivityUtilities.ProcessActivity(ChildActivity childActivity, ChildActivity& nextActivity, Stack`1& activitiesRemaining, ActivityCallStack parentChain, IList`1& validationErrors, ProcessActivityTreeOptions options, ProcessActivityCallback callback)
   at System.Activities.ActivityUtilities.ProcessActivityTreeCore(ChildActivity currentActivity, ActivityCallStack parentChain, ProcessActivityTreeOptions options, ProcessActivityCallback callback, IList`1& validationErrors)
   at System.Activities.ActivityUtilities.CacheRootMetadata(Activity activity, LocationReferenceEnvironment hostEnvironment, ProcessActivityTreeOptions options, ProcessActivityCallback callback, IList`1& validationErrors)
   at System.Activities.Validation.ActivityValidationServices.InternalActivityValidationServices.InternalValidate()
   at Microsoft.TeamFoundation.Build.Workflow.WorkflowHelpers.ValidateWorkflow(Activity activity, ValidationSettings validationSettings)
   at Microsoft.TeamFoundation.Build.Hosting.BuildProcessCache.LoadFromXaml(String workflowXaml, TextExpressionImports textExpressionImports)
   at Microsoft.TeamFoundation.Build.Hosting.BuildControllerWorkflowManager.PrepareRequestForBuild(WorkflowManagerActivity activity, IBuildDetail build, WorkflowRequest request, IDictionary`2 dataContext)
   at Microsoft.TeamFoundation.Build.Hosting.BuildWorkflowManager.TryStartWorkflow(WorkflowRequest request, WorkflowManagerActivity activity, BuildWorkflowInstance& workflowInstance, Exception& error, Boolean& syncLockTaken)

The build fails in the first few seconds as this is the process that is trying to retrieve the source. However, I cannot come to any conclusions as to why this error is happening. A Google search doesn't bring up anything useful.
TFS version 2013
Has anyone encountered this error and if so how did you fix it?
If I need to provide more information please ask.

A: When you modify the Build process template and therefore it's no longer in sync with the build definition you may get TF215097 error.
@jessehouwing's suspicion makes sense. I can't find too many articles to elaborate this issue, but in this MSND documentation mentions, if you want to edit a custom template, You must use only Visual Studio 2013 to edit your build process templates of TFS 2013.


text:
Q: I have problems with executing a while loop
i <- 1
while(i<10){
print(i)
i<-i+1
if(i==4){
next
}
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9

I execute this code, but still have number 4 in my result although I am using "next" in my code to skipp it

A: use the following instead.
if(i!=4){print(i)}

A: or you wanted to test with next, use print after next
{
if(i==4){next}
print(i)
}


text:
Q: Proxy to create object of WCF class Pardon me for this naive question.
I have created a service reference of a WCF service at the client side, In the example I have they mentioned they have created a proxy to create an object of the WCF class, I want to understand where "ServiceCalculateCostClient" came from. Below is the client call -
        CalculateCost.IServiceCalculateCost ICost = new CalculateCost.ServiceCalculateCostClient();
        CalculateCost.ProductData objProductData = new CalculateCost.ProductData();
        objProductData.ProductName = "Shirts";
        objProductData.ProductQuantity = 4;
        objProductData.PerProductCost = 200;
        Response.Write(ICost.getTotalCost(objProductData));

And here is the SVC code
public class ServiceCalculateCost : IServiceCalculateCost
{
    string IServiceCalculateCost.getTotalCost(ProductData objProductData)
    {
        double totalCost = objProductData.PerProductCost * objProductData.ProductQuantity;
        return "The total cost for product " + objProductData.ProductName + " is " + totalCost.ToString();
    }
}


text:
Q: Строка нужного формата и содержит слово только один раз. Регулярное выражение Клиент может отправлять такие строки на вход.
ZZZ/USD:0.0001
или
USD/ZZZ:100000
короче это типа конвертера валют.
Я написал регулярное выражение под эту формулу
static String COEFFICIENT_PATTERN =
            "^[A-Z]{1,3}+/" + "[A-Z]{1,3}+=" + "[0-1\\u002E]{1,6}";

оно работает.
как дополнить его условием, что должки быть только одно слово USD?
USD/USD=1000 уже не верно

A: В общем случае, чтобы исключть совпадение целой строки, если какое-то одно слово в ней повторяется, можно использовать
static String COEFFICIENT_PATTERN =
    "^(?!.*\\bUSD\\b.*\\bUSD\\b)[A-Z]{1,3}/[A-Z]{1,3}:[0-1\\u002E]{1,6}$";
              ^^^^^^^^^^^^^^^^^^^^^^^^^^

См. пример работы выражения
Или, так как повтор определённого слова тут может случиться только в начале строки один раз через /, в данном случае вы можете использовать
static String COEFFICIENT_PATTERN =
    "^(?!USD/USD:)[A-Z]{1,3}/[A-Z]{1,3}:[0-1\\u002E]{1,6}$";
       ^^^^^^^^^^^

См. пример работы выражения
Блок предварительного просмотра вперёд(?!.*\\bUSD\\b.*\\bUSD\\b) исключает совпадение, если сразу после текущей позиции (а тут эта позиция - начало строки) есть

*

*.* - 0+ символов, отличных от символов перевода строки, как можно больше

*\bUSD\b - целое слово USD

*.* - 0+ символов, отличных от символов перевода строки, как можно больше

*\bUSD\b - целое слово USD.


text:
Q: Word or phrase for weaker opponents Someone who picks opponents that are weaker than them, so that they can feel superior but they never pick anyone as strong or stronger than themselves.
Context, someone who brags about being an intellectual arrogantly, but only argues with weaker and dumb opponents to win debates while avoiding more intelligent opponents in case they'd be exposed.
I'm looking for a word to describe their target mostly or a phrase that cover this situation.
Words that come to mind are "They only pick on the [weakest link] or [soft targets]", but I still think there's better ones out there or better ways of phrasing this!

A: A single word for an easily beaten opponent would be someone who is a "pushover".
As an idiom (from the context of your example) it sounds like someone who likes to be a "big fish in a small pond". Although the idiom does not overtly describe the chosen opponents, it does suggest limiting the available "targets/challengers" to a small chosen arena by number and size.
Other idioms/phrases that depict non-challenging opportunities would be "low-hanging fruit" or "easy pickings", but these seem to emphasize the "gain to be had" as much as the "ease of the challenge".
https://www.thefreedictionary.com/pushover
https://idioms.thefreedictionary.com/big+fish+in+a+small+pond
https://idioms.thefreedictionary.com/Low+Hanging+Fruit


text:
Q: Prevent direct call to slot, prefer connect which led to call on another thread In the Qt world we can put heavy duty tasks on separated classes and make the function calls using signal/slot mechanism which then, if designed appropriately and implemented accordingly will led to  a call on a separated thread.
However with all these, seems to me, one can still go and (inappropriately) make the function calls directly. That will led to calls on the same thread.
So I'm wondering if there are ideas on how to write the interfaces to enforce the calls using signal/slot mechanism? Or, all we can do is hope for the best.

A: You can create a thin wrapper object that proxies direct calls into emitting signals that trigger calling slots of an actual worker in a separate thread. Here's a quick and dirty example:
class Task : public QObject {
    Q_OBJECT
public:
    void doStuff();
};

class TaskRunner {
    Task* m_task;
    QThread* m_thread;
public:
    TaskRunner() {
        m_thread = new QThread;
        m_task = new Task;
        connect(this, &TaskRunner::doStuffRequest, m_task, &Task::doStuff);
        m_task->moveToThread(m_thread);
        m_thread->start();
    }

    void doStuff() {
        emit doStuffRequest();
    }

signals:
    void doStuffRequest();
}

You can make a constructor of Task object private and make TaskRunner friend in Task, so users can't instantiate Task object directly.
For a real-world example I would probably make a runner QObject-inherited as well. Also don't forget to stop a thread properly and do a memory cleanup in a destructor.

A: Once you make a slot (a method) public, then you cannot prevent it being called directly. So the only solution is to make the slot private. But then you can only establish the connection from within the class. And therefore you need to pass the instance of the emitting class, e.g. in constructor.
class SomeReceiver: public QObject
{
    Q_OBJECT

public:
    explicit SomeReceiver(SomeEmitter *emitter, QObject *parent = nullptr) : QObject(parent)
    {
        connect(emitter, &SomeEmitter::someSignal, this, &SomeReceiver::someSlot);
    }

private:
    void someSlot() // you cannot call it directly from outside, it is private
    {
        // some stuff here ...
    }
}

(Alternatively, instead of establishing the connection in a constructor, you can make a setter function which would take a pointer to emitter instance and establish the connection. But then there is a danger of this setter being called twice etc. So I would prefer using the constructor...)
You can use it like this:
auto emitter = new SomeEmitter();
auto receiver = new SomeReceiver(emitter);

The code above ensures calling via signals and slots.
And if you want the code to be executed in a secondary thread, then just move the receiver to that thread.
receiver->moveToThread(&someThread);

... and then every time you emit emitter's signal, the conected slot will always be executed in the thread. If you do not move it to secondary thread, it will be executed in the main/GUI thread.
To enforce you move this object to a thread, then you can also move it in the constructor (either by passing also a thread pointer to constructor or by creating a thread in it - but then you need to take care of all the thread destructuring). I would strongly not recommend this, this is extremely ugly design.
PS: If you want to really enforce that some code is run in a thread, then you should inherint from QThread and override its run() method. This is ALWAYS executed in the thread.