text:
Q: Getting Text from Within Nested Elements in HTML Text Using BeautifulSoup in Python I'm trying to extract the Teams playing each day and the Active & Inactive players in each team's lineup. The URL for the page I'm trying to scrape is: https://stats.nba.com/lineups/. I've been using BeautifulSoup to try to get this data, and have tried a few methods to get to it, but I can't seem to extract anything within the

.
I want to get the teams in each matchup within each

,
and each player within the

.
So within the sample of html code below, I want to get the text for MEM, CHA, J. Valanciunas, and J. Crowder, and eventually do this for each player for each team.

        MEM
        vs
        CHA
        Final
        Live

    MEM

Active List

        C
        J. Valanciunas

        SF
        J. Crowder

I tried by doing the following, among other methods, to no avail:
gamesSource = urllib.request.urlopen('https://stats.nba.com/lineups/').read()
gamesSoup = bs.BeautifulSoup(gamesSource,'html.parser')

teams = gamesSoup.find_all("span",{"class":"lineups-game__teams-name"})

All that ever gets returned is an empty list, and when I try to get a specific 'span' line, all that gets returned is 'None'.
Let me know what's going wrong, and what I can do to access the information I'm trying to get.
Thanks.
Sample of HTML Code

A: Unfortunately, you cannot do that with urllib. The website in question uses js to call apis to populate the data after the initial page load.
The urllib is only able to download the initial file that is served by the server but is unable to deal with any subsequent actions that the file might be executing after it's initial render in the browser.
Thus the teams = gamesSoup.find_all("span",{"class":"lineups-game__teams-name"}) call returns empty as the actual HTML you download through urllib.request (as seen here) does not yet have the lineups-game__teams-name elements populated yet.
You can try examining the api calls that the website is making after the initial load (check network tab) and see if you can find where the data that you want is coming from. If you are lucky, you might be able to get to that data through the api call. As the webpage will be making lots of external requests (for images and other media) you can tick XHR to only show you remote API calls in the network list.
If you cannot find the api or if it is blocked from external calls, you can alternatively try js enabled python browsers (i.e. selenium) to download the page that includes and executes the JS code.

A: Piggy-backing off the already stated, since this page is generated via api/js calls, you will need to use a different scraping library. I usually go to Selenium. The code below will pull all the teams and rosters and put them together. There may be some quirks in this code but I think it will get down the road in the right direction:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from datetime import date

desired_link = 'https://stats.nba.com/lineups/'

fire_opts = webdriver.FirefoxOptions()
fire_opts.add_argument("-headless")
fire_path = 'geckodriver.exe'
driver = webdriver.Firefox(options=fire_opts,executable_path=fire_path)
driver.get(desired_link)

team_names_list = driver.find_elements_by_class_name('lineups-game__team-name')
team_names = []
for name in team_names_list:
    team_names.append(name.text)

starting_lineup_list = driver.find_elements_by_class_name('lineups-game__roster--projected')
starting_lineup = []
for lineup in starting_lineup_list:
    starting_lineup.append(lineup.text)

driver.quit()

for teams, players in zip(team_names,starting_lineup):
    print(teams,players)

This should output all the various teams on the page like so:
DET PG D. Rose
SG L. Kennard
SF T. Snell
PF B. Griffin
C A. Drummond

Could probably be formatted a bit better but you could throw it into a spreadsheet (or whatever you like) to use as you wish...

A: You can get it by call to api. Just dynamically change the date parameter. Here's an example: You'll need to either iterate through the games/indexes or flatten out the json format and reconstruct into a dataframe:
import pandas as pd
import requests

url = 'https://stats.nba.com/js/data/dailylineups/2019/daily_lineups_20191118.json'
jsonData = requests.get(url).json()

print (pd.DataFrame(jsonData['results'][0]['LAC']))

Output:
  firstName  lastName playerId pos rotoId team
0   Patrick  Beverley   201976  PG   3072  LAC
1   Terance      Mann  1629611  SG   4860  LAC
2     Kawhi   Leonard   202695  SF   3195  LAC
3      Paul    George   202331  PF   3114  LAC
4     Ivica     Zubac   162726   C   3888  LAC


