text:
Q: When linking a c# asp.net web application with a C++ dll is the dll code running on the server or the client? What I would like to do is write to a log file from the C++ dll but it doesn't seem to work.  I can write to a server side log file from c# code behind so I know it is possible to write to  a file on the server.  I can pass data to and from the C++ dll from the web application so I know the dll is linked correctly.  The dll will write to a file when linked to a console application so I know the file I/O code works.  It won't write to a file when linked to the web application.  So my thinking is the dll is running on the client?  All my testing is done locally so sometimes it is hard to figure out what is client and what is server.
If it is running on the client is it possible to link to a dll and have it run on the server?

A: C# code, and all functions called by C# code, always runs only on the server.
The only way to run code on the client is to send it over the network and ask the browser to run it.
No sane browser will run C++ for you.


text:
Q: What skill does game development require? Does being a game developer require more specific skills than a normal programmer ?
I found that some developers know graphic design and 3D motion etc... so they can work on full projects by themselves ....
so what is really needed to build a good foundation as a game developer ?

A: Very good question. I've been asking myself the same questions. That's why I did a deep research to get good answers.
Let's start this way. The most known project by a single developer is LSA (Lost soul aside) which is not even released, but the game developer claims that he did everything by himself. He is a designer. I've checked other projects as well. Every good single project has been made by a designer. So if you are a designer, you can develop a game yourself. If your a programmer without the design talent, I recommend a team work. If your asking yourself how is it possible that a designer can create a good game. The answer is simple. Game development with existing game engines (UE - Unreal engine) for example, is so simplified that you don't even need to use any programming language. You're just playing with objects and when you get the feeling, you can do a real masterpiece there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to sum total json I want to count total sum for each column:
My code is simply get data row by row and put it to final array.
The problem is here that I don't know how to handle this array in array and moreover count total sum for each column
$.each(data, function(rowNum, rowValue) {
let row = [];
$.each(rowValue, function(cellNum, cellValue) {
    ws_row.push(cellValue.qText);
    });
    console.log('row: ' + row)
    ws_data.push(row);
    });

Data
console.log('data', JSON.stringify(data))

[
  [
    {
      "qText": "-",
      "qNum": "NaN",
      "qElemNumber": -2,
      "qState": "L",
      "qIsNull": true
    },
    {
      "qText": "Values",
      "qNum": "NaN",
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "4444376003694.462000000000000000",
      "qNum": 4444376003694.462,
      "qElemNumber": 0,
      "qState": "L"
    }
  ],
  [
    {
      "qText": "5",
      "qNum": 5,
      "qElemNumber": 7,
      "qState": "O"
    },
    {
      "qText": "Values",
      "qNum": "NaN",
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "578565786417.105600000000000000",
      "qNum": 578565786417.1056,
      "qElemNumber": 0,
      "qState": "L"
    }
  ],
  [
    {
      "qText": "3.3",
      "qNum": 3.3,
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "Values",
      "qNum": "NaN",
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "38846991554.611330000000000000",
      "qNum": 38846991554.61133,
      "qElemNumber": 0,
      "qState": "L"
    }
  ],
  [
    {
      "qText": "3",
      "qNum": 3,
      "qElemNumber": 9,
      "qState": "O"
    },
    {
      "qText": "Values",
      "qNum": "NaN",
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "33036337251.042200000000000000",
      "qNum": 33036337251.0422,
      "qElemNumber": 0,
      "qState": "L"
    }
  ],
  [
    {
      "qText": "3.6",
      "qNum": 3.6,
      "qElemNumber": 5,
      "qState": "O"
    },
    {
      "qText": "Values",
      "qNum": "NaN",
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "31437556611.191444000000000000",
      "qNum": 31437556611.191444,
      "qElemNumber": 0,
      "qState": "L"
    }
  ],
  [
    {
      "qText": "3.2",
      "qNum": 3.2,
      "qElemNumber": 4,
      "qState": "O"
    },
    {
      "qText": "Values",
      "qNum": "NaN",
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "13104541271.185572000000000000",
      "qNum": 13104541271.185572,
      "qElemNumber": 0,
      "qState": "L"
    }
  ]
]

Right now I get rows:

My expected result:

*

*Create new rows for total sum, and also sum should be only for even numbers

Thank you in advance!

A: I don't know if you need the decimals or not but the blow code will not take into account the decimals (based on your image where the numbers were just int types, without all the decimals..) You can start something from here..
What I did was to take only the last object from each sub-array rowValue[2].qNum, transformed it to int and check if the number is even, if yes, I add it to total and return it..
Note that I don't know how the last row data should look like, I just supposed the format..

let data = [
  [{
      "qText": "-",
      "qNum": "NaN",
      "qElemNumber": -2,
      "qState": "L",
      "qIsNull": true
    },
    {
      "qText": "Values",
      "qNum": "NaN",
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "4444376003694.462000000000000000",
      "qNum": 4444376003694.462,
      "qElemNumber": 0,
      "qState": "L"
    }
  ],
  [{
      "qText": "5",
      "qNum": 5,
      "qElemNumber": 7,
      "qState": "O"
    },
    {
      "qText": "Values",
      "qNum": "NaN",
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "578565786417.105600000000000000",
      "qNum": 578565786417.1056,
      "qElemNumber": 0,
      "qState": "L"
    }
  ],
  [{
      "qText": "3.3",
      "qNum": 3.3,
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "Values",
      "qNum": "NaN",
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "38846991554.611330000000000000",
      "qNum": 38846991554.61133,
      "qElemNumber": 0,
      "qState": "L"
    }
  ],
  [{
      "qText": "3",
      "qNum": 3,
      "qElemNumber": 9,
      "qState": "O"
    },
    {
      "qText": "Values",
      "qNum": "NaN",
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "33036337251.042200000000000000",
      "qNum": 33036337251.0422,
      "qElemNumber": 0,
      "qState": "L"
    }
  ],
  [{
      "qText": "3.6",
      "qNum": 3.6,
      "qElemNumber": 5,
      "qState": "O"
    },
    {
      "qText": "Values",
      "qNum": "NaN",
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "31437556611.191444000000000000",
      "qNum": 31437556611.191444,
      "qElemNumber": 0,
      "qState": "L"
    }
  ],
  [{
      "qText": "3.2",
      "qNum": 3.2,
      "qElemNumber": 4,
      "qState": "O"
    },
    {
      "qText": "Values",
      "qNum": "NaN",
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "13104541271.185572000000000000",
      "qNum": 13104541271.185572,
      "qElemNumber": 0,
      "qState": "L"
    }
  ]
]

function isEven(value) {
  return value % 2 ? true : false;
}

function getTotalOfEvenValues(data) {
  let total = 0;
  $.each(data, function(rowNum, rowValue) {
    let intValue = Math.floor(rowValue[2].qNum) // rowValue[2] only if the data will have the same format always..with the value you need in the 3rd object
    console.log(intValue + ' isEven ' + isEven(intValue))
    if (isEven(intValue)) {
      total += intValue;
    }
  });
  return total; // use this total to place it in your new row
}

function addRowToData() {
  const totalOfEvenQNum = getTotalOfEvenValues(data);
  // i don't know how the empty rows should look like behind so i am just guessing the format.. but the last object should look like that
  data.push([{
      "qText": "",
      "qNum": "NaN",
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": "",
      "qNum": "NaN",
      "qElemNumber": 0,
      "qState": "O"
    },
    {
      "qText": totalOfEvenQNum.toString(),
      "qNum": totalOfEvenQNum,
      "qElemNumber": 0,
      "qState": "L"
    }
  ])
}

console.log('total for qNum ' + getTotalOfEvenValues(data));
addRowToData()
console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


text:
Q: How can I use Google Cloud speech API from Android? I have a college project and I'm developing an Android Application that acts like a translator. For normal text translation I'm using Google Cloud Translation API and I saw they have an option to translate text via speech using Google Cloud speech API. Problem is I don't have a starting point, and I didn't understand how can I use it.
So, is there an example of how can I use Google Cloud speech API from my Android application?

A: Android runs Java examples just fine. You can find them on github.
You can also use Android Speech API, it is free, unlike Google Cloud Speech API.

A: Yes it is possible, I have done it, based on Googles "speech" example inside "android-docs-samples-master" (google and download those samples).
Things you need to know:

*

*You will need to setup a free Google Cloud account, and activate
billing. BILLING? WTF DO I NEED TO PAY? Hold on!!! keep reading my
answer!!

*The first 60min of speech recognition time of EVERY month are
FREE.

*Setting up billing and obtaining the PREF_ACCESS_TOKEN_VALUE
value you need to add to your SpeechRecognizer class requires
patience, remember. You also need to obtain an authentication json
from google and add it to the "res -> raw" folder of you project.

*The speech demo is not well suited for fast consecutive ASR
requests, as shutting down the speech recognition service takes 2-6
seconds (I am working on this).

UPDATE: If you got this working, you might have noticed that the 3rd or 4th time you do ASR, it fails. This is because the sample code is not designed to close and open the entire ASR recognizer properly. I got it working, if you need help on a specific error let me know.
This is a summarized guide, if you need more details on a particular step let me know.

A: There are some key differences between Android Speech API and Google Cloud Speech API though. While the Android Speech API is free, it is limited to short phrases and is unable to process audio from files. Each speech recognition also starts and ends with a distinctive beep so the user is aware that the microphone is in listening mode - kind of a Google way to prevent writing a spoofing app, when the speech recognizer runs in the background and sends the transcript to the backend server. These limitations are lifted for Google Cloud Speech, but the integration with Android is almost non-existent. While there is an Android demo project, adapting it to yours won't be easy and one will face multiple challenges and error resolutions. And here is what Google states on their website:

Note: Cloud Java client libraries do not currently support Android.


