text:
Q: Shapefile created with GDAL doesn't hold projection I'm generating a shapefile using the GDAL and shapely libraries in Python. There's a problem with the projection, when I import the resulting shapefile in ArcMap, there is not projection associated with the file. How can I correct that, or how can I project the resulting layer ?
Here's my code:
output_shp = "circle.shp"
data_projection = 26919

[...]

srs = osr.SpatialReference()
srs.ImportFromEPSG(data_projection)

# output of srs: <osgeo.osr.SpatialReference; proxy of <Swig Object of type 'OSRSpatialReferenceShadow *' at 0x00000000099FF5A0> >

driver = ogr.GetDriverByName('Esri Shapefile')
ds = driver.CreateDataSource(output_shp)
layer = ds.CreateLayer(layer_name, srs, ogr.wkbPolygon)
layer.CreateField(ogr.FieldDefn('id',ogr.OFTInteger))
defn = layer.GetLayerDefn()

for x in range(0,length):
    feat = ogr.Feature(defn)
    feat.SetField('id', x+1)

    geome = ogr.CreateGeometryFromWkt(geom_out[x].wkt)
    feat.SetGeometry(geome)
    layer.CreateFeature(feat)

A: Ok. I've found the solution, thanks to MikeT answer in this post.
The problem was that my GDAL_DATA environment variable was not correctly set. Therefore, the SRS I was adding to my layer was empty because it couldn't find it in the directory.
A little checkup to see if the importation fails (thanks to MikeT):
from osgeo import osr
testSR = osr.SpatialReference()
res = testSR.ImportFromEPSG(4326)
if res != 0:
    raise RuntimeError(repr(res) + ': could not import from EPSG')
print testSR.ExportToPrettyWkt()


text:
Q: Stub telephone input jest vue JS I'm trying to stub a tel input plugin I'm using in one of my Vue component.
This is what I've tried, I think I almost got it but I'm missing one small detail.
This is my spec file:
import { mount, createLocalVue } from '@vue/test-utils';
import ModalNewCustomer from "../../../resources/js/subviews/customers/components/ModalNewCustomer";

// Stubs
const telInput = {
    template: `<input type="tel">`
}

import moment from 'moment';

describe('Modal New Customer',() => {
    let wrapper,mockCheckNameDuplicate;

    let districts = [
        {"id":1,"name":"Aberdeen"},
        {"id":2,"name":"Admiralty"},
        {"id":3,"name":"Ap Lei Chau"},
        {"id":4,"name":"Beacon Hill"},
        {"id":5,"name":"Braemar Hill"},
        {"id":6,"name":"Causeway Bay"},
        {"id":8,"name":"Central"}
    ];

    let newCustomerData ={
        firstName: 'Loulou',
        lastName: 'Le Loup',
        emailAddress: 'email@google.com',
        sex: 'M',
        primaryPhoneNumber: '+85200001111',
        secondaryPhoneNumber: '+85233334444',
        birthday: "2020-11-30",
        wayOfContact: 'email',
        electroOrNot: 1,
        asiaMilesMembership: '00001111'
    };

    beforeEach(() => {
        mockCheckNameDuplicate = jest.spyOn(ModalNewCustomer.methods, 'checkNameDuplicate');

        wrapper = mount(ModalNewCustomer,{
            localVue,
            propsData:{
                districts: districts
            },
            data(){
                return{
                    COMPANY_NAME: 'HK'
                }
            },
            router,
            stubs:{
                "vue-tel-input": telInput
            }
        });

        flushPromises();
        jest.resetModules();
        jest.clearAllMocks();
    });

    afterEach(() => {
        flushPromises();
        jest.resetModules();
        jest.clearAllMocks();
    })

    it('can input new customer data and submit it',async() => {
        const {vm} = wrapper;

        let primaryPhoneNumberInput = wrapper.find('#primaryPhoneNumber');
        await primaryPhoneNumberInput.setValue(newCustomerData.primaryPhoneNumber)

        expect(primaryPhoneNumberInput.element.value).toBe(newCustomerData.primaryPhoneNumber);
        console.log(primaryPhoneNumberInput.html())
        console.log(vm.newCustomer.primaryPhoneNumber)

    });
});

In my vue component, the vue tel input looks like this:
             <vue-tel-input
                 id="primaryPhoneNumber"
                 :default-country="COMPANY_NAME"
                 validCharactersOnly
                 v-model="newCustomer.primaryPhoneNumber"
                 :inputOptions="inputOptions">
             </vue-tel-input>

The problem is when I set the value of my stub component, the data of the Vue component I'm testing is not being updated, when it should be rerendered thanks to v-model.
Thanks for your help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: $location partial path change If there is s path of /#/var1/oneVariable/var2/many,more,variables/var3/last,set and I wanted to update the $location, is there a way to only update the variable part of the path without having to re-declare everything from the current path?
Is something like this possible?:
$location.path(var2 = 'changed,all,three';)

and having the result be /#/var1/oneVariable/var2/changed,all,three/var3/last,set

A: I don't think that it is possible by default. However, you can create a function by yourself that keeps track of the current variables and fills them in for you when you need to change one of them and calls $location.path().
var currentParams = {
    var1: 'oneVariable',
    var2: 'many,more,variables',
    var3: 'last,set'
};
function changePath(params) {
    angular.forEach(params, function (value, key) {
        currentParams[key] = value;
    });
    $location.path('/var1/'+ currentParams.var1 + '/var2/' + currentParams.var2 + '/var3/' + currentParams.var3);
}

You can call it now by using changePath({var2: 'changed,all,three'}).
Note that this is a simplified example. You can make it more flexible and it would be good to put it into an Angular service.


text:
Q: Transforming dictionary with lists of tuples to lists Suppose I have a dictionary with this structure:
namedict = {
1880:
    [('Mary', 'F', '7065', 1),
     ('Anna', 'F', '2604', 2),
     ('John', 'M', '9655', 1)],
1881:
    [('Mary', 'F', '8065', 1),
     ('Anna', 'F', '9604', 2),
     ('John', 'M', '5655', 1)],
1882:
    [('Mary', 'F', '9065', 1),
     ('Anna', 'F', '9604', 2),
     ('John', 'M', '5655', 1)]
    }

I'd like to transform the dictionary so that the data is in the following list structure:
[{(Mary, F): {1880: [7065, 1], 1881: [8065, 1], 1882: [9065, 1]}]
[{(Anna, F): {1880: [2064, 2], 1881: [9604, 2], 1882: [9604, 1]}]...

Any suggestions as to how I would do this?

A: From what I understand, the collections.defaultdict() can help in this case:
from collections import defaultdict
from pprint import pprint

namedict = {
    1880:
        [('Mary', 'F', '7065', 1),
         ('Anna', 'F', '2604', 2),
         ('John', 'M', '9655', 1)],
    1881:
        [('Mary', 'F', '8065', 1),
         ('Anna', 'F', '9604', 2),
         ('John', 'M', '5655', 1)],
    1882:
        [('Mary', 'F', '9065', 1),
         ('Anna', 'F', '9604', 2),
         ('John', 'M', '5655', 1)]
}

d = defaultdict(dict)
for key, values in namedict.items():
    for name, gender, value1, value2 in values:
        d[(name, gender)][key] = [value1, value2]

pprint(dict(d))

Prints:
{('Anna', 'F'): {1880: ['2604', 2], 1881: ['9604', 2], 1882: ['9604', 2]},
 ('John', 'M'): {1880: ['9655', 1], 1881: ['5655', 1], 1882: ['5655', 1]},
 ('Mary', 'F'): {1880: ['7065', 1], 1881: ['8065', 1], 1882: ['9065', 1]}}

Or, in case of Python3, you can use the extended iterable unpacking and make the solution a bit more generic:
d = defaultdict(dict)
for key, values in namedict.items():
    for name, gender, *values in values:
        d[(name, gender)][key] = values

A: Based on how I understand the problem, the following code should work. It uses a defaultdict (something I recently started using more, but it is also worth noting that there is another answer that uses it as well )
from collections import defaultdict
def reorder_namedict(namedict):
    new_list_representation = defaultdict(dict)
    for year in namedict:
        for user_tuple in namedict[year]:
            # tuple unpacking has changed based on what version of python is used.
            # I ran this against 3.4.3 and 2.7.6.
            # Use python --version to check if you don't know your version
            name, gender, num1, num2 = user_tuple
            new_list_representation[str((name, gender,))][year] = [int(num1), int(num2)]

    new_list = []

    # sorted so that it comes out in consistent order for string matching
    for key in sorted(new_list_representation):
        new_list.append([{key: new_list_representation[key]}])

    return new_list

The code returns a list of lists to match the second code block in the question. The following input comes from the question (plus or minus some formatting) and expected output (from the question, with the small modification to return a list of the desired lists instead of trying to return multiple lists.
namedict = {
1880:
[('Mary', 'F', '7065', 1),
('Anna', 'F', '2604', 2),
('John', 'M', '9655', 1)],
1881:
[('Mary', 'F', '8065', 1),
('Anna', 'F', '9604', 2),
('John', 'M', '5655', 1)],
1882:
[('Mary', 'F', '9065', 1),
('Anna', 'F', '9604', 2),
('John', 'M', '5655', 1)]
}

output_to_match = [
[{str(('Anna', 'F',)): {1880: [2604, 2], 1881: [9604, 2], 1882: [9604, 2],}}],
[{str(('John', 'M',)): {1880: [9655, 1], 1881: [5655, 1], 1882: [5655, 1],}}],
[{str(('Mary', 'F',)): {1880: [7065, 1], 1881: [8065, 1], 1882: [9065, 1],}}],
]

The following code will demonstrate that the two lists are the same. You can uncomment the print statements that show each list and how it is converted to a string, but I find that having the code check that each character matches is more reliable (I missed a few small mistakes myself).
match_this = str(output_to_match)
iTried = str(reorder_namedict(namedict))
# print(match_this)
# print('---')
# print(iTried)
for i in range(0, len(match_this)):
    if not match_this[i] == iTried[i]:
        print('%d %s %s' % (i, match_this[i], iTried[i],))
print(match_this == iTried)


text:
Q: Recursion to flatten an array not working I was working on the steamroller problem of free code camp. I came up with two solutions: one works perfectly [1, 2, 3, 4], but the other is giving [ 4 ].
The problem asks to write a function that flatten any sort of array.
my working code:
function steamrollArray(arr) {
   newArr = [];
   for (i = 0; i < arr.length; i++) {
     if (Array.isArray(arr[i]) === true) {
       newArr = newArr.concat(steamrollArray(arr[i]));
     } else if (Array.isArray(arr[i]) === false) {
       newArr.push(arr[i]);
     }
   }
   return newArr;
}
steamrollArray([1, [2], [3, [[4]]]]);

my not working code:
function steamrollArray(arr) {
  newArr = [];
  for (i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i]) === true) {
      newArr.push(steamrollArray(arr[i]));
    } else if (Array.isArray(arr[i]) === false) {
      newArr.push(arr[i]);
    }
  }
  return newArr;
}
steamrollArray([1, [2], [3, [[4]]]]);