text:
Q: The notification destination service region is not valid for the bucket location constraint when creating SQS Event on S3 Bucket via Cloudformation I'm creating a cloudformation template which has to create a private bucket and then add event notification that send a message to a queue every time there's an object created in bucket. When i run the stack i get the following error:
The notification destination service region is not valid for the bucket location constraint (Service: Amazon S3; Status Code: 400; Error Code: InvalidArgument;
This is the template in Json format:
    "AWSTemplateFormatVersion": "2010-09-09",
    "Metadata": {
        "AWS::CloudFormation::Designer": {
            "b4cec5e5-e02b-4489-80ee-9627fd1bbbff": {
                "size": {
                    "width": 60,
                    "height": 60
                },
                "position": {
                    "x": 40,
                    "y": 130
                },
                "z": 0,
                "embeds": [],
                "dependson": [
                    "8e5a0dc7-8982-475c-baa7-41de089beb18"
                ]
            }
        }
    },
    "Resources": {
        "S3B2HKY4": {
            "Type": "AWS::S3::Bucket",
            "Properties": {
                "BucketName": "cloudformation.bucket.sqs",
                "AccessControl": "Private",
                "NotificationConfiguration": {
                    "QueueConfigurations": [
                        {
                            "Event": "s3:ObjectCreated:*",
                            "Queue": "arn:aws:sqs:*:*:cloudformation_queue_s3"
                        }
                    ]
                }
            },
            "Metadata": {
                "AWS::CloudFormation::Designer": {
                    "id": "b4cec5e5-e02b-4489-80ee-9627fd1bbbff"
                }
            }
        }
    }
}```

I have checked similar problems but most of them are for SNS and Lambda function.

A: Your arn:aws:sqs:*:*:cloudformation_queue_s3 should be an absolute value (account and region).
The error is noted because the notifications from S3 event notifications must only be queued to resources in the same region as the bucket.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "=" symbols in GAE TextProperty I'm getting strange additional symbols (=) in text property when adding text there via POST.
For example:
The team is back with an unstoppable fury as they are being chased by the p=  olice, Alonzo and Yuuma. Vinnie, Shorty and Kiro=92s skills will be put to =  the test.
There shouldn't be any of = symbols in that text.
My co de is:
class FileUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
    game_file = self.get_uploads()[1]
    screen_file = self.get_uploads()[0]

    if not users.get_current_user():
        game_file.delete()
        screen_file.delete()
        self.redirect(users.create_login_url("/"))
        return

    game = Game()
    game.title = self.request.get('title')
    game.url_name = self.request.get('url')
    if self.request.get('active') == 'active':
        game.active = True
    else:
        game.active = False
    if self.request.get('featured') == 'featured':
        game.featured = True
    else:
        game.featured = False
    query = Category.gql("WHERE url_name = :url_name", url_name=self.request.get('category'))
    game.category = query.get()
    game.width = int(self.request.get('width'))
    game.height = int(self.request.get('height'))
    game.description = db.Text(self.request.get('desc'))
    game.how_to_play = db.Text(self.request.get('htp'))
    game.game_file = game_file
    game.game_screenshot = screen_file

    db.put(game)

What am i doing wrong?

A: This is a known issue of blobstore handler that is breaking the data encoding.

A: I had the same difficulty.  But, I found a fix.  I'm using Python 2.5.  In my model, I have a TextProperty, hooked up to an html TextArea tag.  Like your situation, in the Dev server, it saved what I entered.  However, in Prod, the DataStore somehow added "= " among others, every time I write the content of textarea over to the textproperty field.
Go here:
http://code.google.com/p/googleappengine/issues/detail?id=2749
Then, scroll down to Comment 21.  The poster of that comment attached a file, named appengine_config.py  Download it, and put it on the root folder of your app.  Then Deploy it to Prod and try it out in Prod.
I did that, and my "= " problem went away.


text:
Q: IIS Configuration with HTTPS I have 2 servers I am setting up. They are both Windows Server 2008 R2. They are both getting IIS setup as web servers. I have set up other servers that we currently have in production. I did the setup the same way, and did the security certificates and keyed them right.
The old servers I setup, as soon as I add the intermediary certificates, and the security certificate, the address https://myurl.com works just fine. This is assuming I have done port forwarding and opened up the firewall on the server.
So my question is did I miss something that causes these other servers to work for http but anything across https gives the browser the message 501 Not Implemented the request method is not implemented by this server.
I have done side by side comparisons of servers, roles, features, and config files to determine what is different. Everything matches, and the website stuff is a copy of the working stuff, the only difference is the url is different.

A: You have to go into the site bindings for each site that you want to enable SSL on and bind https to whatever IP your site runs on.

A: Okay so I finally found my solution. It turns out, in my port forwarding, there is an enabled check-box on enabling the rule you just added, having missed that on this one 80 was some how enabled while 443 wasn't. It turns out every thing was set up, but one little check-box was missed in the router settings.


text:
Q: Label consecutive runs of a sequence in a column with consecutive letters I have the following data:
df <- data.frame(week = rep(seq(1, 4, by=1), times = 3) )

   week
1     1
2     2
3     3
4     4
5     1
6     2
7     3
8     4
9     1
10    2
11    3
12    4

I want to label each consecutive runs of 1:4 with a letter so that the result is this:
   week episode
1     1       a
2     2       a
3     3       a
4     4       a
5     1       b
6     2       b
7     3       b
8     4       b
9     1       c
10    2       c
11    3       c
12    4       c

I have tried the following but this does not distinguish the separate consecutive runs of the sequence 1:4
data.frame(df, episode = letters[cumsum(c(1L, diff(df$week) > 1L))])
   week episode
1     1       a
2     2       a
3     3       a
4     4       a
5     1       a
6     2       a
7     3       a
8     4       a
9     1       a
10    2       a
11    3       a
12    4       a

A: If it is already in a sequence, then just do the cumulative of logical vector (week == 1)
library(dplyr)
df %>%
    mutate(episode =  letters[cumsum(week == 1)])
#   week episode
#1     1       a
#2     2       a
#3     3       a
#4     4       a
#5     1       b
#6     2       b
#7     3       b
#8     4       b
#9     1       c
#10    2       c
#11    3       c
#12    4       c

Or using base R (without any additional packages)
df$episode <- letters[cumsum(df$week == 1)]

A: A different dplyr possibility could be:
df %>%
 mutate(episode = letters[gl(n()/4, 4)])

   week episode
1     1       a
2     2       a
3     3       a
4     4       a
5     1       b
6     2       b
7     3       b
8     4       b
9     1       c
10    2       c
11    3       c
12    4       c

Or the same with base R:
df$episode = letters[gl(length(df$week)/4, 4)]

Or:
df %>%
 mutate(episode = letters[ceiling(seq_along(week)/4)])

Or the same with base R:
df$episode = letters[ceiling(seq_along(df$week)/4)]

A: You can use rowid from the data.table package
library(data.table)
setDT(df)

df[, episode := letters[rowid(week)]]

#     week episode
#  1:    1       a
#  2:    2       a
#  3:    3       a
#  4:    4       a
#  5:    1       b
#  6:    2       b
#  7:    3       b
#  8:    4       b
#  9:    1       c
# 10:    2       c
# 11:    3       c
# 12:    4       c


text:
Q: Bitrise CLI - unsupported protocol scheme error I'm trying to run workflow locally for testing,
So I get the bitrise.yml file from the Bitrise dashboard.
So as in secreats section, I add a .bitrise.secrets.yml file to set the secreat Env as they said
So after running
➜ bitrise run deploy-android

I got this error
Download keystore
Failed to download keystore, error: [Get "[REDACTED]": unsupported protocol scheme ""]
|                                                                              |
+---+---------------------------------------------------------------+----------+
| x | sign-apk@1 (exit code: 1)                                     | 0.72 sec |

bitrise.yml
---
format_version: "11"
default_step_lib_source: "https://github.com/bitrise-io/bitrise-steplib.git"
project_type: react-native
trigger_map:
  - pull_request_source_branch: "*"
    workflow: primary
workflows:
  deploy-android:
    description: >.....
    steps:
      - activate-ssh-key@4:
          run_if: '{{getenv "SSH_RSA_PRIVATE_KEY" | ne ""}}'
      - git-clone@6: {}
      - script@1:
          title: Do anything with Script step
      - yarn@0:
          inputs:
            - command: install
      - install-missing-android-tools@3.0: {}
      - change-android-versioncode-and-versionname@1:
          inputs:
            - build_gradle_path: android/app/build.gradle
            - version_code_offset: "2"
            - new_version_name: '"1.0.1"'
      - android-build@1:
          inputs:
            - project_location: android
            - variant: release
            - module: app
            - build_type: aab
      - sign-apk@1:
          inputs:
            - use_apk_signer: "true"
      - deploy-to-bitrise-io@2: {}
      - google-play-deploy@3:
          inputs:
            - service_account_json_key_path: $SERVICE_ACCOUNT_GOOGLE_PLAY
            - track: production
            - package_name: com.myapp.pos
    envs:
      - opts:
          is_expand: false
        GRADLEW_PATH: android/gradlew
  app:
  envs:
    - BITRISEIO_ANDROID_KEYSTORE_URL: $BITRISEIO_ANDROID_KEYSTORE_URL
    - BITRISEIO_ANDROID_KEYSTORE_PASSWORD: $BITRISEIO_ANDROID_KEYSTORE_PASSWORD
    - BITRISEIO_ANDROID_KEYSTORE_ALIAS: $BITRISEIO_ANDROID_KEYSTORE_ALIAS
    - BITRISEIO_ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD: $BITRISEIO_ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD

    - opts:
        is_expand: false
      PROJECT_LOCATION: android
    - opts:
        is_expand: false
      MODULE: app
    - opts:
        is_expand: false
      VARIANT: release
    - opts:
        is_expand: false
      BITRISE_PROJECT_PATH: ios/orderApp.xcworkspace
    - opts:
        is_expand: false
      BITRISE_SCHEME: orderApp
    - opts:
        is_expand: false
      BITRISE_EXPORT_METHOD: app-store
meta:
  bitrise.io:
    machine_type_id: g2.4core

.bitrise.secrets.yml
envs:
  - BITRISEIO_ANDROID_KEYSTORE_URL: android/app/my-upload-key.keystore
  - BITRISEIO_ANDROID_KEYSTORE_PASSWORD: ******
  - BITRISEIO_ANDROID_KEYSTORE_ALIAS: my-key-alias
  - BITRISEIO_ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD: ******

A: According to this discussion on the bitrise.io, the solution was to specify the keystore url the following way:

For local keystores provide file path url. (ex:
file://PATH/TO/keystore.jks).

In my case though, I had to specify file:/// instead of file://.


text:
Q: Is there a difference in the emitted EM radiation from electrons with same kinetic energy coming in rest in an hydrogen atom and in a magnetic field? I had a question about https://physics.stackexchange.com/questions/320426/what-prevents-us-to-build-a-model-where-in-the-atom-the-positive-and-negative-el?noredirect=1#comment720010_320426. The question is about the contribution of the electric fields of charged particles to the EM radiation during the approach of the electron to the nucleus.
Let me explain this thought. Having an electron in infinity from a positive charged hydrogen ion both constituents exert a force on each other. From this starting position it has to be possible to calculate the top speed with which the electron approaches the nucleus. Furthermore it should be possible to compare

*

*the EM radiation from this interaction until the electron reaches the lowest bonded state in the hydrogen atom

*with the EM radiation of an electron of the same speed, coming in rest under the influence of an external magnetic field (under the influence of the Lorentz force).

Is there a difference in the value (the amount) of the emitted EM radiations from electrons with same kinetic energy

*

*reaching the lowest bonded state in a hydrogen atom and

*coming to standstill in a magnetic field?

In short: Both electrons have the same amount of potential energy (in the case of the hydrogen atom) and kinetic energy (in the case of the magnetic field) and came into standstill in both cases. Are the emitted EM radiation of the same amount?

A: Yes, the radiation in those two situations would be drastically different. For concreteness, I'll consider the following two situations:

*

*An electron is dropped in as a wavepacket with mean velocity $\mathbf v$ and a small spatial extent $\sigma$ a large distance away from a proton at rest, with some nonzero impact parameter, in such a way that the total energy is negative (so the electron is bound and only a negligible fraction of the electron population will be scattered to infinity) but arbitrarily close to zero.

*An electron is suddenly injected in a wavepacket of spatial extent $\sigma$ and central velocity $\mathbf v$ into a region with a uniform, static magnetic field $\mathbf B$ orthogonal to $\mathbf v$, with no additional external fields. Since this is an accelerated charge, it will radiate, and therefore slowly spiral down to rest at some location close to the center of its initial circular orbit.

In situation 1, the electron will radiate its energy through all the possible radiative decay pathways, i.e. all the possible dipole-allowed steps down the Bohr-model states, until it reaches the ground state. You will observe a bunch of different photon energies, all of them of the form $\hbar\omega= \mathrm{Ry}\left(\frac{1}{m^2}-\frac{1}{n^2}\right)$, starting small (since the spacings in the Rydberg region are small) and growing until you get to the Lyman-alpha line.

In situation 2, the electron will radiate exclusively at the cyclotron frequency at that magnetic field,
$$ \omega_c = \frac{eB}{m_e}.$$
(This frequency gets its name from the fact that cyclotrons operate at that frequency, but it is a much more general concept.)
From a classical perspective, the electron will follow circular orbits, with the crucial characteristic that the frequency of the orbit is independent of the orbit's size or the electron's velocity or energy. This means that the emitted radiation will always be at that frequency.
From a more quantum perspective, the electron has been prepared in a superposition of excited Landau levels, and through coupling to the electromagnetic vacuum it will experience radiative decay down that ladder. Mirroring the classical constant-frequency property, the Landau ladder is harmonic and equispaced, i.e. all the levels are separated by $\hbar\omega_c$, so you can only radiate at multiples of that frequency (and, moreover, dipole radiation is only possible between adjacent levels).

As to why you think this is useful, or a meaningful comparison, I'm still completely in the dark. And, just to not let this slide, the statement that

From this starting position it has to be possible to calculate the top speed with which the electron approaches the nucleus.

is completely meaningless - it completely relies on an underlying trajectory, which is meaningless in quantum mechanics. Starting off with counterfactual statements will not get you very far.


text:
Q: XGboost Google-AI-Model expecting float values instead of using Categorical values and converting them I'm trying to run a simple XGBoost Prediction based on Google Cloud using this simple example https://cloud.google.com/ml-engine/docs/scikit/getting-predictions-xgboost#get_online_predictions
The model is building fine, but when I try to run a prediction with a sample input JSON it fails with error "Could not initialize DMatrix from inputs: could not convert string to float:" as shown in the screen below. I understand this is happening because the test-input has strings, I was hoping the Google machine learning model should have information to convert the categorical values to floats. I cannot expect my user to submit-online-prediction-request with float values.
Based on the tutorial it should work without converting the categorical values to floats. Please advise, I have attached the GIF with more details. Thanks

import json
import numpy as np
import os
import pandas as pd
import pickle
import xgboost as xgb
from sklearn.preprocessing import LabelEncoder

# these are the column labels from the census data files
COLUMNS = (
    'age',
    'workclass',
    'fnlwgt',
    'education',
    'education-num',
    'marital-status',
    'occupation',
    'relationship',
    'race',
    'sex',
    'capital-gain',
    'capital-loss',
    'hours-per-week',
    'native-country',
    'income-level'
)

# categorical columns contain data that need to be turned into numerical
# values before being used by XGBoost
CATEGORICAL_COLUMNS = (
    'workclass',
    'education',
    'marital-status',
    'occupation',
    'relationship',
    'race',
    'sex',
    'native-country'
)

# load training set
with open('./census_data/adult.data', 'r') as train_data:
    raw_training_data = pd.read_csv(train_data, header=None, names=COLUMNS)
# remove column we are trying to predict ('income-level') from features list
train_features = raw_training_data.drop('income-level', axis=1)
# create training labels list
train_labels = (raw_training_data['income-level'] == ' >50K')

# load test set
with open('./census_data/adult.test', 'r') as test_data:
    raw_testing_data = pd.read_csv(test_data, names=COLUMNS, skiprows=1)
# remove column we are trying to predict ('income-level') from features list
test_features = raw_testing_data.drop('income-level', axis=1)
# create training labels list
test_labels = (raw_testing_data['income-level'] == ' >50K.')

# convert data in categorical columns to numerical values
encoders = {col:LabelEncoder() for col in CATEGORICAL_COLUMNS}
for col in CATEGORICAL_COLUMNS:
    train_features[col] = encoders[col].fit_transform(train_features[col])
for col in CATEGORICAL_COLUMNS:
    test_features[col] = encoders[col].fit_transform(test_features[col])

# load data into DMatrix object
dtrain = xgb.DMatrix(train_features, train_labels)
dtest = xgb.DMatrix(test_features)

# train XGBoost model
bst = xgb.train({}, dtrain, 20)
bst.save_model('./model.bst')

A: You can use pandas to convert categorical strings into codes for model inputs. For prediction input you can define a dictionary for each category with corresponding category values and codes. For example, for workclass:
df['workclass_cat'] = df['workclass'].astype('category')
df['workclass_cat'] = df['workclass_cat'].cat.codes
workclass_dict = dict(zip(list(df['workclass'].values), list(df['workclass_cat'].values)))

If a prediction input is 'somestring' you can access its code as follows:
category_input = workclass_dict['somestring']

A: XGBoost models take floats as input. In your training script you converted the categorical variables into numbers. The same transformation needs to be done when submitting a prediction.

A: Here is a fix. Put the input shown in the Google documentation in a file input.json, then run this. The output is input_numerical.json and prediction will succeed if you use that in place of input.json.
This code is just preprocessing categorical columns to numerical forms using the same procedure as was done with training and test data.
import json

import pandas as pd
from sklearn.preprocessing import LabelEncoder

COLUMNS = (
    "age",
    "workclass",
    "fnlwgt",
    "education",
    "education-num",
    "marital-status",
    "occupation",
    "relationship",
    "race",
    "sex",
    "capital-gain",
    "capital-loss",
    "hours-per-week",
    "native-country",
    "income-level",
)

# categorical columns contain data that need to be turned into numerical
# values before being used by XGBoost
CATEGORICAL_COLUMNS = (
    "workclass",
    "education",
    "marital-status",
    "occupation",
    "relationship",
    "race",
    "sex",
    "native-country",
)

with open("./input.json", "r") as json_lines:
    rows = [json.loads(line) for line in json_lines]

prediction_features = pd.DataFrame(rows, columns=(COLUMNS[:-1]))

encoders = {col: LabelEncoder() for col in CATEGORICAL_COLUMNS}
for col in CATEGORICAL_COLUMNS:
    prediction_features[col] = encoders[col].fit_transform(prediction_features[col])

with open("input_numerical.json", "w") as input_numerical:
    for index, row in prediction_features.iterrows():
        input_numerical.write(row.to_json(orient="values") + "\n")

I created this Google Issues Tracker ticket as the Google documentation is missing this important step.


text:
Q: How long does it take for a published content type in the Gallery to become available across your environment? How long does it take for a published content type in the Gallery to become available across your environment?

A: This will vary based on the number of tenants on the stamp and number of content types across the tenants in the stamp. I.e. if there are 5 tenants and each has 10 CTs in the hub, it'll be super quick. If there are 500 tenants with 1000 CTs in the hub each, it's going to take a lot longer.
And for both scenarios, there will be variances depending on farm load.
There is no SLA around the timer job that executes this process.
Microsoft is putting forth effort to improve performance of CT hub publishing, though.
Ultimately, giving you a number will be anecdotal and inaccurate.


text:
Q: dynamic mean: measurement of randomly distributed events Aim is to estimate an error on a stochastic event rate. I read out the event counter second-wise, every black $1$ is a counted event (new events over time, see the plot below).
During the measurement I am estimating the event rate, so as more statistics is accumulated, mean event rate (red) should asymptotically become more accurate.

as one can see, the mean value oscillates around true value of 0.5

even after one order of magnitude more events collected.
Practical question: How can one calculate the number of events needed to estimate the mean value to a maximum error ($0.5\pm \sigma$)? - error should fall by $\sqrt{N}$
Theoretically: Can this oscillation be described analytically? Can you suggest further reading?
The events are radiation counts, so they are uncorrelated, may by Poisson-distribution applied?
addendum:
idealized first approximation - every 10th event is non-zero:

may be this curve is superimposed with the realer-life example above, is here any techniques of partitioning in arbitrary functions applicable?

A:
How can one calculate the number of events needed to estimate the mean value to a maximum error (0.5±σ)?

If I understood you correctly, this can be done by applying Chebyshev confidence interval or by confidence interval based on Central Limit Theorem (CLT estimate is better, if your stochastic event rate has finite variance). Let $M$ be number of events (samples).  For Chebyshev bound with $\delta$ confidence level (e.g. 0.05):
\begin{array}{l}
 P(|{\overline X _M} - \mu | < {\delta ^{( - 1/2)}}{M^{( - 1/2)}}\sigma ) \ge 1 - \delta
 \end{array}
\begin{array}{l}
 e = {\delta ^{( - 1/2)}}{M^{( - 1/2)}}\sigma  \
 \end{array}
\begin{array}{l}
 M = {(\sqrt \delta  \frac{e}{\sigma })^{( - 2)}} \
 \end{array}
For CLT based interval:
\begin{array}{l}
 P(|{\overline X _M} - \mu | < a{M^{( - 1/2)}}\sigma ) \ge 1 - \delta  \
\end{array}
\begin{array}{l}
 e = a{M^{( - 1/2)}}\sigma  \
\end{array}
\begin{array}{l}
 M = {(a\sigma \frac{1}{e})^2} \
\end{array}
where $\ a = \sqrt 2 erfinv(1 - \delta )$


text:
Q: PROTOCOL BUFFER ERROR due to incompatible versions I am trying to compile on ubuntu 18.04 and receive the following error -
file.pb.h:17:2: error: #error This file was generated by an older version of protoc which is
 #error This file was generated by an older version of protoc which is

protoc --version
libprotoc 3.6.1

from google/protobuf/stubs/common.h
#define GOOGLE_PROTOBUF_VERSION 3006001
So looks like the versions match.
I did do a remove of any older versions just in case using the following link
https://www.howtoinstall.co/en/ubuntu/trusty/protobuf-compiler?action=remove
What am I missing here ?


text:
Q: how to create hover effect with javascript I have three images I want to show some text on one particular image when my cursor goes on that image like on first image text should come from top, second image text should come from left and on third image text should come from right This hover effect already done in css but I have do it in Javascript so please help me with this problem.

A:

     let p = document.querySelectorAll("p");
      let div = document.querySelector("div");
      div.addEventListener("mouseover", mouseOverHandler);
      div.addEventListener("mouseleave", mouseLeaveHandler);
      function mouseOverHandler(e) {
        //top
        p[0].style.top = 0;
        //left
        p[1].style.left = 0;
        //right
        p[2].style.right = 0;
      }
      function mouseLeaveHandler(e) {
        //top
        p[0].style.top = "-75px";
        //left
        p[1].style.left = "-75px";
        //right
        p[2].style.right = "-75px";
      }
      * {
        margin: 0;
        padding: 0;
      }
      div {
        width: 200px;
        height: 200px;
        background-color: pink;
        position: relative;
        left: 300px;
        top: 100px;
        overflow: hidden;
      }
      p {
        width: 50px;
        height: 50px;
        text-align:center;
        line-height:50px;
        background-color: blue;
        position: absolute;
        transition: all 0.5s;
      }
      p:nth-child(1) {
        top: -50px;
        left: 75px;
      }
      p:nth-child(2) {
        top: 75px;
        left: -50px;
      }
      p:nth-child(3) {
        top: 75px;
        right: -50px;
      }
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

top

left

right

How about this


text:
Q: CSSStyleDeclaration not giving any value while using useRef in react I want to get the line-height of the element in Rect after render and for this I'm using useRef
const titleLineHeight = titletext.current?.style.lineHeight;

and I didn't get any value in CSSStyleDeclaration

Im not sure how to get the values. Please help me
Thanks in advance :)

A: use getComputedStyle()
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

const paraRef = useRef(null);

  useEffect(() => {
    const paraStyle = paraRef.current && getComputedStyle(paraRef.current);
    console.log(paraStyle.lineHeight);
  }, []);

  return (

New text

  );


text:
Q: Saving blob (might be data!) returned by AJAX call to Azure Blob Storage creates corrupt image If I post a PDF to my vendors API, they return me a .png file as a blob (see update 2 as I am now unsure if they are returning blob data).
I would like to push this into Azure Blob Storage. Using my code listed below, it pushes something in, but the file is corrupted. Example: downloading the .png from Azure Blob Storage and trying to open it with Paint gives the following error:

This is not a valid bitmap file, or its format is not currently
  supported.

I have verified that the image is sent to me correctly as the vendor is able to open the .png on their side. I am wondering if I need to convert this to base64 or save it to a local Web directory before uploading it to Azure Blob Storage.
Here is my Angular front end Controller that calls my Node/Express backend for uploading to Azure once it receives the returned "image":
$.ajax({
            url: 'http://myvendorsapi.net/uploadPDF,
            type: "POST",
            data: formdata,
            mimeType: "multipart/form-data",
            processData: false,
            contentType: false,
            crossDomain: true,
            success: function (result) {
                var containerName = 'container1';
                var filename = 'Texture_0.png';
                var file = result;
                $http.post('/postAdvanced', { containerName: containerName, filename: filename, file: file }).success(function (data) {
                    console.log("success!");
                }, function (err) {
                    //console.log(err);
                });
            },
            error: function (error) {
                console.log("Something went wrong!");
            }
        })
    }

Here is my Node/Express backend that uploads the blob to Azure Blob Storage. It gives no error, but the file can't be opened/gives the error stated above when opened in Paint:
app.post('/postAdvanced', function (req, res, next) {
    var containerName = req.body.containerName;
    var filename = req.body.filename;
    var file = req.body.file;

    blobSvc.createBlockBlobFromText(containerName, filename, file, function (error, result, response) {
        if (!error) {
            res.send(result);
        }
        else {
            console.log(error);
        }
    });
})

Update 1: The answer provided here allows me to pass in the URL of the vendors API for some endpoints: Download file via Webservice and Push it to Azure Blob Storage via Node/Express
It works as it writes the file at the endpoint to a temp folder. In my current scenario, I upload a PDF file and it returns an image file that I need to upload to Azure Blob Storage. Is there a way to use the answer here, but adjust it for a file that I already have (since it is returned to me) versus file streaming from a URL?
Update 2: In console logging the returned "file", it looks like it may be data. I am not sure, it looks like this:

Is this actually data, and if so, how do I make this into a file for upload?
UPDATE 3:
Since it appears that jQuery AJAX can't manage binary returns. I am able to "open" the blob using XMLHTTPResponse as follows, but I can't seem to push this into Azure as it gives me the following error:
TypeError: must start with number, buffer, array or string

Here is my request. Note that the file opens properly:
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function (ev) {

 var oData = new FormData(form);

    var xhr = new XMLHttpRequest();
    xhr.responseType = "arraybuffer";

    xhr.open("POST", "http://myvendorsapi/Upload", true);
    xhr.onload = function (oEvent) {
        if (xhr.status == 200) {
            var blob = new Blob([xhr.response], { type: "image/png" });
            var objectUrl = URL.createObjectURL(blob);
            window.open(objectUrl);

            console.log(blob);
            var containerName = boxContainerName;
            var filename = 'Texture_0.png';

            $http.post('/postAdvanced', { containerName: containerName, filename: filename, file: blob }).success(function (data) {
                //console.log(data);
                console.log("success!");
            }, function (err) {
                //console.log(err);
            });

        } else {
            oOutput.innerHTML = "Error " + xhr.status + " occurred when trying to upload your file.<br \/>";
        }
    };

    xhr.send(oData);
    ev.preventDefault();
}, false);

A: createBlockBlobFromText will work with either string or buffer. You might need a buffer to hold the binary content due to a known issue of jQuery.
For a workaround, there are several options:
Option 1: Reading binary filesusing jquery ajax
Option 2: Use native XMLHttpRequest
Option 3: Write frontend with Node as well and browserify it.
Your frontend code may look like:
var request = require('request');

request.post('http://myvendorsapi.net/uploadPDF', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    var formData = {
      containerName: 'container1',
      filename: 'Texture_0.png',
      file: body
    };
    request.post({ uri: '/postAdvanced', formData: formData }, function optionalCallback(err, httpResponse, body) {
      if (err) {
        return console.error('upload failed:', err);
      }
      console.log('Upload successful!  Server responded with:', body);
    });
  } else {
    console.log('Get snapshot failed!');
  }
});

Then the backend code may look like:
app.post('/postAdvanced', function (req, res, next) {
  var containerName = req.body.containerName;
  var filename = req.body.filename;
  var file = req.body.file;

  if (!Buffer.isBuffer(file)) {
    // Convert 'file' to a binary buffer
  }

  var options = { contentType: 'image/png' };
  blobSvc.createBlockBlobFromText(containerName, filename, file, options, function (error, result, response) {
    if (!error) {
      res.send(result);
    } else {
      console.log(error);
    }
  });
})

A: Below I have the code to upload the image as binary in angular using FormData.
The server code will be the code to handle a regular file upload via a form.
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function (ev) {

var oData = new FormData(form);

var xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";

xhr.open("POST", "http://vendorapi.net/Upload", true);
xhr.onload = function (oEvent) {
    if (xhr.status == 200) {
        var blob = new Blob([xhr.response], { type: "image/png" });
        //var objectUrl = URL.createObjectURL(blob);
        //window.open(objectUrl);
        //console.log(blob);
        var formData = new FormData()
        formData.append('file', blob);
        formData.append('containerName', boxContainerName);
        formData.append('filename', 'Texture_0.png');

        $http.post('/postAdvancedTest', formData, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        }).success(function (data) {
            //console.log(data);
            console.log("success!");

            // Clear previous 3D render
            $('#webGL-container').empty();

            // Generated new 3D render
            $scope.generate3D();
        }, function (err) {
            //console.log(err);
        });
    } else {
        oOutput.innerHTML = "Error " + xhr.status + " occurred when trying to upload your file.<br \/>";
    }
};

xhr.send(oData);
ev.preventDefault();
}, false);

A: I have solved the issue (thanks to Yang's input as well). I needed to base64 encode the data on the client side before passing it to node to decode to a file. I needed to use XMLHTTPRequest to get binary data properly, as jQuery AJAX appears to have an issue with returning (see here: http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/).
Here is my front end:
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function (ev) {

var oData = new FormData(form);

var xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";

xhr.open("POST", "http://vendorapi.net/Upload", true);
xhr.onload = function (oEvent) {
    if (xhr.status == 200) {
        var blob = new Blob([xhr.response], { type: "image/png" });
        //var objectUrl = URL.createObjectURL(blob);
        //window.open(objectUrl);
        console.log(blob);
        var blobToBase64 = function(blob, cb) {
            var reader = new FileReader();
            reader.onload = function() {
                var dataUrl = reader.result;
                var base64 = dataUrl.split(',')[1];
                cb(base64);
            };
            reader.readAsDataURL(blob);
        };

        blobToBase64(blob, function(base64){ // encode
            var update = {'blob': base64};
            var containerName = boxContainerName;
            var filename = 'Texture_0.png';

            $http.post('/postAdvancedTest', { containerName: containerName, filename: filename, file: base64}).success(function (data) {
                //console.log(data);
                console.log("success!");

                // Clear previous 3D render
                $('#webGL-container').empty();

                // Generated new 3D render
                $scope.generate3D();
            }, function (err) {
                //console.log(err);
            });
        })
    } else {
        oOutput.innerHTML = "Error " + xhr.status + " occurred when trying to upload your file.<br \/>";
    }
};

xhr.send(oData);
ev.preventDefault();
}, false);

Node Backend:
app.post('/postAdvancedTest', function (req, res) {
var containerName = req.body.containerName
var filename = req.body.filename;
var file = req.body.file;
var buf = new Buffer(file, 'base64'); // decode

var tmpBasePath = 'upload/'; //this folder is to save files download from vendor URL, and should be created in the root directory previously.
var tmpFolder = tmpBasePath + containerName + '/';

// Create unique temp directory to store files
mkdirp(tmpFolder, function (err) {
    if (err) console.error(err)
    else console.log('Directory Created')
});

// This is the location of download files, e.g. 'upload/Texture_0.png'
var tmpFileSavedLocation = tmpFolder + filename;

fs.writeFile(tmpFileSavedLocation, buf, function (err) {
    if (err) {
        console.log("err", err);
    } else {
        //return res.json({ 'status': 'success' });
        blobSvc.createBlockBlobFromLocalFile(containerName, filename, tmpFileSavedLocation, function (error, result, response) {
            if (!error) {
                console.log("Uploaded" + result);

                res.send(containerName);
            }
            else {
                console.log(error);
            }
        });
    }
})
})


text:
Q: iphone won't let user scale or scroll this website I am wondering what am i missing here
this is the  html
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link rel="shortcut icon" href="../../nImg/favicon.ico" type="image/x-icon" />
        <title>Gran Melia</title>
        <meta name="Description" content="Gran Meliá"/>
        <meta name="Keywords" content="Gran Melia"/>
        <meta name="Language" content="es"/>
        <meta name="Robots" content="index,follow"/>
        <meta name="og:description" content="red" />
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>

        <!--<meta name="viewport" content="width=device-width">
         <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"> -->
        <!--<meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black" /> -->

        <link href="css/960.css" rel="stylesheet" type="text/css" />
        <link href="css/css.css" rel="stylesheet" type="text/css" />
        <!--<link href="css/media.css" rel="stylesheet" type="text/css" />-->
        <!-- <link href="http://keepyourlinks.com/css/ui.css" rel="stylesheet" type="text/css" /> -->
        <script src="js/jquery.js" type="text/javascript"></script>
        <script src="js/js.js" type="text/javascript"></script>
            <!-- Fondo de galería -->
        <script src="js/graphics.js" type="text/javascript"></script>
        <script src='js/iscroll.js' type='text/javascript'></script>
        <!--[if IE]>
            <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
        <script type="text/javascript">
            /*Fotos de fondo*/
            var photos = [
                "http://www.bancotravel.com/images/hoteles/M/MELIAPALACIOISORAALCALA/foto-hotel-23.jpg",
                "http://www.bancotravel.com/images/hoteles/M/MELIAPALACIOISORAALCALA/foto-hotel-24.jpg",
                "http://larivieramaya.es/wp-content/uploads/2011/04/sol-melia-prepara-el-lanzamiento-en-mexico-de-la-marca-paradisus-con-dos-hoteles-en-playa-del-carmen.jpg"
            ];
        </script>
    </head>

for what i can guess, i am commenting the lines (device-width) that should prevent this to happen so I am kind of lost...
In case this code is not enough, the testing website is http://toniweb.us/gm
-EDIT-
Won't let user scale or scroll even if:
<meta name="viewport" content="width=device-width, initial-scale=0.5, user-scalable=1, minimum-scale=0.5, maximum-scale=2.0">

A: I opt for this as the problem. If you have 100% height of body and html iphone is irritated.
html, body {
    height: 100%;
}

A: <meta name="viewport" content="width=device-width">

That's the problem
<meta name="viewport" content="width=1024">

Should solve it
-edit-
Whoops, that site isn't 1024 pixels. Try experimenting with the value - maybe 320 (iPhone width)
-edit2-
Why would you want to let iPhone users scale the website anyway? If you design it for the right size, it's only annoying if they can scale...


text:
Q: JS async function awaits forever I have read a lot about async await, but apparently I still don't get it. ;-)
I am trying to transform the following .then promise structure into async await:
componentDidMount() {
    const { store } = this.props

    Promise.all([
      API.fetchTodos(),
      API.fetchGoals(),
    ]).then(([ todos, goals ]) => {
      store.dispatch(receiveDataAction(todos, goals))
    })

    store.subscribe(() => this.forceUpdate())

    console.log('test')
}

My result is:
async componentDidMount() {
    const { store } = this.props

    const [todos, goals] = await Promise.all([
      API.fetchTodos(),
      API.fetchGoals(),
    ])

    store.dispatch(receiveDataAction(todos, goals))

    store.subscribe(() => this.forceUpdate())

    console.log('test')
}

The result is that this function never ends. It calls everything including the console.log, but then the program just stops (no error). I'm not showing you any other parts of the application because according to my understanding these two functions should be equivalent - so the rest should not matter. Apparently I am wrong! :-) What am I doing wrong and why doesn't my solution work?

A: The difference between your two snippets is that in the second async/await example, you don't subscribe to the store until after you've fetched the goals and todos, whereas in the first, you subscribe immediately.
So your second example isn't working since now you've guaranteed that
store.dispatch(receiveDataAction(todos, goals))

is called before
store.subscribe(() => this.forceUpdate())

and since the action has already been dispatched by that point, the subscription callback is never called.
To fix that, you might just want to move the subscription part so that it occurs before the await call. That way you are already subscribed before the promise has resolved. So something like this:
async componentDidMount() {
    const { store } = this.props

    // Move to the front so this happens before the await.
    store.subscribe(() => this.forceUpdate())

    const [todos, goals] = await Promise.all([
      API.fetchTodos(),
      API.fetchGoals(),
    ])

    store.dispatch(receiveDataAction(todos, goals))

    console.log('test')
}


text:
Q: How to get particular Column of DataFrame in pandas? I have a data frame name it df I want to have like its first and second colums(series) in variable x and y.
I would have done that by name of the column like df['A'] or df['B'] or something like that.
But problem here is that data is itself header and it has no name.Header is like 2.17 ,3.145 like that.
So my Question is:
a) How to name column and start the data(which starts now from head) right after the name ?
b) How to get particular column's data if we don't know the name or it doesn't have the name ?
Thank you.

A: You might want to read the
documentation on indexing.
For what you specified in the question, you can use
x, y = df.iloc[:, [0]], df.iloc[:, [1]]

A: Set the names kwarg when reading the DataFrame (see the read_csv docs.
So instead of pd.read_csv('kndkma') use pd.read_csv('kndkma', names=['a', 'b', ...]).

A: It is usually easier to name the columns when you read or create the DataFrame, but you can also name (or rename) the columns afterwards with something like:
df.columns = ['A','B', ...]


text:
Q: How to use arrow's type classes? I'm trying to get familiar with the arrow-kt library, but I'm to dumb to get the easiest thing done: Using one of the built in type classes, namely 'Show'
I tried it with kapt using the @extension annotation and kapt itself is generating the necessary code as expected, but the reference to the extension function 'show(): String' is missing.
Could somebody please help me with this problem? I wasted two days getting this to work.
Thank you very much!
Best regards
Alex
The class to be extended:
package org.hudelundpfusch.sqwakkel.arrowtest

import arrow.extension
import arrow.typeclasses.Show

class Fump(private val fumpel: String) {

    companion object {}

    override fun toString(): String {
        return "Fump(fumpel='$fumpel')"
    }

}

@extension
interface FumpShow
    : Show<Fump> {
    override fun Fump.show(): String = toString()
}

Here I wanted to use the extension function:
package org.hudelundpfusch.sqwakkel.arrowtest

class Gump {

    private val fump: Fump = Fump("Fumpel!")

    fun gumpel(): String = fump.show()

}

But the reference to 'fump.show()' is missing   =(

A: You're missing show.run { }. For extension functions defined in interfaces to work you need to be on their scope, using run or making a class where you're using it extend it. Either
class Gump: FumpShow

or
Fump.show().run { fump.show() }

should give you the results that you want.
Another option would be importing the show function Arrow Meta's processor would create for you using @extension. Make sure to have it properly configured in your build.gradle
kapt "io.arrow-kt:arrow-meta:$arrow_version"

and then it should be as easy as importing show from IntelliJ's suggestions.

A: Thank you very much, El Paco!
But I've to admit that this is a bit counterintuitive for me...   =/
I now ended up with this approach:
package org.hudelundpfusch.sqwakkel.arrowtest

import org.hudelundpfusch.sqwakkel.arrowtest.fump.show.show

object FumpShowInstance : FumpShow

class Gump {

    private val fump: Fump = Fump("Fumpel!")

    fun gumpel(): String = FumpShowInstance.run { fump.show() }

}

fun main(args: Array<String>) {
    val gump: Gump = Gump();
    println("${gump.gumpel()}")
}

Best regards
Alex


text:
Q: how to detect if another java thread is suspended or frozen? I searched and found ways to determine if another thread is suspended by adding a boolean to it. But, I do not want (prefer not) to modify that other thread's code. And, I need to detect if it is frozen by any reason (even a bug, so in this case that other thread may also be unresponsive).
I see how eclipse does it and shows the application's thread is not responding, I wonder how they coded that.
Motivation: I need this to release the mouse (ungrab it) from a 3D lwjgl application, and this must be independent of any IDE, the application itself must do it. I am trying to monitor the main application thread.

A: While not necessarily the best idea, you can use Thread#getState() to view the current state of the thread.
However, this will depend on the context of the thread. If it is frozen because it cannot break out of a loop, then this method cannot work. Additionally, if it is simply waiting on a lock or on a bounded collection, it will be a false call.
The thread should in these 3 states: BLOCKED, WAITING, or TIMED_WAITING.

A: in a powershell or command prompt you could use JPS to list all java threads that are currently running. then use jstack "pid" .. this will list all threads running under this thread. their state will also be written next to them.


text:
Q: MagicZoomPlus zoomed image positioning I use MagicZoomPlus as a module in PrestaShop.
but the zoom image is not shown in correct position.
take a look at following URL:
http://beheshtian.org/product.php?id_product=11
how can I fix this?
(when you move your mouse on thumbnail, the zoom image is not in correct position, move to the very left and very right and you'll see the problem)

A: Makes sure that the Zoom image is the same ratio as your main image for example if your main product image is 600x150 (a ratio of 4:1) then your zoom image needs to have the same ratio 1200x300 (4:1).


text:
Q: How to rename multiple columns of a table in Snowflake? I have a table , say table1 and it has three columns ( col1_a , col2_b, col3_c) .  I want to rename the columns to col1 , col2 , col3 .
But the thing is I want to rename all columns in a single query .
Is there a way to achieve this ?

A: You can use a select:
select col1_a as col1, col2_a as col2, col3_a as col3
from t;

If you want to actually change the names in the table, I think you need three alter tables:
alter table t rename column col1_a to col1;
alter table t rename column col2_a to col2;
alter table t rename column col3_a to col3;

I don't think Snowflake allows multiple renames with a single alter table.


text:
Q: Mandrill cron error I get this error in my cron.log and as a result no emails seem to work:

PHP Parse error:  syntax error, unexpected '[' in
  /var/www/vhosts/gsequestrian.co.uk/httpdocs/app/code/community/Ebizmarts/Mandrill/Model/Email/Queue.php
  on line 35

Link to code: https://www.dropbox.com/s/ecnwecmi8pwx9be/Queue.php?dl=0
Section starting line 35:
$mandrill = [
                    'subject' => $parameters->getSubject(),
                    'to' => [],
                    'from_email' => $parameters->getFromEmail(),
                    'from_name' => $parameters->getFromName(),
                    'headers' => $mailer->getHeaders(),
                    'html' => ($parameters->getIsPlain() ? "" : $message->getMessageBody()),
                    'text' => ($parameters->getIsPlain() ? $message->getMessageBody() : ""),
                ];

A: It's a syntax error because you are running an outdated PHP version which does not support short array notation. This version of the Mandrill extension obviously does not support PHP 5.3
The only reasonable solution is to update to PHP 5.5 or 5.6, depending on your Magento version. They added 5.6 support with Magento 1.9.1


text:
Q: Getting gpgkeys host error while installing cookbook of mongodb via Opscode Chef client I am trying to install cookbook of mongodb using opscode chef on ubuntu 10.04 in amzaon Virtual Private Cloud. My error stack is:
[Sat, 14 Apr 2012 04:26:00 +0000] INFO: Processing ruby_block[set-env-java-home] action create (java::openjdk line 36)
[Sat, 14 Apr 2012 04:26:00 +0000] INFO: ruby_block[set-env-java-home] called
[Sat, 14 Apr 2012 04:26:00 +0000] INFO: Processing ruby_block[update-java-alternatives] action nothing (java::openjdk line 43)
[Sat, 14 Apr 2012 04:26:00 +0000] INFO: Processing package[openjdk-6-jdk] action install (java::openjdk line 79)
[Sat, 14 Apr 2012 04:28:03 +0000] INFO: package[openjdk-6-jdk] installed version 6b20-1.9.13-0ubuntu1~10.04.1
[Sat, 14 Apr 2012 04:28:03 +0000] INFO: Processing execute[apt-get update] action nothing (mongodb::10gen_repo line 28)
[Sat, 14 Apr 2012 04:28:03 +0000] INFO: Processing apt_repository[10gen] action add (mongodb::10gen_repo line 32)
[Sat, 14 Apr 2012 04:28:03 +0000] INFO: Processing execute[install-key 7F0CEB10] action run (/var/chef/cache/cookbooks/apt/providers/repository.rb line 23)
[Sat, 14 Apr 2012 04:28:03 +0000] INFO: execute[install-key 7F0CEB10] sh(apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10)
Executing: gpg --ignore-time-conflict --no-options --no-default-keyring --secret-keyring /etc/apt/secring.gpg --trustdb-name /etc/apt/trustdb.gpg --keyring /etc/apt/trusted.gpg --primary-keyring /etc/apt/trusted.gpg --keyserver keyserver.ubuntu.com --recv 7F0CEB10
gpgkeys: HTTP fetch error 7: couldn't connect to host
[Sat, 14 Apr 2012 04:28:24 +0000] ERROR: execute[install-key 7F0CEB10] (/var/chef/cache/cookbooks/apt/providers/repository.rb line 23) has had an error
[Sat, 14 Apr 2012 04:28:24 +0000] ERROR: apt_repository[10gen] (mongodb::10gen_repo line 32) has had an error
[Sat, 14 Apr 2012 04:28:24 +0000] ERROR: apt_repository[10gen] (/var/chef/cache/cookbooks/mongodb/recipes/10gen_repo.rb:32:in `from_file') had an error:
apt_repository[10gen] (mongodb::10gen_repo line 32) had an error: Chef::Exceptions::ShellCommandFailed: execute[install-key 7F0CEB10] (/var/chef/cache/cookbooks/apt/providers/repository.rb line 23) had an error: Chef::Exceptions::ShellCommandFailed: Expected process to exit with [0], but received '2'
---- Begin output of apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10 ----
STDOUT: Executing: gpg --ignore-time-conflict --no-options --no-default-keyring --secret-keyring /etc/apt/secring.gpg --trustdb-name /etc/apt/trustdb.gpg --keyring /etc/apt/trusted.gpg --primary-keyring /etc/apt/trusted.gpg --keyserver keyserver.ubuntu.com --recv 7F0CEB10
gpgkeys: HTTP fetch error 7: couldn't connect to host
STDERR: gpg: requesting key 7F0CEB10 from hkp server keyserver.ubuntu.com
gpg: no valid OpenPGP data found.
gpg: Total number processed: 0
---- End output of apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10 ----
Ran apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10 returned 2
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/shell_out.rb:206:in `invalid!'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/shell_out.rb:192:in `error!'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/mixin/shell_out.rb:36:in `shell_out!'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/provider/execute.rb:58:in `action_run'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/resource.rb:440:in `send'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/resource.rb:440:in `run_action'
/var/chef/cache/cookbooks/apt/providers/repository.rb:26:in `install_key_from_keyserver'
/var/chef/cache/cookbooks/apt/providers/repository.rb:73:in `class_from_file'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/provider.rb:104:in `instance_eval'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/provider.rb:104:in `action_add'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/resource.rb:440:in `send'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/resource.rb:440:in `run_action'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/runner.rb:45:in `run_action'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/runner.rb:81:in `converge'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/runner.rb:81:in `each'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/runner.rb:81:in `converge'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/resource_collection.rb:94
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/resource_collection/stepable_iterator.rb:116:in `call'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/resource_collection/stepable_iterator.rb:116:in `call_iterator_block'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/resource_collection/stepable_iterator.rb:85:in `step'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/resource_collection/stepable_iterator.rb:104:in `iterate'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/resource_collection/stepable_iterator.rb:55:in `each_with_index'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/resource_collection.rb:92:in `execute_each_resource'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/runner.rb:76:in `converge'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/client.rb:312:in `converge'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/client.rb:160:in `run'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/application/client.rb:239:in `run_application'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/application/client.rb:229:in `loop'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/application/client.rb:229:in `run_application'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/../lib/chef/application.rb:67:in `run'
/usr/lib/ruby/gems/1.8/gems/chef-0.10.8/bin/chef-client:26
/usr/bin/chef-client:19:in `load'
/usr/bin/chef-client:19
[Sat, 14 Apr 2012 04:28:24 +0000] ERROR: Running exception handlers
[Sat, 14 Apr 2012 04:28:24 +0000] FATAL: Saving node information to /var/chef/cache/failed-run-data.json
[Sat, 14 Apr 2012 04:28:24 +0000] ERROR: Exception handlers complete
[Sat, 14 Apr 2012 04:28:24 +0000] FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out
[Sat, 14 Apr 2012 04:28:24 +0000] FATAL: Chef::Exceptions::ShellCommandFailed: apt_repository[10gen] (mongodb::10gen_repo line 32) had an error: Chef::Exceptions::ShellCommandFailed: execute[install-key 7F0CEB10] (/var/chef/cache/cookbooks/apt/providers/repository.rb line 23) had an error: Chef::Exceptions::ShellCommandFailed: Expected process to exit with [
0], but received '2'
---- Begin output of apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10 ----
STDOUT: Executing: gpg --ignore-time-conflict --no-options --no-default-keyring --secret-keyring /etc/apt/secring.gpg --trustdb-name /etc/apt/trustdb.gpg --keyring /etc/apt/trusted.gpg --primary-keyring /etc/apt/trusted.gpg --keyserver keyserver.ubuntu.com --recv 7F0CEB10
gpgkeys: HTTP fetch error 7: couldn't connect to host
STDERR: gpg: requesting key 7F0CEB10 from hkp server keyserver.ubuntu.com
gpg: no valid OpenPGP data found.
gpg: Total number processed: 0
---- End output of apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10 ----
Ran apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10 returned 2

Content of My source list file:
deb http://eu.archive.ubuntu.com/ubuntu/ lucid main universe
deb-src http://eu.archive.ubuntu.com/ubuntu/ lucid main universe
deb http://eu.archive.ubuntu.com/ubuntu/ lucid-updates main universe
deb-src http://eu.archive.ubuntu.com/ubuntu/ lucid-updates main universe
deb http://security.ubuntu.com/ubuntu lucid-security main universe
deb-src http://security.ubuntu.com/ubuntu lucid-security main universe

What could be the problem? I have googled it but hadn't find the proper solution.

A: Ok, me and my friend have done it after having some R&D. the solution is change in the cookbook receipe.
I have changed the keyserver "keyserver.ubuntu.com" to "hkp://keyserver.ubuntu.com:80".
Cheers!!


text:
Q: Trying to scrape image and I get empty output I'm trying to scrape Twitter account image, I tried multiple ways and the output keeps give me empty list!
My Code:
import requests
from bs4 import BeautifulSoup

url = requests.get('https://twitter.com/jack/photo')
soup = BeautifulSoup(url.text, 'lxml')
image = soup.find_all('img')

print(image)

Output:
[]

That's a part of my project .. I tried lxml and find by class, but I still get nothing, maybe I'm missing something there but I don't know what it is.
If anyone can help me with it, I will be so appreciated.
Thanks in advance

A: I can see some React being used in the page. If you open the page and inspect the elements, you will see that as soon as you click on the photo to enlarge it, a new div appears as if from thin air. Which implies that that get created by react.
In order to address this you will need to use Selenium to open the page in a virtual browser, let the JavaScript do its magic and then look for the img tag.

A: You're trying to scrape the path for JavaScript twitter.  If you examine the response of your page you will see the following snippit.
    <form action="https://mobile.twitter.com/i/nojs_router?path=%2Fjack%2Fphoto" method="POST" style="background-color: #fff; position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 9999;">

We've detected that JavaScript is disabled in your browser. Would you like to proceed to legacy Twitter?

      <button type="submit" style="background-color: #1da1f2; border-radius: 100px; border: none; box-shadow: none; color: #fff; cursor: pointer; font-size: 14px; font-weight: bold; line-height: 20px; padding: 6px 16px;">Yes</button>

</form>

I would recommend disabling javascript in your browser and then figuring out how to view the photos like that.  Then you could mimic those requests using requests.
What worked for me was sendind a request to the path:
https://mobile.twitter.com/jack
Then using the css selector: class = "avatar".  There should be one child, an image tag, grab the src of that image tag and that should be the link to your photo.
As requested, here is the python code I used:
import requests
from bs4 import BeautifulSoup

response = requests.get('https://mobile.twitter.com/jack')

soup = BeautifulSoup(response.text, 'lxml')

avatars = soup.findAll("td", {"class": "avatar"})

print(avatars[0].findAll('img')[0].get('src'))

Note: Twitter changes their layout frequently, so this may not work for long.


text:
Q: remove "edit your profile" from admin menu bar How can I remove "edit your profile" submenu under "my-account-with-avatar" admin menu bar, while still keeping the avatar and logout?

A: Wordpress has introduced new stufs (nodes).
I was searching for remove completly the 'user account box' and add a simple logout :
//http://codex.wordpress.org/Function_Reference/get_nodes
//http://codex.wordpress.org/Function_Reference/add_node

add_action( 'admin_bar_menu', 'remove_my_account', 999 );
function remove_my_account( $wp_admin_bar ) {
    $wp_admin_bar->remove_node( 'my-account' );
}

add_action( 'admin_bar_menu', 'add_logout', 999 );
function add_logout( $wp_admin_bar ) {
    $args = array(
        'id'     => 'logout',           // id of the existing child node (New > Post)
        'title'  => 'Se déconnecter',   // alter the title of existing node
        'parent' => 'top-secondary',    // set parent
    );
    $wp_admin_bar->add_node( $args );
}

A: There is a remove_menu hook for the admin menu bar.
The class you want to hook into $wp_admin_bar , you can see the remove function here and test it out since there is no documentation on it ( line 86), it should work with the submenu ID.
http://core.trac.wordpress.org/browser/tags/3.2.1/wp-includes/class-wp-admin-bar.php
Since you did not seem to believe me here is the code.........
function ya_do_it_admin_bar_remove() {
        global $wp_admin_bar;

        /* **edit-profile is the ID** */
        $wp_admin_bar->remove_menu('edit-profile');
 }

add_action('wp_before_admin_bar_render', 'ya_do_it_admin_bar_remove', 0);

A: I'm not sure if you can remove it (haven't checked), but you may achieve the same using css to hide the edit your profile link. The list item has an id 'wp-admin-bar-edit-profile' which you use to hide it. This is the html used in the admin bar:

  Edit My Profile

I'm using the following css:
#wp-admin-bar-edit-profile { display: none }

This hides the link in the admin bar without any of the other links. Add this css snippet to your theme's style.css and the link will be hidden in the admin bar when viewing your site. Hiding it in the admin bar when viewing the WordPress backend involves a bit more and might be moot since there's also a link to the profile in the menu on the left.


text:
Q: undefined local variable or method `availability_params' for # I'm trying to create new availability object in a program and all of the sudden I can't find availabilities_params. Not sure what is going on exactly.
class AvailabilitiesController < ApplicationController