text:
Q: aiohttp Runtime Error: Cannot guess the encoding of a not yet read body Working on an asynchronous API wrapper for https://wanderbox.org/api. I'm using the aiohttp to handle most of the asynchronous networking. For one POST method, I keep getting the following error
  File "/Users/dominictarro/Documents/wander/wander/tests/test_client.py", line 114, in coro
    x = await Wandbox.compile_nd(
  File "/Users/dominictarro/Documents/wander/wander/client.py", line 198, in compile_nd
    return await cls._post(url=cls.url.format("compile.ndjson"), data=json.dumps(params), headers=headers, **kwargs)
  File "/Users/dominictarro/Documents/wander/wander/client.py", line 74, in _post
    encoding = response.get_encoding()
  File "/Users/dominictarro/Documents/wander/venv/lib/python3.9/site-packages/aiohttp/client_reqrep.py", line 1063, in get_encoding
    raise RuntimeError(
RuntimeError: Cannot guess the encoding of a not yet read body

It only occurs for this one API endpoint, https://wanderbox.org/api/compile.ndjson. Every other test case is passing. The API for this case is returning an NDJSON which may be causing issues. but it doesn't even get to that error because of the response.get_encoding().
Here are my _post and compile_nd functions.
@classmethod
async def _post(cls, url, *args, **kwargs):
    """
    TODO describe

    :param url:
    :param args:
    :param kwargs:
    :return:
    """
    async with cls.session.post(*args, url=url, ssl=False, **kwargs) as response:
        response.raise_for_status()
        return await response.json(content_type=response.content_type, encoding=response.get_encoding())

@classmethod
    async def compile_nd(
            cls,
            code: str,
            compiler: str,
            codes: typing.List[dict] = (),
            compiler_option_raw: typing.Any = '',
            options: str = '',
            runtime_option_raw: typing.Any = '',
            stdin: str = '',
            **kwargs
    ):
        """
        Sends code to Wandbox to be compiled with the given parameters and returns performance/completion dictionaries.

        :param code:                Code to compile and execute
        :param compiler:            Compiler name as described by Wandbox
        :param codes:               List of supplementary code objects {'code': abcd..., 'file': 'demo.py'}
        :param compiler_option_raw: ...
        :param options:             Compiler options (as would be typed in terminal)
        :param runtime_option_raw:  ...
        :param stdin:               Data to feed into input calls from running program
        :param kwargs:              Keyword arguments to modify aiohttp ClientSession().post() method
        :return:
        """
        params = {
            'code': code,
            'codes': codes,
            'compiler': compiler,
            'compiler-option-raw': compiler_option_raw,
            'options': options,
            'runtime-option-raw': runtime_option_raw,
            'stdin': stdin
        }
        headers = {'Content-type': 'application/x-ndjson', 'Accept': 'text/plain'}
        return await cls._post(url=cls.url.format("compile.ndjson"), data=json.dumps(params), headers=headers, **kwargs)

Here is the test case raising the error.
def test_compile_nd_simple(self):

    async def coro():
        await Wandbox.connect()

        code = "import os\nprint(os.name)\nprint('done')"
        x = await Wandbox.compile_nd(
            code=code,
            compiler='cpython-3.8.0',
            compiler_option_raw=False,
            runtime_option_raw=True
        )
        keys = ('program_message', 'program_output', 'status')
        self.assertTrue(sorted(x.keys()) == sorted(keys), msg=f"{x}\n-----\n{keys}")

        await Wandbox.close()

    asyncio.run(coro())

A: I solved the problem. Firstly, I think there's an issue with the response.get_encoding() function that is outside of my control. However, I can just use response.charset (this assumes the server provides it, but for my purposes it does).
Secondly, the loading issue is solved by importing the ndjson library and using its Decoder().decode function if content_type == "application/x-ndjson". If not, just use the standard json decoder JSONDecoder().decode function.
My code now looks like this.
import json
import ndjson

@classmethod
async def _post(cls, url, *args, **kwargs):
    """
    TODO describe

    :param url:
    :param args:
    :param kwargs:
    :return:
    """
    async with cls.session.post(*args, url=url, ssl=False, **kwargs) as response:
        response.raise_for_status()
        return await cls._parse_response(response)

@classmethod
async def _parse_response(cls, response: aiohttp.ClientResponse) -> typing.Any:
    """
    Takes an aiohttp.ClientResponse object and converts content to Python primitives via json or ndjson

    :param response:
    :return:
    """
    decoder = ndjson.Decoder if (response.content_type == 'application/x-ndjson') else json.JSONDecoder
    return await response.json(content_type=response.content_type, loads=decoder().decode, encoding=response.charset)


text:
Q: Can't get Public IP of Inbound Connections from Behind NAT + Reverse Proxies My network flow looks like this:
Public Client
     ∟--> CDN Reverse Proxy (Cloudflare) - ONLY used for HTTP/S traffic, all else goes direct
          ∟--> Cloud Server w/ firewalld forwarding
               ∟--> Private Server
                         ∟--> Docker Reverse Proxy (Traefik)
                                   ∟--> Docker Containers
                                   ∟--> Docker Reverse Proxy (NGINX)
                                            ∟--> Docker Containers

I'm trying to get the Public Client's IP to show up in the logs files of the various docker containers, but they only log the docker network address of the applicable docker reverse proxy.
To further complicate things, I am forwarding a combination of TCP and UDP traffic, and not all of the traffic is HTTP/S. I mainly want the source IP coming through so that I can take advantage of rate limiting and blocking.
Is this configuration ungodly complicated? Yes. Does it somehow all work shockingly well?  Yes! Except for the elusive logging of the true source's IP...
The Cloud Server's firewall is configured with the following commands:
echo 'net.ipv4.ip_forward = 1' >> /etc/sysctl.conf
sysctl -p
# Enable masquerade on the VPN client address
sudo firewall-cmd --add-rich-rule "rule family=ipv4 destination address={Private Server Private IP]/32 masquerade" --permanent
# These rules receive traffic coming into the server's main ipv4 address - web
sudo firewall-cmd --add-rich-rule "rule family=ipv4 destination address={Cloud Server Public IP]/32 forward-port port=80 protocol=tcp to-port=80 to-addr={Private Server Private IP]" --permanent
sudo firewall-cmd --add-rich-rule "rule family=ipv4 destination address={Cloud Server Public IP]/32 forward-port port=443 protocol=tcp to-port=443 to-addr={Private Server Private IP]" --permanent
sudo firewall-cmd --add-rich-rule "rule family=ipv4 destination address={Cloud Server Public IP]/32 forward-port port=25 protocol=tcp to-port=25 to-addr={Private Server Private IP]" --permanent
sudo firewall-cmd --add-rich-rule "rule family=ipv4 destination address={Cloud Server Public IP]/32 forward-port port=143 protocol=tcp to-port=143 to-addr={Private Server Private IP]" --permanent
sudo firewall-cmd --add-rich-rule "rule family=ipv4 destination address={Cloud Server Public IP]/32 forward-port port=465 protocol=tcp to-port=465 to-addr={Private Server Private IP]" --permanent
sudo firewall-cmd --add-rich-rule "rule family=ipv4 destination address={Cloud Server Public IP]/32 forward-port port=587 protocol=tcp to-port=587 to-addr={Private Server Private IP]" --permanent
sudo firewall-cmd --add-rich-rule "rule family=ipv4 destination address={Cloud Server Public IP]/32 forward-port port=993 protocol=tcp to-port=993 to-addr={Private Server Private IP]" --permanent

and to give an excerpt of one of the ports that Traefik passes straight through to the NGINX reverse proxy, these are the docker-compose lines:
        - "traefik.tcp.routers.mailu_smtp_ssl.rule=HostSNI(`*`)"
        - "traefik.tcp.routers.mailu_smtp_ssl.entrypoints=smtp-ssl"
        - "traefik.tcp.routers.mailu_smtp_ssl.tls.passthrough=true"
        - "traefik.tcp.routers.mailu_smtp_ssl.service=mailu_smtp_ssl"
        - "traefik.tcp.services.mailu_smtp_ssl.loadbalancer.server.port=465"

I'm guessing that a starting point would be swapping SNAT for the current masquerade config. I'm also guessing that some settings for x-layers-deep X-FORWARDED-FOR substitution would be necessary (although that wouldn't help for the non-http/s packets)...but I'm stumped on how to put it all together.


text:
Q: a particular linear combination Fix $a_1,\ldots,a_n\in\mathbb{N}$. I'd like to know if one can characterize the natural numbers that belong to the set $$\{b_1a_1+\ldots+b_na_n:\,b_j\in\{-1,0,1\}\}.$$
EDIT: Maybe this question doesn't have a solution. In fact, I was interested on solving the following problem: consider natural numbers $a_1<a_2<\ldots<a_7< 100$. Suppose that, if $b_1a_1+\ldots+b_na_n=0$ with each $b_j\in\{-1,0,1\}$, then $b_j=0$ for all $j$ (we have some sort of linear independence). Then every $a\in\{a_7+1,\ldots,100\}$ can be written as $a=c_1a_1+\ldots+c_na_n$, where each $c_j\in\{-1,0,1\}$.

A: It is unlikely that there is a characterization, because if there is, we should be able to efficiently test if an element $m$ is in this set; this is equivalent to the problem P: test if there are two subsets of $\{a_1,a_2,\ldots,a_n\}$ whose sum differs by $m$.
This problem is NP-hard with a reduction from the Partition problem known to be hard: https://en.wikipedia.org/wiki/Partition_problem.
The reduction is simple: given a set $V$, we want to know if there exist two sets with the same sum. Solve $P$ on the set $V \cup \{m\}$.


text:
Q: How to create nested nodes in one mutation? Hi I am trying to write data on my https://www.graph.cool/ db with a mutation.
My project is a React web-app and I am using Apollo as graphql client and graphql-tag npm package as template literal parser.
The problem is that i don't know how to arrange the gql template string for the correct mutation with nested data.
My schema looks like this, for example note the field "Addresses" for the type "Company" is an array of "Address" objects type.
type Company {
  name: String!
  website: String
  Owner: User
  Addresses: [Addresses]
}

type User {
  name: String!
  email: String
}

type Address {
  street: String!
  city: String!
  country: String
  contacts: [Contact]
}

type Contact {
  name: String
  email: String
  phone: String
}

For example, I want to create a new company, its new owner and multiple addresses at the same time in one mutation. For the addresses I need to create a new contact as well.

A: You can make use our so called nested mutations to accomplish that.
First of all, let's see how we can do it from the GraphiQL playground:
mutation createNestedCompany {
  createCompany(
    owner: {
      name: "Mickey"
      email: "mickey@mouse.com"
    }
    addresses: [{
      street: "A street"
      city: "A city"
      country: "A country"
      contacts: [{
        name: "Mickey"
        email: "mickey@mouse.com"
        phone: "+1 23456789"
      }]
    }, {
      street: "B street"
      city: "B city"
      country: "B country"
      contacts: [{
        name: "Minney"
        email: "minney@mouse.com"
        phone: "+9 87654321"
      }]
    }]
  ) {
    id
    owner {
      id
    }
    addresses {
      id
      contacts {
        id
      }
    }
  }
}

Note that the createCompany mutation has the object argument owner and the list object argument addresses. addresses has a nested contacts list object argument.
Using Apollo Client, we specify input arguments with GraphQL variables, so let's see how it looks in this case:
const createNestedCompany = gql`
  mutation createNestedCompany(
    $owner: CompanyownerUser
    $addresses: [CompanyaddressesAddress!]
  ) {
    createCompany(
      owner: $owner
      addresses: $addresses
    ) {
      id
      owner {
        id
      }
      addresses {
        id
        contacts {
          id
        }
      }
    }
  }
`

When calling the mutation with Apollo, we now have to specify the variables as an object:
const variables = {
  owner: {
    name: "Mickey"
    email: "mickey@mouse.com"
  },
  addresses: [{
    street: "A street"
    city: "A city"
    country: "A country"
    contacts: [{
      name: "Mickey"
      email: "mickey@mouse.com"
      phone: "+1 23456789"
    }]
  }, {
    street: "A street"
    city: "A city"
    country: "A country"
    contacts: [{
      name: "Minney"
      email: "minney@mouse.com"
      phone: "+9 87654321"
    }]
  }]
}

and call the mutation with the variables:
this.props.createNestedCompany({ variables })
  .then((response) => {
    console.log('Company, owner and addresses plus contacts created');
  }).catch((e) => {
    console.error(e)
  })

The variable types CompanyownerUser and [CompanyaddressesAddress!] depend on a combination of the multiplicity (to-one; to-many), the related models (Company and User; Company and Address) and the related fields (owner; addresses). You can find all type names in the GraphiQL playground docs when you navigate to the createCompany mutation.


text:
Q: Change case of first letter in every cell in spreadsheet I have many cells which I'd like to convert such that the first letter in every cell is capitalized. E.g. cook, chef, fireman becomes Cook, Chef, Fireman.

*

*I have the spreadsheet in OpenOffice.org, but it seems to only have options for "all uppercase" or "all lowercase".

*I can edit it in OpenOffice.org or export to a CSV and edit the CSV with a BASH script, if OpenOffice.org cannot do this.

How can I change the first letter of every cell in the spreadsheet to uppercase?

A: I happen to do this task. You have to install Spreadsheet::ParseExcel and Spreadsheet::WriteExcel modules.
use strict;
use warnings;

use Spreadsheet::ParseExcel::SaveParser;

my $parser   = Spreadsheet::ParseExcel::SaveParser->new();
my $workbook = $parser->Parse('Book1.xls');

if ( !defined $workbook ) {
    die $parser->error(), ".\n";
}

for my $worksheet ( $workbook->worksheets() ) {

    my ( $row_min, $row_max ) = $worksheet->row_range();
    my ( $col_min, $col_max ) = $worksheet->col_range();

    for my $row ( $row_min .. $row_max ) {
        for my $col ( $col_min .. $col_max ) {

            my $cell = $worksheet->get_cell( $row, $col );
            next unless $cell;

            # "ucfirst lc" make sure that only the first letter is capitalized
            # if you dont like that just remove lc
            $worksheet->AddCell( $row, $col, ucfirst lc $cell->value() );

        }
    }
}

# ofcouse save your work
$workbook->SaveAs('Book2.xls');

A: Maybe you just need to udpate to a more recent version. I'm using LibreOffice 3.4.4 and I see Format -> Change Case -> Sentence case which I'd say does exactly what you need.

A: Is Perl an option? There's a module in the CPAN archive called Spreadsheet::WriteExcel that can also handle OpenOffice spreadsheets too.
You basically read in the spreadsheet, search the cells, modify the ones you want, and the create a new spreadsheet with the modified data. You cannot directly modify an Excel spreadsheet. I don't know if this applies to OpenOffice documents.
I used this before to read and write Excel spreadsheets, but that was a while ago. However, this module can handle your situation without first having to save the spreadsheet in CSV format.

A: I have an awk script that will do what you want (I think).
Here is my test intput (test.input):
cook, chef, fireman
cook, chef, fireman
cook, chef, fireman
cook, chef, fireman
house, farm, road

My awk script (up.awk):
# from: http://www.gnu.org/software/gawk/manual/html_node/Join-Function.html
function join(array, start, end, sep, result, i){
         if (sep == "")
            sep = " "
         else if (sep == SUBSEP) # magic value
            sep = ""
         result = array[start]
         for (i = start + 1; i <= end; i++)
            result = result sep array[i]
         return result
}
BEGIN {
    FS="\n";
}
{
    # split input on newline
    for(i=1;i<=NF;i++) {
        # split line on the commas
        size = split($i, s, ",")
        for(ii=1;ii<=size;ii++) {
            # trim whitespace
            gsub(/[[:space:]]*/,"",s[ii])
            # uppercase first char and glue it back together
            s[ii] = toupper(substr(s[ii], 0, 1)) substr(s[ii], 2)
        }
        # join array back and print it out
        print join(s, 1, size, ", ")
    }
}

How I run the script:
awk -f up.awk test.input >test.output
The output in my test.output:
Cook, Chef, Fireman
Cook, Chef, Fireman
Cook, Chef, Fireman
Cook, Chef, Fireman
House, Farm, Road

A: Perl one-liner:
perl -pwe 's/(?:^|,)\s*\K([a-z])/\U$1/g;' file.csv > fileout.csv

You can also use in-place edit with the -i switch. E.g. perl -pi.bak -we ...
Longer version, using Text::CSV_XS. This module will (probably) treat your csv files with more care.
use strict;
use warnings;
use Text::CSV_XS;

my $csv = Text::CSV_XS->new({
        binary  => 1,
        eol     => $/,
    });

my $file = shift;
open my $fh, '<', $file or die $!;
while (my $row = $csv->getline($fh)) {
    s/([a-z])/\U$1/ for @$row;
    $csv->print (*STDOUT, $row);
}

Run it with: perl script.pl file.csv > fileout.csv

A: you could do something pretty dodgy with python or any other language.
#!/usr/bin/env python

lastchar = ""
orig_csv = open("yourfile.csv", "r")
new_csv = open("newfile.csv", "w")
for line in orig_csv:
    for char in line:
        if lastchar == ",":
            new_csv.write(char.upper())
        else:
            new_csv.write(char)
orig_csv.close()
new_csv.close()

This assumes that none of the fields are enclosed in quotes, because it'll just upcase everything after a comma.
Failing that, you'll want to actually use a csv library.

A: If you are using, or if you upgrade to, OOo 3.3 there are options for this built in.
Mark all the cells you want to affect, then choose Format -> Change Case -> Sentence case and voila! See if that does the trick for you?

A: Export it as a csv. Then do something like this.
#psuedo python
out=""
nums = [col numbers to capitalize]
for line in file.read_csv('input.csv'):
    for n in nums:
       line[n] = line[n].capitalize()
       out += ",".join(line) + "\n"

A: You can write up a small gawk and sed combo to get title case -
gawk -v RS="[,\n]" -v ORS="" '
{a=substr($1,1,1); b=substr($1,2); print toupper(a)b" "; if (NR%3==0) print "\n"}' file |
sed -e 's/ /, /g' -e 's/, *$//'

Test:
[jaypal:~/Temp] cat file
cook, chef, fireman
cook, chef, fireman
cook, chef, fireman
cook, chef, fireman
house, farm, road

[jaypal:~/Temp] gawk -v RS="[,\n]" -v ORS="" '
{a=substr($1,1,1); b=substr($1,2); print toupper(a)b" "; if (NR%3==0) print "\n"}' file |
sed -e 's/ /, /g' -e 's/, *$//'
Cook, Chef, Fireman
Cook, Chef, Fireman
Cook, Chef, Fireman
Cook, Chef, Fireman
House, Farm, Road

Obviously this isn't the perfect solution, you might have to tweak it a little bit depending on how many rows of data you have or want. Changes to NR%3 should be good enough.

A: This might work for you:
cat <<! | sed 's/\<[^,]*/\u&/g'
> cook, chef, fireman
> head cook, head chef, chief fireman
> house, farm, road
> !
Cook, Chef, Fireman
Head cook, Head chef, Chief fireman
House, Farm, Road

Probably GNU sed specific.


text:
Q: PyQt5 - Duplicate GUI when multiprocessing I'm attempting to multiprocess the saving for my application. For some reason, when I spawn a pool, a duplicate of my GUI pops up. The GUI pops up on this line and the program doesn't push images onto the pool until I tell it, so the internals of the process shouldn't matter. I cannot for the life of me figure out why it does this. Any help?
self.save_pool = mp.Pool(processes=1)


text:
Q: Problem reading a double from file with 1 decimal place (C) For some reason when I try to read in a double and print it out with this code, it prints out:
"865955189279958860000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000"
    fscanf(inFile, "%.1lf", &value);
    printf("%.lf\n", value);

When I change the code to this:
    fscanf(inFile, "%lf", &value);
    printf("%.1lf\n", value);

I get the output I want. But obviously I want the double to be stored as 8.1 (for instance), rather than having to format when I print it.
Any help would be greatly appreciated!

A: A double has always a certain number of significant decimal digits, for example IEEE 754 gives 15 to 17. So you can't limit stored values to an arbitrary number of decimal places, let alone the problem of decimal fractions represented by binary numbers. For example, there is no way to exactly store 6.1 in an IEEE-754-double.
Anyway, you might like to round the value. But again, be aware of the problem mentioned above.
If you like to have an output with a limited number of decimal places, just use the corresponding format string, for example "%.1lf". The default number is 6 that's why you think it's stored like this.
But the best solution for you might be to use "%g". Note: It's always a good idea to read documentation, in this case for printf().


text:
Q: Ubuntu freezing during copying file to phone Whenever I try to copy files between my phone and Ubuntu 22.04 Desktop LTS,system freezes after a while (during middle of the copying process). What might be the reason ? Is this a bug ? I can assure there's no issues with my phone since my primary OS windows 11) has rock stable connection with my phone( doesn't freeze at all) Ubuntu seems to have problem with MTP. I have been facing this issue sine long in any device(phone) I connect. If this is solvable by any means , I'm ready to take the step. By the way I was copying from Ubuntu to my phone.
Thanks in advance.


text:
Q: Is this a feature envy smell? In my Application, I wanted to seperate GUI and business logic with some kind of ModelViewPresenter-Design.
Therefore I made some Presenter classes, which have not much more code than the properties my forms are databound to.
To provide persistance (load and save) I made new classes with methods setting the properties of the above mentioned presenter classes to seperate concerns (present data to GUI and persist data).
Since my presenter classes are now only datacontainers without any behavior, I wonder if I should better merge persistance and presenter to simplify my code. It seems very overdone to me as it is at the moment.
Here is some C# snippet from one of the Persistance classes:
public override void LoadData()
{
    Presenter = (PersonalColorSettingsPresenter) PresenterFactory.GetPresenter(m_User, "ColorSettings");
    loadData();
}

private void loadData()
{
    var color = Settings.GetSelectionColor(m_User);

    Presenter.ActiveRowBackColor = color.BackColor;
    Presenter.ActiveRowBackColor2 = color.BackColor2;
    Presenter.IsActiveRowBackgroundGradientActive = color.GradientActive;
    Presenter.ActiveRowForeColor = color.ForeColor;
}

A: No, you should not merge persistence into your presenter. It may not seem important right now, but doing so would be a violation of the Single Responsibility Principle, and if such decisions were made repeatedly in the long term would lead to code that is difficult to maintain.
As a side note, if you're using the MVP pattern, your persistence layer should interact with your model objects, not with your presenter. The presenter should read data out of the model to pass to the view, and then write the results back to the model after it has finished. A data storage module (e.g.some kind of repository or DAO - please don't use active record here as this violates SRP too) is used to load and save the model objects. The presenter should know as little about how this works as possible, I.e. if possible it shouldn't interact with the data storage at all (have that happen at a higher level) but if it must then have it do so through an abstract interface.


text:
Q: How to add on_press to change the screen in python using kivy? I have defined my screens in .kv file, and I can access them without any problem when using ie. on_release: app.root.current = 'main' in .kv.
But I have a problem when Buttons are created dynamically in python, what is equivalent to on_release: app.root.current = 'main' in python? Because I cant make it recognize app.root.

A: You can access the current App in Python by calling App.get_running_app(). So, in other words:
from kivy.app import App
def change_screen(*args):
    App.get_running_app().root.current = 'main'

from kivy.uix.button import Button
btn = Button(text='abc')
btn.bind(on_press=change_screen)


text:
Q: Want to write T-SQL Code to insert single row from text file into SQL Server 2008 I want to write one Transact SQL code which can read a text file and insert data into SQL Server 2008 database table. How can I do that? Text file is separated by comma and has only 1 record. But I don't want to use bulk insert or any other auto method. I want to do it by coding for doing some processing.

*

*Text file path: C:\fakepath\record.txt

*Text file content (only 1 row) - 1,John,2000

*Table name: Employee

*Structure - Id,Name,Salary
Can you help me out to write down script?
Thanks !

A: I've used this method in the past on 05. While you said you didn't want to use bulk it's effective: Reading a text file with SQL Server

A: BULK INSERT should be easiest way to do this.
Otherwise, you can try OPENROWSET
   select
      c1
   from
      OPENROWSET (BULK 'C:\fakepath\record.txt',SINGLE_CLOB) as T1(c1)


text:
Q: Thoughts on having a generic, reusable grid viewmodel I'm developing a wpf-based application and I'm currently struggling to find the best way of supporting a recurring scenario in it.
This app uses grids a lot. There are a bunch of features I want in it that are meant to be used in grids, such as drag & drop, multiple row edition, conditional row coloring, etc. But at the same time, I want my data objects to derive from a specific, data-oriented class that is unaware of any UI context and could be used by a single form, with standalone editors.
Therefore, I'd like to have a DataGridViewModel class that will in turn expose two collections: Rows as DataGridRowViewModel and Columns as DataGridColumnViewModel. The row view model would expose a RowData property which will be the actual data object, while the column view model would have a PropertyDescriptor (from System.ComponentModel namespace) that will indicate which data object field the column is meant for.
You can think of the DataGridRowViewModel as a container for the "real" row object.
The goal is to allow separation of concerns between grid-specific functionalities (controlling row height, color, selection, etc) and data-specific functionalities, so that one doesn't need to know about the other. Ideally, a third component will be aware of both and ensure proper communication between the two layers (observing a data field and change the row color under condition x or y, for example).
Does this approach makes any sense? What kind of complications should I expect out of this (binding issues, performance and the likes)?

A: I've been working with grids for a while and had simmilar idea and scenarios.
There is a flaw in this approach: you want many features on your grid, but this means you'll have many very different kinds of data in it.
So your grid will have to visualize and edit all this data.
This isn't a problem by itself, but, this means that grid will become "God Object" itself. There is a different approach to solve this: make grid as a "thin" container. I mean don't think of a grid as a cells with text.
Think of it as a layouts.
Then:

*

*Grid is really a list of rows. Each row can have cells, so you'll have to create some mechanism to sync columns' width, but some rows may be special (grouping, totals, details, seprators, spans ...)

*Each cell is really a panel for other components: it can be quite complex, so it won't be just text in it: there can be an edit with 2 buttons and an image.

*This way grid and row doesn't know about what the cell is, except that it's size and location.

*This all means that binding data to cells isn't binding data to two dimensional array of values, but rather binding an array of rows to an array of objects.

*Rows should handle binding cells to object's fields or to some computed values over some fields.

*Cells should pass bindings to their child components

*And the components inside cells (texboxes in simplest and most common cases) will finally handle the binding.

The approach I proposed is quite complex to implement though. Maybe you don't need such complex cases.
Also be warned that having this many components requires optimizations (specifically in simple and most common cases).
But in the result you can have a swiss-knife solution for all scenarios with grids.
Comparing to your proposial it have some benefits (and your proposial have limitations in this areas): it can take data from deep fields inside your objects, it can have computed values, you don't have to convert your objects to "RowData@, it can handle several hungry components in one cell.
For your question "Is this really ok?" - yes it is. There are several big frameworks do grids your way, from what comes to my mind right now: Qt have this way of binding. So your approach is a well known good practice anyway too whith some known problems and limits though.

A: We're aiming to do something similar in our web-based UI project, so what you're trying to achieve makes perfect sense to me.  The view model should be flat, so binding should be straightforward to achieve.
In our case, we found that we are using lists of data all over our project, but there were only three use cases for the list: "select one of these items" (single select button per row), "select one or more of these items" (checkboxes and a submit button), and "manage this list of items" (Add New button at the top, Edit and Delete buttons per row).  In any case, the columns of data are read only.
We're working to develop a component with a constructor that takes a parameter to describe which type of list is needed and a view model object that has 1-4 columns of display data plus an Id as a reference.  The component will figure out what the list should look like from there.  We made a custom annotation class to decorate the view model with:
[System.AttributeUsage(System.AttributeTargets.Property)]

public class ListViewColumn : System.Attribute
{
    private string _columnName;
    public int ColumnOrder;
    public string FormatString;

    public ListViewColumn(string columnName)
    {
        _columnName = columnName;
        ColumnOrder = 1;
        FormatString = null;
    }
}

Usage:
    [ListViewColumn("Option Code", ColumnOrder = 1)]
    public string OptionCode { get; set; }

    [ListViewColumn("Version", ColumnOrder = 2)]
    public float Version { get; set; }

    [ListViewColumn("Description", ColumnOrder = 3)]
    public string Description { get; set; }

If you were generating a list for the "Select One" metaphor (a class attribute can drive that), this would result in a list that looked similar to the following:
        Option Code   Version   Description
Select  101-10G       4.2       Whatever this thing is
Select  234-567       4.35      A clear description of this other thing
Select  456-987       2.9       Something completely different

Using the same class to generate a "Manage" list would produce the following:
                                                                 Add New
Option Code   Version   Description
101-10G       4.2       Whatever this thing is                   Edit | Delete
234-567       4.35      A clear description of this other thing  Edit | Delete
456-987       2.9       Something completely different           Edit | Delete

A:
What kind of complications should I expect out of this

There is a very nice consistency in our app's UI behavior that is deep. And it comes from the basic building blocks of which gridview is one. At this fundamental level someone did a very nice job with the design. These very basic building blocks are the base(s) (and basis!) for less abstract, general functional area, base classes.
The keys to a very esoteric yet useful set of "legos" are the design of the concrete builders and programmer training.
You must train your coders how to work with these artifacts. It simply is not obvious how our abstractions are built up; it seems like you start with a window-base with nothing but a couple of buttons, a generic gridview (with no actual designer) and then a big bang happens. A window with 3 drop-downs that interactively populate 2 grids that have filtering, selection, and possibly mutual interaction.
Your builder code must be reasonably designed; the simplest of OO application often is enough but when your coders do not have an appreciation of the existing design you're screwed. And honestly most coders I've worked with are bad at OO. I hope you have code reviews. The deeper the code in the building process, the more painful are its flaws.
For example we have a class that is metadata for building concrete gridviews. It is nothing but string properties - a true DTO poster child. One is a CSV list of DB table column names (the 1st is the default sort, who knew?), another is the gridview headings, some are SQL snippets. Some values are quoted, some not. Some single quotes, some double. And where's the rest of the SQL?! Some properties were used together but not always. I understood nothing until I read lots of code and did lots of debugger tracing. What idiot doesn't know what a constructor is for? Method parameters? Crap. Client classes are littered with procedural code picking apart these values. Bad and absent OO design makes itself felt far into the call stack.
I ended up writing lots of extension methods for this class for use in new functionality. With lots of unit tests! I did not dare re-write the class because it was being used in about 100 places, and was pretty deep inside the building process


text:
Q: How to code this on numpy raster, raster_B8a_166 - numpy array (xsize / xsize)
for i in range(xsize):
    for j in range(xsize):
        if raster[i][j] == 166 and raster_B8a_166[i][j]:
            raster[i][j] = 39
        elif raster[i][j] == 166 and raster_B8a_166[i][j] == False:
            raster[i][j] = 11

A: Here is an example on two 1D arrays. The same code should apply to a pair of 2D arrays.
Note that with numpy arrays  a == 166 will return a Truth array with the same shape as a. Then logical_and takes two truth arrays, performs a logical and, and returns a third truth array. Finally you can return or set specific items in a numpy array by feeding a truth array into it.
import numpy as np

a = np.array([1, 2, 166, 166])
b = np.array([True, False, True, False])

a[np.logical_and((a == 166), (b == True))] = 39
a[np.logical_and((a == 166), (b == False))] = 11

print(a)


text:
Q: How can i use param in path as prop react router dom v6 I have a route <Route path="post/:id" element={<PostByIdPage />} />
How can i get param id as props in react router dom v6?
Here is my PostByIdPage component :
import React, { Component } from 'react';
import OneSecret from '../OneSecret';
import getSecretsPublic from '../../../action/getSecretsPublic';
import { connect } from 'react-redux';

export class index extends Component {

    constructor(props) {
        super(props);
        this.state = {
            secretPublic: {
                content: ''
            }
        }
        let id = decodeURI(window.location.pathname.substring(6));
        let params = {
            id: id
        }
        this.props.getSecretsPublic(params)
            .then(res =>{
                if (res.type === 'ERROR_MESSAGE') {
                    return;
                }
                this.setState({secretPublic: res.payload.data[0]})
            });
    }

    render() {
        return (

                <OneSecret element={this.state.secretPublic} key={this.state.secretPublic.id} />

        )
    }
}

export default connect(null, {getSecretsPublic})(index)

I'm using window.location.pathname and split to get param but i want to get params from props to re render() my component based in params

A: Little late to answer but you can achieve it easily.
<this.props.match> will be available once you use {useParams} from react-router-dom but its a little tricky for class-based components.
If using functional component, you have a choice of directly using {useParams} and props.match will be available.
For Class-based components like your case, You can do this with High order component:
import { useParams } from 'react-router-dom';
export function withRouter(Children) {
  return (props) => {
    const match = { params: useParams() };
    return <Children {...props} match={match} />
  }
}
class PostByIdPage extends Component {
  render() {
    return (

Page for {this.props.match.params.id}

    );
  }
}
export default withRouter(PostByIdPage);

Now in you classbased component, You can access id as:
this.props.match.params.id

No more Error for ' this.props.match is undefined'

A: i think its the same as before you can use useParams()
like this:
let { id } = useParams();

update:
<Route path= "third/:id"  element={Content}/>

this is my code to call to the component
and this is the component:
 class Content extends Component {
    componentDidMount () {

        console.log( this.props.match.params.id );
    }
  render() {
    return (

Third

    );
  }
}

A: you will get it as this.props.match.params.id in PostByIdPage component.


text:
Q: Motivation for the Deformed Nekrasov Partition Function I have recently been doing research on the AGT Correspondence between the Nekrasov Instanton Partition Function and Louiville Conformal Blocks (http://arxiv.org/abs/0906.3219). When looking at the Nekrasov Partition Function one defines a deformed metric in terms of the "deformation parameters" $\epsilon_1, \epsilon_2$ which seem to define a $SO(4)$ action on a standard Euclidean Metric, breaking translational symmetry. Much of the literature on these functions seems to be in the math department, defining the functions categorically in terms of sheaves and what-not (http://arxiv.org/abs/math/0311058) and even the original paper (http://arxiv.org/abs/hep-th/0206161) approaches the subject from a cohomological perspective.
Is there any obvious physical motivation for looking at partition functions in this strange deformed spacetime? Or should I view it as simply a mathematical manipulation?

A: The most physical and understandable definition of Nekrasov's partition function to me uses five-dimensional gauge theories. Namely, any 4d N=2 susy gauge theory has a 5d version with the same matter content, so that compactifying it on a small $S^1$ brings it back to the original 4d theory.
Then we put the theory on the so-called Omega background: it is $\mathbb{R}^4 \times [0,\beta]$, but $(\vec{x},0)$ and $(\vec{x'},\beta)$ are identified by a rotation
$$
\vec x'=\begin{pmatrix}
\cos \beta\epsilon_1 & \sin\beta\epsilon_1 & 0 & 0\\
-\sin \beta\epsilon_1 & \cos\beta\epsilon_1 & 0 & 0\\
0& 0 &\cos \beta\epsilon_2 & \sin\beta\epsilon_2\\
0& 0 &-\sin \beta\epsilon_2 & \cos\beta\epsilon_2
\end{pmatrix}\vec x.
$$
Then we take the limit $\beta\to 0$, keeping $\epsilon_{1,2}$ fixed. (Strictly speaking we also need to add a background $SU(2)_R$ symmetry gauge field, so that some of the susy is preserved.)
Most of what Nekrasov did using his cohomological framework can be seen directly in this higher-dimensional setup. See e.g. Sec. 3.2 of my review article in preparation, available here.


text:
Q: android.app.RemoteServiceException: Bad notification posted from package I have an app which creates notifications every so often. It is in use by a few hundred thousand users. Typically I have no issues with notifications but this one user is getting the exception I've added below.
All users with this exception have a TCL phone with Android 4.4.4
Anyone have any idea what might be causing this?
Thanks.
Fatal Exception: android.app.RemoteServiceException: Bad notification posted from package mypackage: Couldn't expand RemoteViews for: StatusBarNotification(pkg=mypackage user=UserHandle{0} id=74219 tag=null score=10: Notification(pri=1 contentView=mypackage/0x7f0400a2 vibrate=null sound=null defaults=0x0 flags=0x62 kind=[null]))
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1366)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:136)
       at android.app.ActivityThread.main(ActivityThread.java:5095)
       at java.lang.reflect.Method.invokeNative(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:515)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
       at dalvik.system.NativeStart.main(NativeStart.java)

Edit: Layouts. I have two layouts, one big and one small.
Small:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/notification"
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@color/white"
              android:orientation="horizontal"
    >
    <ImageView
        android:id="@+id/image"
        android:layout_width="@dimen/notification_image_size_small"
        android:layout_height="@dimen/notification_image_size_small"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="12dp"
        android:layout_marginRight="12dp"
        android:scaleType="centerCrop"
        android:src="@drawable/drawable0"/>
    <TextView
        android:id="@+id/title"
        style="@style/title_style"
        android:text="title"></TextView>
    <ImageView
        android:id="@+id/button1"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_gravity="center"
        android:background="@drawable/ripple"
        android:clickable="true"
        android:scaleType="center"
        android:src="@drawable/drawable1"
        android:text="@string/text1"
        android:contentDescription="@string/test1"
        />
    <ImageView
        android:id="@+id/button2"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_gravity="center"
        android:background="@drawable/ripple"
        android:clickable="true"
        android:scaleType="center"
        android:src="@drawable/drawble2"
        android:text="@string/text2"
        android:contentDescription="@string/test2"
        />
    <ImageView
        android:text="@string/text3"
        android:contentDescription="@string/text3"
        android:id="@+id/button3"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_gravity="center"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:background="@drawable/ripple"
        android:clickable="true"
        android:scaleType="center"
        android:src="@drawable/drawable3"></ImageView>
</LinearLayout>

Big:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/notification"
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="110dp"
              android:background="@color/white"
              android:clickable="true"
              android:focusable="true"
              android:foreground="@drawable/ripple_rect"
              android:orientation="horizontal">
    <ImageView
        android:id="@+id/image"
        android:layout_width="@dimen/notification_image_size_big"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:scaleType="centerCrop"
        android:src="@drawable/drawable0_big"
        />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="32dp"
            android:layout_marginLeft="12dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="8dp"
            android:orientation="horizontal">
            <TextView
                android:id="@+id/title"
                android:text="title"
                style="@style/title_style"></TextView>
            <ImageView
                android:id="@+id/button1"
                android:layout_width="32dp"
                android:layout_height="32dp"
                android:layout_gravity="center_vertical"
                android:background="@drawable/ripple"
                android:clickable="true"
                android:scaleType="center"
                android:src="@drawable/drawable1"/>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/buttons"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:layout_marginTop="12dp"
            android:orientation="horizontal"
            >
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:orientation="horizontal"></LinearLayout>
            <ImageView
                android:id="@+id/button2"
                style="@style/buttons_style"
                android:src="@drawable/drawable2"
                android:text="@string/text2"
                android:contentDescription="@string/text2"
                />
            <LinearLayout
                android:id="@+id/spacer1"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:orientation="horizontal"></LinearLayout>
            <ImageView
                android:id="@+id/button3"
                style="@style/buttons_style"
                android:src="@drawable/drawable3"
                android:text="@string/text3"
                android:contentDescription="@string/text3"
                />
            <LinearLayout
                android:id="@+id/spacer2"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:orientation="horizontal"></LinearLayout>
            <ImageView
                android:id="@+id/button4"
                style="@style/buttons_style"
                android:src="@drawable/drawable4"
                android:text="@string/text4"
                android:contentDescription="@string/text4"
                />
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:orientation="horizontal"></LinearLayout>
            <ImageView
                android:id="@+id/button5"
                style="@style/buttons_style"
                android:scaleX="-1"
                android:src="@drawable/drawable5"
                android:text="@string/text5"
                android:contentDescription="@string/text5"
                />
            <LinearLayout
                android:id="@+id/spacers3"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:orientation="horizontal"></LinearLayout>
            <ImageView
                android:id="@+id/button6"
                style="@style/buttons_style"
                android:src="@drawable/drawable6"
                android:text="@string/text6"
                android:contentDescription="@string/text6"
                />
            <LinearLayout
                android:id="@+id/spacer4"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:orientation="horizontal"></LinearLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

While adding that layout I noticed android:scaleX="-1" and I have no idea why I had that there so I'm going to send the user an apk without that.  I have that there because it is the same image facing the other way. I'll see if I can replace it just in case that's the issue.
Edit: Sent the user a new version without android:scaleX="-1" and the crash still happened.
Edit: Adding the ripple drawables. Since the user is on 4.4 they would get these ones:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/color_primary_translucent" android:state_focused="true"/>
    <item android:drawable="@color/color_primary_light_translucent" android:state_pressed="true"/>
    <item android:drawable="@android:color/transparent"/>
</selector>

and
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/color_primary_translucent" android:state_focused="true"/>
    <item android:drawable="@color/color_primary_light_translucent" android:state_pressed="true"/>
    <item android:drawable="@android:color/transparent"/>
</selector>

A: I would suggest remove all the background ripple and foreground ripples from the layout and to keep the ripple in the notification.
In your notifications layout.
<ImageButton
            android:id="@+id/notification_base_previous"
            style="@style/NotificationAction.Previous"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

Now declare the style in the manifest.
This is for your individual buttons.
 <style name="NotificationAction.Previous" parent="@style/NotificationAction">
        <item name="android:src">@drawable/btn_playback_previous_light</item>
    </style>

This should be the parent of style.
<style name="NotificationAction">
        <item name="android:layout_width">@dimen/notification_action_width</item>
        <item name="android:layout_height">@dimen/notification_action_height</item>
        <item name="android:gravity">center|right</item>
        <item name="android:scaleType">fitCenter</item>
        <item name="android:padding">@dimen/notification_action_padding</item>
        <item name="android:background">?android:selectableItemBackground</item>
    </style>

It works this all the devices I have used so far. Please have a look.


text:
Q: How can I create multiple rows using semantic markup in Bootstrap 3? I have eight "simple" panels that I want to layout using Bootstrap 3. The markup is

Panel 1

This is panel 1 (and a random piece of text)

Panel 2

This is panel 2 (and a random piece of text)

    // ...and so on - up to panel 8.

I'd like two two rows of four in md column size and four rows of two in sm column size.
I'm using this following LESS rules:
.dashboard {
    .make-row();
}

.dashboard-panel {
    .make-sm-column(6);
    .make-md-column(3);
}

However, this creates problems in that the panels don't always form two rows of four. It depends on how much content is in the respective panels. If one of the panels is relatively short, a third row gets created with other panels until the short panels.
I thought that, as I'm filling up all 12 slots with the first four panels, the next four would move cleanly to the second row.
What am I doing wrong? And how can I make this work while retaining the semantic markup?

A: The problem you describe is documented here: http://getbootstrap.com/css/#grid-responsive-resets
The grid-responsive-resets add additional div's to your html which will break your semantic markup.
I have never tried to append (for example with :after) the grid-responsive-resets properties conditional. With conditional i mean every fourth element for the md-grid. Theoretical i think i should be possible, we should ask @ScottS maybe :)
Something like this (won't work, example)
.col-md-3:nth-child(4n+0):after
{
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

Alternative is to give all your panels the same height, which don't work if you don't know the max possible height in the case of dynamic content. If you don't know the max height you could fix this with javascript / jQuery. (see: https://stackoverflow.com/a/19777087/1596547)


text:
Q: I try to use module to add my own methods to Array class (but not override it) class Check
  include TestParser
  # so on
end

and module structure:
module TestParser
  class Array
    def parse_test
      # method
    end
  end
end

What I want to achieve is so that every array in file check.rb can be called by parse_test method.
Where I got it wrong? (throws undefined method error)

A: What you're looking for is Ruby 2.0's refinements. Note that this feature is experimental:
module TestParser
  refine Array do
    def parse_test
      42
    end
  end
end

using TestParser  # This applies only to the current file

class Check
  [].parse_test  #=> 42
end

You could also inherit from Array and add your method:
class TestParser < Array
  def parse_test
    42
  end
end

arr = TestParser.new
arr.is_a? Array  #=> true
arr.parse_test   #=> 42

However, I strongly discourage doing either of these things. It would be better to make an object that encapsulates an Array and only provides the methods you need:
class TestParser
  def initialize array = []
    @array = array
  end

  def parse_test
    # do stuff to @array
  end
end

Finally, for why what you have does not work:
module TestParser
  class Array
    def parse_test; end
  end
end

creates two things: a module TestParser with no methods and a class TestParser::Array with one method (parse_test). Since TestParser has no methods, including it into another Module/Class has no effect on the methods available. Including TestParser does not do anything with TestParser::Array.

A: You've defined a new class TestParser::Array containing the parse_test method; you have not modified the Array class.
You also may be confusing modules and inclusion.
If your goal is to add the method parse_test to arrays in your Ruby program, you can put this in a file called test_parser.rb, with no module declaration:
class Array
  def parse_test
    # method
  end
end

But that will modify the base Array class, which you said you didn't want to do. Furthermore, it will make that modification as soon as the file is required.  No inclusion is necessary.
Outside of a currently-experimental Ruby 2.0 feature called refinements, there's no way to localize those sorts of modifications to base classes (which is called "monkey patching").
If you want arrays to behave differently but only within your code, your best bet is to define your own class that extends Array (that is, make it a container class wrapping and delegating to a regular Array, or a subclass if you feel you must).

A:
What I want to achieve is so that every array in file check.rb can be
  called by parse_test method.

You just have to know how to create the array:
module TestParser
  class Array
    def parse_test
      puts 'hello'
    end
  end

end

class Check
  include TestParser

  Array.new.parse_test

  def do_stuff
    Array.new.parse_test
  end
end

Check.new.do_stuff

Check::Array.new.parse_test

--output:--
hello
hello
hello

Of course, the TestParser::Array class has none of the methods found in the Array class:
module TestParser
  class Array
    def parse_test
      puts 'hello'
    end
  end

end

TestParser::Array.new.parse_test
TestParser::Array.new.size

--output:--
hello
1.rb:11:in `<main>': undefined method `size' for #<TestParser::Array:0x00000101141700> (NoMethodError)

That's because you created a new Array class inside the namespace TestParser--you did not reopen ruby's built in Array class.
Then when you write include TestParser, that is equivalent to doing this:
class AnonymousClass
  class Array
    def parse_test
      puts 'hello'
    end
  end
end

class Check  < AnonymousClass
  Array.new.parse_test
end

And when a constant isn't found in Check, ruby goes up the inheritance chain looking for the constant:
class Parent
  CONST = 10
end

class Child < Parent
  puts CONST
end

--output:--
10

Because the built in Array class is a constant that lives at the very top of the inheritance chain, the Array constant in AnonymousClass hides the ruby built in Array class.  To refer to the ruby built in Array class, you have to write ::Array:
module TestParser
  class Array
    def parse_test
      puts 'hello'
    end
  end

end

class Check
  include TestParser

  p Array
  p ::Array
end

--output:--
TestParser::Array
Array

And for the coup-de-grace*:
module TestParser
  class Array
    def parse_test
      puts 'hello'
    end
  end

end

class Check
  include TestParser
end

puts TestParser::Array.object_id
puts Check::Array.object_id

--output:--
2152779400
2152779400

*coup de grace: a death blow to end the suffering of a severely wounded person or animal


text:
Q: How to split an image dataset into train and test sets? I'm working on 256_ObjectCategories dataset from Caltech. They have organised all the images in 256 categories in different folders. I'm using ImageDataGenerator from Keras to load the dataset but I'm not able to split it into training and testing using the same. How can I do this in a terminal without moving images or changing directories? Any help is appreciated. Thank you. :)

A: This doesn´t seem to be possible out of the box with ImageDataGenerator right now. See this thread: https://github.com/fchollet/keras/issues/5862
User AloshkaD suggests as a workaround that you create an index list with glob: rasterList = glob.glob(os.path.join(path_of_your_image_directory, '*.jpg')), split that programmatically and feed the validation part of that list into the validation_data parameter of fit_generator().


text:
Q: How to clear out search box value in one component when another component is called? I have a search bar in the header of my application , when i search anything and press enter a grid opens in the page .
But when I navigate to a different page , I want the search bar input to be cleared . Currently the searched input stays as it is .
As the search bar is in header component , and the page is another component , I am having issues clearing the search box value on page navigations .
Can anyone help me with the approach ?

A: You can simply listen to your routerEvents and at any navigationEnd you can clear the input value.


text:
Q: Using Regex as delimeter to split a string I want to split the following strings into two substrings.
"somestring(otherstring)"
I came with the following regex split
"somestring(otherstring)".split(/(.+)\((.+)\)/)

but this excludes the following strings, which dont have the substring in braces..
"somestring"
how can change the regex so that, even if there is not substring of the pattern "(otherstring)", it still generates the first substring as output.
thanks a lot in advance!

A: >> "somestring(otherstring)".split(/[()]/)
=> ["somestring", "otherstring"]
>> "somestring".split(/[()]/)
=> ["somestring"]

A: Try using something like this as the regex: /([^\(\)]+)(?:\((.+)\))?/.


text:
Q: My Spider crashes whenever I schedule to production on Heroku My spider is working both on the local machine and on the Heroku platform, however, I wish to schedule the spider so it works according to the time given through cron expression.
This is my periodic_requests.py file:
from pytz import timezone
import requests, pytz
from apscheduler.schedulers.twisted import TwistedScheduler
from twisted.internet import reactor

def send_request():
    requests.post(
        url="https://datacrawlapp.herokuapp.com/schedule.json",
        data={"project":"datahubsitecrawler",
        "spider":"datahubcrawlapp",
        "data_url": "https://drive.google.com/file/d/1zBfsWZdoFzoAq6ZELfw-tvvBFcVmCMI7/view?usp=sharing"
    }
    )

    if __name__ == '__main__':
        scheduler = TwistedScheduler(timezone=pytz.utc),
        scheduler.add_job(send_request, 'cron', day_of_week='mon-sun', hour='19', minute='47')
        scheduler.start()

        try:
            reactor.run() # the script will block here until the crawling is finished
        except (KeyboardInterrupt, SystemExit):
            pass

Procfile:
web: scrapyd
clock: python periodic_requests

I get error:
 File "/app/.heroku/python/lib/python3.8/site-packages/scrapyd/website.py", line 212,
in prep_tab_finished
2022-02-07T08:58:06.697647+00:00 app[web.1]: return '\n'.join(
2022-02-07T08:58:06.697647+00:00 app[web.1]: builtins.TypeError: 'NoneType' object is not iterable:

and then it crashes as shown below:
2022-02-07T08:48:32.411005+00:00 heroku[web.1]: State changed from starting to up
2022-02-07T08:48:32.611649+00:00 heroku[clock.1]: Process exited with status 0
2022-02-07T08:48:32.721748+00:00 heroku[clock.1]: State changed from up to crashed
2022-02-07T08:48:32.742567+00:00 heroku[clock.1]: State changed from crashed to starting
2022-02-07T08:48:41.000000+00:00 app[api]: Build succeeded
2022-02-07T08:48:42.473990+00:00 heroku[clock.1]: Starting process with command `python periodic_requests.py`
2022-02-07T08:48:43.195961+00:00 heroku[clock.1]: State changed from starting to up
2022-02-07T08:48:44.920927+00:00 heroku[clock.1]: Process exited with status 0
2022-02-07T08:48:44.984024+00:00 heroku[clock.1]: State changed from up to crashed

Will appreciate your help!


text:
Q: Misunderstanding the integration of MATLAB everybody!
Could you, guys, please explain why the answer for the exact integration
quad( @(x)x.^3-2.*x,0,2)

is
-2.220446049250313e-016

istead of a zero, just like it should be?

A: The quad function computes the integral numerically, not symbolically.
Even though most integration methods will compute the integral of a 3rd degree polynomial 'exactly' , that is only true if all the calculations are done exactly as well. When doing the calculation on a computer, round-off error still is a factor.


text:
Q: Converting a file to Base64 to embed in XML file (to show as and attachment in InfoPath) If I look inside of an MS Infopath XML file, the atttachments appear to be look something like: stu2zAQvBfIPwi8BhadFCiKwnIOSXNMA8QFeqWptUWYr5Lr1P77rqg4MQLHimoCzUWURHJmdpaPnVxtjC4eI
I'm told this is Base64.
However, if I go to https://www.browserling.com/tools/file-to-base64 and convert a PDF file, take the result and throw it into an XML tag meant for attachments and then open that file using InfoPath, nothing is displayed where I'd expect to see a file icon. There are no errors, but clearly something is wrong.
What am I missing? What else besides encoding the file do I need to do in order for InfoPath to recognize it?

A: Probably because when you convert it into the normal, the data is in PDF format and it may not be able to interpret it. Do you have some programming knowledge? I was thinking to read the XML using a C# program, extract the BASE64 data, decode it and write to a file and you should be able to open it as a PDF.


text:
Q: BTST not working as expected to determine if number is odd I'm confused as to why this code isn't working as expected. From what I understand BTST.L #1,D1 checks if the last bit of the value stored in D1 is 1, in which case the value in D1 would be odd and the program would branch to ADDSUM.
It seems to work correctly with some values (9*2, 8*2 or 10*10), but fails when I try and do others (11*11 gives me 110, same as 10*11). I believe it is whenever the multiplier is odd.
START:
              MOVE.W #MULTIPLICAND,D0  ; Set D0 equal to the multiplicand
              MOVE.W #MULTIPLIER,D1    ; Set D1 equal to the multiplier
              MOVE.L #00000000,D2      ; Clear D2 as it will be used to store the product

LOOP          BTST.L #1,D1     ; Check if D1 is odd
              BEQ ADDSUM      ; If so branch to ADDSUM

RETURN        CMP #$01,D1      ; Check if the multiplier is equal to 1
              BEQ END         ; If so, terminate the loop

              ASL #1,D0       ; Multiply the multiplicand by 2
              ASR #1,D1       ; Divide the multiplier by two

              BRA LOOP        ; Branch back to the top of the loop

ADDSUM        ADD.W D0,D2     ; Add D0 to D2
              BRA RETURN      ; After adding, we have to branch back to where we were in the loop

END           SIMHALT

A: I figured it out. I figured I'd post it as an answer just in case anybody else ever stumbles upon this.
It turns out I didn't understand how the BTST.L #1,D1 instruction works. I thought the code in the original example was supposed to be checking if the last bit in D1 was equal to 1. In reality, BTST works by setting the Z condition code flag to 1 when the bit being tested is 0. The #1 in the instruction was specifying that it was testing the second bit from the right.
In order to determine even/odd, the rightmost bit is the one that has to be tested. I fixed my code by changing it to have the following:
LOOP          BTST.L #0,D1    ; Check if D1 is even (Z-flag will be set to 1 if bit is zero)
              BNE ADDSUM      ; BNE will branch to ADDSUM if Z-flag is not set (meaning D1 is odd)

Hopefully this is able to help somebody else who is having the same problem.


text:
Q: Is there a way to log automatically the start and end of function definition in PHP? I want a way to log the beginning and end of the function call without explicitly making a call to a method in log object.
I know we can use xdebug to trace the flow, but I have a requirement where I have to make the functions call to be written in the log file without (having code) calling $logObj->info('Function call');.
For ex:
<?php

class something
{
    public function test()
    {
        echo "Test.";
    }
}

$some = new something();
$some->test();

?>

Now, I want to see the following entries in my out.log:
2010-08-03T09:06:15+02:00 ERR (1): Entering something::test()
...
...
2010-08-03T09:06:15+02:00 ERR (1): Leaving something::test()

A: You can create a wrapper class for your object.
E.g.:
class LoggingSomethingWrapper {
  protected $something;
  protected $logger;
  function __construct($something, $logger) {
    $this->something = $something;
    $this->logger = $logger;
  }
  public function test() {
    $this->logger->logBefore(__FUNCTION__);
    $result = $this->something->test();
    $this->logger->logAfter(__FUNCTION__);
    return $result;
  }
}

A: What you need is AOP ( http://en.wikipedia.org/wiki/Aspect-oriented_programming )
But PHP doesn't support AOP natively (there are some extensions for it, but I don't know how good they are).
As troelskn mentioned, you should create a wrapper class (untested):
class LogWrapper
{
    protected $object;

    protected $logger;

    public function __construct($object, $logger)
    {
        $this->object = $object;
        $this->logger = $logger;
    }

    public function __call($name, $arguments)
    {
        //log
        $returnValue = call_user_func_array(array($this->object, $name), $arguments);
        //log

        return $returnValue;
    }
}

A: You can implement functions in obcject named as func_xxx. And do a magic method call() with get a argument xxx, do start logging, calling $this->func$xxx() and do finish logging


text:
Q: Get Release Version Properties Visual Studio 2019 I am trying to get the release version from properties in visual studio 2019:

click to enlarge
I am trying to get what is highlighted in yellow. How can I do this in VS2019?

A: Try using:
Assembly.GetExecutingAssembly().GetName().Version.ToString()


text:
Q: Handsontable formulas at column level and syncing we have a handsontable based sheet .. built on top of Reactjs+Immutablejs actually.
This spreadsheet has a simple usecase :

*

*compute some values when you are editing/adding the sheet.

*sync the data to server

*when you get new data from server - dont compute,
just take the data as it is . Server is authoritative.

Currently, I'm doing this by hardcoded javascript functions in afterChange hook. Because I'm simply not able to figure out how to do these three things using Handsontable rulejs.
Q1. a rulejs formula is of type "=A1+B1". I have 500 rows in my sheet  - how can I create these formulas on a column level ? It seems I have to hand create 500 formulas for a single column.
Q2. How do I stop formula from being applied when I get data from server ? Or rather, I dont care if formulas are applied, I still want to use the data from the server. Is there a hook for afterFormulaComputed or something that I can use to override ?
Q3. silly question - how do I get the computed value of a cell and not the formula itself. I found "hot.plugin.helper.cellValue" on Stackoverflow somewhere, but was not able to figure it out. Especially because my code uses row and column ids to do stuff rather than "A1" or "C1"
any help would be highly appreciated !


text:
Q: Where would I place a search function in this javascript? I think I'm really close with this, but I'm having trouble placing the search function in my existing code.
I want it so that if the word that's searched corrolates to a last_name then the function displays the entire related array. Without the search function, the code works fine as long as I specify the string in the JS. I.e.
return item.last_name == "Simpson";

will display
{"username":"esimpson7n","first_name":"Elizabeth","last_name":"Simpson","gender":"Female","sexuality":"Future-proofed solution-oriented definition","language":"Malay"},
This is great, but I need the user to type in a name and the appropriate array to display.
What I have so far:-
<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>

<input type="search" id="mySearch" /> <button onclick="myFunction()">Try it</button>

Am I calling the right function with onclick? I'm not even sure if .value is the right method for this job. When checking the API it seemed like the most relevant.
Let me know if more detail is needed.
JSfiddle

A: This solution does not allow for partial matches or for case insensitivity. Hope this helps :)

var users = [{"username":"nphillips7m","first_name":"Nicole","last_name":"Phillips","email":"nphillips7m@ebay.co.uk","gender":"Female","sexuality":"Networked static concept","language":"Gagauz"},
{"username":"esimpson7n","first_name":"Elizabeth","last_name":"Simpson","gender":"Female","sexuality":"Future-proofed solution-oriented definition","language":"Malay"},
{"username":"llawrence7o","first_name":"Lillian","last_name":"Lawrence","email":"llawrence7o@technorati.com","gender":"Female","sexuality":"Re-contextualized demand-driven middleware","language":"Tetum"}];

 function myFunction() {
  var searchValue = document.getElementById("mySearch").value;
   for(var i = 0; i < users.length; i++){
     if(users[i]['last_name'] === searchValue){
       document.getElementById("return").innerHTML = JSON.stringify(users[i]);
       return;
     }
   }
}
<input type="search" id="mySearch" /> <button onclick="myFunction()">Try it</button>

A: Well, you just have to define your myFunction. Basically create a function with what you already have so it executes when the button is clicked.
//this could be outside because is like the data base
var users = [{"username":"nphillips7m","first_name":"Nicole","last_name":"Phillips","email":"nphillips7m@ebay.co.uk","gender":"Female","sexuality":"Networked static concept","language":"Gagauz"},{"username":"esimpson7n","first_name":"Elizabeth","last_name":"Simpson","gender":"Female","sexuality":"Future-proofed solution-oriented definition","language":"Malay"},{"username":"llawrence7o","first_name":"Lillian","last_name":"Lawrence","email":"llawrence7o@technorati.com","gender":"Female","sexuality":"Re-contextualized demand-driven middleware","language":"Tetum"}]

function myFunction() { //TODO rename it to something more descriptive
    var foundUser = users.find(callback);
    document.getElementById("return").innerHTML = JSON.stringify(foundUser );
}

//this goes outside because it's other function
function callback(item){
    var x = document.getElementById("mySeach").value;
    return item.last_name == x;
}

You could also invoke the funcition on the input event so it searchs as the user types.

A: Could do something like this. I was having some issues with your fiddle since it myFunction isn't defined before. I modified as such:

<input type="search" id="mySearch" /> <button onclick="myFunction()">Try it</button>

JSFiddle


text:
Q: What options do I have for checking if an IntentService is already running? I have an AlarmService that wakes up every 15 minutes and fires off an IntentService.  However, I would like to make sure that if a previously started IS is already running, that the AlarmService doesn't try to start another one (the IS is dealing with files and there would be an odd race condition if a second version tried to act on the same files).
What's the best way to poll the system to see if an instance of my IS is already running and just skip the current iteration of the AlarmService cron?

A:
that the AlarmService doesn't try to start another one (the IS is dealing with files and there would be an odd race condition if a second version tried to act on the same files).

There will be no race condition. First, there will only ever be one instance of the IntentService. Second, the IntentService will only process one Intent at a time in onHandleIntent().

What's the best way to poll the system to see if an instance of my IS is already running and just skip the current iteration of the AlarmService cron?

Don't do it that way. In your IntentService, track the last time you did work in a data member. If, in onHandleIntent(), that value is null, it's your first pass through in a while, and so you probably want to go ahead and do the work. If the value is not null, compare it to the current time, and if it's too soon, just return from onHandleIntent().


text:
Q: How to find WPF TextBox's changed text? Suppose we inherit from WPF TextBox and then try to get text changes through overriding OnTextChanged.
Then we would notice when changes occurred, but the only information that we would have is:

*

*Offset that this change occurred

*Removed Length

*Added Length

Can we get the accurate added text by using,
Text.Substring(Change.Offset, Change.AddedLength)

in OnTextChanged?
Text Change occurs in different conditions (such as user input, pasting text, or setting Text property in-code). Is there any possibility of conflicting changes coming into e.Changes?
Is this approach a trust way? If answer is No, Is there any other standard way(s) to get accurate changed text?

A: For a TextBox, this event occurs when its text changes; for a RichTextBox, this event occurs when any content or formatting changes (for example, images, table, or background color).

*

*Can we get the accurate added text by using ... ?

Yes, you will always get accurate text in case of TextBox. You can make use of e.UndoAction to check for addition/deletion of text.
Read documentation here.

*Is there any possibility of conflicting changes coming into e.Changes?

There won't be conflicting changes.
In general, the following will always be true:

*

*The changes that occur result in the document being in a valid state.
     The collection is ordered consecutively, related to where the change    occurred in the control. For example, a TextChange object
  that    represents a change at position 2 is before a TextChange
  object that    represents a change at position 10.

*Two TextChange objects do not represent an overlapping area. The       value of Offset plus the value of AddedLength of one TextChange
  object is always less than or equal to the value of Offset of the
  next TextChange object in the collection. Likewise, the value of
  Offset plus the value of RemovedLength of one TextChange object is
  always less than or equal to the value of Offset of the next
  TextChange object in the collection.

*The collection reflects whatever changes occurred, even if there       seems to be no net change. In the preceding example, neither the
  first or fourth change results in a net change, because each simply
  removed and re-added the  and  symbols, respectively. But
  the symbols were actually removed and added, so they are included in
  the collection.

More can be read here.

A: I made a short test program with one TextBox and one Label and I could not find the problems you describe. If I implement an TextChanged event for the TextBox like the following it works even if I paste something.The checking for null is needed because if the Textbox has an initial value the Initilialize method will trigger the change event before the label is created.
 private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        TextBox tbSource = (sender as TextBox);

        if (lblOutput == null)
            return;

        lblOutput.Content = tbSource.Text;

    }


text:
Q: Laravel multiple workers and being rate limited I have an application which has a queue with multiple workers. The workers are scaled based on the number of jobs in the queue. One of the main point of the jobs being processed by the workers is to make API calls to an external service to retrieve some data. The external service implements api rate limiting at a rate of 2 calls / second with a leaky bucket algorithm (https://en.wikipedia.org/wiki/Leaky_bucket). My api calls are not towards a single service but against accounts of the service. So the rate limit only applies when I make multiple api calls towards an account of the service. The rate limit is not shared among different accounts. The number of the jobs that make api calls are in the number of thousands (for one account alone) so the bucket will always get full and I will start to get rate limited.
The problem with something like this is that if my jobs are not observing the rate limit before I hit it, I might try to delay them and place them back in the queue when that happens but because I have multiple workers and thousands of jobs I might end up in an infinite loop of rate limit.
I've thought about using something like memcache or redis to store some kind of information that can be shared among the workers so that before I attempt to make an api call in the job I will stop, delay the job and place it back in the queue so it won't raise the rate limit. The problem with this approach is that every time I would do something like that I would increase the number of attempts of the job. I have a max number of attempts per job. I also realized that the number of attempts cannot be change in any way with the Laravel worker and I am fine with that, I believe that makes the worker more stable and predictable. The only option to reset that attempts number is to delete the job and redispatch it as a new job (but this feels very messy).
If anyone has ever came across an issue like this, would you be willing to share how would the queue implementation look like in this case? Should workers share state between them (this feels wrong)?
NOTE: I don't believe that sleeping a worker is a good way of solving the rate limit due to the fact that I might be making api calls to different accounts of the service (based on what jobs are next in the queue) and therefore if the worker sleeps for one account while it could service another this would feel a lost time.
Thanks

A: Sounds like you are using the Shopify API?
I managed to use this in Laravel 5.5 to get this working. From the documentation:
Redis::throttle('key')->allow(2)->every(1)->then(function () {
    // Job logic...
}, function () {
    // Could not obtain lock...

    return $this->release(10);
});

https://laravel.com/docs/5.5/queues#rate-limiting


text:
Q: STS freeze during build workspace on startup I am running Spring STS 3.4.0 on Mac OS 10.8 with Tomcat 7, maven 3.1.1 installed, but almost everytime I start STS, try to open any project it freezes while building workspace at exactly 42%. By checking the log file, I found the following:
Can someone please tell me what is wrong and how I can possibly fix this problem?
Note: I don't have any firewall
Thanks

!ENTRY org.eclipse.m2e.logback.appender 2 0 2014-02-09 16:04:41.657
  !MESSAGE Failed to retrieve plugin descriptor for
  org.apache.maven.plugins:maven-eclipse-plugin:2.9: Plugin
  org.apache.maven.plugins:maven-eclipse-plugin:2.9 or one of its
  dependencies could not be resolved: Failed to read artifact descriptor
  for org.apache.maven.plugins:maven-eclipse-plugin:jar:2.9
!ENTRY org.eclipse.m2e.logback.appender 2 0 2014-02-09 16:04:41.695
  !MESSAGE Failed to retrieve plugin descriptor for
  org.codehaus.mojo:exec-maven-plugin:1.2.1: Plugin
  org.codehaus.mojo:exec-maven-plugin:1.2.1 or one of its dependencies
  could not be resolved: Failed to read artifact descriptor for
  org.codehaus.mojo:exec-maven-plugin:jar:1.2.1
!ENTRY org.eclipse.m2e.logback.appender 2 0 2014-02-09 16:04:42.178
  !MESSAGE Failed to retrieve plugin descriptor for
  org.apache.maven.plugins:maven-eclipse-plugin:2.9: Plugin
  org.apache.maven.plugins:maven-eclipse-plugin:2.9 or one of its
  dependencies could not be resolved: Failed to read artifact descriptor
  for org.apache.maven.plugins:maven-eclipse-plugin:jar:2.9
!ENTRY org.eclipse.m2e.logback.appender 2 0 2014-02-09 16:04:42.194
  !MESSAGE Failed to retrieve plugin descriptor for
  org.codehaus.mojo:exec-maven-plugin:1.2.1: Plugin
  org.codehaus.mojo:exec-maven-plugin:1.2.1 or one of its dependencies
  could not be resolved: Failed to read artifact descriptor for
  org.codehaus.mojo:exec-maven-plugin:jar:1.2.1
!ENTRY org.eclipse.m2e.logback.appender 2 0 2014-02-09 16:04:44.447
  !MESSAGE Using platform encoding (US-ASCII actually) to copy filtered
  resources, i.e. build is platform dependent!
!ENTRY org.eclipse.m2e.logback.appender 2 0 2014-02-09 16:04:44.525
  !MESSAGE Using platform encoding (US-ASCII actually) to copy filtered
  resources, i.e. build is platform dependent! !SESSION 2014-02-09
  16:21:47.448 -----------------------------------------------
  eclipse.buildId=3.4.0.201310051614-RELEASE-e43 java.version=1.7.0_45
  java.vendor=Oracle Corporation BootLoader constants: OS=macosx,
  ARCH=x86_64, WS=cocoa, NL=en_US Framework arguments:  -product
  org.springsource.sts.ide -keyring /Users/mkm/.eclipse_keyring
  -showlocation Command-line arguments:  -os macosx -ws cocoa -arch x86_64 -product org.springsource.sts.ide -keyring
  /Users/mkm/.eclipse_keyring -showlocation
!ENTRY org.eclipse.jface 2 0 2014-02-09 16:22:07.157 !MESSAGE
  Keybinding conflicts occurred.  They may interfere with normal
  accelerator operation. !SUBENTRY 1 org.eclipse.jface 2 0 2014-02-09
  16:22:07.157 !MESSAGE A conflict occurred for COMMAND+SHIFT+F10:
  Binding(COMMAND+SHIFT+F10,
    ParameterizedCommand(Command(org.jboss.tools.common.ui.RegisterAsService,Register
  As Service,       Adds class name to META-INF/services/%serviceType% file
  after service type is selected in the dialog from types extended and
  implemented by the class.,
        Category(org.eclipse.ui.category.file,File,null,true),
        org.eclipse.ui.internal.WorkbenchHandlerServiceHandler@241a8926,
        ,,true),null),  org.eclipse.ui.defaultAcceleratorConfiguration,
    org.eclipse.ui.contexts.window,,,system) Binding(COMMAND+SHIFT+F10,
    ParameterizedCommand(Command(org.eclipse.ui.window.showSystemMenu,Show
  System Menu,      Show the system menu,
        Category(org.eclipse.ui.category.window,Window,null,true),
        org.eclipse.ui.internal.WorkbenchHandlerServiceHandler@4a22304e,
        ,,true),null),  org.eclipse.ui.defaultAcceleratorConfiguration,
    org.eclipse.ui.contexts.window,,cocoa,system)


text:
Q: How to configure Commons VFS to automatically detect gz files Our application is using Commons VFS to read various types of files. We use the automatic file type detection VFS provides, via its file extension mapping.
The problem: VFS misclassifies gz files (ie. files whose name ends in .gz) as regular files, rather than as GZIP files. This prevents us from using VFS to read the (decompressed) content of gz files, without some special-case manually hack-arounding.
I've traced the problem to org.apache.commons.vfs2.impl.FileContentInfoFilenameFactory.create(), which calls
FileNameMap fileNameMap = URLConnection.getFileNameMap();
contentType = fileNameMap.getContentTypeFor(name);

This loads the file content-types.properties from the current Java installation. This file (on Windows, at least) contains this mapping:
application/octet-stream: \
    description=Generic Binary Stream;\
    file_extensions=.saveme,.dump,.hqx,.arc,.obj,.lib,.bin,.exe,.zip,.gz

According to the source code, org.apache.commons.vfs2.impl.FileTypeMap allows this mapping to take precedence over the file extension map with which VFS was configured.
Can anyone think of a way of either (a) extending a class or two of VFS to work around this problem or (b) configuring VFS and/or Java itself so that VFS correctly classifies gz files?

A: Create a class like the following, to override the getContentTypeFor method of FileNameMap and exclude the troublesome application/octet-stream entry:
public static class MyFileNameMap implements FileNameMap
{
    private FileNameMap delegate = URLConnection.getFileNameMap();

    @Override
    public String getContentTypeFor( String fileName )
    {
        String contentType = delegate.getContentTypeFor( fileName );
        if( "application/octet-stream".equals( contentType ) )
        {
            // Sun's java classifies zip and gzip as application/octet-stream,
            // which VFS then uses, instead of looking at its extension
            // map for a more specific mime type
            return null;
        }
        return contentType;
    }
}

Install this new class via:
URLConnection.setFileNameMap( new MyFileNameMap() );

Now when you call FileSystemManager.resolveFile(), VFS will choose the correct file type for gz files by falling back to its extensions map.
Note: This is a global change to the current JVM, so be careful if you are using any other code that needs this mime type entry for things like .exe files.