Q:

Putting Some Items First in List

I am just wondering the best approach to place certain items in a List at the top of the List.  This model is used in a view to display search results and comes from the controller as a List<T>.  So My goal is Display all Items , but Items with a certain property will go to the beginning of the list so they are displayed first.
so my controller would be something like :
List<Item> listFromRepository = repository.GetSearchResults();
List<Item> topItems = listFromRepository
                            .Where(x => x.Subject == 5)  // any filter for items to be at top of search results
List<Item> listForView = new List<Item>();
listForView.AddRange(topItems);
listForView.AddRange(listFromRepository.Exclude(x => x.Subject == 5));
return Json(listForView);

A:

Probably this:-
List<Item> topItems = listFromRepository.Where(x => x.Subject == 5)
                       .Concat(listFromRepository.Where(x => x.Subject != 5));


Q:

Bringing specific items back from an array in a drop-down menu

I currently have a standard registration form. In this form I have a drop down menu to select which type of school you are. I specially only want 2 out of the 5 items that appear in the drop down menu. What is the best way of approaching this? I am able to see all 5 options in the drop down menu. But only want the 2nd and 3rd to show.
I have an array of 5 objects. "item": [ {"id": 1,"name": "Company"}{"id":2,"name": "School District"},{"id": 3,"name": "High School"},{"id": 4,"name": "Community College"},{ "id": 5,"name": "Non Profit"}],
onCombinedSuccess = response => {
 this.setState(prevState => {
  return {
    ...prevState,
    schoolTypes: response.item.schoolTypes.map(this.mapSchoolTypes),
    )
    };
   });
  };

 mapSchoolTypes = type => (
  <option key={type.id} value={type.id}>
  {type.name}
  </option>
   );

I only want Id 2: "School District, and Id 3 " High School" to show. Currently getting back all 5

A:

You can try Array.prototype.filter() like this:

const items = [{"id": 1, "name": "Company"}, {"id": 2, "name": "School District"}, {"id": 3, "name": "High School"}, {"id": 4, "name": "Community College"}, {"id": 5,"name": "Non Profit"}];
const arrIDToSelect = [2, 3];
const arrFilteredItems = items.filter(item => arrIDToSelect.includes(item.id));

console.log(arrFilteredItems)


Q:

What is the winning strategy for this problem?

Before the game starts, there are a few "points" on the desktop, and then the two players take turns to do the following operations until the operation can not be completed:
Starting from a "point" to draw a line continuously and uninterruptedly, and it does not intersect with any "point" and "line" on the way, and finally ends the curve on a "point". Later, we call the drawn line "line" and choose any point from the line to call it "point" (in fact, which point we choose as "point" will not have any impact).
However, every "point" is required to be connected with at most three "lines". A "line" passes through a "point" means that the "point" is connected with two "lines".
Meanwhile, you can also draw a "line" from a "point" to itself if satisfies the terms above.
My research shows that when the numbers of "points" in the very beginning are $ 1,2,5,6$, there are winning strategies for the second hand. However, when the numbers of "points" are $3,4,7$, there are winning strategies for the first hand. I guess that if the numbers of "points" are in the form of $4n+2, 4n+1$, the second hand has winning strategies.
My question is, is my result right? How to prove it? (And disprove it if it wrong)

A:

This game is well-known and studied. It's called Sprouts.
It seems $5$ is a win for the first player (contrary to your assertion) and $6$ for
the second (which was a record for some time).
The as yet unproven conjecture is that it's a win for the first player when the number of starting points is $3,4,5$ modulo $6$. (Yours is a conjecture modulo $4$)
This has been confirmed up to $44$ points.


Q:

NSURLSession get response from Servlet

Currently, I am using NSURLSession and HTTPPost method to upload data to Java servlet. The java servlet will parse the data received and update it into database.
let dataTest:NSData = dao.readStringFromDb().data
let request = NSMutableURLRequest(URL: NSURL(string: urlSubmit)!)
    request.HTTPMethod = "POST"
    request.addValue("multipart/form-data", forHTTPHeaderField: "Accept")
    request.HTTPBody = dataTest
let session = NSURLSession.sharedSession()
let task    = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    print("Response: \(response)")})
    task.resume()
}

During update process (in Java), different status flags are updated into DB based on different conditions. Now, my requirement is to get that status returned from the web server and show locally.
I am aware that I can use HTTPGet method again, pass the key value and get the status flag.
I am trying to explore if there are any callback handlers available to use with java servlets like the one available in javascript.
Any suggestions would be highly helpful.
Regards.

A:

You already implemented the call back to handle the response.
In order to get the response code, all you have to do is:
cast the response as NSHTTPURLResponse then call the statusCode property
So your code would be:
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response ,error ) in
        if let response = response {
            let httpResponse = response as! NSHTTPURLResponse
            print("response code = \(httpResponse.statusCode)")
        }
    })
task.resume()

You had an error which is calling the task.resume() inside the clouser, I fix it too.
Don't forget to check for errors as well


Q:

Error in android SDK - Android studio

In my Android SDK I see the error below. What can I do?

A:

In Android Studio

Click on Tools from Header Menu.
Select Android
Select SDK Manager From Dropdown.
Reinstall Android Repositary.
Restart and Rebuild the project after installation.


Q:

Finding pairs of complementary numbers

This is the "Pairs with Positive Negative values" problem from geeksforgeeks.org.

Given an array of distinct integers, print all the pairs having positive value and negative value of a number that exists in the array.
NOTE: If there is no such pair in the array , print "0".
Input:
  The first line consists of an integer T i.e number of test cases. The first line of each test case consists of an integer n. The next line of each test case consists of n spaced integers.
Output:
  Print all the required pairs in the increasing order of their absolute numbers.

Here is my code:
def findPairs(l):
    listLen=len(l)
    nums=set()
    for i in range(listLen):
        if (-1*l[i]) in l[i+1:]:
            nums.add(abs(l[i]))
            continue
    nums=sorted(nums)
    #print (nums)
    pairs=[]
    for num in nums:
        pairs.extend([-1*num,num])

    return pairs

T=int(input())
pair=[]
for i in range(T):
    input()
    pair=findPairs(list(map(int,input().split())))
    if len(pair):
        print(" ".join(str(x) for x in pair))
    else:
        print("0")

A:

You definitely incorporated the response to your previous questions, such as:

Extract code into functions.
Always indent with 4 spaces.
Process input immediately instead of storing all input data and results in lists.

There is still too little (horizontal) whitespace, I suggest to check
your code against the PEP8 coding style,
for example at PEP8 online.
Also function and variable names should be snake_case according to PEP8.
More suggestions:

Variable names: T is too short and non-descriptive, num_tests
would be better. pair is better named pairs.
There is no need to pre-assign pair=[].
The value of the iterator variable i in the main loop is not needed,
a common convention is use _ instead:
for _ in range(T):

Negation as in -1*l[i] can be simplified to -l[i]
When printing the result list
print(" ".join(str(x) for x in pair))

you can use map instead, as you already do when reading the input:
print(" ".join(map(str, pair)))

Improving the performance:
Your algorithm has two nested loops traversing through the list, i.e. the
time complexity is \$ O(n^2) \$ as a function of the list length.
This can be improved by sorting the list first. One option would be to sort
the numbers in increasing order, e.g.
-3 -1 1 2 3 6

for the first test case, and then traverse the list from both ends to find
pairs. The time complexity is \$ O(n \log n) \$ for the sorting, and
 \$ O(n) \$ for the traversal, so this would be faster for large input.
Another option is to sort the number in increasing absolute value, e.g.
 -3 3 -1 1 2 6

Again a linear sweep of the sorted list is now sufficient to find matching pairs,
which are now consecutive entries.
Here is a possible implementation of the second approach:
def find_pairs(numbers):
    numbers.sort(key=lambda x: x + 0.5 if x >= 0 else -x)
    pairs = []
    for pair in [(x, y) for x, y in zip(numbers, numbers[1:]) if x == -y]:
        pairs.extend(pair)
    return pairs

using

sort() with a custom key. This relies on the given fact that the numbers are
distinct integers.
zip and list comprehension to enumerate pairs of consecutive list entries.


Q:

Is using if/else if/else this way a good practice?

I am working on an app we inherited from a previous vendor and many places in the client side javascript I see something like this:
if (self.DESIGNEE_TYPE_SCREEN_ROUTE_REGEX.test(url)) {
    goToSelectDesigneeType.call(self);
} else if (self.FUNCTION_CODES_SCREEN_ROUTE_REGEX.test(url)) {
    goToSelectFunctionCodes.call(self);
} else if (self.DISCIPLINE_SCREEN_ROUTE_REGEX.test(url)) {
    goToSelectDiscipline.call(self);
} else {
    goToSelectDesigneeType.call(self);
} else ...

This is used to to go to the next step in a workflow, and it works fine but something about it just does not sit right with me. Is this pretty common, or is there a better way to do the same thing?

A:

You can use switch(true) idiom here.
switch(true) {
  case self.DESIGNEE_TYPE_SCREEN_ROUTE_REGEX.test(url) :
    goToSelectDesigneeType.call(self);
    break;
  case self.FUNCTION_CODES_SCREEN_ROUTE_REGEX.test(url) :
    goToSelectFunctionCodes.call(self);
    break;
  case self.DISCIPLINE_SCREEN_ROUTE_REGEX.test(url) :
    goToSelectDiscipline.call(self);
    break;
  default :
    goToSelectDesigneeType.call(self);
}

just my opinion though, this is much easier to read.


Q:

Change text colors by clicking on button with javascript

i want to change color of text by clicking button with javascript. I have problem with my code. It's changing color, but counter variable is not resetting to value of zero.
IMAGEstack.imgur.com/sFwbb.png

A:

On line 8 your are doing a comparison check using triple equals "===" instead of an assignment using the "=". In order to set the value of a variable use the assignment operator "=". Your new code will be this on line 8:
counter = 0;


Q:

Concatenate two numbers

How do I concatenate two numbers in BigDecimal? I have this example:
BigDecimal d = BigDecimal.valueOf(5.5);
        int a = 1;
        int b = 11;

and I want to concat d.a and d.b to generate 5.501 and 5.511 in same length without using divide or other operation!
Is there an instruction with BigDecimal to make it directly ?

A:

Use the fact that BigDecimal can parse stings, and that strings are easy to concatenate.
BigDecimal d = BigDecimal.valueOf(5.5);
int a = 1;
int b = 11;

BigDecimal da = new BigDecimal(String.format("%s%02d", d, a));
BigDecimal db = new BigDecimal(String.format("%s%02d", d, b));

System.out.println(da);
System.out.println(db);

Output:
5.501
5.511

The length is hard coded in %02d. You could generate the format string dynamically by inspecting String.valueOf(a).length().

A:

da = d.add(new BigDecimal("0.00" + a);
db = d.add(new BigDecimal("0.0" + b);


Q:

Is there a way in Netty to get specific TCP options?

Does Netty support getting low-level, custom TCP options from a connection?  We need to put the client IP address in a TCP option from the F5 LTM to be read by Netty.
References:
https://www.iana.org/assignments/tcp-parameters/tcp-parameters.xhtml
https://devcentral.f5.com/articles/accessing-tcp-options-from-irules#.U5shRiTSBKQ

A:

It doesn't as there is no support for this in Java at all.


Q:

Loading Ajax Response Data with Adsense Codes inside

I'm 10000000% sure that this question has been asked before, however, the majority of the responses that I came across were from back in 2005, 2006 and so on. Not to mention, almost all of the questions themselves were too general. Therefore, I'm asking this so that for anyone else needs to find this out, then they won't need to dig through about 50 webpages to get an idea.
My question is simply that I have a webpage that has Google Ads embedded into the HTML of the website. The website was first developed as a static HTML site where each link reloaded a new page. Nevermind the backend technology of the website - the website itself produces purely dynamic content. The website is close to completion and now a fully-ajax listener has been added to all the links. When any of the links are clicked, JavaScript takes over, parses the link and sets that using popstate or the hashbang. The page itself is then queried to the server via AJAX and the content is updated using document.getElementByID('container').innerHTML=ajax.responseText; This way, there is almost a 100% method of accessing content that was replaced by AJAX.
This all works fine, but the responseText itself may, WILL contain Google Ads, and I was just wondering how to display them as if it were a static page. Clearly this doesn't work. Here are the options that I've come across:

Use an IFrame:
An IFrame seems to be an effective way to load the content; just stick the adsense codes a simple adsense.html iframe file and let the browser and

A:

directly into page, it isn't possible

it's against their TOS
there is document.write() omitted in ajax request

Your chance is:
Create simple iframe
<iframe src="advert.html"></iframe>

and in advert.html, add your advert code
It's then loaded fine without problems.
Good luck


Q:

Database backup with no frozen I/O

Is there a way to make automated  backups of a DB without having the I/O frozen ?
I am using an Amazon EC2 instance .
I/O is frozen on database distribution. No user action is required. However, if I/O is not resumed promptly, you could cancel the backup.

A:

Shadow backups are taken by VSS backing up all the C: drive  lead into baking up the database and then lead into the I/O frozen message seen in the SQL server log.
The database backup when it is done normally via maintenance plan, via SQL Management Studio or via user  SQL query  does not generate I/O frozen message .


Q:

Converting From XDate To Normal Date Format?

In ZedGraph, I had to convert my date to XDate in order to plot it.
Now, I want to know how to convert from XDate to normal date for some other process.
Thanks!

A:

Use the DateTime property

Gets or sets the date value for this item in .Net DateTime format.


Q:

Can a player ever lose her or his rating (voluntarily)?

I am just curious. Is it possible for a rated player to quit his association with FIDE and start afresh, as an unrated player?

A:

I found FIDE regulations 7.21 which state:

Players whose ratings drop below 1000 are listed on the next list as
  ‘delisted’. Thereafter, they are treated in the same manner as any
  other unrated player.

This sounds like a "reset" to me.
Note that this is different to an inactive player which you become after not playing rated games for a year. However in the case of inactive players you retain your rating.
Other than this "delisting" I don't think there is a way to lose your rating.


Q:

Change underline color for Disqus tabs

How to change underline color for tabs in disqus on my site?
I tried to rewrite disqus rules by own:
.nav-primary>ul>li.active>a:after {
    content: " ";
    display: block;
    right: 0;
    height: 2px;
    background: #000 !important;
    position: absolute;
    bottom: -2px;
    left: 0;
}
.active .publisher-nav-color::after {
    background: #000 !important;
}

My rules has no effect (because of iframe, suppose)

A:

The active tab underline color can't be changed. Disqus uses the default link color of the page it's on. If it is using a different color other than your link color, make sure your main <a> color style is inheritable by Disqus.
See the "Link color" section: https://help.disqus.com/customer/portal/articles/545277-disqus-appearance-tweaks


Q:

Add author to pdf

I produce a quarterly bulletin, which I publish as a pdf. This is written in Pages 4.3 and exported. Previous issues on OS X 10.8 have my name as Author. Recent issues on OS X 10.9 show unknown author.
How can I change this on new exports?

A:

Doesn't fix your export problem, but this is a fairly easy workaround.
You can easily edit PDF metadata using a very simple automator workflow:

Open Automator and create a new Service
Set 'Service receives selected' to PDF files 'in' Finder.app
Search for 'set meta' and drag and drop the Set PDF Metadata action to the right
At the bottom under 'Options' select Show this action when workflow runs
Save the service and give it a name
Optionally, create a keyboard shortcut under System Preferences > Keyboard > Shortcuts, select 'Services' from the left pane and look for your service under 'Files and Folders'

Now you can right click a PDF file and under services select your service, or select a PDF file and use your newly created shortcut to launch your Service.
Hope this helps.


Q:

Outdated row doesn't move out from foreign table partition postgres

I'm trying to learn how sharding is configured in Postgres.
My Postgres setup has a temperature table which has 4 partitions each covering different range of "timestamp" value.
postgres=# \d+ temperature
                                                     Partitioned table "public.temperature"
  Column   |            Type             | Collation | Nullable |                 Default                 | Storage | Stats target | Description
-----------+-----------------------------+-----------+----------+-----------------------------------------+---------+--------------+-------------
 id        | bigint                      |           | not null | nextval('temperature_id_seq'::regclass) | plain   |              |
 city_id   | integer                     |           | not null |                                         | plain   |              |
 timestamp | timestamp without time zone |           | not null |                                         | plain   |              |
 temp      | numeric(5,2)                |           | not null |                                         | main    |              |
Partition key: RANGE ("timestamp")
Partitions: temperature_201901 FOR VALUES FROM ('2019-01-01 00:00:00') TO ('2019-02-01 00:00:00'),
            temperature_201902 FOR VALUES FROM ('2019-02-01 00:00:00') TO ('2019-03-01 00:00:00'),
            temperature_201903 FOR VALUES FROM ('2019-03-01 00:00:00') TO ('2019-04-01 00:00:00'),
            temperature_201904 FOR VALUES FROM ('2019-04-01 00:00:00') TO ('2019-05-01 00:00:00')

temperature_201904 table, in particular, is a foreign table
postgres=# \d+ temperature_201904
                                                           Foreign table "public.temperature_201904"
  Column   |            Type             | Collation | Nullable |                 Default                 | FDW options | Storage | Stats target | Description
-----------+-----------------------------+-----------+----------+-----------------------------------------+-------------+---------+--------------+-------------
 id        | bigint                      |           | not null | nextval('temperature_id_seq'::regclass) |             | plain   |              |
 city_id   | integer                     |           | not null |                                         |             | plain   |              |
 timestamp | timestamp without time zone |           | not null |                                         |             | plain   |              |
 temp      | numeric(5,2)                |           | not null |                                         |             | main    |              |
Partition of: temperature FOR VALUES FROM ('2019-04-01 00:00:00') TO ('2019-05-01 00:00:00')
Partition constraint: (("timestamp" IS NOT NULL) AND ("timestamp" >= '2019-04-01 00:00:00'::timestamp without time zone) AND ("timestamp" < '2019-05-01 00:00:00'::timestamp without time zone))
Server: shard02

Insert works as expected. If I insert the following value and check from the remote host shard02, then the value exists. Fantastic!
postgres=# select * from temperature_201904;
 id | city_id |      timestamp      | temp
----+---------+---------------------+-------
  1 |       1 | 2019-04-02 00:00:00 | 12.30
(1 row)

However, if I update the timestamp of this row such that it's no longer valid for the range defined for the partition, I'd expect it to get moved out and placed into the correct partition, temperature_201901, but it's not.
postgres=# update temperature set timestamp =  '2019-01-04' where id=1;
UPDATE 1
postgres=# select * from temperature_201904 ;
 id | city_id |      timestamp      | temp
----+---------+---------------------+-------
  1 |       1 | 2019-01-04 00:00:00 | 12.30

Again, just to reiterate, this table has a range temperature_201904 FOR VALUES FROM ('2019-04-01 00:00:00') TO ('2019-05-01 00:00:00') and is a foreign table.
Feels like I'm missing something here.
Is this an expected behavior? If so, is there a way to configure such that data are automatically moved between nodes as their partition constraints are changed?
Thanks in advance!
postgres=# SELECT version();
                                                     version
------------------------------------------------------------------------------------------------------------------
 PostgreSQL 12.2 (Debian 12.2-2.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit

A:

This seems to be expected.  From the docs

While rows can be moved from local partitions to a foreign-table partition (provided the foreign data wrapper supports tuple routing), they cannot be moved from a foreign-table partition to another partition.

Now I would have expected an ERROR rather than silently violating the implied constraint, but I wouldn't expect this to have worked the way to you want it to.


Q:

Scaling a sprite in unity

I am trying to make it so my sprite will always be the same proportion for all screen sizes. Is there a way that I can scale my sprite to be a certain width and or height compared to the rest of the screen? I have tried multiple ways but everything I have looked up goes over my head. Is there an easy way to implement this? Or any way at all in Unity? Thanks for any help. Here is an image to help further what I am trying to accomplish.

I want the detailed image to be the size of the black and green rectangle. Thanks for any help!

A:

I figured it out, I just needed to convert from pixels per world unit like so:
     Mathf.Abs(Camera.main.orthographicSize - (GetComponent<SpriteRenderer>().sprite.texture.height / GetComponent<SpriteRenderer>().sprite.pixelsPerUnit));


Q:

how do i see the difference between two images in python using pil?

I'm trying to make a program that looks from my macbook's camera (or any camera) and lets me know when something happened (lights turned on/off, any motion, etc), the program takes a screenshot every 1 second and compares the last image taken with the one that it just took.
Here is the code in my while loop
while True:
    time.sleep(1)

    image = capture_image()

    if last_image == None:
        last_image = image

    # compare the two images

    print('image', image)
    print('last image', last_image)
    print('')

    last_image = image

A:

Your question somewhat implies you are at the initial stages of this project and things are a bit vague, so I have just put together a few general ideas till you are further down the road.

Consider moving to OpenCV as it has an abundance of useful functions and there are plenty of examples on Stack Overflow. Look for cv2.VideoCapture() to grab your camera stream and cv2.imshow() and cv2.waitKey() to display your frames. PIL is not very good for displaying dynamically changing images such as video and you will be much better served by cv2.imshow(). Also, you will find yourself converting PIL images to Numpy arrays to do processing, so you might as well use OpenCV and work directly with Numpy arrays already.
If you want to detect changes in lighting, try converting your image to greyscale cv2.cvtColor(...BGR2GRAY...) and taking the mean with np.mean(). Try running your loop, which is looking about right, and just printing the mean in the Terminal at each iteration as you turn the lights and off. Then you can see how much it changes and work out a sensible threshold.
As regards movement, you are probably not looking for movement at the pixel level, else you will detect the wind moving a leaf visible out of your window. So, you want large-scale changes. So, if your camera is 1080p (1920x1080), try resizing your image down to 16 pixels by 9 with cv2.resize(im, (16,9),... INTER_LINEAR ...) then you just have 144 pixels to quickly look at and compare between images. You can always scale these images back up to a side length of 300-400 cv2.resize(...NEAREST_NEIGHBOUR..) to display previous and current frames. Then look at the colour distances between each of the 144 image rectangles and see if any of them exceed a threshold you derive from your testing.

Try to develop your code a bit and get some experience, then come back and ask another question if you get stuck - questions, and answers, are free.


Q:

TemplateBinding in Binding Path

I have an Custom Control with dependency property Header. In Generic.xaml there is a style for that control. I want to set visibility of some part of the template so that it depends on Header property from the control.
<Style TargetType="{x:Type CustomControl1}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type CustomControl1}">
                <Grid MinWidth="400" Focusable="False">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition />
                    </Grid.RowDefinitions>

                    <TextBlock Text="{TemplateBinding Header}"
                               Style="{DynamicResource SomeStyle}"
                               Margin="0,0,80,0"
                               Grid.Row="0" Grid.Column="0">
                        <TextBlock.Visibility>

                            <Binding Path="{TemplateBinding Header}">

                            or alternatively

                            <Binding Path="{Binding Path=Header, RelativeSource={RelativeSource TemplatedParent}}">

                                <Binding.Converter>
                                    <converters:ValueConverterGroup>
                                        <converters:StringNullOrEmptyToBooleanConverter />
                                        <BooleanToVisibilityConverter />
                                    </converters:ValueConverterGroup>
                                </Binding.Converter>
                            </Binding>
                        </TextBlock.Visibility>
                    </TextBlock>

                   ...

This line throws an exception:
<Binding Path="{Binding Path=Header, RelativeSource={RelativeSource TemplatedParent}}">

According to the exception message there can't be a Binding inside Path property of Binding (I already knew that) xD
How could this be done without double-binding? How to access property of Custom Control without using TemplateBinding?

A:

Path property of a Binding is not a DependencyProperty, I doubt you may want it to be like this:
<TextBlock.Visibility>
   <Binding Path="Header" RelativeSource="{RelativeSource TemplatedParent}">
          <Binding.Converter>
              <converters:ValueConverterGroup>
                   <converters:StringNullOrEmptyToBooleanConverter />
                    <BooleanToVisibilityConverter />
              </converters:ValueConverterGroup>
          </Binding.Converter>
   </Binding>
</TextBlock.Visibility>


Q:

Howto add content to Response?

My WebService (I want to put the uuid string in the response)
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Response createObject(final String jsonString) {
    String uuid;
    //logic
    ...
    String mt = new MimetypesFileTypeMap().getContentType(uuid);
    return Response.ok(uuid, mt).build();
    //also tried: Response.status(200).entity(uuid).build();
}

My Request (reading the uuid from response)
Response response = target.request().post(Entity.entity(new Gson().toJson(params, Map.class), MediaType.TEXT_PLAIN));
response.getEntity() //returns null if i access it

The entity is always null when i try to access it. What am i doing wrong?

A:

Hi i found the problem:
It was a parsing Problem, somehow i always got null until i changed my request code from
response.getEntity()

to this:
String uuid = new Gson().fromJson(response.readEntity(String.class), String.class);


Q:

Why addLast() not working properly

I created a DeQueue as follws
Deque<Integer> deque = new ArrayDeque<Integer>(8);

// use add() method to add elements in the deque
deque.add(20);
deque.add(30);
deque.addLast(12);
deque.add(18);
deque.addFirst(22);
deque.add(24);

// let us print all the elements available in deque
for (Integer number : deque) {
    System.out.println("Number = " + number);
}

The expected output is:
Number = 22
Number = 20
Number = 30
Number = 18
Number = 24
Number = 12

But the actual output is :
Number = 22
Number = 20
Number = 30
Number = 12
Number = 18
Number = 24

Anybody please explain this?

A:

addLast doesn't somehow maintain a notion of "this should be last" forever - it just adds to the end of the current dequeue. It's equivalent to add, as documented.
So if we look at the values at each step, we have:
deque.add(20);      // Contents: 20
deque.add(30);      // Contents: 20, 30
deque.addLast(12);  // Contents: 20, 30, 12
deque.add(18);      // Contents: 20, 30, 12, 18
deque.addFirst(22); // Contents: 22, 20, 30, 12, 18
deque.add(24);      // Contents: 22, 20, 30, 12, 18, 24

... which exactly corresponds to the output you got.

A:

The addLast method adds to the last position relative to the current deque, not absolutely:
deque.add(20);      // [20]
deque.add(30);      // [20, 30]
deque.addLast(12);  // [20, 30, 12] <- 12 is last
deque.add(18);      // [20, 30, 12, 18]
deque.addFirst(22); // [22, 20, 30, 12, 18]
deque.add(24);      // [22, 20, 30, 12, 18, 24]

12 was the last element when you only had [20, 30] but then you are adding other elements, so it won't be the last one anymore.
So, if you want that value to be the last one, you need to call addLast after all other calls.
UPDATE
If you have a look at the source code of ArrayDeque:
public boolean add(E e) {
    addLast(e);
    return true;
}

So, the addLast does the same thing as add: It adds at the end of the current deque, which means that once you add other elements, the one added with addLast won't be the last one anymore.


Q:

Evaluate $\lim \limits_{x\to 1}\frac{\sin (\pi x^{\alpha})}{\sin (\pi x^{\beta})}$

Evaluate the following limit: $$\lim \limits_{x\to 1}\dfrac{\sin (\pi x^{\alpha})}{\sin (\pi x^{\beta})}$$ without using L'Hospital rule. I suppose that here we can use $\lim \limits_{x\to 0}\dfrac{\sin x}{x}=1$ but I can't use it.
Can anyone help please?

A:

Hint
Replace $x=1+y$ and use the generalized binomial theorem $$x^a=(1+y)^a=1+a y+\frac{1}{2} a\left(a-1\right) y^2+\cdots$$ So $$\sin(\pi x^a)=\sin(\pi+\pi a y+\cdots)=-\sin(\pi a y+\cdots)$$ Now, use the fact that, for small $z$, $\sin(z)\simeq z$.
I am sure that you can take it from here.

A:

Notice, $$\lim_{x\to 1}\frac{\sin(\pi x^{\alpha})}{\sin(\pi x^{\beta})}$$
$$=\lim_{x\to 0}\frac{\sin(\pi (1-x)^{\alpha})}{\sin(\pi (1-x)^{\beta})}$$
using binomial expansion: $(1-x)^{\alpha}=1-\alpha x$ & $(1-x)^{\beta}=1-\beta x$ as $x\to 0$,
$$=\lim_{x\to 0}\frac{\sin\left(\pi(1-\alpha x)\right)}{\sin\left(\pi(1-\beta x)\right)}$$
$$=\lim_{x\to 0}\frac{\sin\left(\pi-\alpha\pi x\right)}{\sin\left(\pi-\beta\pi  x\right)}$$
$$=\lim_{x\to 0}\frac{\sin\left( \alpha \pi x\right)}{\sin\left( \beta \pi x\right)}$$
$$=\lim_{x\to 0}\frac{\alpha}{\beta}\cdot \frac{\sin\left( \alpha \pi x\right)}{\alpha\pi x}\cdot \frac{\beta \pi x}{\sin(\beta \pi x)}$$
$$=\frac{\alpha}{\beta}\cdot \lim_{x\to 0}\frac{\sin\left( \alpha \pi x\right)}{\alpha\pi x}\cdot \lim_{x\to 0}\frac{\beta \pi x}{\sin(\beta \pi x)}$$
$$=\frac{\alpha}{\beta}(1)\cdot (1)=\color{red}{\frac{\alpha}{\beta}}$$


Q:

Handling signin flow in React

I'm trying to implement Last.fm signin in React. After the user logins to Last.fm, they are redirected to
http://localhost:3000/loginlanding/?token=${token id goes here}

How do I capture the url using React Router?
So far, I have tried all these:
path="/loginlanding/?token:id"
path="/loginlanding/:id"
path="/loginlanding/?:id"

None of these seem to work.
Basically, I need to capture the access token and store it in global state.

A:

specify route
<Route path="/loginlanding/:token_id" component={LoginLanding} />

pass token
<Link to=`/loginlanding/${token_id}` />

get token
this.props.match.params.token_id


Q:

Adding additional DNS search domains when using DHCP

How can I add additional DNS search domains to a network connection which is configured using DHCP?
At work, we have several sub-domains (test.example.com, dev.example.com, etc), and I've grown tired of perpending the sub-domain every time I need to access a server in one of the sub-domains.

A:

Here is a complete solution that works at least with 12.04:
sudo nano /etc/dhcp/dhclient.conf
# add next line (alternatively you can use append instead of prepend)
prepend domain-name "example.com other.example.com";
# before: request subnet-mask...

(you can also use sudo -e /etc/dhcp/dhclient.conf if you trust the default editor)
If you're on any sort of "professional" network that has its own DNS servers and/or if you've setup your own DNS service(s) on said network and also on your workstation, then, you might also want to comment-out this line:
# domain-name, domain-name-servers, domain-search, host-name,

--Doing so lets you use your own domain-name-servers, enabling your personalized domain-search to work much more smoothly, which is probably better than using whatever somebody else has setup for you.  E.G.: I'm on the network 192.168.10.0; the company has name server 192.168.10.10 and 192.168.10.11 -- but, I run my own name server with a more extensive list of names on 192.168.10.20 (which will forward to 192.168.10.10 and .11 as needed). All my network configurations declare 192.168.10.20 and 8.8.8.8 and 8.8.4.4 (the Google name servers), but, DHCP will tend to override that preference, feeding me 192.168.10.10 as the default server. In the end... not requesting those aspects from DHCP makes for a much better network life.
Now restart the networking:
sudo service networking restart

(you can also use sudo /etc/init.d/networking restart with old rc scripts)

A:

In more recent versions of Ubuntu, Network Manager allows you to add additional search domains and DNS servers while still using the values from DHCP.

Click on the Network Manager indicator and select Edit Connections...
Select the connection you want to adjust, and click Edit. Depending on the type of the connection, you may have to switch tabs.
In the Editing dialog, switch to the IPv4 Settings tab (or the IPv6 Settings tab if you're using IPv6).
Leave it set at Automatic (DHCP). Simply fill in the Additional search domains field with a comma-separated list of domains, and click Save.
You may need to disconnect and reconnect.

A:

Sorin's answer and Ib33X's answer are correct if you are not using the Network Manager. If you are using the Network Manager, then it appears that the Network Manager completely controls generation of the resolv.conf file (which is ultimately what the networking system uses for dns lookups). Changing the dhcpclient.conf is ineffective.
However, there is an (imperfect) solution if you are using the Network Manager:

Make note of the DNS servers setup by DHCP by inspecting the resolve.conf file:
cat /etc/resolv.conf
Right-click on the Network Manager indicator and select Edit Connections...
Select the connection you want to adjust, and click Edit. Depending on the type of the connection, you may have to switch tabs.
In the Editing dialog, switch to the IPv4 Settings tab (or the IPv6 Settings tab if you're using IPv6).
Change the Method from Automatic (DHCP) to Automatic (DHCP) addresses only.
Copy the DNS servers you saved in step #1 into the DSN servers text box (sue commas to separate multiple entries).
Enter each of the domain names to search by into the Search domains text box.
Click Save...
Disconnect and reconnect the connection.

The downsides of this approach is that you must specify both the DNS servers and the search domain names. It isn't possible to still pull the DNS server addresses from DHCP.
Additionally, the settings must be changed for each connection. I don't know of any way of changing the settings for all connections. However, this is often an advantage. For example, you might want different settings for your home wireless network and your work wireless network.


Q:

Why couldn't tributes blow up each other with a heavy object before the Hunger Games begin?

I got an idea after re-reading THG: Tributes could conceivably blow up other tributes before the sixty-second countdown was over, for example a boot or shoe to the mines surrounding the tribute. In this case, the tribute could potentially blow up two others.
I assume the same could be done with a sufficiently heavy district token, or perhaps a fruit pilfered from the Launch Room.

A:

The mines might be activated manually.
You're assuming the mines around each tribute's launch pad automatically go off when someone or something touches the ground around them, but this may not be the case. Many of the tricks and traps in the Games are set up and activated manually by the Gamemakers. It could be that they're carefully watching each tribute during the sixty-second countdown and standing ready to explode the mines around any one who steps off their pad.
In this scenario, a tribute who threw their shoe at the ground around the neighbouring tribute, intending to get rid of one of their adversaries before the Games even start, would find themselves blown to bits instead. That would be quite the backfiring plan!

Additionally, I should reiterate one of the points I made in answering your last question, and which @Richard also made in a comment on this one:
People who cheat in the Hunger Games usually aren't allowed to win.
Once the tributes are in the arena, they're more or less at the Gamemakers' mercy. It'd be easy for a cheating tribute to be singled out by some mutt or natural disaster, to come to a quick and grisly end. If the Gamemakers really don't want a particular tribute to win, there's no way they'll be able to. It's best to play by the rules unless there's a massive advantage in not doing so.
The only reason Katniss and Peeta were allowed to win after their stunt with the berries was because they were the Capitol's only possibility for a victor. If Cato had still been alive but dying at that point, the Gamemakers would have blown the District 12 'cheaters' sky-high and pronounced Cato the victor. Anyone who cheats isn't someone the Capitol wants walking around forever as a victor - as the fallout from the berries incident, and the third Quarter Quell, demonstrate only too well.
As another example of this attitude from the Capitol, consider what happened to Haymitch after he gamed the system by using the force field around the arena to win his Games:

"No. My mother and younger brother. My girl. They were all dead two weeks after I was crowned victor. Because of that stunt I pulled with the force field," he answers. "Snow had no one to use against me."
"I'm surprised he didn't just kill you," I say.
"Oh, no. I was the example. The person to hold up to the young Finnicks and Johannas and Cashmeres."
-- Catching Fire


Q:

Vlookup Function - Run-Time Error '1004'

I keep getting this error when I am running my code and I am unsure where else to look.
The Error message Reads: Run-Time Error '1004' - Unable to get the Vlookup Property of the WorksheetFunction Class
Here is my code, varMajor is declared as a global variable in another worksheet. Any help would be greatly appreciated!
Private Sub cmdRank_Click()
    Dim strMajorRank As String
    'Declare worksheet as an object variable
    Dim shtRankings As Worksheet
    'Set the variable
    Set shtRankings = Application.Workbooks("MGMT 3210 Final Project.xlsm").Worksheets("Rankings")
    varMajor = InputBox("Please Enter Your Major", "Where Does Your Major Rank?", vbOKOnly)
    'Set rngMajorRank = Application.Workbooks("MGMT 3210 Final Project.xlsm").Worksheets("Rankings").Range("H2")

    'Check to see if the major entered is listed in the Majors column in the data on the Rankings Worksheet using VLookup
    If varMajor = "Finance" Then
        strMajorRank = Application.WorksheetFunction.VLookup(varMajor, shtRankings.Range("B2:B21"), 1, True)
        MsgBox "Your major is among the 20 most popular at CU!"

        ElseIf varMajor = "Management" Then
        strMajorRank = Application.WorksheetFunction.VLookup(varMajor, shtRankings.Range("B2:B21"), 1, True)
        MsgBox "Your major is among the 20 most popular at CU!"

        ElseIf varMajor = "Marketing" Then
        strMajorRank = Application.WorksheetFunction.VLookup(varMajor, shtRankings.Range("B2:B21"), 1, True)
        MsgBox "Your major is among the 20 most popular at CU!"
    Else
        MsgBox "Your major is still a good one to have!"
    End If
    'Go to worksheet with top 20 majors at CU Application.Workbooks("MGMT 3210 Final Project.xlsm").Worksheets("Rankings").Activate

shtRankings.Range("H2").Value = "strMajorRank"

End Sub

A:

So it looks like your syntax is correct, this error actually just means that the Vlookup is not returning a value, i.e. in Excel this Vlookup would return N/A#, you can handle this with error handling.  If the formula is correct you'd want to put "On Error Resume Next" and "On Error Goto 0" around your uses of Vlookup.
Your code's a bit unclear, assuming you're trying to determine if the value the user enters is in the list as you say, then it should be:
'Check to see if the major entered is listed in the...
On Error Resume Next 'Goes to next line of code on error
    strMajorRank = Application.WorksheetFunction.VLookup(varMajor, shtRankings.Range("B2:B21"), 1, True)
On Error Goto 0 'Returns error handling to default

If strMajorRank <> "" Then
    MsgBox "Your major is among the 20 most popular at CU!"
Else
    MsgBox "Your major is still a good one to have!"
End If
...


Q:

How do I lock my MacBook?

Possible Duplicate:
Is there a keystroke that can lock the Mac OS X screensaver?

Is there no feature to lock the current logged in user like in Windows or can I only log off or switch off?

A:

In System Preferences, under Security, check the box that says "Require password to wake this computer from sleep or screen saver", and check the "Disable automatic login" box.  This will require your password once the screen saver becomes active, or if the box falls to sleep.
You can also set up Exposé with a hot-corner for turning on the screen saver.  System Preferences => Exposé & Spaces => Exposé (tab-like-thing), and then choose which screen corner to put it in.

A:

In the settings for keychain access there is an option to show the keychain access icon on the menu bar.
This gives you a two-click method to lock the screen.


Q:

Looping through multiple pages of a JSON request (Guzzle, Laravel, PHP)

New dev here so I am sorry if this is a simple question or something like that but haven't been able to find exactly what I am looking for (it totally could be that I am not asking the question correctly either) Basically I have a paginated list coming back from an api and I am not sure what the logic would be to be able to cycle through those pages. Here is the code that I have so far that works perfectly for the first page lol.
    public function handle()
    {
        //This is the artisan command that runs on a timer and gets all the ticket and update fields that are needed and saves them to the database.
        $tickets = $this->pullTicketSummary();
        collect($tickets['data'])
            ->each(function ($currTicket) {

                $ticketRow = Tickets::query()->firstOrCreate(['ticket_id' => $currTicket['id']]);
                $ticketRow->status_id = $currTicket['status']['id'];
                $ticketRow->category_id = $currTicket['category']['id'];
                $ticketRow->user_id = $currTicket['assigned_to']['id'];
                $ticketRow->jira_issue_id = $currTicket['jira_issue_id'];
                $ticketRow->save();

                collect($currTicket['updates'])->each(function ($update) use ($currTicket){
                    $updateRow = Update::query()->firstOrCreate(['update_id' => $update['update_id']]);
                    $updateRow->ticket_id = $currTicket['id'];
                    $updateRow->assignee_change = $update['assignee_change'];
                });
            });
        Log::info('All tickets and updates were pulled successfully');
    }

    protected function pullTicketSummary()
    {       //Function makes the guzzle request and returns the response from the happyfox api
            $client = new Client();
            $request = $client->get('https://happyfox.com/api/1.1/json/tickets/?size=50&page=1',
                ['auth' => ['N/A']);
            $response = json_decode($request->getBody()->getContents(), true);
            return $response;

    }

With the fact that I am new if this is something that has been answered before that I missed please just shoot me over a link or if you are aware of any documentation that would help me get to the answer on my own that would be awesome! thanks!

A:

Update your function to use the page number:
protected function pullTicketSummary($page)
{       //Function makes the guzzle request and returns the response from the happyfox api
        $client = new Client();
        $request = $client->get('https://happyfox.com/api/1.1/json/tickets/?size=50&page='.$page,
            ['auth' => ['N/A']);
        $response = json_decode($request->getBody()->getContents(), true);
        return $response;

}

//new function only to save the data from tickets variable. Necessary to reuse.
public function saveTicketsOrSomething($tickets)
{
    collect($tickets['data'])
        ->each(function ($currTicket) {

            $ticketRow = Tickets::query()->firstOrCreate(['ticket_id' => $currTicket['id']]);
            $ticketRow->status_id = $currTicket['status']['id'];
            $ticketRow->category_id = $currTicket['category']['id'];
            $ticketRow->user_id = $currTicket['assigned_to']['id'];
            $ticketRow->jira_issue_id = $currTicket['jira_issue_id'];
            $ticketRow->save();

            collect($currTicket['updates'])->each(function ($update) use ($currTicket){
                $updateRow = Update::query()->firstOrCreate(['update_id' => $update['update_id']]);
                $updateRow->ticket_id = $currTicket['id'];
                $updateRow->assignee_change = $update['assignee_change'];
            });
        });
}

Then iterate until you finish all the pages:
    $tickets = $this->pullTicketSummary(1); //first time
    $numPages = $tickets['numPages']; //update here to get the actual value of number of pages
    $this->saveTicketsOrSomething($tickets);

    for ($i = 2; $i < $numPages; $i++) { //start on 2, cause we already have fetched page 1
        $tickets = $this->pullTicketSummary($i); //other pages
        $this->saveTicketsOrSomething($tickets);
    }
    Log::info('All tickets and updates were pulled successfully');


Q:

Why converting output from beautiful soup to text gives me an error?

I need to get a list so I can break output into 3 columns.
So to convert it to list I simply .text . But it gives me an error.
import requests
from bs4 import BeautifulSoup as bs

lis=[]
headers = {'X-Requested-With': 'XMLHttpRequest'}
r = requests.get('https://www.governmentjobs.com/careers/home/index?agency=sdcounty&sort=PositionTitle&isDescendingSort=false&_=', headers=headers)
soup = bs(r.content, 'lxml')
containers  = soup.findAll('li', attrs = {'class':'list-item'}) # gives container with all we need
smt = soup.findAll('ul', attrs={'class':'list-meta'})
for s in smt:
    for li in s.findAll('li')[1]:
        print(li.text)

Error:
    self.__class__.__name__, attr))
AttributeError: 'NavigableString' object has no attribute 'text'

If i just print(li):

What exactly causes this error? Span tag?
I just need 3 columns:
Column1: Regular - Full time
Column2: $63,606.40 - $70,137.60
Column3: Regular - Full time

A:

You can use select to get Tag elements with text method.
headers = {'X-Requested-With': 'XMLHttpRequest'}
r = requests.get(
    'https://www.governmentjobs.com/careers/home/index?agency=sdcounty&sort=PositionTitle&isDescendingSort=false&_=',
    headers=headers)
soup = bs(r.content, 'lxml')
smt = soup.select("li.list-item")
for s in smt:
    print("---------------")
    for p in s.select("li"):
        print(' '.join(p.text.strip().split()))

Output:
---------------
County of San Diego, CA
Regular - Full time - $63,606.40 - $70,137.60 Annually
Category: Building Maintenance
Department: Facilities Management
---------------
County of San Diego, CA
Regular - Full time - $125,000.00 - $135,000.00 Annually
Category: Airports
Department: DPW-Airport Enterprise Fund
---------------


Q:

$M_n(I)\subseteq J$ for ideal $J$ in $M_n(R)$

Let $R$ be a unital ring, $J$ an ideal in $M_n(R)$ and $I= \{x\in R\colon x\text{ is an entry in } A\in J\}$.
I'm trying to understand the proof here http://planetmath.org/sites/default/files/texpdf/34767.pdf but I'm stuck on the stupid detail $M_n(I)\subseteq J$, everything else is clear. I believe I'm missing something obvious.
Let $(a_{i,j}) \in M_n(I)$ then $(a_{i,j})$ is an $n\times n$ matrix with entries in $I$, i.e. $a_{i,j} \in I \implies$ there exists a matrix $A^{i,j}\in J$ which has $a_{i,j}$ as an entry somewhere. It is not a priori clear to me that $(a_{i,j}) \in J$. I've tried to construct $(a_{i,j})$ from the "entry associated matrices" $A^{i,j}$ by doing operations together with $E_{p,q}$ matrices but with no luck. I'm staring myself blind on this little problem, it feels like it should be obvious. What am I missing?

A:

Let $E_{ij}$ be the standard basis for $M_n(R)$. These multiply by the rule $E_{ab}E_{cd} = \delta_{bc}E_{ad}$ where $\delta_{bc}$ is Kronecker's delta function. Let $A = (a_{ij}) = \sum_{i,j} a_{ij}E_{ij} \in J$. Then
$$ E_{pq} A E_{rs} = \sum_{ij} a_{ij} E_{pq}E_{ij}E_{rs} = \sum_{ij} a_{ij} \delta_{qi}\delta_{jr} E_{ps} = a_{qr}E_{ps}. $$
The point is that we can isolate any entry of a given matrix in $J$. We can also move any single-entry $a E_{ij}$ anywhere we want in the matrix by the same trick:
$$ a E_{kl} = E_{ki} (a E_{ij}) E_{jl}. $$
Using these two facts, it follows that $M_n(I) \subseteq J$.


Q:

Unexpected behaviour of a program using doubles

Possible Duplicate:
Why does Visual Studio 2008 tell me .9 - .8999999999999995 = 0.00000000000000055511151231257827?
Why do simple doubles like 1.82 end up being 1.819999999645634565360?

I get a really weird behaviour while I compile and run the following program:
#include <iostream>

#define DIV 10000ll

long long gcd(long long a, long long b) {
  if(b==0) return a;
  else return gcd(b, a % b);
}

int main() {
  int t;
  std::cin >> t;
  while(t--) {
    double n1;
    std::cin >> n1;
    long long inum=(long long)(n1*DIV);
    std::cout << inum << std::endl;
    if(inum==0) { std::cout << 1 << std::endl; }
    else std::cout << DIV/gcd(inum,DIV) << std::endl;
  }
  return 0;
}

When I enter as input:
1
0.0006

I get as output
5
2000

That means: (long long)0.0006*10000 is equal to 5 and not to 6. Why is this happening?

A:

0.0006 cannot be represented exactly as a double. Most likely the actual result stored is something like 0.00059999999... When this value is multiplied by 10000 it gives a number slightly smaller than 6. Casting this to an integer type truncates (rounds down) it to 5.
This is not weird behaviour. This is how floating point arithmetic works. If you wanted to get the value 6 you should round to the nearest integer instead of truncating.
Related

round() for float in C++


Q:

BadImageFormatException when attempting to use LuaInterface

I imported LuaInterface into a console project, referenced it, and wrote a small test script. When i run it, i get this:
Could not load file or assembly 'LuaInterface, Version=2.0.0.16708, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Forgive me for being a newbie or something, but i can't figure out what it means. What am i supposed to do?

A:

Are you running on a 64-bit operating system?
If you are then you'll need to either get an x64 build of LuaInterface or set the platform target of your console project to x86.

You can read up on the platform target option here:
http://visualstudiohacks.com/articles/visual-studio-net-platform-target-explained/


Q:

matplotlib creating 2D arrays from 1D arrays - is there a nicer way?

I am trying to visualise some 3d data I have using matplotlibs contour plots, surface plots and wireframe plots.
my raw data is in the form of a numpy array with x,y and z each in their own column (e.g.):
| xs | ys | zs  |
|---|---|----|
| 1 | 1 | 3  |
| 2 | 1 | 4  |
| 3 | 1 | 2  |
| 4 | 1 | 3  |
| 5 | 1 | 5  |
| 1 | 2 | -1 |
| 2 | 2 | -1 |
| 3 | 2 | -2 |
| 4 | 2 | 2  |
| 5 | 2 | 7  |
| 1 | 3 | 5  |
| 2 | 3 | 2  |
| 3 | 3 | 3  |
| 4 | 3 | 2  |
| 5 | 3 | 3  |
Now some of the plotting functions just take the data in 1D arrays corresponding to my columns (xs,ys,zs). However, some require a 2D array (meshgrid) format. Is there an easy way to convert from the 3 1D arrays to the correct format of 3 2D arrays? I have tried using numpy.meshgrid and, whilst this works for creating the X and Y 2D arrays, I can't work out a nice way to create the corresponding Z 2D array. I have managed to do it by making a blank 2D array and filling it with the appropriate values for Z, but this isn't very nice. Is there a better way to create the Z 2D array?
Below is my attempt (which works). Is there a way to make the Z array without cycling through both X and Y?
def getMeshGrid(dataArray):
    """get 2d coordinate grid and Z values in meshgrid format. requires values in
    dataArray to have a rectangular region of x-y space covered uniformly"""
    xs = dataArray[:,0]
    ys = dataArray[:,1]
    xmin,xmax = xs.min(), xs.max()
    xstep = xs[xs!=xmin].min()-xmin
    ymin,ymax = ys.min(), ys.max()
    ystep = ys[ys!=ymin].min()-ymin
    X = numpy.arange(xmin, xmax+xstep, xstep)
    Y = numpy.arange(ymin, ymax+ystep, ystep)
    X,Y = numpy.meshgrid(X,Y)
    Z = numpy.zeros(X.shape)
    height, width = X.shape
    for i in range(0, height):
        for j in range(0,width):
            halfway = dataArray[dataArray[:,0]==X[i,j]] # finds all with that value of x
            row = halfway[halfway[:,1]==Y[i,j]] # finds y value
            Z[i,j] = row[0,6]
    return X,Y,Z

Thanks in advance

A:

If your data is like the one you gave in the example, you already have a mesh (you have a value of z for each pair (x,y)) and you only need to reshape the arrays:
cols = np.unique(xs).shape[0]
X = xs.reshape(-1, cols)
Y = ys.reshape(-1, cols)
Z = zs.reshape(-1, cols)


Q:

update table with data from other table in remote oracle db

I have table X from remote Oracle DB A, and table Y in local Oracle DB B.
The data in Y is a partial copy of the data in X (X has some columns that aren't needed in Y; the columns I need in Y have the same names in both tables).
I periodically need to synchronize the data Y with what's in X (this is unidirectional - there's nothing in Y that needs to be copied back to X). Y has constraints that prevent simply dropping all the data in Y and repopulating it; I need to update what's already in 'Y', and insert any new rows from X that don't already exist in Y.
I've looked at a couple of options that won't work:

The copy feature in SQL Developer would copy X into a brand new table, not into Y
The export option would insert everything as new records, not update existing rows

What's the best way to do this?

A:

I did it by:
creating dblink from db A to DB B
and using : merge into Y y using select X.columns from X@dblink x on (x.idX=y.idY)
when matched then update set
y.columns=x.columns --here ids are not included
when not matched then
insert (y.columns) values(x.columns) --ids are included
x.colums and y.colums mean shared columns


Q:

getting to phpmyadmin with mamp

I'm using MAMP, and trying to get to phpmyadmin. loaclhost/phpmyadmin isn't working.. the sql light is green so it is enabled.
I have changed the Document Root to /Users/troycosentino/Sites/easyuniv/ and when i open the start page from MAMP it is a page created by apple it looks like, not MAMP.
Any ideas?

A:

If i go to localhost:8888/MAMP it gives me the MAMP screen, from which i can go to phpmadmin.

A:

If MAMP has MySQL Server and Apache Server running.
You can go to phpMyAdmin via url http://localhost/phpMyAdmin/

A:

Try this localhost:8888/MAMP/?language=English
Click on phpMyAdmin tab and you have it.


Q:

need help understanding ngRepeat with filter

I'm trying to figure out what this ng-repeat line of code is doing,

I understand that the line below will simply create a div for all the users in main.users

What is the first example doing? I assume theres some filter going on but it doesn't resemble the syntax of any filter examples I see in the angular docs

A:

Basically the above syntax does filtering main.users by candidate filter by passing main.filterBy value to that filter by using this line (main.users | candidate: main.filterBy) and the result of this is getting stored in filtered variable. So each time when digest cycle fires up you will see the filtered value updated.
Official refactored and semantic syntax is here

which clearly says that you can have filtered result in filtered scope variable which is used as alias of that output.
Sample Plunkr


Q:

double bracket does not work for -d and -f commands

if [[ -d "$HOME/test_bash/$KIT.stat_$KIT" ]; then
echo $KIT
else
mkdir $KIT.stat_$KIT
fi
if [[ "14"=="14" ]]; then
echo "FOO"
fi

The first if statement with [[ -d does not work, but the second if statement "14"=="14" does work when I use the bash test.sh command. However, if I replace the first if statement '[[' with a single bracket '[', it works. Any idea why this is the case?

A:

You only have a single closing ] on your first line.


Q:

No realiza las operaciones

Como doy estilo de bold a cualquier texto desde Javascript?

window.addEventListener("DOMContentLoaded",()=>{
var iLabel = document.getElementById('labelamodificar');
iLabel.style.fontWeight = "900";
});
<label id="labelamodificar" for="labelf">Nombre Usuario: </label>
<input type="text" id="labelf">

Por ejemplo esto funciona, pero lo que necesito es darle en sí la etiqueta \<b> como si lo hubiese puesto en el HTML.

A:

Solo recuerda usar class en vez de id si vas a cambiar multiples label
document.querySelectorAll('.labelamodificar').forEach(function(elemento) {
    elemento.innerHTML = '<b>' + elemento.innerHTML + '</b>';
});

JSBin


Q:

как сделать добавление блоков влево а не вниз

По клику на кнопку js формирует минимальный блок, которые я хочу размещать в мини полосу прокрутки

$('#add-photo').on('click', function() {
  let add = '

<input type="text" name="photo_name" class="notot-name-position">
'
  $('.photo-list').append(add)
})
.modal {
  width: 700px;
  min-height: 500px;
  margin: auto auto;
  background-color: #ffffff;
  border-radius: 10px;
  padding: 25px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

#add-photo {
  margin: 150px 0 15px 0;
  padding: 4px 10px;
  border-radius: 3px;
}

.photo-list {
  height: 130px;
  background-color: #3097D1;
  padding: 5px 0;
  box-sizing: border-box;
  position: relative;
  /*overflow-y: scroll; !* прокрутка по вертикали *!*/
  overflow: auto;
}

.image-block {
  float: left;
  height: 100%;
  margin: 0 3px;
  background-color: rgba(0, 0, 0, 0.2);
}

  <button id="add-photo">Add photo</button>

Для наглядности
Какого свойства мне не хватает? Спасибо

A:

display: flex; - надо задать родителю

$('#add-photo').on('click', function() {
  let add = '

<input type="text" name="photo_name" class="notot-name-position">
'
  $('.photo-list').append(add)
})
.modal {
  width: 700px;
  min-height: 500px;
  margin: auto auto;
  background-color: #ffffff;
  border-radius: 10px;
  padding: 25px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

#add-photo {
  margin: 150px 0 15px 0;
  padding: 4px 10px;
  border-radius: 3px;
}

.photo-list {
  display: flex;
  height: 130px;
  background-color: #3097D1;
  padding: 5px 0;
  box-sizing: border-box;
  position: relative;
  /*overflow-y: scroll; !* прокрутка по вертикали *!*/
  overflow: auto;
}

.image-block {
  float: left;
  height: 100%;
  margin: 0 3px;
  background-color: rgba(0, 0, 0, 0.2);
}

  <button id="add-photo">Add photo</button>


Q:

Perl EV module create periodic events

I'm using EV module to create a timed events that will run indefinitely in a defined time interval, here is my code with defined intervals.
#!/usr/bin/perl
use strict;
use warnings qw/ all FATAL /;
use feature 'say';
use EV;
use Time::Piece 'localtime';

my $one_sec = EV::timer 1,1, sub {
   say "(1s)  Periodic event at ", localtime(EV::now)->hms;
};

my $five_sec = EV::timer 5, 5, sub {
  say "(5s)  Periodic event at ", localtime(EV::now)->hms;
};

EV::run;

I'm trying to define these functions dynamically from hash reference, by looping through it to create these functions.
my $hash = {
    'one_sec'  => '1',
    'five_sec' => '5',
};

I have used foreach to loop through the hash.
foreach my $key ( keys %$hash )
{

        my $key = EV::timer $hash->{$key},$hash->{$key}, sub {
        say "($hash->{$key})  Periodic event at ", localtime(EV::now)->hms;
        };

        EV::run;
}

It works, but only for the first iteration, I'm not sure why is that?
Your thoughts are highly appreciated.

A:

The following code is not tested.

There are two things wrong with your code:
First, you are starting the event loop in the body of your foreach loop, which will make it run within the first iteration of the foreach. It will then get stuck there, and only one of the timers will be created. To fix that, the EV::run needs to be moved to outside of the foreach.
However, it will then not do anything at all. That's because the event-loop has nothing to do. That is because you are defining your EV::timer objects lexically within the body of the foreach. Once one iteration is done, that variable ($key) will go out of scope, destroying the timer object. When it's done creating both, it will just run an empty event-loop. In addition to that, you redefined $key, which was already the "one_sec" or "five_sec" string that comes out of the hash.
Instead, you need to put the event objects somewhere that's outside of the loop, too (because each block creates a lexical scope in Perl when you use my, which is a feature).
You should also use more speaking variable names so you don't get confused.
#!/usr/bin/perl
use strict;
use warnings qw/ all FATAL /;
use feature 'say';
use EV;
use Time::Piece 'localtime';

my $config = {         # was $hash
    'one_sec'  => '1',
    'five_sec' => '5',
}

my $timers;
foreach my $key ( keys %$config ) {
    $timers->{$key} = EV::timer $config->{$key},$config->{$key}, sub {
        say "($config->{$key})  Periodic event at ", localtime(EV::now)->hms;
    };
}

EV::run;


Q:

Static library: hiding private members from header file

I wish to compile part of my code as a static library to include in other project. Of course I'll have to distribute the compiled library and an header file containing the class declaration and the public members, but I don't know if it's possible to move all private members and declarations to a place different than the header file.
Example:
In the project.h file:
class MyClass
{
public:
  MyClass();
  void Give_me_an_input(int);
  int Get_your_output();

private:
  int a, b;
  int MySecretAlgorithm();
};

In the .cpp file:
MyClass::MyClass()
{
  a = 1;
  b = 0;
}

void MyClass::Give_me_an_input(int c)
{
  b = c;
}

int MyClass::Get_your_output()
{
  return MySecretAlgorithm();
}

int MyClass::MySecretAlgorithm()
{
  return (a + b);
}

Is there a way to move all private members int a, b; and int MySecretAlgorithm(); to a place different than the header file?

A:

The pointer to implementation idiom can be used in such a scenario, commonly referred to as pimpl.
The basic idea is to take the implementation details out of the declaration
and simply have an opaque pointer to the implementation details.
std::unique_ptr is used in the the following example; but you could of course just use normal pointers.
// my_class declaration unit.
class my_class {
private:
   class impl;
   unique_ptr<impl> pimpl;

public:

};

// my_class implementation unit
class my_class::impl {
   int whatever;
   int whenever;
};

my_class::my_class(): pimpl( new impl )
{
}


Q:

Improper multiple integals involving inner porduct

I'm trying to evaluate the following expression:
$$\int_{\mathbb{R}^n} \langle x,a \rangle^2e^{-\frac{1}{2}\lvert x \rvert^2}dx$$
where $x,a \in \mathbb{R}^n$.

I tried reduction to the case where $a$ is an element of the "natural basis" in $\mathbb{R}^n$ but I can't see how to go from there.

A:

Note : I know I forgot the square in this proof, but please read the proof without the square, as the approach with the square is very analogous.
Write $\langle x,a \rangle = a_1 x_1 + \cdots + a_n x_n$ and $|x|^2 = x_1^2 + \cdots + x_n^2$, so that $e^{-|x|^2} = e^{-x_1^2} \cdots e^{-x_n^2}$. By Fubini's theorem, your integral becomes
$$
\int_{\mathbb R^n}\langle x,a \rangle e^{-|x|^2} dx = \sum_{i=1}^n  \int_{\mathbb R^n} a_i x_i e^{-|x|^2} \, dx_i = \sum_{i=1}^n a_i \left( \int_{\mathbb R} e^{-x^2} \, dx \right)^{n-1} \int_{\mathbb R} x_i e^{-x_i^2} \, dx_i.
$$
The power to the $n-1$ appears because the integrals $\int_{\mathbb R} e^{-x_j^2} \, dx_j$ do not depend on $j$ for $1 \le j \le n$, $j \neq i$. These integrals correspond to the error function, so their value is well-known ; by integration by parts you can do the last integral with respect to $x_i$. I leave the computations to you.
Now if you want to do it with the square, do the exact same trick ; the integrals appearing are just a bit more complicated (the integral of $x^2 e^{-x^2}$ instead of $xe^{-x^2}$) and there are a bit more terms. Fubini's theorem splits the product of variables appearing when you square the inner product. The error function $\mathrm{erf}(x_i)$ should show up in the computations.
Added : As suggested by the OP in the comments, let $T : \mathbb R^n \to \mathbb R^n$ be an orthogonal transformation with $Ta = (|a|,0,\cdots,0)$. Since the Jacobian is $1$, letting $u = Tx$, because $|u| = |Tx| = |x|$, this integral becomes
$$
\int_{\mathbb R^n} \langle x,a \rangle^2 e^{-|x|^2} \, dx = \int_{\mathbb R^n} \langle Tx,Ta \rangle^2 e^{-|x|^2} \, dx = \int_{\mathbb R^n} \langle u,Ta \rangle^2 e^{-|u|^2} \, du = \int_{\mathbb R^n} |a|^2u_1^2 e^{-|u|^2} \, du.
$$
Now use Fubini and complete as in my other example. But as I said above, you still need to integrate $\int_{\mathbb R} x^2 e^{-x^2} \, dx$ in any case ; with the hint you only spare yourself the sums and re-arranging.
Hope that helps,


Q:

What are the factors need to be taken into consideration while using Microsoft Sync Framework

Right now we have got an developed application for maintenance and one of the major issue is the Sync Time.
It's almost taking 50 to 60 secs to synchronize between the local CE database and remote SQL Server.
It takes less than 12secs while synchronizing the same local CE database with local SQL Server.
This points that location of server is definitely ruling the grounds but again what are the other factors need to be evaluated while using Microsoft Sync Framework.
Is there any standards specified as such how many scopes and how to use provisioning efficently.

A:

Too long to post here, so posting a link instead : Sync Framework Scope and SQL Azure Data Sync Dataset Considerations
Other things you can look at are batching and metadata clean up.
Note that Sync Framework is just like any other database app, so stuff like proper indexing also is a plus.


Q:

Set updated date

I'm using EF database first
I have a table with a 'date updated' column in it. It needs to have the current datetime when a record is updated in it. I am using EF so I can't edit any autogenerated model classes. I don't want to edit T4 templates because I assume that will be overwritten if I upgrade EF
To solve a different problem I followed this: http://www.ozkary.com/2015/01/add-data-annotations-to-entity.html to generate a 'buddy' class which as far as I can tell just extend the autogenerated EF class
So then I followed the answer to this: set default value in class constructor C# which seems to show a solution to what I need. However when I test, the DateUpdated is not changed
Here's part of my autogenerated class. You can see DTUpdated in here
namespace bt2.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Task
    {
        public int Task_ID { get; set; }
        public int TaskType_ID { get; set; }
        public int Emp_ID { get; set; }
        public System.DateTime DTInserted { get; set; }
        public System.DateTime DTUpdated { get; set; }

        public virtual TaskType TaskType { get; set; }
        public virtual Task Tasks1 { get; set; }
        public virtual Task Task1 { get; set; }
    }
}

Here's my 'buddy' class where I tried to add extra code to the autogenerated class:
namespace bt2.Models
{
    [MetadataType(typeof(TaskMD))]
    public partial class Task
    {
    }

    internal sealed class TaskMD
    {
        [DisplayName("ID")]
        public int Task_ID { get; set; }

        [DisplayName("Task Type")]

        public int TaskType_ID { get; set; }

        public System.DateTime DTUpdated {
            get { return DateTime.Now; }
            set { this.DTUpdated = value; }
        }
    }

As far as I can tell this second class is extending the original class
I want to solve my problem but I also want to understand whats going on in more detail here.

A:

Because the Context class is a Partial class you can create your own partial class with an overload of the SaveChanges method.
In this method you can use reflection to get the DTUpated property and set the Updated Date Time Value. (if the name of the property is the same, if the name is NOT same pass in the name as a parameter)
Something like the following.
public partial class TBCompanyEntities
{

    public void SaveChanges(object o)
    {
        try
        {
            var propertyInfo = o.GetType().GetProperty("DTUpdated");

            // This hasn't been tested by me yet - will test and update if need changes
            if(propertyInfo != null)
                propertyInfo.SetValue(o, Convert.ChangeType(DateTime.UtcNow, propertyInfo.PropertyType), null);
        }
        catch (Exception ex)
        {
            //  Logging.Log.Error(ex);
        }

        base.SaveChanges();

    }
}

Then in your code instead of calling dbContxt.SaveChanges(); you can call
dbContext.SaveChanges(YOUR_ENTITY_OBJECT);

Example:
            using (var dbContext = new TBCompanyEntities())
            {
                // Entity with DTUpdated
                var notification = dbContext.NotificationArchives.First(s => s.iNotificationId == 1);
                notification.bIsRead = true;
                dbContext.SaveChanges(notification);

                //Entity without DTUpdated
                var asset = dbContext.Assets.First(s => s.iAssetId == 1);
                asset.iDriverId = null;
                dbContext.SaveChanges();
            }

EDIT:
An override is when the parameters of the overridden method are same as the base method.
So you will have to do something like this:
public partial class TBCompanyEntities
{

    public override void SaveChanges()
    {
       //TODO: Here you will have to detect which entity has been modified/updated.
       // This should be possible, by using the Track Entity Changes features

               var modifiedEntities = ChangeTracker.Entries()
        .Where(p => p.State == EntityState.Modified).ToList();

        base.SaveChanges();

    }
}

here is a good link of override in which the author tracks changes to Entities and then creates a Log. (like Audit Log)
https://www.exceptionnotfound.net/entity-change-tracking-using-dbcontext-in-entity-framework-6/


Q:

FAILED CONFIGURATION: @AfterMethod tearDown Even the driver is checking for null before quitting

I have code like below...
@BeforeClass(alwaysRun = true)
public void setup() throws InterruptedException {
    driver = DriverFactory.getDriverInstance();
    softwarepage = new SoftwarePage(driver);
    loginpage = new LoginPage(driver);
    projectpage = new ProjectPage(driver);
}

@Test(description="Create Software",dataProviderClass=AddSoftwareProvider.class,dataProvider="testCasesAddSoftware")
public void createSoftware(AddSoftwareBean softwareBean) throws InterruptedException
{
    softwareName = "AutoSoftware"+DataGenerator.randomNumber();
    log.info("Create Software test case Started...");
    assertEquals(true, loginpage.gotoSignPage());
    assertEquals(true,loginpage.logintoPortal(PropertyMap.getInstance().getmySSISSGName(), PropertyMap.getInstance().getmySSISSGPassword(), "myToday"));
    //assertEquals(true,softwarepage.createSoftware(softwareName));
    //assertEquals(true,softwarepage.AddSoftwareDefault(softwareName, "Low"));
    assertEquals(true,softwarepage.AddSoftware(softwareBean));

}

I am quitting the driver in teardown method like below, but before checking whether the driver is null or not... Even, then the above test case is not executing...
@AfterClass(alwaysRun = true)
public void tearDown() {
    if (driver != null) {
        assertEquals(true,loginpage.logout());
        driver.quit();
        }
}

in the softwarePage, the code is like this...
public SoftwarePage(WebDriver driver) {
        this.driver = driver;
    }
@Override
protected WebDriver getDriver() {
    return driver;
}

Please help me in this...
Edit:
The full stack is here... The assertion is in logout method I have written...
FAILED CONFIGURATION: @AfterClass tearDown
java.lang.AssertionError: expected [false[ but found ]true]
    at org.testng.Assert.fail(Assert.java:94)
    at org.testng.Assert.failNotEquals(Assert.java:494)
    at org.testng.Assert.assertEquals(Assert.java:123)
    at org.testng.Assert.assertEquals(Assert.java:286)
    at org.testng.Assert.assertEquals(Assert.java:296)
    at com.cigital.myssi.automation.commons.Verification.assertEquals(Verification.java:33)
    at com.cigital.myssi.automation.tests.SoftwareTest.tearDown(SoftwareTest.java:69)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
    at org.testng.internal.TestMethodWorker.invokeAfterClassMethods(TestMethodWorker.java:225)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:114)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1197)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1122)
    at org.testng.TestNG.run(TestNG.java:1030)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

EDIT: without assertion in tearDown method, this is what I am getting...
===============================================
    Default test
    Tests run: 0, Failures: 0, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 0, Failures: 0, Skips: 0

A:

Thank you all for your help, I found my mistake after debugging. The error lied in my CSVReader file which it reads data from the 2nd line after the heading. It prone the error.


Q:

How to assign current year in with tag

In django I want to do something like this, which will pass current year to url name
{% with now "Y" as year %}
 Create
{% endwith %}

but its not able to interpret I want to do

year = now 'Y'

How should I do this

A:

Did you simply try:
{% now "Y" as current_year %}
 Create


Q:

Efficient use of SQL Transactions

My application currently needs to upload a large amount of data to a database server (SQL Server) and locally on a SQLite database (local cache).
I have always used Transactions when inserting data to a database for speed purposes. But now that I am working with something like 20k rows or more per insert batch, I am worried that Transactions might cause issues. Basically, what I don't know is if Transactions have a limit on how much data you can insert under them.
What is the correct way to use transactions with large amounts of rows to be inserted in a database? Do you for instance begin/commit every 1000 rows?

A:

No there is no such limit. Contrary to what you might believe, SQLite writes pending transactions into the database file, not RAM. So you should not run into any limits on the amount of data you can write under a transaction.
See SQLite docs for these info: http://sqlite.org/docs.html
Follow the link "Limits in SQLite" for implementation limits like these.
Follow the link "How SQLite Implements Atomic Commit" for how transactions work


Q:

How can I view the data I retrieved from my .SQLITE database in my debug area using the NSLog command?

Whenever when I press build, it would give me the SIGABORT sign and goes back to the code.
Do I need a usable storyboard view or without it I could see the output in the Debug Area
The code I used was
for (PokemonAbility *theability in items) {

 NSLog(@"Number: %@  Name: %@ Generation: %@ Desc: %@",theability.rowid, theability.abilityname, theability.abilitygeneration, theability.abilitydesc);

 }

Referenced from:
Code Reference

A:

Hard to tell from what you wrote, but I bet that you're using raw data from SQLite, which is a C string, and using it in NSLog as an NSString.  Try
[NSString stringWithCString:theability.rowid];

etc.


Q:

Using i18n resources from WEB-INF in Junit test

I think I ran into an error with my classpath settings.
I want to test an internationalized web-app which has the messagesource defined like this:
<bean id="messageSource"
  class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>/WEB-INF/i18n/errors</value>
            <value>/WEB-INF/i18n/messages</value>
            <value>/WEB-INF/i18n/links</value>
            <value>/WEB-INF/i18n/forms</value>
            <value>/WEB-INF/i18n/communication</value>
        </list>
    </property>
</bean>

Loading these values works perfectly in a production environment.
When running a Junit Test however, it can't resolve those property files because they are not on the classpath.
However, I want them to be NOT on the classpath because then I can make use of the feature where I can change something in the property files and it's reflected on the website immediately: Since application servers typically cache all files loaded from the classpath, it is necessary to store resources somewhere else (for example, in the "WEB-INF" directory of a web app). Otherwise changes of files in the classpath will not be reflected in the application.
The spring applicationContext is located there: /src/main/resources/spring/applicationContext.xml
and loaded into the Junit test with these annotations:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring/applicationContext.xml"})

How can I get Junit to pick up those non-classpath resources as well?
The property files are on /src/main/webapp/WEB-INF/i18n/*
Junit: 4.7.
Spring: 3.0.5.

A:

I fixed my initial problem in the meantime.
Matthew's solution didn't help me - still very good input.
And he couldn't know that I was using maven in my project since I never told.
However, within maven, I found a solution to my problem:
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <skipTests>true</skipTests>
                <additionalClasspathElements>
                    <additionalClasspathElement>src\main\webapp\</additionalClasspathElement>
                </additionalClasspathElements>
            </configuration>
        </plugin>

I configured the surefire-plugin to pickup additional elements for the classpath.

A:

It seems to me the simplest solution is just use a property which you override when junit is executing:
<bean id="messageSource"
  class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>${path.prefix}/WEB-INF/i18n/errors</value>
            <value>${path.prefix}/WEB-INF/i18n/messages</value>
            <value>${path.prefix}/WEB-INF/i18n/links</value>
            <value>${path.prefix}/WEB-INF/i18n/forms</value>
            <value>${path.prefix}/WEB-INF/i18n/communication</value>
        </list>
    </property>
</bean>

You set the default value for this in the PropertyPlaceholderConfigurer
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="properties">
        <props>
            <prop key="path.prefix"></prop> <!-- empty -->
        </props>
    </property>
</bean>

This propertyConfigurer bean definition needs to be before the messageSource bean definition. In the junit tests, you can either:

set the property through using a different version of the propertyConfigurer specific to your tests, or
setting the system property through a -Doption on the command line or System.setProperty("path.prefix", "src/main/webapp") in your @Before.

Note that if you do (2), then Spring sometimes caches the values of system properties, so you can't subsequently change the system property. It uses the original value.


Q:

Message not sent completely. Some text are missing

I'm trying to send a text message from my Android application. Everything works fine, but some of the text are missing. Here is my code:
String phoneNumber = "99********";  //Masked the number intentionally.
String message = "";
message += "This is Prabha, and thanks for using my application. ";
message += "Hope you enjoy this application. ";
message += "If you face any problem or issue, you can report the issue to our ";
message += "official mail id: pbha701@yahoo.com.";

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);

I am receiving the message, but it is not full. Some text are missing. I'm getting only the below text:
This is Prabha, and thanks for using my application. Hope you enjoy this application. If you face any problem or issue, you can report the issue to our officia
I've added the below permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.SEND_SMS" />

I am not able to find why the remaining text are truncated. Should I add any other permission or any setting changes required? Any ideas or help will be appreciated.
Thanks.

A:

You need to use sendMultipartTextMessage() method available in SmsManager class.
sendTextMessage() method available in SmsManager class can send a text message of length 160 characters only.
To send multi-part SMS, divide the message using divideMessage() method available in SmsManager class. Then send this parts as an parameter in sendMultipartTextMessage(), as shown below:
SmsManager smsManager = SmsManager.getDefault();
ArrayList<String> parts = smsManager.divideMessage(message);
smsManager.sendMultipartTextMessage(phoneNumber, null, parts, null, null);


Q:

consume Asp.net MVC api from android volley

i am trying to consume a MVC 4 api from my android application
i am using Volley library and it work fine to get data from server
the problem is when i try to send data to the web service which i understand it should be done by using post Method and JsonObjectRequest
my method in MVC Api is :
public class ItemController : ApiController
{
 public IEnumerable<string> Post(List<string> val)
        {

            return val;
        }
}

and for volley :
    String tag_string_req = "req_login";
    Map<String, String> params = new HashMap<>();
    params.put("email", "S@b.Com");
    params.put("username", "basheq");
    JsonObjectRequest req = new JsonObjectRequest(Method.POST ,
    AppConfig.URL_REGISTER, new JSONObject(params),new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d(TAG, "Login Response: " + jsonObject.toString());
            }
        }
      , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
            }
        });
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(req, tag_string_req);

but i keep getting null in response and it look like the api doesn't parse the parameter .
what is wrong ?? , and is this the proper way to do it or is there a better way ??

A:

The main problem was that i was setting list as a parameter which for some reason does not work
the solution was by wrapping the input parameter into a class and of course change the json structure to correspond to that


Q:

Assert that ActionBar item becomes visible after CAB is dismissed

I have the following two tests shown:
public void testOnClickCheckboxStartActionMode() {
    int index = 4;
    this.solo.clickOnCheckBox(index);
    Assert.assertTrue(this.solo.waitForView(R.id.delete_menu));
}

public void testOnClickCheckboxStopActionMode() {
    this.testOnClickCheckboxStartActionMode();

    int index = 4;
    this.solo.clickOnCheckBox(index);
    View addMenu = this.activity.findViewById(R.id.add_menu);
    Assert.assertNotNull(addMenu);
    Assert.assertTrue(addMenu.isShown());
}

The first checks that my ActionMode is correctly started when an item in my ListView is checked. The second checks that the ActionMode stops after unchecking the ListView item. The problem is that testOnClickCheckboxStopActionMode() fails on the line Assert.assertTrue(addMenu.isShown());. I can manually verify the correct behavior in my app, so the test seems to be broken. I believe the problem is that this assertion occurs before the UI thread has a chance to remove the CAB and restore the regular ActionBar.
I have tried Instrumentation.runOnMainSync() in order to synchronize my test with the UI thread:
    this.inst.runOnMainSync(new Runnable() {
        @Override
        public void run() {
            View addMenu = activity.findViewById(R.id.add_menu);
            Assert.assertNotNull(addMenu);
            Assert.assertTrue(addMenu.isShown());
        }
    });

It still fails at the same assertion. Worse, the entire test suite stops, rather than simply signaling a failed test and continuing with the next one, because the AssertionFailedError is thrown on a separate thread.
How do I properly synchronize with the main thread in order to verify that the ActionBar menu items are indeed visible at the end of my tests?

A:

I was able to fix the problem by inserting a call to Solo.waitForView():
public void testOnClickCheckboxStopActionMode() {
    this.testOnClickCheckboxStartActionMode();

    int index = 4;
    this.solo.clickOnCheckBox(index);

    // Added this call:
    Assert.assertTrue(this.solo.waitForView(R.id.add_menu));
    View addMenu = ButterKnife.findById(this.activity, R.id.add_menu);
    Assert.assertNotNull(addMenu);
    Assert.assertTrue(addMenu.isShown());
}

Strangely, I had originally tried modifying this test with waitForView() while fixing a bug. However, alone it didn't cause the test to fail in the presence of the bug. On the other hand, addMenu.isShown() didn't pass after the bug was fixed. Apparently a combination of both is required for this test to be correct.


Q:

trigger javascript function when a key is pressed in fckeditor

I need to trigger a custom javascript function when something is typed into FCKeditor 2 textarea. However, I have searched far and wide and can't find an answer to this. Would like to do something like add onkeypress="customfunction()" to the textarea somehow.
Thanks for any help!

A:

managed to find something in the end using some hints of words. Here is how to do an onkeypress even on FCKeditor 2.0. You need to load this javascript AFTER the editor code is called:
function FCKeditor_OnComplete(editorInstance){
    if (document.all) {        // If Internet Explorer.
      editorInstance.EditorDocument.attachEvent("onkeydown", function(event){alert('key was pressed');} ) ;
    } else {                // If Gecko.
      editorInstance.EditorDocument.addEventListener( 'keypress', function(event){alert('key was pressed')}, true ) ;
    }

}


Q:

dynamic sql query php with AND

I have some sql code:
    $id = "2000";
    $model = $_GET["model"]

    $result = mysql_query("SELECT
    Left(Right(Base.inputs.Data_inf,4),3) As 'Datas',
    count(Base.Data.Data_ID) As `U_Count`
    FROM
        Base.Data
    WHERE
        Product = '$id'
        AND model in ('a','b','c')
    GROUP BY ");

I would like to make AND part of query to be dynamic. Something like this:
$m= $model;
switch ($m)
{
    case "basic":
        $m = "AND model in ('a','b','c')";
        break;

    case "upgrade":
        $m = "AND model in ('d','e','f')";
        break;

    default:
        $m = "AND model in ('a','b','c')";
}

I put $m in the query and it doesn't work:
WHERE
      Product = '$id'
      '$m'

Any suggestion will be appreciated.

A:

Remove the quotes around $m. Also, add spaces and replace AND with the right condition:
$m= $model;
switch ($m)
{
    case "basic":
        $m = " AND model in ('a','b','c') ";
        break;

    case "upgrade":
        $m = " AND model in ('d','e','f') ";
        break;

    default:
        $m = " AND model in ('a','b','c') ";
}

And then do:
$result = mysql_query("SELECT
Left(Right(Base.inputs.Data_inf,4),3) As 'Datas',
count(Base.Data.Data_ID) As `U_Count`
FROM
    Base.Data
WHERE
    Product = '$id'
    $m ");


Q:

ajax enabling problem

Hello friends a day ago i made my visual studio(2005, 2.0) ajax enabled.
But i am already having a web site which is not ajax enabled so how can i make that ajax enabled. Because it doesn't recognize script manager tag and update panel tag on putting .
While whenever i make a new web site it ask for ajax enable web site but how can i make my existing web site ajax enable

A:

I suggest creating a new ajax enabled web site, and carefully comparing its web.config with your current site's web.config. That should help you identify the critical points.


Q:

The character does not follow the path

I want the character to follow the path, but its doesnt work...When i click the armature in object mode and add object constraint follow path, the character will move away and doesnt animated as desire.Seek for help

A:

Actually it does follow the path, except that you’re supposed to place the armature at the exact same point as the beginning of the path, to do so just press AltG, it resets the location at 0/0/0 but as the armature is constrained by the Follow Path its new 0/0/0 is the beginning of the curve.
Now second problem, once you’ve reset the location, the armature still goes away. The reason is that you’ve given it an animation as you can see if you open the NLA Editor, and this animation contains location datas that moves it away from the 0/0/0. So either delete this NLA strip or delete the location infos of this action.
To delete the location datas of this action: In the 3D View select the armature, in the NLA select the first NLA strip of the top track (the one that plays), press Tab to display the action of this strip in the Dopesheet. Go in the Dopesheet, click on the arrow icon button to only see the actions of the selected object, in the left panel unfold the action datas, double click on the X Location track and press X to delete this row, same thing with Y Location and Z Location tracks.


Q:

error:Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

I get this error when I insert an interstitial ad. Help me
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mBinding = DataBindingUtil.setContentView(this, R.layout.module_home_activity_home);
    mViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
    getLifecycle().addObserver(mViewModel);

    initView();
    subscribeUi();

    MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");

    mInterstitialAd = new InterstitialAd(this);
    mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
    mInterstitialAd.loadAd(new AdRequest.Builder().build());

    Button tvOk = (Button) findViewById(R.id.tvOk);

    tvOk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mInterstitialAd.isLoaded()) {
                mInterstitialAd.show();
            }
        }
    });

    mPermissionReqHandler = new PermissionReqHandler(self());
}

Logcat Message:
FATAL EXCEPTION: main
Process: com.xxx.xxx, PID: 29573
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxx.xxx/com.xxx.xxx.app.tally.module.home.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at com.coderpage.mine.app.tally.module.home.HomeActivity.onCreate(HomeActivity.java:86)
    at android.app.Activity.performCreate(Activity.java:6975)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

A:

First, you need to set the content view in your onCreate function like the following.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set the content view like this
    setContentView(this, R.layout.module_home_activity_home);

    mBinding = DataBindingUtil.setContentView(this, R.layout.module_home_activity_home);
    mViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
    getLifecycle().addObserver(mViewModel);

    initView();
    subscribeUi();

    MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");

    mInterstitialAd = new InterstitialAd(this);
    mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
    mInterstitialAd.loadAd(new AdRequest.Builder().build());

    Button tvOk = (Button) findViewById(R.id.tvOk);

    tvOk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mInterstitialAd.isLoaded()) {
                mInterstitialAd.show();
            }
        }
    });

    mPermissionReqHandler = new PermissionReqHandler(self());
}

And secondly, please check if the id of the button is set to tvOk in your module_home_activity_home.xml file.