Can anyone explain why the second code give only [4] ?

A: That happens because in first code, you are using
newArr = newArr.concat() in which you are assigning it to local variable. So, even in recursion, the state will be stored.
But in second code, you are using newArr.push() and in recursion, you are again declaring newArr=[];
That is the issue.

A:

function steamrollArray(arr) {
  // I'm a steamroller, baby
  let newArr = arr.slice(); //newArr is a copy of arr
  var result = []; //this is going to be the flatted array
  checkArray(newArr, result);
  return result;
}

function checkArray(myArray, resultedArray) {
  //this function is a a recursion
  return myArray.map(elt => {
    if (!Array.isArray(elt)) {
      //so this is a simple element, it is not an array, lets push it
      resultedArray.push(elt);
      return elt;
    } else {
      return checkArray(elt, resultedArray);
    }
  });
}
console.log(steamrollArray([1, {},
  [3, [
    [4]
  ]]
])); // should return [1, {}, 3, 4].

Comments in the code are helpful


text:
Q: Title-case words in string that are only bordered by whitespace (or start/end of string) I need to apply title-casing to my string, but with some exceptions.
If the substring is separated by spaces and contains only letters, make the first letter uppercase and the rest lowercase.
If there are letters and non-letters, they should remain unchanged:
ucwords(strtolower("NEW APPLE IPHONE X 64GB CVX-Dk46"))

For example:NEW APPLE IPHONE X 64GB CVX-Dk46
Should become:New Apple Iphone X 64GB CVX-Dk46

A: This will loop through each word and see if there is a digit in the word, if no then do the strtolower and ucwords.
$str = "NEW APPLE IPHONE X 64GB CVX-Dk46";

$arr = explode(" ", $str); // make it array

foreach($arr as &$word){ // loop array
    if(!preg_match("/\d/", $word)){ // is there not a digit in the word
        $word = ucwords(strtolower($word));
    }
}

echo implode(" ", $arr); // implode array to string
//New Apple Iphone X 64GB CVX-Dk46

https://3v4l.org/qccG9

A: Here is another method.  The only difference is the use of the array_walk() function instead of the foreach() loop in Andreas' answer. (Which is also a good answer.)
$str = 'NEW APPLE IPHONE X 64GB CVX-Dk46';

$data = explode(' ', $str); //This will take the sting and break the string up
//into an array using the space bewtween the words to break apart the string.

array_walk($data, function(&$item){  //Walk each item in the array through a function to decide what gets UC letter.

  if(!preg_match('/\d/', $item)){ //Test for any numbers in a word.

    //If there are no numbers convert each character to lower case then upper case the first letter.
    $item = ucwords(strtolower($item));

  }

});

$newString = implode(' ', $data);  //Take the new array and convert it back to a string.

echo $newString; //This will output:  "New Apple Iphone X 64GB CVX-Dk46"

A: You can not achieve this with a single line.Please see the below code if it can be helpful for you.
$val = "NEW APPLE IPHONE X 64GB CVX-Dk46";
$val = explode(" ", $val);
$finalString = '';
foreach ($val as $value) {
 if(preg_match('/^[a-zA-Z]+[a-zA-Z0-9._]+$/', $value)) {
   $finalString = $finalString . " " . ucwords(strtolower($value));
 } else {
 $finalString = $finalString . " " . $value;
 }
}
echo $finalString;

Output will be as below:-
New Apple Iphone X 64GB CVX-Dk46

A: first of all you need to find the number in your string
 - if have the number you need to separate your string to array
the first array is contain only  string , the second array is contain number(or number and string)
 - if have not the number you need to use php function  strtolower to lower your string and use php function ucwords to converts the first character of a string to uppercase
 you can try the code below:
Link: https://3v4l.org/jW6Wf

function upperCaseString($string)
{
$pattern = '/(?=\d)/';
$array = preg_split($pattern, $string, 2);
$text='';
 if(count($array)>1)
 {

  $text=ucwords(strtolower($array[0])).' '.strtoupper($array[1]);
 }
 else
 {
  $text=ucwords(strtolower($array[0]));
 }
 return $text;
}
$str = "NEW APPLE IPHONE X 64GB CVX-Dk46";
echo upperCaseString($str);

A: For your sample string, this can be achieved with a single matched substring within a preg_replace_callback() call!
Code: (Demo) (Regex Demo)
echo preg_replace_callback(
         '~(?:\G ?)\p{Lu}+(?= |$)~u',
         function($m) {
             return mb_convert_case($m[0], MB_CASE_TITLE);
         },
         'NEW APPLE IPHONE X 64GB CVX-Dk46'
     );
// New Apple Iphone X 64GB CVX-Dk46

The \G (continue metacharacter) starts matching from the start of the string OR from where the pattern previously stopped matching.  I am using spaces and anchors to satisfy the requirement of matching whole ALL-CAPS words.
This performs better than nested lookarounds. e.g. (?:(?:^| )\p{Lu}+(?= |$))+


text:
Q: Azure Function error for REST Api using Table Storage Hi I am trying out simple Azure Function with REST Api.
My env is MSVC 2019 and created a simple mmApi Fucntion app
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using AzureFuncApp.Model;
using System.Collections.Generic;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage;

namespace AzureFuncApp
{
    public static class mmApi
    {
        //static List<Board> boards = new List<Board>();

        [FunctionName("CreateBoard")]
        public static async Task<IActionResult> CreateBoard(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "board")] HttpRequest req,
            [Table("boards", Connection ="AzureWebJobsStorage")] IAsyncCollector<BoardTableEntity> boardTable,
            ILogger log)
        {
            log.LogInformation("Creating a new board.");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var input = JsonConvert.DeserializeObject<BoardCreateModel>(requestBody);
            var board = new Board() { PlayerCount = input.PlayerCount };
            board.Players.Add(input.Player);
            await boardTable.AddAsync(board.ToTableEntity());
            return new OkObjectResult(board);
        }

It is this line that I have added to Table Storage
[Table("boards", Connection ="AzureWebJobsStorage")] IAsyncCollector
Is throwing the below error

Function (AzureFuncAppmmApi/CreateBoard) Error:
  Microsoft.Azure.WebJobs.Host: Error indexing method 'CreateBoard'.
  Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'boardTable' to
  type IAsyncCollector`1. Make sure the parameter Type is supported by
  the binding. If you're using binding extensions (e.g. Azure Storage,
  ServiceBus, Timers, etc.) make sure you've called the registration
  method for the extension(s) in your startup code (e.g.
  builder.AddAzureStorage(), builder.AddServiceBus(),
  builder.AddTimers(), etc.).

What I am not following is where do I register builder.AddAzureStorage() when I don't have the startup file in my project.
Attached is my project details, any help and pointer is appriciated

A: I found the answer, Microsoft.NET.Sdk.Functions updates to v3.0.2, manually added the below refrences in the csprog file and it works fine. @tubakaya your suggestion helped
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.23" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="3.0.1" />   </ItemGroup>```


text:
Q: Can lucene only sort and search for nothing? I want to list the lastest 10 rows order by id DESC
Sort sort = new Sort(new SortField[]{new SortField("id",SortField.INT,true)});
TopDocs topDocs=indexSearch.search(null,null,10,sort);//no need Query,only sort
...

I got a 500 exception because the Query parameter is null
How can I implement it in a best way?
btw:id field is a NumericField,write using:
new NumericField("id",Integer.MAX_VALUE,Field.Store.YES,true)

A: You should use the MatchAllDocsQuery for that.
Lucene Query is a peculiar object that isn't only the specification of the query semantics, but also the implementation of the most efficient execution strategy for each particular query type. That's why there must be a special Query even for this "no-op"

A: BTW: if you want to search the latest X rows it's better you add a new date field with the time this doc was added to repository and not to rely on the counter (id on your case).
try to think what happen if you update an existed doc or you reach Integer.MAX_VALUE


text:
Q: Origin and usage of "a shambles" "Shambles" is one of the few singular nouns in English that blatantly resembles a plural noun. What is the origin of "a shambles"? Why do we really need to prefix an "a" in front of "shambles"? Which of the following is perfect?

*

*The country's economy is in shambles.

*The country's economy is in a shambles.

*The country's economy is a shambles.

A: "in a shambles" or "a shambles" would be correct. The only form that the last one would work for is "shambolic".
Given the origin, it actually does make sense, because the object is in [or just is ] a place of chaos and disorder - one of many such places. But it seems that an economy should be a shamble. The s is not a pluralisation, but a part of the word.
In York, UK, The Shambles is still a street, and a popular one for tourist shops.

A: The weird usage seems to have developed in the same way as "a headquarters". Consider the following Ngram:

The original phrase seems to have been "shambles" or "the shambles", almost always plural. It meant "a place for slaughtering animals", but later came to be also used for scenes of carnage, scenes of great disorder, and certain dangerous shoals at sea.
Etymonline says that "shambles" originally meant "meat market", having evolved from the word schamil meaning "table or stall for vending". I assume that it naturally started out as a plural, because there would be several butcher's stalls at a meat market.
However, once "shambles" came to mean "a scene of great disorder or carnage", the things it referred to were more naturally singular, and so "shambles" slowly came to be used as a singular.

A: Merriam Webster says:

shambles: a place of mass slaughter or bloodshed; a scene or a state of great disorder or confusion

and offers an example:

the city was a shambles after the bombing

note that it doesn't use 'in' at all.
Traditional usage would say your first option is incorrect.
Given the definition above we can elaborate your sentence as:

The country's economy is (figuratively) 'a place of mass slaughter' or 'a scene of great disorder' thus,
  The country's economy is a shambles would be optimal, I think.

Perhaps using the state of disorder definition would allow one to use 'in a ~'
So, your second option, "The country's economy is in a shambles" could also work.
As long as we're throwing Ngrams in, here is one that shows that Option 1 has gained popularity quite recently:

A: I have understood that the term goes back to Biblical times, and indicated the meat market where meat from the pagan temples and the Jewish Temple was offered for sale.
Apparently the priests received more in meat offerings than they could ingest, and sent the excess to the shambles for sale to the general public. If originally offered to idols, the meat may have brought a higher price that the same cuts from local producers.
H Craft
Houston

A: 1 Corinthians 10:25  King James Bible
"Whatsoever is sold in the shambles, that eat, asking no question for conscience sake:"
Perhaps this expression, "in the shambles" increased in usage after the publishing of the first King James Bible.
I researched the rendition of this word in the Greek, Hebrew and Latin and those words do not resemble this pronunciation.
It would be interesting to see the notes written by the translators who worked on this version of the Bible to see whether they discussed which way to put this idea in English at the time.

A: The Wycliffe Bible (c.1390) has 25 All thing that is sold in the butchery, eat ye, asking nothing for conscience.
The Tyndale Bible (1535) has, 1 Corinthians 10:25 appears as 25 What soever is solde in the market that eate and axe no questions for conscience sake
The Geneva Bible (1560) has 25 Whatsoever is sold in the shambles, eat ye, and ask no question for conscience sake.
From at least 1390, the concept of a shamble(s) was thus of an area in which animals were slaughtered and their (and other) meat sold.
Its development was: (From OED)

†1. A stool, footstool. Chiefly in figurative context.

c825   Vesp. Ps. cix. 1   Oð ðæt ic sette feond ðine scomul [scabellum] fota ðinra.

and then it became

2.†a. In Old English, a table or counter for exposing goods for sale, counting money, etc. Obsolete.

971   Blickl. Hom. 71   He þa ineode on þæt halige Salemannes templ, & þa ut awearp þa sceomolas þara cypemanna.

It then became more specialised, and by Middle English it had become

2b. spec. A table or stall for the sale of meat.

α c1305   Of Men Lif, etc. xv, in Early Eng. Poems & Lives Saints (1862) 155
Hail be ȝe potters [? bochers] wiþ ȝur bole ax..ȝe stondiþ at þe schamil [printed sthamil in Rel. Ant. II. 176], brod ferlich bernes.

And 100 years later synecdoche had taken place, and as used in the Geneva Bible:

*a. plural. A place where meat (or occasionally fish) is sold, a flesh- or meat-market. ? Now local.

a1410   in York Myst. Introd. 24 (note)    All the folks of the salsemaker crafte..without the Flesshchameles.

The potential for use in a transferred/figurative sense was not lost on the people:

5. transferred and figurative.

a. A place of carnage or wholesale slaughter; a scene of blood. Chiefly plural construed as singular; rarely in singular form.

1593   T. Nashe Christs Teares 12 b   The Infidell-Romaines..shall inuade thee, and make thy Citty..a shambles of dead bodies.

However, it took another 300 years to become acceptable as

5 b. plural. In more general use, a scene of disorder or devastation; a ruin; a mess. Originally U.S.

1926   P. H. de Kruif Microbe Hunters iii. iv. 83   Once more his laboratory became a shambles of cluttered flasks and hurrying assistants.

And this is the only meaning that is now common.


text:
Q: How can I find why my Python program doesn't put me through to the next question? There is an error in this part of the code:
extraAttractions = input("do you want to know about extra attractions, yes or no? ")
if extraAttractions == "yes":
  def attraction():

When I ask about extra attractions, even when I type yes as my input, it doesn't put me through to the next question and I'm not sure why.
oneAdult = [20.00, 30.00]
oneChild = [12.00, 18.00]
oneSenior = [16.00, 24.00]
familyTicket = [60.00, 90.00]
sixPeoplePlus = [15.00, 22.50]
lionFeeding = 2.50
penguinFeeding = 2.50
eveningBarbeque = 5.00

while True:
  try:
    oneOrTwo = int(input("are you buying tickets for 1 or 2 days? "))
    if oneOrTwo == 1:
      print("day succesfully selected. the prices are, for one adult $", oneAdult[0], "for one child $", oneChild[0], "for one senior $", oneSenior[0], "for a family ticket $",familyTicket[0], "for a group of six people or more(price per ticket) $",sixPeoplePlus[0])
      break;
    elif oneOrTwo == 2:
      print("the prices are, for one adult $", oneAdult[1], "for one child $", oneChild[1], "for one senior $", oneSenior[1], "for a family ticket $",familyTicket[1], "for a group of six people or more(price per ticket) $",sixPeoplePlus[1])
      break;
    else:
      print("your answer needs to be either '1' or '2'")
  except ValueError:
    print("provide this value in integer form")
  continue

extraAttractions = input("do you want to know about extra attractions, yes or no? ")
if extraAttractions == "yes":
  def attraction():
    attractionDay = int(input("Have you booked a ticket for 1 or 2 days"))
    if attractionDay == 1:
      print("The extra attractions are lion feeding for $",lionFeeding,", penguin feeding for $",penguinFeeding,"and the evening barbeque for $",eveningBarbeque)
    elif attractionDay == 2:
      print("The extra attractions are lion feeding for $",lionFeeding,"and penguin feeding for $",penguinFeeding)
    else:
      print("you must input either '1' or '2'")

    return attraction()
if extraAttractions == "no":
  print("okay, that's fine")

A: For your error, you define a function, but you don't run it. Fix it like so:
extraAttractions = input('... ')
if extraAttractions == "yes":
  def attraction():
    # Code
  attraction()

More importantly though, I don't think you understand how functions work. Take a look at this link for help. Your function returns itself, which looks like something that shouldn't happen (thanks to 9769953 for commenting this). It's perfectly fine not to have a return statement for your function, like so:
def attraction():
    attractionDay = int(input("Have you booked a ticket for 1 or 2 days"))
    if attractionDay == 1:
      print(f"The extra attractions are lion feeding for {lionFeeding}, penguin feeding for {penguinFeeding}, and the evening barbeque for {eveningBarbeque}")
    elif attractionDay == 2:
      print(f"The extra attractions are lion feeding for {lionFeeding}, and penguin feeding for {penguinFeeding}")
    else:
      print("You must input either '1' or '2'")

For tidying up your code, it doesn't look like there's too much to do: most of your code is print statements. If you wanted, you could make a list of everything you print, but I don't recommend doing this. (Example below):
list_statements = [
    'thing to print number 1',
    'thing to print number 2',
    'thing to print number {}'
]
print(list_statements[0])
# code
print(list_statements[1])
# code
print(list_statements[2].format('3'))

This is just a way to clean up your print statements, you can use .format() for the variables as shown. Again, I don't recommend this, since it's messy and hard to edit.
If you want code cleanup, you should consider removing the def attraction() function, and just pasting the code into the if block, like so:
extraAttractions = input("do you want to know about extra attractions, yes or no? ")
if extraAttractions == "yes":
    attractionDay = int(input("Have you booked a ticket for 1 or 2 days"))
    if attractionDay == 1:
      print("The extra attractions are lion feeding for $",lionFeeding,", penguin feeding for $",penguinFeeding,"and the evening barbeque for $",eveningBarbeque)
    elif attractionDay == 2:
      print("The extra attractions are lion feeding for $",lionFeeding,"and penguin feeding for $",penguinFeeding)
    else:
      print("you must input either '1' or '2'")

You could also reformat your try-except block, but it'd just make the indentation cleaner, it wouldn't change the code length much.


text:
Q: How do I simulate location for xctest I'm trying to write some unit tests (using xctest) that verify that my Google Maps mapView is centered on my "current location".
- (void) testMapCentersOnMyLocation {
  WtHomeController *controller = [[WtHomeController alloc] init];
  [controller viewDidLoad];

  //Simulator's location is stubbed to be in San Francisco, at this lat/lon
  CLLocationDegrees expectedLatitude = 37.787359f;
  CLLocationDegrees expectedLongitude = -122.408227f;

  // FIXME this loop runs forever - location isn't being updated in simulator.
  while(controller.firstLocationUpdate == NO) {
    NSLog(@"Waiting on location...");
    NSLog(@"my location is: %f, %f", controller.mapView.myLocation.coordinate.latitude, controller.mapView.myLocation.coordinate.longitude);
  }

  CLLocationCoordinate2D mapCenter = [controller.mapView.camera target];
  XCTAssertEqualWithAccuracy(mapCenter.latitude, expectedLatitude, 0.00001f);
  XCTAssertEqualWithAccuracy(mapCenter.longitude, expectedLongitude, 0.00001f);

}

Here are the relevant methods from the controller that is allocating the mapView
@interface WtHomeController ()

@property(nonatomic, strong) GMSMapView *mapView;
@property(nonatomic) BOOL firstLocationUpdate;

@end

@implementation WtHomeController

- (void)viewDidLoad {
  [super viewDidLoad];

  //Initialize map pane on Los Angeles lat/lon
  CLLocationDegrees latitude = WtLosAngelesLatitude;
  CLLocationDegrees longitude = WtLosAngelesLongitude;

  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:latitude
                                                          longitude:longitude
                                                               zoom:6];

  self.mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  self.mapView.myLocationEnabled = YES;

  // Listen to the myLocation property of GMSMapView.
  [self.mapView addObserver:self
                 forKeyPath:@"myLocation"
                    options:NSKeyValueObservingOptionNew
                    context:NULL];

  self.view = self.mapView;
}

- (void)dealloc {
  [self.mapView removeObserver:self
                    forKeyPath:@"myLocation"
                       context:NULL];
}

#pragma mark - KVO updates

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {

  DDLogDebug(@"my location is: %f, %f", self.mapView.myLocation.coordinate.latitude, self.mapView.myLocation.coordinate.longitude);

  if( [keyPath isEqualToString:@"myLocation"] ) {
    if (!self.firstLocationUpdate) {
      // If the first location update has not yet been recieved, then jump to that
      // location.
      self.firstLocationUpdate = YES;
      CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey];
      self.mapView.camera = [GMSCameraPosition cameraWithTarget:location.coordinate
                                                       zoom:14];
    }
  }
}

Here's what I've figured out so far: I can simulate location when I build my app by editing the scheme preferences in Xcode.

Then, when I build the app from xcode, I can see in the simulator that my location get's updated to "San Francisco". Here's the output from the log when I build and run on the simulator:
2014-04-02 17:28:09.253 DEBUG WtHomeController: observeValueForKeyPath:ofObject:change:context: 109 - my location is: 37.787359, -122.408227