def create
    @availability = Availability.new(availability_params)
    @availability.save

    if member_signed_in?
      redirect_to member_path(current_member)
    elsif provider_signed_in?
      redirect_to provider_path(current_provider)
    end

end

def new
    @availability = Availability.new
end

def show
    @availability
end

private

def availabilty_params
    params.require(:availability).permit(:time, :date, :provider_id, :user_id)
end

end

Here is the form to create availability
= form_for(@availability) do |f|
   =    f.date_field :date, :min=> "2014-11-00", :value => "2015-01-01"
   = f.time_field :time, :placeholder => "Available Time"
   -if member_signed_in?
     = f.hidden_field :member_id, value: current_member.id
   -elsif provider_signed_in?
     = f.hidden_field :provider_id, value: current_provider.id
= f.submit

A: You got a typo in the method name. It should be def availability_params rather than def availabilty_params.

A: In your create action, you had this
 @availability = Availability.new(availability_params)

In your availability_params method you had this
def availabilty_params
    params.require(:availability).permit(:time, :date, :provider_id, :user_id)
end

Please changeavailabilty_params to availability_params


text:
Q: converting bytecode to dex: Cause: com.android.dex.DexException: Multiple dex files define
Error:Error converting bytecode to dex: Cause: com.android.dex.DexException: Multiple dex files define Landroid/arch/lifecycle/LiveData$LifecycleBoundObserver;