Cool. But when running the unit tests, my location never gets updated.
Output from the test log is:
2014-04-02 17:02:41.919 wetap[71081:60b] Waiting on location...
2014-04-02 17:02:41.919 wetap[71081:60b] my location is: 0.000000, 0.000000
2014-04-02 17:02:41.919 wetap[71081:60b] Waiting on location...
2014-04-02 17:02:41.920 wetap[71081:60b] my location is: 0.000000, 0.000000
2014-04-02 17:02:41.920 wetap[71081:60b] Waiting on location...
2014-04-02 17:02:41.921 wetap[71081:60b] my location is: 0.000000, 0.000000
2014-04-02 17:02:41.921 wetap[71081:60b] Waiting on location...
2014-04-02 17:02:41.921 wetap[71081:60b] my location is: 0.000000, 0.000000
...to infinity

How do I simulate the location for my unit tests?
Edited my test per @Paulw11's suggestion:
  WtAppDelegate *appdelegate = (WtAppDelegate *)[UIApplication sharedApplication].delegate;
  CLLocationManager *locationManager = appdelegate.locationManager;
  [locationManager startUpdatingLocation];

  while(controller.firstLocationUpdate == NO) {
    NSLog(@"Waiting on location...");
    NSLog(@"my location is: %f, %f", controller.mapView.myLocation.coordinate.latitude, controller.mapView.myLocation.coordinate.longitude);
    NSLog(@"Location manager think's we're at: %@",  [locationManager location]);
  }

And the new log output from running that test:
2014-04-02 18:08:56.394 wetap[73922:60b] Location manager think's we're at: (null)
2014-04-02 18:08:56.394 wetap[73922:60b] Waiting on location...
2014-04-02 18:08:56.394 wetap[73922:60b] my location is: 0.000000, 0.000000
2014-04-02 18:08:56.395 wetap[73922:60b] Location manager think's we're at: (null)
2014-04-02 18:08:56.396 wetap[73922:60b] Waiting on location...
2014-04-02 18:08:56.396 wetap[73922:60b] my location is: 0.000000, 0.000000
2014-04-02 18:08:56.397 wetap[73922:60b] Location manager think's we're at: (null)

A: The Google Map View is just a view, it doesn't automatically connect to the location tracking in iOS and update itself.  You need to allocate a CLLocationManager and track your location using it's delegate methods.  You can then update the myLocation property as in this answer -  GMSMapView myLocation not giving actual location
I don't think you have set the delegate method for your CLLocationManager - it is the didUpdateLocations delegate method that will transfer the location to the Google Map View
in viewDidLoad
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate=self;
[self.locationManager startUpdatingLocation];

the implement the delegate method (note that the method referred to in the previous answer, didUpdateLocation has been deprecated and replaced with the didUpdateLocations method
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *latestLocation=(CLLocation *)[locations lastObject];

    [self.mapView animateToLocation:latestLocation.coordinate]  <== this is the important bit - it transfers the location from CLLocationManager to the GM view

}

Refer to the CLLocationManager reference


text:
Q: Using ubuntu and windows 10 natively on a machine without dualbootinb I recently installed ubuntu 17.04 on my machine but still had to use windows from time to time , so my idea was using a vm.
It turned out that using a vm was very slow and the performance was not enough for me , so i think my only option now is running windows on my machine natively.
I don't want to dualboot since i tried that before and i saw that windows doesn't play well with other bootloaders on the same machine.
I had an idea of buying another hard drive and installing windows on it and simply swapping the drives when needing to use windows (i have a laptop and the hard drive slot can be easily accessed).
I don't see any possible issued with doing that and just wanted to get an opinion if it will work , or if there is an easier way around.

A: Drive swapping is a viable solution.  However, there is a method I use to dual boot Windows and Linux Mint.  This works with most modern computers that let you select the boot device as the computer posts.  This usually comes up at the same time as the BIOS option.  On my Dell, I would hit F2 to go into BIOS and F12 to select a boot device.  A boot device would be anything configured to boot from in BIOS, such as hard drives, CD/DVD, USB, and network.  I simply disabled my Windows drive by unplugging it to be 100% sure I didnt nuke my Windows drive (although you could disable it in BIOS).  I installed Linux on the other drive and then plugged my Windows drive back in.  Now, I can reboot and hit F12 to select which hard drive I want to boot from.  I dont have to deal with bootloader confusion.  This also allows me to use my Linux drive as a raw drive in VirtualBox.  I can boot my Linux Mint machine from inside Windows when I dont want to reboot.  This also works the other way around.


text:
Q: How to set the path to "context path" for uploaded files using Apache Common fileupload? I'm using Apache common fileupload library  with Netbeans 6.8 + Glassfish.I'm trying to change the current upload path to be in the current context path of the servlet , something like this:
WEB-INF/upload
so I wrote :
File uploadedFile = new File("WEB-INF/upload/"+fileName);
session.setAttribute("path",uploadedFile.getAbsolutePath());
item.write(uploadedFile);

but I noticed that the library saves the uploaded files into glassfish folder , here what I get when I print the absolute path of the uploaded file :
C:\Program Files\sges-v3\glassfish\domains\domain1\WEB-INF\upload\xx.rar

My Question :

*

*How can I force the common fileupload to save the uploaded file in a path relative to the current servlet path , so I don't need to specify the whole path ? is this possible ?

A: The java.io.File acts on the local disk file system and knows absolutely nothing about the context it is running in. You should not expect it to find the "right" location when you pass a relative web path in. It would become relative to the current working directory which is dependent on how you started the environment. You don't want to be dependent on that.
You can use ServletContext#getRealPath() to convert a relative web path to an absolute local disk file system path.
String relativeWebPath = "/WEB-INF/uploads";
String absoluteFilePath = getServletContext().getRealPath(relativeWebPath);
File uploadedFile = new File(absoluteFilePath, FilenameUtils.getName(item.getName()));
// ...

That said, I hope that you're aware that the deploy folder isn't the right location for uploaded files which are supposed to be saved permanently. Everything will get lost when you redeploy the webapp. See also How to write a file to resource/images folder of the app?


text:
Q: Automatically Refresh JmDNS Services in Activity I'm trying to automatically refresh JmDNS services in the background.  Nothing is happening when I try:
@Override
public void onDestroy() {
    try {
        hiNeighborService.unregisterListener(this);
        this.unbindService(this.serviceConnection);

    } catch (Exception ex) {
        Log.e(LOG_TAG, "Exception occur during destroying the app.");
    }

    super.onDestroy();
}

@Override
public void onStart() {
    /*new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                refreshServices();
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }).start();*/

    ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

    // This schedule a runnable task every 2 minutes
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
      public void run() {
        rebindService();
        refreshServices();
      }
    }, 0, 1, TimeUnit.SECONDS);

    super.onStart();
}

@Override
public void onRestart() {
    /*new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                refreshServices();
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }).start();*/
    ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

    // This schedule a runnable task every 2 minutes
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
      public void run() {
        rebindService();
        refreshServices();
      }
    }, 0, 1, TimeUnit.SECONDS);

    super.onRestart();
}

@Override
public void onResume() {
    /*new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                refreshServices();
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }).start();*/

    ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

    // This schedule a runnable task every 2 minutes
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
      public void run() {
        rebindService();
        refreshServices();
      }
    }, 0, 1, TimeUnit.SECONDS);

    super.onResume();
}

This is my resfreshServices() method:
private void refreshServices() {
    Log.i(LOG_TAG, "Refresh available neighbors...");
    final List<Neighbor> activeNeighbors = this.hiNeighborService
            .getActiveNeighbors();
    Log.d(LOG_TAG, activeNeighbors.size() + " active neighbors are found!");

    new Thread(new Runnable() {
        public void run() {
            Log.i(LOG_TAG, "refresh UI...");
            try {

                synchronized (activeNeighborsViewModel) {
                    activeNeighborsViewModel.clear();
                    for (Neighbor neighbor : activeNeighbors) {
                        NeighborViewModel vm = new NeighborViewModel(
                                neighbor);
                        vm.setNeighborUnreadCount(ConnectActivity.this
                                .getUnreadMessageCount(neighbor));
                        if (activeNeighborsViewModel.contains(vm)) {
                            activeNeighborsViewModel.remove(vm);
                        }

                        activeNeighborsViewModel.add(vm);
                    }
                }
                notifyServiceListChanged();

                Log.i(LOG_TAG, "refresh completed!");
            } catch (Exception ex) {
                ex.printStackTrace();
                Log.e(LOG_TAG, ex.toString());
            }
        }
    }).start();
}

Normally that gets call when a button is clicked however I would like it to be automatic.  This code doesn't do anything unless I hit the Resfresh button that call resfreshServices().  I attempted to try it with threads but the activity closes and so does the app.  Any ideas?

A: First a little comment on your code. Why are you implementing the same code three times in three different methods. I assume that you are programming android (loking at your method names). The method onresume is executed every time the activity is started or resumed. See this link for more information on this topic.
Ok, then... Did you already check the docs for more information about the ScheduledExecutorService?
Now for the jmdns issue. The jmDns library has a build in functionality to update the services. you can listen to new services and take the appropriate action when new services are available. I do not think, that repeated polling of the services is the right approach.
Look here for a little tutorial on using jmdns in android.


text:
Q: Excel locking cells with a date and time not working I want to have a sheet were after I enter a truck number it automatically places the date and time in a following cell, that works no problem, but when I try to place a protection on the cells after data has been enter so it cannot be modify it gives me errors, what am I doing wrong?
I have selected the complete sheet and unlock the cells, then I have wrote this code on the visual basic for excel
Private Sub Worksheet_Change(ByVal Target As Range)

ActiveSheet.Unprotect Password:="YourPassword"
Target.Locked = True
ActiveSheet.Protect Password:="YourPassword"

Dim x As Integer
Dim y As Integer
For x = 2 To 1000
For y = 2 To 1000

If Cells(x, 3).Value <> "" And Cells(x, 5).Value = "" Then
Cells(x, 5).Value = Date & " " & Time
Cells(x, 5).NumberFormat = "m/d/yyyy h:mm:ss AM/PM"
End If
Next
Range("B:B").EntireColumn.AutoFit

If Cells(y, 6).Value <> "" And Cells(y, 7).Value = "" Then
Cells(y, 7).Value = Date & " " & Time
Cells(y, 7).NumberFormat = "m/d/yyyy h:mm:ss AM/PM"
End If
Next
Range("B:B").EntireColumn.AutoFit

End Sub

[ ]2]2
this is the code and error

after I apply the code for the protection the time and date doesnt stamp anymore

A: Worksheet Change: Monitoring 2 Non-Adjacent Columns

*

*Adjust the values in the constants section, especially the password ('pw').

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    ScanTrucks Target
End Sub

Private Sub ScanTrucks(ByVal Target As Range)
    On Error GoTo ClearError

    ' Scan In
    Const siCol As String = "C"
    Const diCol As String = "E"
    ' Scan Out
    Const soCol As String = "F"
    Const doCol As String = "G"
    ' Both
    Const fRow As Long = 2
    Const afCol As String = "B"
    Const pw As String = "123"

    Dim ws As Worksheet: Set ws = Target.Worksheet

    Dim scrg As Range
    Dim srg As Range
    Dim sCell As Range
    Dim drg As Range
    Dim dCell As Range

    ' Scan In
    Set scrg = ws.Columns(siCol)
    With scrg
        Set srg = Intersect(Target, _
            .Resize(.Rows.Count - fRow + 1).Offset(fRow - 1))
    End With
    If Not srg Is Nothing Then
        For Each sCell In srg.Cells
            If Len(CStr(sCell.Value)) > 0 Then
                Set dCell = sCell.EntireRow.Columns(diCol)
                If Len(CStr(dCell.Value)) = 0 Then
                    Set drg = RefCombinedRange(drg, dCell)
                End If
            End If
        Next sCell
    End If

    ' Scan Out
    Set srg = Nothing
    With scrg.EntireRow.Columns(soCol)
        Set srg = Intersect(Target, _
            .Resize(.Rows.Count - fRow + 1).Offset(fRow - 1))
    End With
    If Not srg Is Nothing Then
        For Each sCell In srg.Cells
            If Len(CStr(sCell.Value)) > 0 Then
                Set dCell = sCell.EntireRow.Columns(doCol)
                If Len(CStr(dCell.Value)) = 0 Then
                    Set drg = RefCombinedRange(drg, dCell)
                End If
            End If
        Next sCell
    End If

    If drg Is Nothing Then Exit Sub

    ' Unprotect, format, write and protect.

    ws.Unprotect Password:=pw
    Application.EnableEvents = False
    ws.Columns(afCol).AutoFit

    With drg
        .NumberFormat = "m/d/yyyy h:mm:ss AM/PM"
        .Value = Now
        .Locked = True
    End With

SafeExit:
    If Not Application.EnableEvents Then Application.EnableEvents = True
    If Not ws.ProtectionMode Then ws.Protect Password:=pw

    Exit Sub

ClearError:
    Debug.Print "Run-time error '" & Err.Number & "':" & Err.Description
    Resume SafeExit
End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Creates a reference to a range combined from two ranges.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefCombinedRange( _
    ByVal CombinedRange As Range, _
    ByVal AddRange As Range) _
As Range
    If CombinedRange Is Nothing Then
        Set RefCombinedRange = AddRange
    Else
        Set RefCombinedRange = Union(CombinedRange, AddRange)
    End If
End Function


text:
Q: Best language for data transformation (ETL) What is the best end-user language for data transformation (ETL), ideally something that can run in a JVM (with a LGPL like license).
With end-user meaning users who are IT related but might not be experts in OO or like.

A: You can try CloverETL. It is Java based ETL tool. You can either define transformation through its visual designer or handcode directly in XML files that are used to store data about transformations.
It also uses its own transformation language - CTL that is used inside transformation components. You do not need to be expert in OOP to use it.

A: Rust is the best language. In fact, companies can now evolve from ETL to STL or Stream, Transform and Load with a technology like InfinyOn Cloud. InfinyOn Cloud is a fully managed Fluvio service. This solution brief explains how the Financial Services industry is leveraging this tech:
https://www.infinyon.com/resources/real-time-data-trasformation/


text:
Q: Get OS version on OS X I have an old script which I use to run in Ubuntu.
Now, I have a Mac and want to reuse the script.
Does anyone know what would be equivalent of the following commands in Mac OS?
def runCmd(cmd):
    p = subprocess.Popen(cmd,
                         shell=True,
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         close_fds=True)
    result=p.stdout.readlines()
    s=result[0].split()[0]
    return s

def getKernelVer():
    cmd="uname -r| cut --delim=\'.\' -f1-2"
    return runCmd(cmd)

def getUbuntuVer():
    cmd="lsb_release  -a | grep Release | cut -f 2"
    return runCmd(cmd)

Thanks

A: uname -r works identically under Darwin. The kernel version isn't something that most people talk or care about, but it's there. Only gotcha is that cut doesn't support the --delim long option, so, try this instead:
uname -r | cut -d. -f1-2