my gradle file
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.ayoubdesigner101.Sinbad.sealling"
minSdkVersion 19
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')

implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'com.google.firebase:firebase-auth:11.0.4'
implementation 'com.google.firebase:firebase-database:11.0.4'
implementation 'com.google.firebase:firebase-crash:11.0.4'
implementation 'com.google.firebase:firebase-storage:11.0.4'
// FirebaseUI for Firebase Realtime Database
implementation 'com.firebaseui:firebase-ui-database:2.3.0'

compile 'com.google.android.gms:play-services:11.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:cardview-v7:27.1.1'
compile 'com.aurelhubert:ahbottomnavigation:2.1.0'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:support-v4:27.1.1'
compile 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.github.bumptech.glide:glide:4.6.1'
compile 'com.firebase:geofire-android:2.1.1'
}

apply plugin: 'com.google.gms.google-services'`

**this is the error I get it **
Error:Error converting bytecode to dex:
Cause: com.android.dex.DexException: Multiple dex files define Landroid/arch/lifecycle/LiveData$LifecycleBoundObserver;
Error:com.android.dex.DexException: Multiple dex files define Landroid/arch/lifecycle/LiveData$LifecycleBoundObserver;
Error:  at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:661)
Error:  at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:616)
Error:  at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:598)
Error:  at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
Error:  at com.android.dx.merge.DexMerger.merge(DexMerger.java:198)
Error:  at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:61)
Error:  at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:36)
Error:  at java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
Error:  at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
Error:  at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
Error:  at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
Error:  at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Error:Execution failed for task ':app:transformDexArchiveWithDexMergerForDebug'.
com.android.build.api.transform.TransformException: com.android.dex.DexException: Multiple dex files define Landroid/arch/lifecycle/LiveData$LifecycleBoundObserver;
Information:BUILD FAILED in 14s
Information:15 errors
Information:0 warnings
Information:See complete output in console

A: You need to upgrade your Firebase Ui dependencies as well as GeoFire
And once you do, ensure compatibles between it and the other Google and Firebase versions
And rather than :play-services:11.0.4, please compile the specific dependencies of Google Play you actually are going to use. That dependency  is all of them, and it slows down your build adding libraries you're not using.
This error also typically appears if you've added any JAR files into your libs folder. For the mentioned class, that JAR would have to be a android support library such as Android Architecture


text:
Q: Which element in Flash Builder defines the iPhone app shortcut name? I've created an air app in Adobe Flash Builder 4.6 with air 3.5 for publishing on Android and iOS. My application.xml file starts off like this:
<id>com.one.two.three</id>
<filename>foobar</filename>
<name>FOO BAR</name>
<versionNumber>1.0.0</versionNumber>

When I exported the release build, and installed the App on an android device, the icon appeared in the applications folder with the name "FOO BAR".
However, when I installed the app on an iPhone, the icon appeared on the homescreen with the name "foobar".
The desired name for both devices is FOO BAR. What element is setting this incorrectly for iOS? I imagine it's the <filename> value, but I would really rather not have spaces in my filename.
Looking forward to an answer, I've checked other resources like:
http://www.adobe.com/devnet/air/articles/packaging-air-apps-ios.html, but it doesn't get very descriptive with what element does what.
Thank you very much for your time,
Rob

A: Take this with a grain of salt, but like it says in your xml :
<!-- The name that is displayed in the AIR application installer.
May have multiple values for each language. See samples or xsd schema file. Optional. -->
<name></name>

Like it says there, This value is only for your AIR installer.  The node you are looking for is the <filename> node.
<!-- Used as the filename for the application. Required. -->

Considering iOS will install directly from the store, you will never have the need to specify a name for the installer when it comes to iOS.  I think the <name> node is for desktop apps or .apks where you actually see the installer.
How about naming them both FOOBAR? :)


text:
Q: Dealing with recursion depth limitation in R The algorithm is from https://www.math.upenn.edu/~wilf/eastwest.pdf page 16 RandomKSubsets
RandomKSubsets = function(n, k){
  if (n<0 | k<0 | k<n){
    return()
  }
  else {
    if (n==0 && k==0){
      return(c())
    }
    else {
      rno = runif(1)
      if (rno < n/k){
        east = RandomKSubsets(n-1,k-1)
        return (c(east, k))
      }
      else{
        west = RandomKSubsets(n,k-1)
        return(west)
      }
    }
  }
}

Running the program with k=4000 and n=1200 I run into recursion depth limit. I tried options(expressions=500000) but it's not enough for the algorithm. How can I run this code for my variables?

A: This is close to tail recursion:  the only recursive calls are in the return statements.  This blog:  http://blog.moertel.com/posts/2013-05-11-recursive-to-iterative.html describes how to change such functions into loops.  I followed the mostly mechanical process described there, and came up with this version:
RandomKSubsetsLoop = function(n, k) {
  acc <- NULL
  while (TRUE) {
    if (n<0 | k<0 | k<n){
      return(acc)
    }
    else {
      if (n==0 && k==0){
        return(acc)
      }
      else {
        rno = runif(1)
        if (rno < n/k){
          acc <- c(k, acc)
          k <- k - 1
          n <- n - 1
          next
        }
        else{
          k <- k - 1
          next
        }
      }
    }
    break
  }
}

I haven't tested it extensively, but it produces the same result as the original in this test:
set.seed(1)
RandomKSubsets(5, 10)
# [1]  1  3  6  9 10
set.seed(1)
RandomKSubsetsLoop(5, 10)
# [1]  1  3  6  9 10

You'll probably want to do more extensive testing, and read the blog to make sure I've done things as it describes.
By the way, there are other algorithms to do this sampling, e.g. the one described in
AUTHOR="McLeod, A.I. and Bellhouse, D.R. ",
YEAR = 1983,
TITLE="A convenient algorithm for drawing a simple random sample",
JOURNAL="Applied Statistics",
VOLUME="32",
PAGES="182-184"

That one is based on a loop by design, and has the advantage that you don't need to know the population size (k in your notation) in advance:  you just keep updating your sample until there are no more items to process.


text:
Q: making a contact list I'm teaching myself android programming. I'm looking for a good contact list tutorial (it'll help me with content providers and the sqlite database).  I've spent hours on google looking for one but they are mostly outdated and the few that I found that aren't give code examples but no explanations.  I've looked on the google developers site but that honestly confuses me more than helps me.
Thanks in advance.

A: 1: You must have read the doc on the Andoid developer site regarding retrieving a list of contacts. It shows the steps you might need to take. There is also a sample of the code in the API Demos which you can find in android-sdk/samples/android-X/ApiDemo/ in your system( if you've installed samples). If you haven't installed samples you can install that from android sdk manager for your version of sdk.
2: There is one good answer of How to call Android contacts list? question. Following the steps would help you.
Hope after reading the two links and trying to understand the sample code in API Demos you would be able to deal with it better. All the best!


text:
Q: How should I print out the position of the first occurrence of a specific letter in a String? Say my string is as follows
String str = "What is up tod?";
I want to use an accessor method to print out the position of the first occurrence of the letter "t". What is an efficient use of code to use? I also want to ensure that it doesn't try to tell me the occurrence of the second "t". Please keep in mind I am searching for how to do this in Java.
Any help or link to similar question is greatly appreciated.

A: Unless I'm missing something, use String.indexOf(int) like
String str = "What is up tod?";
System.out.println(str.indexOf('t'));

Which outputs the first match
3

Alternatively, iterate the characters of the String from left to right checking for 't'; if you find it, print the index and terminate the loop. Like,
String str = "What is up tod?";
for (int i = 0; i < str.length(); i++) {
    if (str.charAt(i) == 't') {
        System.out.println(i);
        break;
    }
}


text:
Q: Server side clusterer for Google Maps After doing a lot of research on different types of clustering coordinates (server side) I am still having problems with choosing the best approach for my project.
My requirements:

*

*Ability to work with more than 1.000,000 coordinates.

*Be able to filter coordinates by point of interest.

*Support map zooming and dragging.

*Fast

*I can't use any third party services.

Here is what I found:

*

*Region quadtree seems to the most suitable algorithm.

*Geo hashing coordinates + Solr for quick retrieval/filtering of points (might only work with small set of data since the clustering will have to happen on the fly)

I would like to know how to deal with map zooming & dragging while maintaining fast response from the server. How can clusters be cached if the maps is dragged, zoomed? Some clusters can be pre-clustered for large areas (continents) but what if there are 10,000 points within once city?
My software stack is postgresql, python, django.

A: Source Code for Clustering with Google Maps and Python with Django
http://forum.mapaplace.com/discussion/3/server-side-marker-clustering-python-source-code/
you will need to modify for postgres database as this uses MySQL (+spatial extensions)
Working Example:
http://www.mapaplace.com/Vancouver/BC/

A: Maptimize could be useful.

A: You could also try this:
https://github.com/biodiv/anycluster
it uses kmeans and/or grid clustering, and you can easily adjust/rewrite it to your needs.


text:
Q: Problem with for loop iterations over data from a queue I'm having a problem reading and processing data from my server. I've spent hours debugging this and it seems as though the problem has nothing to do with the server but is really just an issue with one of my for loops. Its difficult to explain this without actually seeing the data from the server, but I'll do my best to explain this.
Basically I have a server that when I send a command, it returns to me 5 different XML strings sequentially. My program parses this data into Python dictionaries and stores them in different class attributes. As TCP is a stream, I usually don't receive each string separately. What usually happens is I'll receive the first string, then the next 4 strings in groups of 2. So theres normally 3 different iterations of the for loop. However, the last string fails to get processed and stored in an attribute. Here's the logic containing the for loop in question:
 def xmlParser(self, newData):
     print newData
     for string in newData:
         if 'a' in string:
             print 'string1 being processed'
             xmlToDictionary(string, 'string1')
         elif 'b' in string:
             print 'string2 being processed'
             xmlToDictionary(string, 'string2')
         elif 'c' in string:
             print 'string3 being processed'
             xmlToDictionary(string, 'string3')
         elif 'd' in string:
             print 'string4 being processed'
             xmlToDictionary(string, 'string4')
         elif 'e' in string:
             print 'string5 being processed'
             xmlToDictionary(string, 'string5')

The print statements are solely for debugging purposes. My first reaction to the last string not being processed was that it simply wasn't being received. However, by printing newData I can verify that all the strings are received and sent to this function. The newData is a list containing the strings to be processed. For the 3 different iterations, newData looks like this
newData = ['string1']
newData = ['string2', 'string3']
newData = ['string4', 'string5']

Its 'string5' that isn't processed, and I don't believe its because of an exception being raised in xmlToDictionary() because the string 'string5 being processed' isn't printed. And if I include an else statement in the function, that isn't executed either. Its as if the for loop just refuses to perform a second iteration on the last group of data. To test things further, I modified the server script to send 'string5' before 'string4' and, to my surprise, completely fixed the issue and caused 'string5' to be processed and stored as a dictionary. In this situation, newData looked like this
newData = ['string1']
newData = ['string2', 'string3', 'string5']
newData = ['string4']

I also tried modifying the server script to stop sending 'string4' altogether. This also was successful in allowing 'string5' to be processed. The for loop only performed two iterations and newData looked like this
newData = ['string1']
newData = ['string2', 'string3', 'string5']

I tried to put all this together into determining what the problem is, but I'm totally confused. I've never encountered something like this before. If I can't come up with a solution, I'll either leave the script to send 'string5' before 'string4' or I may simply combine all the strings on the server and have it sent as one big string. Regardless, I would still like to determine what is going on here since it may indicate a deeper problem with my program.

A: "As TCP is a stream, I usually don't receive each string separately "
You can't reliably and predictably receive them separately.  TCP makes things into a single stream of data.   That's what TCP/IP must do.  It must buffer to create a "stream" of data, not matter what you try to do at each end to send or receive things "separately".  Separately has no meaning when you use TCP/IP.
You must break up the strings at your end using some feature of the string.  Syntax.  Punctuation.  Something.
Usually, what we do is combine the 5 XML strings into a single XML message.
<message>
    <string1>...</string1>
    <string2>...</string2>
    <string3>...</string3>
    <string4>...</string4>
    <string5>...</string5>
</message>

Parse the one message, find your five strings.  It's much simpler.  And it fits with the way TCP/IP actually works.

A: I just tried your code with the following result:
def xmlParser(newData):
     for string in newData:
         print string
         if 'a' in string:
             print 'string1 being processed'
         elif 'b' in string:
             print 'string2 being processed'
         # ...
         elif 'e' in string:
             print 'string5 being processed'

newData = ['string1']
xmlParser(newData)
newData = ['string2', 'string3']
xmlParser(newData)
newData = ['string4', 'string5']
xmlParser(newData)

And here is the output:
$ python test.py
string1
string2
string3
string4
string5

The loop will process exactly all the element if there is no exception throw inside xmlToDictionary. If you want to verify if throw an exception, try this code:
def xmlParser(self, newData):
     print newData
     for string in newData:
         try:
             if 'a' in string:
                 print 'string1 being processed'
                 xmlToDictionary(string, 'string1')
             # ...
             elif 'e' in string:
                 print 'string5 being processed'
                 xmlToDictionary(string, 'string5')
          except:
             print "excetion error"

Maybe the test condition is not exactly what you want:

if 'a' in string:

Hope I helped you

A: Well, this is a stumper.  Especially since you have not posted the real code, but your own concept of how the code should be working.  Since there is nothing wrong with this concept, there is nothing wrong with your example.
Still, I copied out your code, and then tried to perturb it to get your results.  I think the most likely culprit is that you have some undesirable side effect occurring in your code that processes string4's.  Your description sounds very much like what happens when a list is modified while it is being iterated over.  Here's one example that would cause the exact behavior you describe:
elif 'd' in string:
    print 'string4 being processed'
    # undesirable side effect occurs here
    newData.remove(string)
    xmlToDictionary(string, 'string4')

Try sending a sequence like [string4, string1] and see if string1 gets through.  If not, there is a strong chance that some kind of side-effect is coming from this chunk of code.


text:
Q: submit form in jquery ui i have several form that their name are different, my php code create these forms.
so i created a dynamic javascript that take form id and submit this.
but submit doesnt work and it havent any error!!!
my javascript code:
 $( ".create_form" )
            .click(function() {
                var b = $(this).attr('id');
                $tempId = ("#dialog-form" + b);
                $tempName = ("#NemberForm" + b);
                //==========
                 $( $tempId ).dialog({
                    autoOpen: false,
                    height: 200,
                    width: 350,
                    modal: true,
                    buttons: {
                        "accept": function() {

                                $($tempName).submit(function() {
                                return true;
                            })
                            $( this ).dialog( "close" );
                        }
                    },
                    Cancel: function() {
                        $( this ).dialog( "close" );
                    }
         })
                $( $tempId ).dialog( "open" );
            });

        });

my form code:
 <form method="post" id="NemberForm1" action="index.php?file=trade&operation=accept&id=1&flag=true">

                            <label for="name">number of trade</label>
                            <input type="text" name="number" id="number" class="text ui-widget-content ui-corner-all" />

                        </form>

A: You need to use: $($tempName).submit();

A: There looks like you have an error in your javascript:
Cancel: function() {
                    $( this ).dialog( "close" );
                }
     })// <---- this should not be here
            $( $tempId ).dialog( "open" );


text:
Q: Term for a word that is unintentionally made up of two or more other words? For example, therapist may be split into the + rapist, neither of which (arguably) has anything to do with the original words.
Another example would be conflagration: con + flag + ration. Or weather: we + at + her.
Note that words like threesome and purebred would not qualify, because the parts are intentional and contribute to the original word's meaning.
It seems to me there might be a word for this, which I would describe as "accidental lexical componentry" — but I'm not sure there is one. And if I do think of one I will be sure to add a supplemental (supple + mental) section (sect + ion) to this question (quest + ion).

A: The terms pun, false segmentation, and metanalysis are used in discussion of the phenomenon in p. 132 of Attardo's Linguistic Theories of Humor, which cites several other works that might be worth consulting.

A: They are called redividers or redivided words:

(puzzles) A sequence of letters that can be segmented into two or more different sentences
2001, David B. Searls, "From Jabberwocky to Genome: Lewis Carroll and Computational Biology", Journal of Computational Biology, volume 8, number 3, page 344:
Latter-day puzzle makers in a direct lineage from Carroll's tradition and even more extreme instances of segmentation oddities in what are called redividers (Michaelsen, 1998), for example, observing that the sentence "In every ode linger many" can be resegmented to read "I never yodel in Germany" (Shortz, 1997); such cases serve to point out the duality of the problems of gap assignment and boundary detection, and also inject a combinatorial flavor.

They are apparently also known as charades. Quoting from The Dictionary of Wordplay by Dave Morice:

A few wordplay terms were especially problematic. Recently some writers have tried to upgrade some of the older, more traditional terminology. Some believe that pyramid should be replaced with triangle. Some feel that redivider should replace charade. The terms in the dictionary are usually those that have appeared most often in print. Any other terms may be listed as synonyms, or they may appear as separate entries with a brief notation that cross-references them to the older terms.

There are a number of domain names which have become infamous thanks to their ... redivisibility:

*

*therapistfinder.com

*penisland.com

*expertsexchange.com

*powergenitalia.com

*whorepresents.com

A: As a humorous neologism, you might call them polyparses.


text:
Q: SQL: Get the latest message for the current user I want to get the latest message for each user who chats with the current user
I wrote this code:
This is my data:

SELECT messages.id, messages.body, messages.created_at, messages.is_seen,
            o.username AS from_username, o.image_url AS from_image_url, o.gender AS from_gender,
            c.username AS to_username, c.image_url AS to_image_url, c.gender AS to_gender,

            (SELECT count(messages.id) from messages where messages.to_user_id = 1) AS unread_message_count

            FROM messages

            LEFT OUTER JOIN users AS o ON messages.from_user_id = o.id
            LEFT OUTER JOIN users AS c ON messages.to_user_id = c.id

            WHERE messages.id IN
                (SELECT MAX(messages.id) FROM messages
                    WHERE (messages.to_user_id = 1 OR messages.from_user_id = 1)
                    GROUP BY messages.from_user_id, messages.to_user_id)
            OFFSET 0 LIMIT 5

but it gives me two records for each user chat
for user_id = 1 the desired result is:
id ... from_user_id to_user_id
9 |    | 2          | 1
8 |    | 1          | 3
7 |    | 4          | 1

How can achieve the desired result?
Thanks to @Deepan to provides this
with t(id,body,created_at,is_seen,from_user_id,to_user_id) as (values
(1,'hello how are you man','2022-08-12 03:07:15',false,1,4),
(2,'are you okay','2022-08-12 03:08:14',false,1,4),
(3,'yesIknow you man','2022-08-12 03:08:25',false,1,4),
(4,'where are you from','2022-08-12 03:13:45',false,1,4),
(5,'Iamfromnothing','2022-08-12 03:13:51',false,1,4),
(6,'areyouok?','2022-08-12 03:13:58',false,1,4),
(7,'yesitis','2022-08-12 05:37:09',false,4,1),
(8,'thankyousomuch','2022-08-12 07:09:36',false,1,3),
(9,'youareverywelcome','2022-08-12 07:10:10',false,2,1)
)
select * from t

and this is Online Postgresql Compiler

A: I use CTE and UNION to solve the problem:
WITH CTE AS (SELECT messages.id, messages.body, messages.created_at, messages.is_seen, messages.from_user_id AS user_id FROM
            messages
            where messages.to_user_id = 1
            UNION
            SELECT messages.id, messages.body, messages.created_at, messages.is_seen, messages.to_user_id AS user_id FROM
            messages
            WHERE messages.from_user_id = 1)

        SELECT CTE.id,
                CTE.body,
                CTE.created_at,
                CTE.is_seen,
                users.username,
                users.image_url,
                users.gender,

                (SELECT count(messages.id) from messages where messages.from_user_id = CTE.user_id AND messages.to_user_id = 1 AND messages.is_seen = FALSE ) AS unread_message_count

            FROM CTE
            LEFT OUTER JOIN users on users.id = CTE.user_id
            WHERE CTE.id IN
            (SELECT MAX(CTE.id) FROM CTE GROUP BY CTE.user_id)
        OFFSET 0 LIMIT 5

we don't need the current user anymore, because we have its id, then, we can get its info (username, image_url, gender)
IF THIS ANSWER HAS A PERFORMANCE ISSUE, PLEASE LET ME KNOW, THANKS.


text:
Q: Convert jQuery Deferred into Promise/A+ compliant code with unknown executor function I am using jQuery Deferred for some asynchronous event handling. More or less
due to theoretical purity of my code I want to be Promise/A+ compliant. (The
more practical reason is that later I can update my code to use native Promise
implementations as soon as all major browsers support them.)
However, I use a particular feature of jQuery's Deferred that sets it apart
from Promise/A+ and I do not know how to work around it. Hence, I would
like to know how I can solve the following problem in a Promise/A+ compliant
manner.
The core of the problem is that I already need the Promise object in order
to bind a handler to it before I know the exact executor of the promise,
because the executor depends on some parameters that will become known later.
With jQuery's Deferred this is not a problem because I can create an "empty"
Deferred first, bind some handler to it and then attach the executor to it.
With Promise/A+ the executator must be immediately given as the parameter
of the constructor and will be immediately executed even before the
constructor of the Promise returns.
At the moment I have something like this:
// Create "empty" deferred
deferred = jQuery.Deferred();

// Attach one or more handlers
deferred.then(
  function onFullfilled( value ) {
    // do something
  }
);

// Somewhere at some totally different part of code after the particular
// URL has become known

jQuery.ajax( "www.myhost.com/my/url", {
  error: function( jqXHR ) {
    deferred.reject( jqXHR );
  },
  success: function( data, status, jqXHR ) {
    deferred.resolve( jqXHR );
  }
});

With Promise/A+ I have to do something like this but I can't:
// Create promise
promise = new Promise( function( resolve, reject ) {
  // Error, ups: I do not know the URL yet
  jQuery.ajax( "www.myhost.com/my/url", {
    error: function( jqXHR ) {
      resolve( jqXHR );
    },
    success: function( data, status, jqXHR ) {
      reject( jqXHR );
    }
  });
);

// Attach one or more handlers
promise.then(
  function onFullfilled( value ) {
    // do something
  }
);

Thanks you!
http://www.html5rocks.com/en/tutorials/es6/promises/
https://github.com/promises-aplus/promises-spec
https://www.promisejs.org/
https://api.jquery.com/category/deferred-object/