Kernel versioning is quite different for Darwin than for Linux, though, so the purpose of running cut here is unclear. (In fact, it's not quite clear on Linux either, as the versioning scheme changed significantly with the release 3.0.)
To get the current version of Mac OS (roughly equivalent to the "release" you're getting for Ubuntu), you can use the command:
sw_vers -productVersion

A: You could use the python "platform" module (i've no access to Ubuntu, pls try and post your finding :)

*

*use platform.system() to distinguish between Linux or Darwin

*call platform.release() to get kernel version

*call platform.linux_distribution() or platform.mac_ver() to get vendor specific version number.

On CentOS:
$ python
Python 2.7.5 (default, Jul 23 2013, 17:26:16)
[GCC 4.7.2 20121015 (Red Hat 4.7.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.32-358.18.1.el6.x86_64'
>>> platform.linux_distribution()
('CentOS', '6.4', 'Final')
>>>

On OS X:
$ python
Python 2.7.5 (default, Aug 25 2013, 00:04:04)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform
>>> platform.system()
'Darwin'
>>> platform.release()
'13.0.0'
>>> platform.mac_ver()
('10.9', ('', '', ''), 'x86_64')


text:
Q: How to make an API request from server side? I want to make a request from the Coinmarketcap API. They don't allow to use CORS configuration because security matters, the option is execute that in the browser by routing calls through an own backend service.
People said to me use several serverless options with free tier out there, AWS Lambda, Google Cloud Functions, Azure Functions.
But I don't know how to do that, I'm wondering to use Aws Lambda, what I need to do?
That is my node.js code:

const rp = require('request-promise');
const requestOptions = {
  method: 'GET',
  uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
  qs: {
    'start': '1',
    'limit': '5000',
    'convert': 'USD'
  },
  headers: {
    'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c' //that isn't my real api key
  },
  json: true,
  gzip: true
};

rp(requestOptions).then(response => {
  console.log('API call response:', response);
}).catch((err) => {
  console.log('API call error:', err.message);
});

A: The AWS Lambda function can help you to execute the api and return the response. You will also need probably AWS API Gateway to connect the response from lambda to your api. The code in lambda will look like this:
const rp = require('request-promise');

exports.handler = async (event) => {
  const requestOptions = {
    method: 'GET',
    uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
    qs: {
      'start': '1',
      'limit': '5000',
      'convert': 'USD'
    },
    headers: {
      'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c' //that isn't my real api key
    },
    json: true,
    gzip: true
  };

  const response = rp(requestOptions);
  console.log(response);
  return response;
}

basically pass the input in event object and then you could use like a normal object. Also see - https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html


text:
Q: What is the proper HTTP method for modifying a subordinate of the named resource? I am creating a web client which has the purpose of modifying a set of database tables by adding records to them and removing records from them. It must do so atomically, so both deletion and insertion must be done with a single HTTP request. Clearly, this is a write operation of some sort, but I struggle to identify which method is appropriate.
POST seemed right at first, except that RFC 2616 specifies that a POST request must describe "a new subordinate" of the named resource. That isn't quite what I'm doing here.
PUT can be used to make changes to existing things, so that seemed about right, except that RFC 2616 also specifies that "the URI in a PUT request identifies the entity enclosed with the request [...] and the server MUST NOT attempt to apply the request to some other resource," which rules that method out because my URI does not directly specify the database tables.
PATCH seemed closer - now I am not cheating by only partly overwriting a resource - but RFC 5789 makes it clear that this method, like PUT, must actually modify the resource specified by the URI, not some subordinate resource.
So what method should I be using?
Or, more broadly for the benefit of other users:
For a request to X, you use

*

*POST to create a new subordinate of X,

*PUT to create a new X,

*PATCH to modify X.

But what method should you use if you want to modify a subordinate of X?

A: To start.. not everything has to be REST. If REST is your hammer, everything may look like a nail.
If you really want to conform to REST ideals, PATCH is kind of out of the question. You're only really supposed to transfer state.
So the common 'solution' to this problem is to work outside the resources that you already have, but invent a new resource that represents the 'transaction' you wish to perform. This transaction can contain information about the operations you're doing in sequence, potentially atomically.
This allows you to PUT (or maybe POST) the transaction, and if needed, also GET the current state of the transaction to find out if it was successful.
In most designs this is not really appropriate though, and you should just fall back on POST and define a simple rpc-style action you perform on the parent.

A: RFC 2616 is obsolete. Please read RFC 723* instead, in particular https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.3.

A: First, allow me to correct your understanding of these methods.
POST is all about creating a brand new resource. You send some data to the server, and expect a response back saying where this new resource is created. The expectation would be that if you POST to /things/ the new resource will be stored at /things/theNewThing/. With POST you leave it to the server to decide the name of the resource that was created. Sending multiple identical POST requests results in multiple resources, each their own 'thing' with their own URI (unless the server has some additional logic to detect the duplicates).
PUT is mostly about creating a resource. The first major difference between PUT and POST is that PUT leaves the client in control of the URI. Generally, you don't really want this, but that's getting of the point. The other thing that PUT does, is not modify, if you read the specification carefully, it states that you replace what ever resource is at a URI with a brand new version. This has the appearance of making a modification, but is actually just a brand new resource at the same URI.
PATCH is for, as the name suggest, PATCHing a resource. You send a data to the server describing how to modify a particular resource. Consider a huge resource, PATCH allows you to send just the tiny bit of data that you wish to change, whilst PUT would require you send the entire new version.
Next, consider the resources. You have a set of tables each with many rows, that equates to a set of collections with many resources. Now, your problem is that you want to be able to atomically add resources and remove them at the same time. So you can't just POST then DELETE, as that's clearly not atomic. PATCHing the table how ever can be...
{ "add": [
  { /* a resource */ },
  { /* a resource */ } ],
  "remove" : [ "id one", "id two" ] }

In that one body, we have sent the data to the server to both create two resources and delete two resources in the server. Now, there is a draw back to this, and that is that it's hard to let clients know what is going on. There's no 'proper' way of the client of the two new resources, 204 created is sort of there, but is meant have a header for the URI of the one new resource... but we added two. Sadly, this a problem you are going to face no matter what, HTTP simple isn't designed to handle multiple resources at once.

Transaction Resources
So this is a common solution people propose, and I think it stinks. The basic idea is that you first POST/PUT a blob of data on the server the encodes the transaction you wish to make. You then use another method to 'activate' this transaction.
Well hang on... that's two requests... it sends the same data that you would via PATCH and then you have fudge HTTP even more in order to somehow 'activate' this transaction. And what's more, we have this 'transaction' resource now floating around! What do we even do with that?

A: I know this question has been asked already some time ago, but I thought I should provide some commentary to this myself. This is actually not a real "answer" but a response to thecoshman's answer. Unfortunately, I am unable to comment on his answer which would be the right thing to do, but I don't have enough "reputation" which is a strange (and unnecessary) concept, IMHO.
So, now on to my comment for @thecoshman:
You seem to question the concept of "transactional resources" but in your answer it looks to me that you might have misunderstood the concept of them. In your answer, you describe that you first do a POST with the resource and the associated transaction and then POST another resource to "activate" this transaction. But I believe the concept of transactional resources are somehow different.
Let me give you a simple example:
In a system you have a "customer" resource and his address with customer as the primary (or named) resource and the address being the subordinate address. For this example, let us assume we have a customer with a customerId of 1234. The URI to reach this customer would be /api/customer/1234. So, how would you now just update the customer's address without having to update the entire customer resource? You could define a "transaction resource" called "updateCustomerAddress". With that you would then POST the updated customer address data (JSON or even XML) to the following URI: POST /api/customer/1234/updateCustomerAddress. The service would then create this new transactional resource to be applied to the customer with customerId=1234. Once the transaction resource has been created, the call would return with 201, although the actual change may not have been applied to the customer resource. So a subsequent GET /api/customer/1234 may return the old address, or already the new and updated address. This supports well an asynchronous model for updating subordinate resources, or even named resources.
And what would we do with the created transactional resource? It would be completely opaque to the client and discarded as soon as the transaction has been completed. So the call may actually not return a URI of the transactional resource since it may have disappeared already by the time a client would try to access it.
As you can see, transactional resources should not require two HTTP calls to a service and can be done in just one.


text:
Q: WordPress mouse over select option I'm working on a drop down list that has a mouse over function with content from the datbase.
I'm stuck on the 'load content from the database' part
Here is a Fiddle of where I currently am
http://jsfiddle.net/TJ6Fz/22/
$(document).ready(function(){

$('option').hover(function(){
    var optionVal = $(this).text();
   $('#display').html(optionVal)

})

})

I found this Fiddle and does exactly what I want.
I'm not a star in JQuery. So if anyone would be such a gentleman to provide me with a jquery solution where I could get values from my database I would me thrilled,

A: Suppose if you are looking for the solution like, you need to take the values from database depends on the change happen in the select box. If you are looking for something like this you need to use ajax call or json for accessing the php file that can take the data from your database. And push in to the html.

A: In order to get information from your WordPress database to a script you'll need to use AJAX to pass that information from PHP to the JavaScript.
WordPress and AJAX in the WordPress Codex: http://codex.wordpress.org/AJAX
WordPress AJAX template I use: https://gist.github.com/theantichris/6600226


text:
Q: Embedded picture not showing in gmail body when snding mail using vba I am trying to send a mail using gmail service(not outlook) with a picture in it's body as embedded picture using vba.
I have added Microsoft CDO Windows 2000 Library

Option Explicit

Sub SendEmailUsingGmail()
    Dim NewMail As Object
    Dim mailConfig As Object
    Dim fields As Variant
    Dim msConfigURL As String
    Dim rng As Range
   Set rng = Nothing
    On Error Resume Next

    Set rng = Selection.SpecialCells(xlCellTypeVisible)

    On Error GoTo Err:

    'late binding
    Set NewMail = CreateObject("CDO.Message")
    Set mailConfig = CreateObject("CDO.Configuration")

    ' load all default configurations
    mailConfig.Load -1

    Set fields = mailConfig.fields

    'Set All Email Properties
    With NewMail
        .Sender = ""
        .From = "Sourav Bhattacharya"
        .To = ""
        .CC = ""
        .BCC = ""
        .Subject = "Demo Spreadsheet Attached"
        .Textbody = "Let me know if you have questions about the attached spreadsheet!"
        .Addattachment "C:\Users\allso\Desktop\new vba projects\temp.jpg"
        .HTMLBody = .Textbody & "
CPS Daily progress Report of Nov 2020
" & _
                ""

    End With

    msConfigURL = "http://schemas.microsoft.com/cdo/configuration"

    With fields
        .Item(msConfigURL & "/smtpusessl") = True             'Enable SSL Authentication
        .Item(msConfigURL & "/smtpauthenticate") = 1          'SMTP authentication Enabled
        .Item(msConfigURL & "/smtpserver") = "smtp.gmail.com" 'Set the SMTP server details
        .Item(msConfigURL & "/smtpserverport") = 465          'Set the SMTP port Details
        .Item(msConfigURL & "/sendusing") = 2                 'Send using default setting
        .Item(msConfigURL & "/sendusername") = "" 'Your gmail address
        .Item(msConfigURL & "/sendpassword") = "" 'Your password or App Password
        .Update                                               'Update the configuration fields
    End With

    NewMail.Configuration = mailConfig
    NewMail.Send

    MsgBox "Your email has been sent", vbInformation

Exit_Err:
    'Release object memory
    Set NewMail = Nothing
    Set mailConfig = Nothing
    End

Err:
    Select Case Err.Number
    Case -2147220973  'Could be because of Internet Connection
        MsgBox "Check your internet connection." & vbNewLine & Err.Number & ": " & Err.Description
    Case -2147220975  'Incorrect credentials User ID or password
        MsgBox "Check your login credentials and try again." & vbNewLine & Err.Number & ": " & Err.Description
    Case Else   'Report other errors
        MsgBox "Error encountered while sending email." & vbNewLine & Err.Number & ": " & Err.Description
    End Select

    Resume Exit_Err

End Sub

I am able to send the mail and the image gets attached to the mail just fine
However in the mail body it shows blank instead of the picture
I tried searching many places,however could not find the solution
Can Someone please help
Thank You
Sourav Bhattacharya


text:
Q: wavefronts and wave I am confused over this one...my textbook says that wave speed is the speed with which the wavefront travels which, to me, seems like they are the same thing but their definition looks different, to me.
Wavefront: A wavefront is a surface where all of the particles are vibrating in the same phase.
Wave: The disturbance which transfers energy through matter in space.
Does this mean that wavelets in wavefronts are the matter which transfer energy in space and hence cause wave disturbances according to these definitions? Can somebody help me with how should I relate these two definitions.
P.S-All definitions are from my school textbook.

A: A wavefront is a surface where some particular condition holds. It is a locus of points.
The wave is the whole phenomenon of a propagating oscillation.
In theory the wave extends through all space in three dimensions. A wavefront is only a surface through the wave (typically a surface that is perpendicular to the direction the energy is travelling). You could define an infinite number of wavefronts associated with any particular wave.

A: The textbook is giving you a clumsy definition of what physicists call phase velocity vs group velocity.
Phase velocity: This is the velocity of the disturbance, e.g. the velocity of a crest of the wave. In your case this is the "wave speed", because it is the velocity of the wavefront.
Group velocity: This is the velocity of the particules of matter. This velocity transports matter, it is the speed of the energy transfer.


text:
Q: Android Hijri Calendar Arabic format not working correctly? I want to convert the Gregorian calendar into Hijri calendar in Arabic letters.
Could please guide me?
void HijriCalender() {
    UmmalquraCalendar now = new UmmalquraCalendar();

    HijriDatePickerDialog dpd = HijriDatePickerDialog.newInstance(
        Volunteer.this,
        now.get(UmmalquraCalendar.YEAR),
        now.get(UmmalquraCalendar.MONTH),
        now.get(UmmalquraCalendar.DAY_OF_MONTH)
    );

    locale = new Locale("ar", "AE");

    dpd.setLocale(locale);
    dpd.show(getFragmentManager(), "HijriDatePickerDialog");
}

enter image description here
This is My Current output


text:
Q: External disk drive no longer visible when using Parallels My MacMini Late 2012 has a 1Tb external USB drive, which I use as the main data store (the internal 256Gb SSD being too small).
I have been running parallels on this Mac for years and both native Mac drives were visible... I think it listed each twice in Windows Explorer for some reason.
Just today I really need to access large (several GB) files but now the external drive is not visible (of course). I found this but it doesn't help: http://kb.parallels.com/en/118147
MacOS 10.10.5, Parallels 13.

A: Take your drive to another computer and Cloud your files.


text:
Q: Count of a count- PHP MYSQL My table is as follows:
 guid version

 A1   lol
 A2   roflmao
 A1   lol
 A1   lol
 A2   lol
 A3   roflmao
 A3   roflmao
 A3   roflmao
 A3   roflmao
 A3   roflmao
 A3   roflmao
 A4   roflmao
 A4   roflmao
 A5   lol
 A5   lol

I want to count then number of times roflmao appear under 3 times (per GUID) in total.
So far I've the following but it's not outputting anything:
$sql="select guid,version, count(*) as `count`
from mytable WHERE version = 'roflmao' group by guid having `count` < 3'";

if ($result=mysqli_query($con,$sql))
{

 // Return the number of rows in result set

 $rowcount=mysqli_num_rows($result);
 printf($rowcount);

 // Free result set

 mysqli_free_result($result);
 }

A: Try this:
SELECT COUNT(*) FROM (
    SELECT guid
    FROM YourTable
    WHERE version = 'roflmao'
    GROUP BY guid
    HAVING COUNT(*) <3) t

This first select all the guids that has 'roflmao' appearing less them 3 times, and then counts the them.


text:
Q: Why does Italian word sì lose the ì in TextView? In the textview, all I see is "s"  when I should have "sì"
My values-it/strings.xml:
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <string name="msg_yes">sì</string>

And my code:
    txtMsg.setText(R.string.msg_yes);

A: I just tested on my Samsung Nexus S running Jellybean by copying/pasting and I found that both in the preview pane and on my device the character was displayed correctly. This may have to do with OS version, phone, font, theme, or some other factor...


text:
Q: How to update user profile picture in QuickBlox using php api? How to update user profile picture in Quickblox using php codeigntier ?
Documentation found at
http://quickblox.com/developers/Users

A: after found rest api i have found the solution for how to upload profile picture to quickblox user.
there are three 3 steps for uploading content as per quickblox rest api
First you generate token from the quickblox and then perform these 3 steps

*

*Create file

https://quickblox.com/developers/Content#Create_a_file
  $strFilename = '2.jpeg';
  $post_body = http_build_query(array(
        'blob[content_type]' => 'image/jpeg',
        'blob[name]' =>$strFilename,
    ));
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, QB_API_ENDPOINT.'blobs.json');
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_body);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Accept: application/json',
        'Content-Type: application/x-www-form-urlencoded',
        'QuickBlox-REST-API-Version: 0.1.0',
        'QB-Token: ' . $token
    ));
    $response = curl_exec($curl);
    $error = curl_error($curl);

    if ($response) {
            return $response;
    } else {
            return false;
    }
    curl_close($curl);

After this curl call you have got the response and in response got the response like this
[blob] => Array
    (
        [id] => 7178102
        [uid] => f9cc9d7938c4468f8bdccdcb68fb5d8c00
        [content_type] => image/jpeg
        [name] => 2.jpeg
        [size] =>
        [created_at] => 2017-02-07T10:35:38Z
        [updated_at] => 2017-02-07T10:35:38Z
        [ref_count] => 1
        [blob_status] =>
        [set_completed_at] =>
        [public] => 1
        [last_read_access_ts] =>
        [lifetime] => 8600
        [account_id] => 56721
        [app_id] =>
        [blob_object_access] => Array
            (
                [id] => 7178102
                [blob_id] => 7178102
                [expires] => 2017-02-07T11:35:38Z
                [object_access_type] => Write
                [params] => https://qbprod.s3.amazonaws.com/?Content-Type=image%2Fjpeg&Expires=Tue%2C%2007%20Feb%202017%2011%3A35%3A38%20GMT&acl=public-read&key=f9cc9d7938c4468f8bdccdcb68fb5d8c00&policy=eyJleHBpcmF0aW9uIjoiMjAxNy0wMi0wN1QxMTozNTozOFoiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJxYnByb2QifSx7ImFjbCI6InB1YmxpYy1yZWFkIn0seyJDb250ZW50LVR5cGUiOiJpbWFnZS9qcGVnIn0seyJzdWNjZXNzX2FjdGlvbl9zdGF0dXMiOiIyMDEifSx7IkV4cGlyZXMiOiJUdWUsIDA3IEZlYiAyMDE3IDExOjM1OjM4IEdNVCJ9LHsia2V5IjoiZjljYzlkNzkzOGM0NDY4ZjhiZGNjZGNiNjhmYjVkOGMwMCJ9LHsieC1hbXotY3JlZGVudGlhbCI6IkFLSUFJWTdLRk0yM1hHWEo3UjdBLzIwMTcwMjA3L3VzLWVhc3QtMS9zMy9hd3M0X3JlcXVlc3QifSx7IngtYW16LWFsZ29yaXRobSI6IkFXUzQtSE1BQy1TSEEyNTYifSx7IngtYW16LWRhdGUiOiIyMDE3MDIwN1QxMDM1MzhaIn1dfQ%3D%3D&success_action_status=201&x-amz-algorithm=AWS4-HMAC-SHA256&x-amz-credential=AKIAIY7KFM23XGXJ7R7A%2F20170207%2Fus-east-1%2Fs3%2Faws4_request&x-amz-date=20170207T103538Z&x-amz-signature=5e236c3da60a922951c8ab6281ae82af3a88e37c15d8630ad6ff590610a87fd8
            )

    )

*Upload file

so you have to used the params url parameters and make another call for uploading file
$strFilename = '2.jpeg';
    $url = 'https://qbprod.s3.amazonaws.com/';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array(
        'Content-Type' => $arr['Content-Type'],
        'Expires'=>$arr['Expires'],
        'acl'=>$arr['acl'],
        'key'=>$arr['key'],
        'policy'=>$arr['policy'],
        'success_action_status'=>$arr['success_action_status'],
        'x-amz-algorithm'=>$arr['x-amz-algorithm'],
        'x-amz-credential'=>$arr['x-amz-credential'],
        'x-amz-date'=>$arr['x-amz-date'],
        'x-amz-signature'=>$arr['x-amz-signature'],
        'file' => new CurlFile('2.jpeg', $arr['Content-Type'], $strFilename)
    ));
    $response = curl_exec($ch);
    if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 204) {
        echo 'Success!';
    } else {
        $error = substr($response, strpos($response, '<Code>') + 6);
        echo substr($error, 0, strpos($error, '</Code>'));
    }
    return $response;

so by using this code your content file will be uploaded and you got the location of the file and used as profile picture or etc .

*Declare file
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://api.quickblox.com/blobs/" . $strId . "/complete.xml");  // strId is blod id return by 1 step
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "blob[size]=10000"); //your file size
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

 $headers = array();
 $headers[] = "Quickblox-Rest-Api-Version: 0.1.0";
  $headers[] = "Qb-Token: " . $token;
 $headers[] = "Content-Type: application/x-www-form-urlencoded";
 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

 $result = curl_exec($ch);
 if (curl_errno($ch)) {
     echo 'Error:' . curl_error($ch);
 }
  curl_close($ch);
  return $result;

Please let me know the any issue regards the same.
Thanks


text:
Q: Is int 9h called the moment a new scancode is available at port 60h? Int 9h is always called immediately after a new make/break code is made available at port 60h, right? If so, I intend to chain onto it so that my input code can react as soon as a new scancode is ready.
This webpage says, "When a key is pressed the keyboard sends the corresponding keyboard scancode to the keyboard controller, and the keyboard controller translates that and interrupts the CPU."
This pdf talks about in a little more detail (at the top of page 1155).
"When the scan code arrives at the PC, a second microcontroller chip receives the scan code, does a conversion on the scan code, makes the scan code available at I/O port 60h, and then interrupts the processor and leaves it up to the keyboard ISR to fetch the scan code from the I/O port."
It's talking about the int 9h ISR, right?
Here's my input code. (It's just a procedure in my main program at the moment, it's not associated with int 9h yet.) It takes a make code from port 60h, and makes it available globally in BP. It only accepts a break code if it corresponds with the previously collected make code.
HANDLE_INPUT PROC

;CLEARS THE KEYBOARD TYPEHEAD BUFFER AND COLLECTS A SCANCODE

;ALTERS BP

    push ax
    push bx
    push es

    ;Clear the type ahead buffer to prevent the annoying PC speaker beep.

    mov ax, 40h
    mov es, ax                  ;access keyboard data area via segment 40h
    mov WORD PTR es:[1ah], 1eh  ;set the kbd buff head to start of buff
    mov WORD PTR es:[1ch], 1eh  ;set the kbd buff tail to same as buff head
                                ;the keyboard typehead buffer is now cleared

    ;Collect scancode from port 60h.
    ;Always accept a make code.
    ;Only accept a break code if it corresponds with collected make code.

    xor ah, ah
    in al, 60h                  ;al -> scancode
    test al, 80h                ;Is a break code in al?
    jz ACCEPT_KEY               ;If not, accept it.
                                ;If so, check to see if it's the break code
                                ;that corresponds with the make code in bp.
    mov bx, bp                  ;bx -> make code
    or bl, 80h                  ;change make code into it's break code
    cmp bl, al                  ;Do the new and old break codes match?
    je ACCEPT_KEY               ;If so, accept the break code.
    pop es                      ;If not, bp retains make code.
    pop bx
    pop ax
    ret

ACCEPT_KEY:
    mov bp, ax                  ;bp -> scancode, accessible globally

    pop es
    pop bx
    pop ax
    ret

HANDLE_INPUT ENDP

The major flaw with this code is that make codes can appear and disappear from port 60h while the rest of my program is still executing. This is disastrous when a new key is pressed a fraction of a second before lifting my finger from the previous key. This leaves the break code that corresponds with the last detected make code waiting at port 60h, so the break code is accepted even though a new make code was available.
My hope is that I won't miss those split-second make codes if I chain to int 9h.
And of course, the code will need to be modified before being chained to the interrupt. It's probably best to make the scancode available via a memory variable rather than BP among other things.


text:
Q: CakePHP 2.x How to call a helper in a foreach in a View? Here's my situation put into generalized terms:
CakePHP 2.x
I have a Model called SalesLog that holds user_id, sale_id, action, and description.
The SalesLogs index shows the list of logs (Offers some filters).
The View code currently runs an if statement to decide which label class to use when rendering the actionvalue.
But, this kind of rendering happens in many places throughout the app. Each time, whatever View it is runs its own if statement.
I am trying to take this decision away from the Views and put it into one centralized place, so that whenever any View needs to render action, they can just call on this place and get the answer.
I came across CakePHP 2.x Helpers and have successfully created my ActionLabelHelper.php.
The problem now is that the index View lists the logs with a foreach statement and when I call the method in the foreach, it says I can't do that to a non-object.
// Just a shortened example here:
<?php foreach($SalesLogs as $sl) { ?>

           <?= $sl['SalesLog']['user_id']; ?>
           <?= $sl->ActionLabel->actionLabel($sl['SalesLog']['action']); ?>

<?php } ?>

If I call it like this (Based on what the documentation shows):
<?= $this->ActionLabel->actionLabel($sl['SalesLog']['action']); ?>
The View shows the list with all of the right actions, but they all get labeled based on whatever the first log's action was.
Any ideas on how to adjust the call and/or places where this method should be in order for this to work?
I also work with Rails, which made me want to create a partial for action, but it seemed silly to have a partial for one field and it doesn't look like CakePHP works with those as naturally as Rails does.
What do you guys have for me?
Helper Code:
App::uses('AppHelper', 'View/Helper');

class ActionLabelHelper extends AppHelper {

public function actionLabel($action)
{
  switch ($action) {
    case 'inserted':
        $type = 'primary';
    case 'removed':
        $type = 'danger';
    case 'changed':
        $type = 'warning';
    default:
        $type = 'warning';
    }
    return "" . $action . "";
    }
}

A: You are right, calling the Helper function like this, since the Helper is a property of the View – not the Model:
<?= $this->ActionLabel->actionLabel($sl['SalesLog']['action']); ?>

If this does not output the expected result, I would recommend to debug($action); inside the actionLabel method to see if the right stuff goes in, in the first place.


text:
Q: Programmatically scroll/move to an item in a .net asp:listview control I have a web page that has an asp:ListView and I am trying to figure out how to programmatically scroll to a certain item.  Here is my aspx markup:
<asp:ListView ID="lvGlossary" runat="server" DataSourceID="SqlDataSource1" OnItemDataBound="lvGlossary_ItemDataBound">
    <LayoutTemplate>

Glossary

    </LayoutTemplate>
    <ItemTemplate>

                <asp:Label ID="lbWord" runat="server" Text='<%# Bind("Word") %>' />:

                <asp:Label ID="lbDefinition" runat="server" Text='<%# Bind("Definition") %>' />

    </ItemTemplate>
    <AlternatingItemTemplate>

                <asp:Label ID="lbWord" runat="server" Text='<%# Bind("Word") %>' />:

                <asp:Label ID="lbDefinition" runat="server" Text='<%# Bind("Definition") %>' />

    </AlternatingItemTemplate>
</asp:ListView>

In my c# code behind I am populating a text box with text and when the user selects a word I want to automatically scroll to the word in the listview so it is visible.  It most likely needs to be done client side, so I think I need some javascript to do this.  Can anyone point me to an example of how to do this?
Any help is appreciated!!
Thank you

A: You could use an element's scrollIntoView javascript method:
document.getElementById('id').scrollIntoView(true);


text:
Q: Prove that $6^{\sqrt n} = O({n \choose n/2})$
Prove that $6^{\sqrt n} = O({n \choose n/2})$

I was able to show that prove that $6^{\sqrt n} = O({n \choose n/2})$ with defining $ n=2k$ and  $ a_k= \frac {k!^26^\sqrt k} {2k!} $ and then show that $\frac {a_{k+1}} {a_k}\rightarrow\frac1 4 \Rightarrow a_k\rightarrow0$  .
I want to see other ways of proving that.
Thanks

A: Presumably $n$ is supposed to be even.  Then ${n \choose {n/2}} 2^{-n}$ is the probability $p(n/2)$ of getting exactly $n/2$ heads when tossing $n$ fair coins.
Since the distribution of the number of heads is unimodal with mode $n/2$,
$p(n/2) > p(k)$ for all other $k$.  In particular, since there are just $n+1$
possibilities for the number of heads,
$p(n/2) > 1/(n+1)$, i.e. ${n \choose {n/2}} > 2^n/(n+1)$.  Can you go on from there?

A: $$\frac{(n!)^26^{\sqrt{n}}}{(2n)!} = \frac{1\cdot2\cdots(n-1)\cdot n \cdot 6^{\sqrt{n}}}{(n+1)\cdot (n+2) \cdots (2n-1)\cdot 2n} \leq (\tfrac{1}{2})^n6^{\sqrt{n}} \leq (\tfrac{1}{2})^{4\sqrt{n}}6^{\sqrt{n}} \leq (\tfrac{6}{16})^{\sqrt{n}}\rightarrow 0.$$
The first inequality follows since $\frac{1}{n+1},\frac{2}{n+2},\ldots,\frac{n}{2n} \leq \frac{1}{2}$, and the second inequality follows since $n\geq4\sqrt{n}$ (which holds for every $n\geq 16$).


text:
Q: Calling a SOAP web service in a different domain using jQuery ajax? I am implementing a web page purely with javaScript/jQuery (SSL enabled) which is to consume different services available from different domains.
I want to integrate a SOAP service which is not secured (with http) using jQuery ajax method as the need not to be reloaded.
I am getting security issue as well as cross domain control issue while trying this out.
Can you please suggest a better approach for the purpose as I couldn't find a proper way to do this anywhere?
Thanks in Advance,
idsTect


text:
Q: Type casting from an Object I have some code in Java as follows:
private Object addVertex(String label, int posX, int posY) {
    Vertex newVertex = new Vertex();
    this.getModel().beginUpdate();
    try {
        newVertex = insertVertex(parent, null, label, posX, posY, 80, 30);
    }
    finally {
        this.getModel().endUpdate();
    }
    return newVertex;
}

That code wont work because of a type mismatch, insertVertex will return an Object, but I get a type mismatch since it can't convert from Object to Vertex (which is an object I created).
Firstly, how come that can't work, since the object Vertex inherits Object by default surely you should be able to do that.
Also, if I try and type cast the Object to a Vertex as follows
newVertex = (Vertex) insertVertex(parent, null, label, posX, posY, 80, 30);

I get an error saying I can't make that conversion.

A: Vertex inherits from Object, but not the other way round. Basically you're trying to do:
Object tmp = insertVertex(...);
newVertex = tmp;

You can't assign an Object reference to newVertex because the latter is of type Vertex.
Now, with your cast it should be okay, so long as insertVertex is genuinely returning a Vertex at execution time. Please give details of exactly what error message you're getting.

A: Try to use
Object insertResult = insertVertex(parent, null, label, posX, posY, 80, 30);
if(insertResult instanceof Vertex){
   newVertex = (Vertex)insertResult;
}

If you get the default implementation the returned type is not a Vertex object.
The insertVertex method has to return an Object which extends from Vertex!

A: You should be able to cast the result of insertVertex to whatever you want. It may fail at runtime, but if you know that it will always be a Vertex, then it should not fail. As Markus suggests, you can use instanceof to test that.
As an aside, the code looks strange in the you create a new Vertex and assign it to the newVertex variable, but then don't pass that reference anywhere?

A: You cannot convert Object into an instance of Vertex, because Object is a superclass of Vertex, not the other way around.
Can you modify InsertVertex to return a Vertex object instead of an Object? There's really no reason not to. Otherwise, you will have to manually cast the Object to the Vertex object through a function.

A: You can't assign a Fruit to a Banana. The Banana is more specific than a Fruit, it's a subclass of Fruit. You can do the opposite, Fruit f = new Banana();
This is what is happening here. If your insertVertex returns an Object it can only be assigned to another Object. If you cast it to Vertex and you get an error, then your insertVertex method must be declaring another type of Object that is not a subclass of Vertex.

A: Well for the definition of the function looks that what you want is to return Object, so probably you dont need to cast to Vertex and just define newVertex as an Object. However it looks that in any case you will need to do the casting in another function. It sounds to me that the cast should work and if not, please send the exceptions that have been generating.


text:
Q: Passing SQL results from controller to chart.js Situation
I would like to pass the count of X from my SQL database from my controller to my view where a chart picks up this data and renders it.
What I have done so far
So far I have the controller code. which gets the count from the table and I am trying to pass this figure back to the chart.
public ActionResult currentPopulation()
{
    var dests = db.personal_info.Count();
   // return Json(dests, JsonRequestBehavior.AllowGet);
    return Content(JsonConvert.SerializeObject(dests), "application/json");
}

I also have the chart (code below) from the view
<script>

        var barChartData = {
                    url: '/Home/currentPopulation',//Local
                  type: "GET",
                 dataType: "JSON",

            labels: ["A", "B", "C"],
            datasets: [

            {
             //   url: '/Home/currentPopulation',//Local
               //  type: "GET",
               //  dataType: "JSON",

                fillColor: "#26B99A", //rgba(220,220,220,0.5)
                strokeColor: "#26B99A", //rgba(220,220,220,0.8)
                highlightFill: "#36CAAB", //rgba(220,220,220,0.75)
                highlightStroke: "#36CAAB", //rgba(220,220,220,1)
                data: [51, 30, 40], //this is the hard coded values which the chart loads
                                    //
            },

            ],
        }

        $(document).ready(function () {

  //  new Chart($("#canvas_bar").get(0).getContext("2d")).Bar()

new Chart($("#canvas_bar").get(0).getContext("2d")).Bar(barChartData, {
tooltipFillColor: "rgba(51, 51, 51, 0.55)",
responsive: true,
barDatasetSpacing: 6,
barValueSpacing: 5
});

});

</script>

Problem
The problem I have is that, I cannot replace the [51,30,40] for the A,B,C values
which is supposed to come from my controller. I am a bit confused as my action "currentPopulation" is not getting called, and i cannot move the link cause according to the code, the data is picked up from barChartData and assign when the new chart is called.
new Chart($("#canvas_bar").get(0).getContext("2d")).Bar(barChartData, {

Any help would be appreciated.

A: If you want your controller to be hit you need to make an ajax request. This ajax call should be done on the action which you want the controller to be called. Button click or so on. Start using console.logs to debug your javascript.
If you want this code to be execute on page open, wrap the ajax call in document.ready function.
   $.ajax({
        type: "POST",
        url: "Home/currentPopulation",
        //data: jsonData, if you need to post some data to the controller.
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        error: OnErrorCall
    });

    function OnSuccess(response) {
        var aData = response.d;
        console.log(aData);
        //build here your **data** as object wanted by Bar. Colors which you want and so on, options could be empty object {}. I think is possible to call bar without options, you need to read the documentation.

        var ctx = $("#myChart").get(0).getContext("2d");
        var myBarChart = new Chart(ctx).Bar(data, options);
    }

    function OnErrorCall(response)
    {
        alert('error');
    }

Here I show you little example how to do it. You can just google chart.js with mvc there is a lot of examples. Check if the url is correctly written I think you should remove the / in the begging.
This is just suggestion.
Also if you had the money and this is serious chart project use highcharts.js ! This is the best library which can work totally offline and gives you really good flexibility.
Usefull links:
ChartJS documentation


text:
Q: Get all instances of a class in JavaScript I'm trying to get the instances of a class, but I can't find a way to do it. The instances are created before my script loads, so I can't just make a variable that stores the instances. I've tried changing prototype methods, which does work for some classes that call the methods all the time, but not all of them do, and changing all of the methods is very annoying. So, is there a way to get all the instances of a class, reliably and arbitrarily timed?

A: No. JavaScript doesn't have any features that would make that possible.
Normally, I'd approach this by modifying the constructor of the class to include something like instance_of_foo.push(this) but you don't appear to have control over the source code of the class so that wouldn't work for you.

A: I don't know if you are using a framework, but you could define an array in a place where all the needed callees have access to. There you can store the instance via the constructor.
Here is an example:
"use strict";

var exampleInstances = [];

class Example{
    prop = "";

    constructor() {
        this.prop = "Example"+exampleInstances.length;
        exampleInstances.push(this);
    }
}

var eInstance = new Example();
var eInstance2 = new Example();
var eInstance2 = new Example();

for (var i=0; i<exampleInstances.length; i++) {
    console.log(exampleInstances[i].prop);
}