Q:

Are there drawbacks to taking a job where I will be using a unique programming language?

I just graduated from college with a degree in CS, so I would like to find a job where I can learn more about the field and build up some professional experience.
I've interviewed at a company that uses their own in-house programming language, and I don't think any others use it.  They have not mentioned using any other languages or what they use for a development environment.
What should I be concerned by taking a job like this?  If I were to switch jobs later, would I have to start looking for entry level positions again because I haven't gained any language-specific experience?

A:

Run away, and run away quickly.  Unless you're desperate for a job and are very hungry, this is a situation you want to steer clear of.
I have experience with a company that did this, and the only reason that they did so was so that their employees wouldn't gain meaningful, transferable experience.  It really was all about control.
Others who said here that "programming is programming" are right, but I'd turn that on its head and ask, why not use some standard language for which there is external support, libraries, forums, and a pool of available programmers to choose from?
The only time I think such a situation would be OK would be if the company-only language was for custom hardware.  For example, you have to write everything for the 9000X Gamma-Ray Interferometer using an assembly/machine code specific to that machine.

A:

The main downsides:

working in a "custom environment" can mean limited tools/support which can be infuriating when you get stuck on a problem.
The language they use may be poorly designed, leading to you picking up bad habits early on and write hacky code to create workarounds.
HR baffoons will not recognize your experience. (This is OK. A company that leans on HR to make technical hires is not the kind you typically want to work for. After a couple years, most of the great jobs come through connections anyway.)

If it were me, I would ask them why they use an in-house language. If it is for a legitimate reason, such as crazy hardware contraints, a domain that is not easily modeled in any existing languages then this is totally fine. On the other hand, if their answer suggests that they created their own language so that they could roll together a bunch of hacks and business logic into what amounts to a bunch of wacky macros, then this is a big red flag. You want to make sure that they use good engineering principles, so that you can learn from them and succeed with them. In this case you can see whether they can rationally justify using a home-grown language that does not have a community knowledge base and external support. You may find that their decision is perfectly rational (I believe facebook built their own version of PHP to deal with scalability, which has done pretty well for them), or you may find that they have created a monstrosity of a language that has been so tightly coupled with their core systems, that they cannot seem to break away from it. Trust me, you do not want to be working in a language who's core data type is called ImARInObj (Immutable Accounts Receivable Invoice Object). Tight coupling between a language and a business need often occur in these types of situations, and it would be an absolute nightmare to deal with that sort of system everyday.

A:

Since your resume is basically blank after you graduate, your first job puts a lot of momentum on your future career path.  Your next potential employer(s) will be putting a lot of weight on this job.  So, unless you will be programming in other (more marketable) languages as well, I would highly recommend against taking this job.
I say this from experience because I just left the first job I had after graduating with my C.S. degree, where I was in a position almost exactly as you describe.  Most of the programming was done in a basically unknown language called Progress (a.k.a. OpenEdge ABL).  It's horrible.  Not as bad as COBOL, but close.  I was stuck there because the area around where I graduated does not have many programming jobs, and I was waiting on my wife to graduate with her degree before moving.
Getting that language to talk with other languages or databases was nearly impossible (it came locked in with its own proprietary database as well - bonus!).  I spent a lot of time writing frameworks on my own that already existed in other languages, and were probably better implemented already as the language did not support this type of "extension" paradigm very well.  The language was more tailored towards a "contact Progress Corp. with a feature request, and wait until version n+1 for the new feature" approach.  Needless to say, the software industry doesn't move slow enough for this to be a viable approach.  I won't go on about how bad it was, but I assume you will face a similar thing if you are dealing with a proprietary language as well.  Rewriting existing frameworks in unknown languages has proven to not be a very marketable skill, in my own experience.
To add to that, the existing codebase was, shall we say, sub-optimal.  Lots of legacy code dating back to the late 80's / early 90's.  I would wager you should expect something similar, since I think most companies only stick with the proprietary languages because they carry a lot of this legacy baggage with them.  Remember, it's probably hard for such an employer to find programmers willing to code in this legacy/proprietary environment, plus they probably have to pay for training as well since no one's ever heard of it.  Your coworkers probably won't be titans of software engineering, either, due to the Dead Sea effect (anyone with talent probably already left).  I had a lot of trouble at code reviews trying to use object-oriented code, let alone any type of design patterns, as they just didn't understand it (the people on my team had, at best, an MIS degree (no offense)).
Finally, assuming you do take this job but yearn to do something better once you leave, in order to make yourself competitive for your next job you either have to sacrifice a lot of your free time outside work creating breakable toys in more marketable languages (and probably open source most of what you make), or do what I did and save up some money before you quit and spend a month or two doing same.  Either way, this is a very stressful thing, especially if you enjoy having any type of social relationships outside of work or spending your free time doing something that isn't coding once in awhile.
Now, my experiences may not map directly to your choice, but I'm sure some of it will apply.  Hopefully it will at least give you some questions to bring up.  As others have mentioned, you probably want to find out what tools they use (hardware, software development environment/IDE, and definitely version control).  The Joel Test might be a useful guide.
TL;DR
Don't do it.
P.S. To those saying that learning any new language is useful, that on its own is true.  The problem is when you get stuck using that language almost exclusively full-time for a long period of time, losing exposure to more useful languages (and techniques).  That is what you want to avoid.


Q:

The opacity works with the hover but not the background color. Why?

I want to create a black transparent overlay on 4 images, keeping the size and if possible add some text with the hover. I've looked preview answers but it doesn't work for me. Begginer. Could you help me ?
HTML

CSS
img {
  width: 47%;
  height: auto;
}

#John:hover {
  background: black;
  ;
  opacity: 0.7;
  /* i also tried */
  background: rgba(0, 0, 0, 0.7))
  /* the only thing that works on it is the opacity */
}

section.image {
  text-align: center;
}

Thank you

A:

The background you are trying to apply will not appear on the  tags because your image is blocking it out.
Think of your  tag as a layered element, the top is your actual picture, and below it is the container where the background is set.  Since your image fills up the entire container, your background will never appear.
What you want to do instead is create an element that appears on-top of your image, and appears upon hover.
In order to do this, you need to first wrap your  tags with an element, like this:

I used an  tag because I'm assuming you want something clickable.
Next we can apply some basic styling that inserts an element after the  tag, and makes it appears upon hover.  The result is something like this:

.img-link {
  display: inline-block;
  line-height: 0;
  position: relative;
}

.img-link:after {
  background: rgba(0,0,0,0.3);
  display: inline-block;
  content: '';
  height: 100%;
  opacity: 0;
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  transition: opacity 0.2s linear;
}

.img-link:hover:after {
  opacity: 1; /* show overlay */
}


Q:

How can I read a php file into a string using php?

Lets say I want to use a php script to read the current page's code into a string how would I do that without executing the php contents of the page?
For example using
file_get_contents("test.php");

Will get the contents of test.php but as it does it will execute the code... How can I just get the source code of the file?

A:

file_get_contents() will only execute that file and give you the output as the content if you refer to it as a URL. If you just give a filename, it will attempt to read it from (in your case) the current directory.


Q:

Is it possible to have a git repo inside another git repo

I have a django project managed with git. I am git pushing it to my host. Now, I want to be able to push just one of the directories (inc. all sub dirs) to another git repo. How is it possible, if it is possible at all?
Edit: So I want that directory to be a git repo itself.

A:

You could look at git's support for submodules.  You would add the second repository as a submodule to your main project, e.g. with commands like:
git submodule add git://wherever/blah.git library-code
git commit -m "Added a new submodule called 'library-code'"

When you change into the library-code subdirectory, it's as if the parent repository doesn't exist - you can change origin to use a transport that you can push over and then push as if it were completely independent.
To specify that you want the submodule to be at a particular version, you should change into the submodule and use git checkout to switch to the right version.  Then you change back up to the main repository and stage and commit that new submodule version with:
git add library-code
git commit -m 'Change the submodule version'

The tree of the main repository just stores the version that the submodule should be at, so when you push the main repository, it's not pushing any of the files in the submodule.
In order to split off this subdirectory, while preserving history, you'll need to clone your original repository and user git filter-branch to rewrite the history, as described in this answer:

Detach (move) subdirectory into separate Git repository

Then you can push that to a newly created repository GitHub repository, return to your original project, remove the subdirectory, and replace it with the submodule as described above.
If you're not very familiar with git concepts then this may be difficult for you - I  would recommend reading up on git submodules beforehand.


Q:

How many XP do I get by killing monsters?

I have some items that gives me +X experience points for each kill, or +X%, but how does this compare to the XP obtained by killing those monsters? I can't see how many points I get when I kill them.

A:

Since patch 2.1.2 the "Monster Kills Grant +X experience" secondary affix is multiplicative with your Bonus Experience %.
Sadly, I don't have any sources, but I've done some extensive testing and I found the following formula for XP per kill:
XP per kill = (Base XP * Monster type + Bonus Experience per Kill) * (1 + Bonus Experience * 0.01) * Multiplier * Pool of Reflection
Basically, the system works as follows: every monster has a certain base XP. For instance, a Risen on level 1 give you 30 XP per kill, but only when you are level 1 as well. Once you start gaining levels, you lose 10% XP for each level that you're higher than the monster you just killed.
When you enter Old Tristram Road at level 1, then all monsters will spawn at level 1. Should you reach level 2, then the monsters will not automatically level with you and you'll start receiving 10% less XP per kill (27 at level 2, 24 at level 3, etc.). Only monsters that spawn from this moment on will be at your level, such as Risen crawling out of the ground or graves, or when you enter a new area.
You don't get more XP when the monster level is higher than your level. I started a level 2 co-op game, had my level 1 character join, made the level 2 character spawn some monsters, made the level 2 character leave and let the level 1 character kill the level 2 monster: it gave the regular, level 2 monster XP.
Anyway, the amount of XP that the white version of a monster gives without any bonus XP modifiers on Normal mode is what we'll call Base XP.
Monster type is a modifier that's only relevant for champions or rares. For champions it's 3, for rares it's 5. Otherwise, it's 1. Minions don't give any extra XP.
When you open your inventory screen, and open the details, you'll see two items under the heading Adventure which contribute to how much XP you're earning: Bonus Experience and Bonus Experience per kill. The first item is split in two separate points, the descriptions are from the game itself:

Experience gains from killing monsters increased by X%. This is Bonus Experience
Multiplier: X. This multiplier is granted in multiplayer games. This is Multiplier.

The second point is not entirely true, as activating a Shrine of Enlightenment will increase this value by 0.25.
The second item is Bonus Experience per Kill. This is a value that is added to Base XP before any kind of multiplication occurs.
The last is Pool of Reflection, which were added in patch 2.0.1. Basically, a Pool of Reflection increases any and all experience earned by 25, or times 1.25. This includes not only XP from a kill, but also XP from bounties, quests or Rifts.
Basically, this value in the formula is 1 if you are not under the effects of a Pool of Reflection, and it's 1.25 if you are under the effects of the Pool.
With the Flawless Royal endgame gems, you can have +41% XP on your helmet, or 82% with a well-rolled Leoric's Crown. Note, that the percentage you can get from gear (Ruby in Helm, Level 70 Hellfire Ring, etc.) is additive with the percentages you get from difficulty.
With the recently added Gem of Ease, you get at least 500 bonus XP per kill and per rank you'll get an another extra 50 XP on top of that. This is additive with the +XP from kill secondary affixes.
Grabbing the above formula, a level 50 Gem of Ease, 3380 bonus XP per kill, a Pool of Reflection and Torment VI, a Risen will yield 597762 XP, as opposed to 369750 XP on just Torment VI alone without any of the modifiers and 462187 with a Pool of Reflection. So in here, the +XP per kill grants you 135575 extra XP, but at the cost of DPS from the Emerald in your weapon and probably some more useful secondary affixes.

A:

In general, from about Normal difficulty Act 2 onwards, a +10% or higher bonus (from putting a Ruby into a socketed helmet) is going to beat the pants off of any +XP bonuses you can find.
The +XP bonus enchant tends to max out around +15 XP, which would mean it would beat a +10% XP enchant if monsters were worth less than 150 XP per kill.  About midway through Act 2, I sampled some of the monsters XP values as I was killing them, by monitoring my current XP to level before and after encounters.  Routinely, the average per-kill was more than 200 XP.  As you progress through the game, the amount of XP per-kill will increase, and easily dwarf the small bonuses you can get from +XP gear.
This doesn't mean that you should not use +XP enchants on other equipment - but especially later in the game, it becomes less and less worth the investment.  Almost always,  if you have a choice between a socketed helm with a good quality ruby, or a non-socketed helm with a +XP enchant, take the helm with the ruby.
Bear in mind that the XP you gain from monsters also depends on your level versus the level of the monsters, and information about monster levels is not readily available in-game.  Thus, the only real way you can say how much the monsters you are fighting are contributing to your XP is to hover over your XP bar before and after killing them, and then do the math based on these values.


Q:

add NA for a value based on a condition, with tidyverse only, R

I have age variable with very odd numbers such as 1000, 6666. Now obviously this data is bad for any analysis. I want to keep the obvious age, but want to replace weird numbers with NA. For example, 0, 1,2,3 4, ... 100, I shall keep. But from >100 I want to put them as NA. Yet, want this only with tidyverse. I looked int several functions like na_if for example but cannot achieve what I want.
This is an example of data I have. Look at row 66 and you will see what I am talking about.
age_dput <- structure(list(Age = c(63, 19, 23, 28, 40, 31, 60, 26, 35, 44,
    30, 47, 26, 45, 21, 38, 40, 28, 26, 40, 60, 33, 72, 40, 32, 32,
    43, 24, 25, 39, 50, 22, 37, 53, 51, 42, 52, 29, 19, 42, 58, 61,
    29, 26, 45, 29, 20, 26, 28, 43, 2, 42, 40, 33, 43, 53, 55, 27,
    36, 41, 30, 54, 55, 6222, 21, 26, 38, 23, 48, 29, 44, 42, 35,
    27, 28, 20, 59, 80, 35, 36, 24, 29, 34, 31, 25, 37, 30, 31, 48,
    28, 30, 65, 45, 27, 39, 29, 34, 29, 76, 40)), row.names = c(NA,
    -100L), class = c("tbl_df", "tbl", "data.frame"), problems = structure(list(
        row = c(2910L, 35958L), col = c("how_unwell", "how_unwell"
        ), expected = c("a double", "a double"), actual = c("How Unwell",
        "How Unwell"), file = c("'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'",
        "'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'"
        )), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
    )))

A:

You can use replace or if_else :
library(dplyr)
age_dput %>%
  mutate(clean_age_replace = replace(Age, Age > 100, NA_real_),
         clean_age_if_else = if_else(Age > 100, NA_real_, Age))


Q:

Generate non-obfuscated binary content for PDF files

When I open a PDF file compiled from LaTeX with a text editor (e.g. Notepad++), the content of the file is a not human readable and it looks like below, so it seems to me that the information cannot be processed by potential crawlers.

n×å9.â^ÑäùàÉ¨•”    HTÏ•ì#ò Ž–}q”mÃ¤Š9ÒrbtRšá™g—û}Açú¦nƒÖ…‡”jKœˆ FàÆµÀmþåá•N:º‚~éWF¶DX‹m#‚D˜Àm;Ñum?OŠÀÊ¢ßÎ[ÈuóõÄ÷;Ý6"-@pñÃ¤Ù(ÖXÜÕËaœyýûdRìørêÑbÎ²(\n^Øþ2Öƒ;¬÷ª»¦Òv0þ®±úßY'°³½‹%…ß¥ºíúŸKåÒì¶¶\êæñÕ_–áúª  –ò1üj9¶,Ö×VæY¼wæ¬Döð}]

Is there a possibility to generate the PDF file so that when the PDF document displays an information like "Specific detail 1", I can also find this string "Specific detail 1" in the binary content of the file when I open it with a text editor?
This is useful for example when a PDF resume is created in LaTeX and it must be automatically parsed by various text analyzers.

A:

For pdfTeX
\pdfcompresslevel = 0 %
\pdfobjcompresslevel = 0 %

For LuaTeX
\pdfvariable compresslevel = 0 %
\pdfvariable objcompresslevel = 0 %

For use with (x)dvipdfmx (XeTeX, upTeX, etc.)
\special{dvipdfmx:config z 0}
\special{dvipdfmx:config C 0x40}

For ps2pdf routes
\special{/setdistillerparams where
    {pop<</CompressPages false>>setdistillerparams}
  if
}
\special{/setdistillerparams where
    {pop<</CompressStreams false>>setdistillerparams}
  if
}


Q:

A question in Banach space

Given $A\in\Bbb R^{m\times n}$, define $$\gamma_2(A)=\min_{XY=A}\max_{i,j}\|x_i\|_{\ell_2}\|y_j\|_{\ell_2}$$ where rows of $X$,columns of $Y$ given by $\{x_i\}_{i=1}^m,\{y_j\}_{j=1}^n$ respectively.
Where could I find a reference for fact that $$\gamma_2^2(A)\leq\| A\|_{\ell_1^n\rightarrow\ell_{\infty}^m}rank(A)?$$
Should this be  $$\gamma_2^2(A)\leq\| A\|_{\ell_1^n\rightarrow\ell_{\infty}^m}^2rank(A)?$$
Above is lemma 4.2 in http://www2.mta.ac.il/~adish/Pubs/Papers/complexity_matrices.pdf
What is terminology for $\gamma_2(A)$ in literature?
posted https://math.stackexchange.com/questions/1196950/a-question-in-banach-space

A:

Given a linear operator $A$ from a Banach space $E$ to a Banach space $F$, the quantity $\gamma_2(A)$ is the infimum (actually, it is a minimum) of $\|X \| \cdot \|Y\|$, where the minimum is over all operators $Y: E\to H$, $X: H \to F$ s.t. $XY=A$ with $H$ a Hilbert space.  This agrees with your definition when $E= \ell_1^n$ and $F= \ell_\infty^m$. The quantity $\gamma_2(\cdot)$ is an important operator ideal norm; it is discussed in many books on Banach space theory. The most elementary of those is the book of Albiac and Kalton (section 7.3), but they do not use the notation $\gamma_2(\cdot)$.  Or look at Diestel, Jarchow, Tonge or Tomczak-Jaegermann. The second form for your inequality is the correct one (after all, it must be homogeneous) and is immediate from the ideal property of $\gamma_2(\cdot)$ and John's theorem that the isomorphism constant of an $n$-dimensional Banach space to $\ell_2^n$ is at most $\sqrt{n}$.


Q:

Handling Leap Day, both when it exists and when it doesn't

I have a data set that is supplied via CSV.  Whenever that csv is supplied in a leap year it contains the 29th of February and whenever it is supplied in a non-leap year it does not.  I only get a single year of data and I have to copy that data forward for X amount of years.
I need to remove the 29th if it exists in years it shouldn't and create it if it doesn't exist in the years it should.
EDIT:
I am going back to the beginning so that the entire picture is presented.
I am given 3 csv files that I utilize to make a single dataframe:

df0 contains 4 columns that I require to filter and create a final dataframe
from df1
df2 contains 3 columns that I require to filter and create a final
dataframe from df1
df1 is the dataframe that contains a single year
of data (but it is initially missing the year, I have to add it from df0 based on start date)

df0 Partitioned for the correct columns looks like this:
+------------+------------+--------------------+--------------------+
| project_id | start_date | degredation_factor |      snapshot      |
+------------+------------+--------------------+--------------------+
| pid1       | 1/1/2021   | 0.60%              | 2/28/2020 18:35:46 |
| pid2       | 1/1/2024   | 0.40%              | 2/28/2020 18:35:46 |
+------------+------------+--------------------+--------------------+

*note this could have 20+ unique projects in it
df2 looks like this :
+------------+---------------+--------------------+
| project_id | duration_year |      snapshot      |
+------------+---------------+--------------------+
| pid1       |            10 | 2/28/2020 18:35:46 |
| pid1       |            15 | 2/28/2020 18:35:46 |
| pid2       |            20 | 2/28/2020 18:35:46 |
| pid2       |            25 | 2/28/2020 18:35:46 |
+------------+---------------+--------------------+

*can contain multiple lines per project, need only the line with the longest duration
df1 looks like this:
+-----+-------+------+-------------+--------------------+------------+------+
| day | month | hour | hourly_rate |      snapshot      | project_id | year |
+-----+-------+------+-------------+--------------------+------------+------+
|   1 |     1 |    1 |      123.43 | 2/28/2020 18:35:46 | pid1       | 2021 |
|   1 |     1 |    2 |      120.11 | 2/28/2020 18:35:46 | pid1       | 2021 |
| ... |   ... |  ... |         ... | ...                | ...        |  ... |
|  31 |    12 |   24 |      123.43 | 2/28/2020 18:35:46 | pid1       | 2021 |
+-----+-------+------+-------------+--------------------+------------+------+

*every day, every hour, 1 year
I have to take that 1 year dataframe and append to it all the forward years for every project.  so in the case of pid1 I need to append 2022 - 2036 and I need to perform the degradation on the hourly rate for 2022 and beyond ( formula : hourly_rate  * (1 - (float(row.loc['degradation_factor_solar'].strip('%')) * (year# - 1)/ 100))
my code previously (which was doing all of the appending and calculations, except it had the 29th of February in all years and hence the problem):
        df0_partition_1 = df0[['project_id', 'start_date', 'degradation_factor', 'snapshot_datetime']]
        df0_partition_2 = df0_partition_1.groupby(
            ['project_id', 'start_date', 'degradation_factor', 'snapshot_datetime']).size().reset_index()
        df2_partition_1 = df2.groupby(['project_id', 'snapshot_datetime'])['duration_year'].max().reset_index()
        df_merge = pd.merge(df0_partition_2, df2_partition_1, on=['project_id', 'snapshot_datetime'], how='left')
        df_parts = df_merge[
            ['project_id', 'start_date', 'duration_year', 'degradation_factor', 'snapshot_datetime']].dropna()

        for index, row in df_parts.iterrows():
            df1_filtered = df1[(df1['project_id'] == row['project_id']) &
                               (df1['snapshot_datetime'] == row['snapshot_datetime'])]
           df1_filtered['year'] = pd.to_datetime(row['start_date']).year
            df1_filtered.reset_index(inplace=True, drop=True)
            df1_filtered.drop(columns='project_name', inplace=True)
            df_stg_1 = df1_filtered.copy()  # deep=True)
            df_stg_2 = pd.DataFrame()
            df_final = pd.DataFrame()

            for y in range(1, int(row['duration_year']) + 1):
                year = df1_filtered['year'] + (y - 1)
                hourly_production = df1_filtered['hourly_production']
                df_stg_1['year'] = year
                df_stg_1['hourly_production'] = hourly_production * (
                        1 - (float(row.loc['degradation_factor_solar'].strip('%')) * (y - 1)/ 100))
                df_stg_2 = df_stg_2.append(df_stg_1)
            df_final = df1_filtered.append(df_stg_2)

this was giving me all of the years, but it presented the leap year problem when the data was input on a leap year.  The 29th exists and it gets populated into every year.  On Non-leap years when they provide the data it will lack the leap day and thus the leap day would have to be created from the 28th.
This is now a partial duplication of a previous post, my apologies.  I needed to expand to show the entire issue and why I am trying to solve what I am trying to solve.
I am happy to create the final dataframe in a different manner if it gets rid of this issue for leap day.
EDIT 2:
I tried df_stg_3.drop(df_stg_3[(df_stg_3['year'] % 4 != 0) & (df_stg_3['month'] == 2) & (df_stg_3['day'] == 29)].index)
for the drop is not actually working, I had the wrong file.

A:

Here is where I ended up.  It may not be the most elegant, but it does work.
        df0_partition_1 = df0[['project_id', 'start_date', 'degradation_factor', 'snapshot_datetime']]
        df0_partition_2 = df0_partition_1.groupby(
            ['project_id', 'start_date', 'degradation_factor', 'snapshot_datetime']).size().reset_index()
        df2_partition_1 = df2.groupby(['project_id', 'snapshot_datetime'])['duration_year'].max().reset_index()
        df_merge = pd.merge(df0_partition_2, df2_partition_1, on=['project_id', 'snapshot_datetime'], how='left')
        df_parts = df_merge[
            ['project_id', 'start_date', 'duration_year', 'degradation_factor_solar', 'snapshot_datetime']].dropna()

        for index, row in df_parts.iterrows():
            df1_filtered = df1[(df1['project_id'] == row['project_id']) &
                               (df1['snapshot_datetime'] == row['snapshot_datetime'])]
            dest_key_name = 'dw/project_8760/{}/{}/{}'.format(row['project_id'], file_partition_time, 'df.csv')

            df1_filtered['year'] = pd.to_datetime(row['start_date']).year
            df1_filtered.reset_index(inplace=True, drop=True)
            df1_filtered.drop(columns='project_name', inplace=True)
            df_stg_1 = df1_filtered.copy()
            df_stg_2 = pd.DataFrame()
            df_final = pd.DataFrame()

            for y in range(2, int(row['duration_year']) + 1):
                year = df1_filtered['year'] + (y - 1)
                hourly_production = df1_filtered['hourly_production']
                df_stg_1['year'] = year
                df_stg_1['hourly_production'] = hourly_production * (
                        1 - (float(row.loc['degradation_factor'].strip('%')) * (y - 1)/ 100))
                df_stg_2 = df_stg_2.append(df_stg_1)
            df_stg_3 = df1_filtered.append(df_stg_2)

            if df1_filtered[(df1_filtered['month'] == 2) & (df1_filtered['day'] == 29)].empty is False :
                filter_final_1 = df_stg_3[(df_stg_3.year % 4 != 0) & (df_stg_3.month == 2)]
                filter_final_2 = filter_final_1[(filter_final_1.day == 29)]
                df_final = pd.concat([df_stg_3, filter_final_2, filter_final_2]).drop_duplicates(keep=False)
            else:
                df_stg_3_filtered = df_stg_3[(df_stg_3.year % 4 == 0) & (df_stg_3.month == 2)]
                df_stg_4 = df_stg_3_filtered[(df_stg_3_filtered.day == 28)]
                df_stg_4['day'] = 29
                df_final = pd.concat([df_stg_3, df_stg_4])
                df_final.sort_values(by=['year', 'month', 'day', 'hour'])


Q:

How to replicate only one data type 'n' times in list using rep()

fred <- list(num = c(1:10) , name = "hello")

How to repeat num type 5 times and name type 10 times in lists using rep()?

A:

You can try mapply which applies the function to the elements of fred and the times vector.
mapply(function(x, y) rep(x, times=y), fred, c(5, 10))
$num
 [1]  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9
[30] 10  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10

$name
 [1] "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello"

The list is replicated simply using
rep(fred, c(5,10))


Q:

Connecting to remote mysql works in terminal, not via PHP PDO script

I am facing a weird problem here
we have a server A where the app files are stored
and B server with database
Tried to connect via command prompt from server A to B using the command
mysql -h xx.xx.xx.xx -u root -p password - and it worked

NOw i tried to create a php script in server A to connect to server B
the command is
$this->db=new PDO('mysql:host=xx.xx.xx.xx;dbname=databasename','root','password');

Connection failed: SQLSTATE[HY000] [2003] Can't connect to MySQL
  server on 'xx.xx.xx.xx' (13) Fatal error: Uncaught exception
  'Exception' with message 'SQLSTATE[HY000] [2003] Can't connect to
  MySQL server on 'xx.xx.xx.xx' (13)'

Unable to find a solution on this.
Can any help on this?
thank you

A:

I got it working by running a command in the database server :)
setsebool httpd_can_network_connect_db=1

thanks for the replies yycdev


Q:

Order by most contained in a field from another table

Cars table
---ID---    ----car----
   1            bmw
   2            mercedes
   3            volvo

Posts table
---ID---      ----post----
   1              I have a volvo car
   2              I like volvo cars
   3              I dont like bmw

I would like to get a result that ordering cars from most contained in posts text to fewer.
Expected result:
Volvo
Bmw
Mercedes

A:

You could try a simple join here with aggregation:
SELECT
    c.car
FROM Cars c
LEFT JOIN Posts p
    ON p.post LIKE CONCAT('%', c.car, '%')
GROUP BY
    c.car
ORDER BY
    COUNT(p.ID) DESC;

Strictly speaking, we should use a regex match to detect a car name occurring inside a post.  REGEXP can be used for that, and the join condition would then become:
ON p.post REGEXP CONCAT('[[:<:]]', c.car, '[[:>:]]')


Q:

Multiple asp:Repeater DataBind

I am 90% certain I have acheived this before, but I cannot remember how I did it.
I have a repeater which I would like to use twice on a page as the structure and databinding events are the same, but the data binding to the repeater is obviously different.
In the past I believe I set the datasource on the repeater then databinded, and then did the same again but with another datasource, so effectively:
MyRepeater.DataSource = DataSourceOne;
MyRepeater.DataBind();
MyRepeater.DataSource = DataSourceTwo;
MyRepeater.DataBind();

Now this would have produced the html twice on the page. In this instance two lists, with different data contained inside of them.
Thinking about it, it could possibly the type of datasource used. Before it might of been a dataset/table I was binding to the repeater, but this time I am using an ArrayList.
ArrayList Items = new ArrayList();
Items = this.GetMenu(this._ProductsPageID);
this.rep_ProductsPortfolio.ItemDataBound += new RepeaterItemEventHandler(ProdPortItemDataBound);
this.rep_ProductsPortfolio.DataSource = Items;
this.rep_ProductsPortfolio.DataBind();

// Get portfolio
Items = this.GetMenu(this._PortfolioPageID);
this.rep_ProductsPortfolio.ItemDataBound += new RepeaterItemEventHandler(ProdPortItemDataBound);
this.rep_ProductsPortfolio.DataSource = Items;
this.rep_ProductsPortfolio.DataBind();

I have also tried using a different ArrayList for each repeater, but that didn't work either.
At the moment all that happens is the second databind is rebinding over the old repeater and I only have one on the page.
Any ideas?
Thanks in advance

A:

Are you sure in the past you didn't use two repeaters with one datasource?
I think you need to use two repeaters here.

A:

If you change the DataSource it owerrite the first one.
My idea is to use two repeaters.


Q:

How to customize the DatePickerDialog to show custom date in the text? - Swift

I am trying to change the date written inside the datePickerDialog to make Hijri Islamic date.
I found the function of showing the Hijri date as NSDateComponents
func hijriDate(dateToConvert: NSDate) -> NSDateComponents{
        let islamic = NSCalendar(identifier:NSCalendarIdentifierIslamicCivil)!
        let hijriComponents = islamic.components(NSCalendarUnit(rawValue: UInt.max), fromDate: dateToConvert)
        print("Date in system calendar:\(dateToConvert), in Hijri:\(hijriComponents.year)-\(hijriComponents.month)-\(hijriComponents.day)")
        return hijriComponents
        //"Date in system calendar:2014-09-25 09:53:00 +0000, in Hijri:1435-11-30"
}

So when the datePicker will print the date i wanna show the islamic component by converting the NSDate to Hijri Components.
So is there any way to show custom text for the datePickerDialog ? So I can use the function above to print out the date as Hijri from the NSDate ?
UPDATE:
The current DatePickerDialog I use is this:
let STR_DATE_FORMAT = "EEEE d, MMM yyyy"

DatePickerDialog().show("Select date".localized(), doneButtonTitle: "OK".localized(), cancelButtonTitle: "Cancel".localized(), datePickerMode: .Date, defaultDate:self.data.event_date ) {
                (date) -> Void in
                self.data.event_date = date
                self.event_date.text = date.toString(format: .Custom(STR_DATE_FORMAT)) as String
}

A:

Set calendar of the date picker as below,
  datePicker.calendar = NSCalendar(identifier:NSCalendarIdentifierIslamicCivil)!

Result looks like,


Q:

MonoDroid Bluetooth

I have been working with Monodroid for a few days and still can't figure out how to send a command through Bluetooth.
This is my scenario: I have a Tablet/Cellphone working with Android 2.1+ and need to send and receive data to a Bluetooth printer (in bytes).
What i managed so far:
using Android.Bluetooth; // library necessary

BluetoothAdapter bth = BluetoothAdapter.DefaultAdapter;
if (!bth.IsEnabled)
    bth.Enable();

ICollection<BluetoothDevice> bthD = bth.BondedDevices;

foreach (BluetoothDevice d in bthD)
{
    if (d.Name == "DPP-350")
    {
        Java.Util.UUID UUID = Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");
        // Get the BLuetoothDevice object
        BluetoothSocket s = d.CreateRfcommSocketToServiceRecord(UUID);

        s.Connect();

        // Try to send command
        ...

        s.Close()
    }
}

The program asks for the pairing info, with is done correctly.
I have tried many ways to send the command:
// the command
// Self_Test = Chr(27) + Chr(84) = ESC T
byte[] dBytes = System.Text.Encoding.GetEncoding(1252).GetBytes(Self_Test);

// wont work
new Java.IO.ObjectOutputStream(s.OutputStream).Write(dBytes);
// wont work
System.IO.Stream st = s.OutputStream;
if (st.CanWrite)
{
   st.Write(dBytes, 0, dBytes.Length);
   st.Flush();
}
// wonk work
s.OutputStream.Write(dBytes, 0, dBytes.Length);
s.OutputStream.Flush();

No error is raised. I'm running out of options here...
Thanks in advance!

A:

I know this is a very old thread, but I wanted to post a reply so others will know the answer. I too searched hard with no luck.
s.OutputStream.BeginWrite(buffer, 0, buffer.Length,new AsyncCallback(delegate {}), State.Connected);

Thanks.


Q:

English to Propositional Calculus: M. If M and T then P. If L then T.

I have the following collection of statements:

I have money. If I have money, and have time, I can buy a pizza. If I left home early enough, I have time.

The atomic sentences can be represented as the following symbols:

M: I have money.
T: I have time.
P: I can buy pizza.
L: I left home early enough.
T: I have time.

How would I express the statements in terms of propositional calculus?
The part I'm confused about is how to join '$M$', '$M\land T\Rightarrow P$' and '$L \Rightarrow T$'.

A:

Simply use the "$\land$" connective to join them, but note that since it has higher precedence than "$\to$" (by standard convention), you have to use brackets:

$M \land ( M \land T \to P ) \land ( L \to T )$".


Q:

What term means "to imagine one is someone else"?

I am looking for a professional term, used to describe a situation in which a person imagines that they are someone else. E.g., someone playing a first-person game will imagine that they are within the game, and "super-impose" their personality onto that character. Or, a child might imagine they are a superhero from their favorite story and consider what they would do with the superhero's abilities.
The term "role-play" is related, but not precisely what I am looking for. "Role-play" seems to emphasize the "playing" or "acting" aspect. I want a term that just means, "imagining you are someone else".

A:

Impersonate:
to assume the character or appearance of; pretend to be; to act or play the part of; (Archaic.) to represent in personal or bodily form; personify.
Less common is
Personate:
to act or portray; to assume the character or appearance of; personify.
Impersonate is often used in a negative sense where deception is involved, but this definition shows that personate can be used the same way in legal terms.
UPDATE
Another word that might come across is immersion. The linked article is somewhat convoluted (which is no surprise given that it is posted under the heading "The Gaming Philosopher"), but the general meaning is here:

Fictional identification with a character (immersion) is helped by mechanics that give total authorship over the character's beliefs, desires, decisions and so forth to one player.

So a person having an immersion experience has total control over the traits of the character they are imagining or pretending to be.
UPDATE 2
I have come across another term that is more about one's state of mind (imagination) rather than ones actions (role-playing).
Escapism

The avoidance of reality by absorption of the mind in entertainment or
  in an imaginative situation, activity, etc.

Escapism is more a state-of-mind than an action, as it attests to the mental state that may drive one to actually escape their current circumstances. It begins with the visualization of alternative conditions. These conditions might be the environment (a vacation escape usually begins with the visualization of that other place), but one can also turn to an alternative identity.
From this article on the subject, the writer discusses escapism and identity in both positive and (clinically) negative terms. Here is an excerpt:

From a psychology perspective, Baumeister (1991) commented that
  individuals may be trying to escape their current ideas of “self”. He
  also suggested that escape may be temporarily achieved by “shrinking”
  down the self to its bare minimum. … The feeling of flow experience
  has been described as an enjoyable and focused concentration in which
  one experiences a loss of self-consciousness (Csikszentmihalyi, 1990).
  Hence, being in flow means temporarily escaping one’s ideas of self.
  From a psychology perspective, Baumeister (1991) commented that
  individuals may be trying to escape their current ideas of “self”. He
  also suggested that escape may be temporarily achieved by “shrinking”
  down the self to its bare minimum. … being in flow means temporarily
  escaping one’s ideas of self.

It’s not a great leap to say that imagining that one is someone else is a form of escapism. This would be the case whether it's as a short-term entertaining diversion or as a short- or long-term means to avoid reality in one's personal life.
Since escapism covers more than imagining about one's identity, I suggest a phrase such as identity escapism might meet your needs.

A:

This can be described as role-projection.  I.e. "imagining oneself in the role of another".
This usage isn't common, but it exists in the psychology literature.  E.g.:

Hirschman (1983) and others (d'Astous & Deshenes 2005) posit that
  certain traits can influence participation in fantasy-related consumption behaviours,
  including role-projection and escapism
  (i.e., to get away from one's everyday life)
  or other activities involving visualization.
  Specifically, an individual's preference for using imagination,
  can predict a tendency to engage in a certain types of fantasy,
  including both role-projection and escapism.

link

Imaginal Responses mainly refer to role projection and escapism.

link

A:

I don't see why Roleplay isn't considered valid here...but if you are looking for another term...
"Acting" or "to act" describes how one can pretend to be another person, and does not necessarily have to mean in media or otherwise.
The word "avatar" describes such a person that one uses to act as another or as a representation of themselves, but doesn't act as a verb.
"Impersonate" can be used if you are acting like a specific person, though not if they are an imaginary person such as a made-up superhero, or if you are acting through them like in a video game.
If you're looking for another hyphenated term, "to act something out" describes the way in which one portrays a certain personality, activity, or other imagined thing.
Hopefully one of these are what you are looking for.


Q:

ReDim in Subroutine VBA

Sub testCov()
    Rng2 = Sheets("20 Asset Model").Range("b3:f48")
    Dim covMatrix() As Variant
    ReDim covMatrix(1 To Rng2.Columns.Count, 1 To Rng2.Columns.Count)
    Call constructCovMatrix(Rng2, covMatrix)
    MsgBox (covMatrix)
End Sub

Sub constructCovMatrix(rng, ByRef covMatrix)
    '@rng The Range of the return series.

    Dim i As Integer
    Dim j As Integer
    For i = 1 To rng.Columns.Count
        For j = 1 To rng.Columns.Count
            covMatrix(i, j) = Application.WorksheetFunction.Covar(rng.Columns(i), rng.Columns(j))
        Next
    Next
End Sub

The code stops at the line ReDim, saying object missing. Why is this? Thanks

A:

Try this to set your range as a range object be declaring it: (comments in-line)
Sub testCov()

    Dim Rng2 As Range '- Declare variable
    Set Rng2 = Sheets("20 Asset Model").Range("b3:f48") '-Set range
    Dim covMatrix() As Variant
    ReDim covMatrix(1 To Rng2.Columns.Count, 1 To Rng2.Columns.Count)
    Call constructCovMatrix(Rng2, covMatrix)
    MsgBox (covMatrix)

    Set Rng2 = Nothing '- Cleanup anytime 'Set' is used
End Sub

Note:
You may want to go to the VBA editor's setting sand click tools > options > Declare varible decleration > checked
This will ensure that you need to declare all your variables.
As is, the above code did not declare Rng2 as a range. So when Excel first sees the name Rng2 it creates a Variant type variable and sets it equal to the range of the sheet in the first line. Excel notices that Sheets("20 Asset Model").Range("b3:f48") is an array of cells, and it treats the variant Rng2 as an array type variable going forward for the rest of your code. Assuming that you want to use the variable named Rng2 as a range, we can declare it as such and use the Set command to assign it.
When you don't declare your variable types its easy for a mix-up like this to happen.


Q:

How to select row values for max(2 columns)

I am working out a query in MS SQL Server. I have my table like this
Table( Level int, Stage int, values varchar)
Level Stage Value
1     1
1     2
1     3
2     1
2     2

I need to find the row having maximum value by level and then by stage. ie., I need to get the result as
Level  Stage
2      2

When I try the below query I get the value 22 and in one column. I need that in 2 distinct columns as specified above.
SELECT MAX(CAST(wfLevel as varchar(2)) + CAST(approvalStage as varchar(2)))
  FROM [AuditReporterDB].[dbo].[RequestHistory]

Can anyone help.

A:

SELECT TOP 1 Level,Stage
FROM tableName
ORDER BY Level Desc,Stage Desc


Q:

Find UTC time zone using offset

I find rawoffset from google API(https://maps.googleapis.com/maps/api/timezone/json?location). Now i want to find UTC timezone not UTC time.
For example: I have New York City rawoffset and Wana to result UTC-5:00.
It is possible in php or javacript?

A:

You can use moment-timezone. Then you can use like this to get timezone
moment.tz([2012, 0], 'America/Denver').format('Z z');
It will results -> -07:00 MST


Q:

Proving by contradiction that if $a\in\mathbb Q,b\in \mathbb R\setminus \mathbb Q$ then $a+b\in \mathbb R \setminus \mathbb Q$

I'm trying to prove by contradiction that if $a\in\mathbb Q,b\in \mathbb R\setminus \mathbb Q$ then $a+b\in \mathbb R \setminus \mathbb Q$, I already proved it with contra position and a direct proof seems impossible.
Suppose $a\in\mathbb Q,b\in \mathbb R\setminus \mathbb Q$ show that $a+b\in \mathbb Q$.
So $a=\frac p q, p,q\in \mathbb Z,q\neq 0$, so we have $\frac p q+b=\frac {p+bq}q$ and now I'm basically back to square one since I can't assume that a sum and product of integers and irrationals isn't an integer.

A:

To put it simply, you only need to use that the sum of rationals is again a rational. If $a+b \in \Bbb Q$, you would get that $b = (a+b) - a$ would be a rational, contradiction.

A:

Or if this isn't correct (by contradiction) then let $f_a:\mathbb R \setminus \mathbb Q\to \mathbb Q$ with $f_a(b)=a+b$. Then $f_a$ is $1-1$ which is wrong because $\mathbb Q$ is countable.

A:

Your problem is a misunderstanding of the technique of proof by contradiction.
When performing a proof by contradiction, you make your usual assumptions (e.g., $a\in\mathbb Q, b\in\mathbb R\setminus \mathbb Q$) and you assume the logical negation of what you're trying to prove (e.g., $a+b\in\mathbb Q$).
Per your description, it looks like you made your usual assumptions, and then tried to prove the logical negation of what you were trying to prove; that is impossible to do.


Q:

Estimation of Location of First Acoustic Peak

This question is inspired by the page at NED and references it throughout the question.
On the linked page there is a method for calculating the location of the first acoustic peak of the CMB. It involves calculating the distance to the surface of last scattering.
The expression they have for calculating this is
$$d_{sls} = \frac{c}{H_0 \sqrt{\Omega_m} (1+z_{sls})}\int_{0}^{z_{sls}} [\Omega_m(1+z)^3+\Omega_\Lambda]^{-1/2} dz$$
Where $\Omega_m = .3$ is the current mass density, $\Omega_\Delta = .7$ is the current dark energy density, and $z_{sls} = 1100$ is the redshift at the surface of last scattering.
They then calculate the integral by estimating it as a binomial expansion. As a result, they calculate (and I verified) that
$$\int_{0}^{z_{sls}} [\Omega_m(1+z)^3+\Omega_\Lambda]^{-1/2} dz \approx 1.21$$
And as a result, they calculate $l \approx 200$.
However, if I plug this integral into Wolfram Alpha, I get
$$\int_{0}^{z_{sls}} [\Omega_m(1+z)^3+\Omega_\Lambda]^{-1/2} dz \approx 3.19$$
And as a result, I calculate $l \approx 500$.
Given that $l \approx 200$ has been measured by the Planck satellite, this is a huge discrepancy! I have two questions:

Is there something about Wolfram Alpha that would given a bad approximation to this integral? Is it possible that the binomial approximation method gives a more accurate result?
If not, then why is such a bad approximation used in the calculation and accepted as accurate?

Apologies if this is not clear. At the end of the day, I'm trying to understand this calculation better and anything that helps me do so would be appreciated.
Thank you!

A:

The webpage you linked to is remarkable, to say the least. It contains a whole chain of errors, producing a wrong result that the authors mistakenly interpret as accurate. Based on what I've seen on that page alone, I wouldn't trust anything else from that article.
So, first of all, Wolfram Alpha is correct, and I applaud you for checking their calculations. I should point out that
$$
d_{sls} = \frac{c}{H_0\,(1+z_L)}\int_0^{z_L}\left[\Omega_{m,0}(1+z)^3 + \Omega_{\Lambda,0}\right]^{-1/2}\,\text{d}z,
$$
so in your question you've put an extra $\sqrt{\Omega_{m,0}}$ in the denominator, which shouldn't be there.
Let's see where things go wrong:
The most glaring mistake is the step from (55) to (56):
$$
\begin{align}
d_{sls} &= \frac{2c}{7H_0(1+z_L)}\left[7\,\Omega_{m,0}^{-1/2} - 2\,\Omega^{\vphantom{1/2}}_{\Lambda,0}\,\Omega_{m,0}^{-3/2} + \mathcal{O}\left((1+z_L)^{-1/2}\right)\right]\\
&\approx \frac{2c}{7H_0(1+z_L)}\left[9\,\Omega_{m,0}^{-1/2} -2\,\Omega_{m,0}^{-3/2}\right] = \frac{2c\,\Omega_{m,0}^{-1/2}}{7H_0(1+z_L)}\left[9 -2\,\Omega_{m,0}^{-1}\right].
\end{align}
$$
So there's a $\Omega_{m,0}^{-1}$ term instead of $\Omega_{m,0}^3$. As a result, $d_{sls}/r_s \approx 60$ instead of $221$.
The second mistake is that (55) itself is wrong. The binomial expansion of the integrand in $d_{sls}$ is only accurate for large values of $z$, but the integration is taken over the entire range $[0,z_L]$, and depends crucially on the value of the primitive function in $z=0$. This is why this approximation is so different from the correct numerical calculation with Wolfram Alpha. If you insert the correct value, you should get $d_{sls}/r_s \approx 149$ (and not $300$, because of the $\sqrt{\Omega_{m,0}}$ you added).
But the problems don't stop there. The calculation of the sound horizon $r_s$ is also wrong. Equation (47) should be
$$
r_s = a_L\int_0^{t_L}\frac{c_s}{a(t)}\,\text{d}t.
$$
Using (49) and the convention $a_0 = 1$, this can be written as
$$
r_s = \frac{a_L}{H_0}\int_0^{a_L}\frac{c_s\,\text{d}a}{\sqrt{\Omega_{r,0}
+ \Omega_{m,0}\,a + \Omega_{k,0}\,a^2 + \Omega_{\Lambda,0}\,a^4}}.
$$
The authors then make the assumption that the speed of sound $c_s$ remains roughly constant and that the matter term is dominant, such that all other terms can be ignored. This then leads to
$$
r_s \approx \frac{c_s\,a_L}{H_0\sqrt{\Omega_{m,0}}}\int_0^{a_L}a^{-1/2}\,\text{d}a = \frac{2\,c_s}{H_0\sqrt{\Omega_{m,0}}}a_L^{3/2} = \frac{2\,c_s}{H_0\sqrt{\Omega_{m,0}}}(1+z_L)^{-3/2},
$$
so there is a factor $3$ wrong in (53). However, this is also a poor approximation, because the radiation term $\Omega_{r,0}$ is quite significant in the early universe. A better approximation is therefore
$$
\begin{align}
r_s &\approx \frac{c_s\,a_L}{H_0}\int_0^{a_L}\frac{\text{d}a}{\sqrt{\Omega_{r,0}
+ \Omega_{m,0}\,a}}\\
&= \frac{2\,c_s}{H_0\,\Omega_{m,0}}(1+z_L)^{-1}\left[\sqrt{\Omega_{r,0} + \Omega_{m,0}\,(1+z_L)^{-1}} - \sqrt{\Omega_{r,0}}\,\right].
\end{align}
$$
Using the value $\Omega_{r,0}\approx 9\times 10^{-5}$, this leads to $d_{sls}/r_s \approx 86$. A full calculation with non-constant $c_s$, which I won't derive here, gives $d_{sls}/r_s \approx 96$.
Finally, a first-order approximation to the position of the first acoustic peak is not given by $d_{sls}/r_s$, but by $\pi d_{sls}/r_s$, and we find  $\pi 96 \approx 300$. As you see, this is still not very close to the actual value of $\approx 220$. The reason for this is that the low-order acoustic peaks are significantly influenced by the propagation of the density fluctuations and by gravitational redshift effects in the early universe. The full treatment of these is very complex, and for specialists only (which I'm not, by the way).
I don't think I've ever seen a website that looks professional, yet is so wrong on so many levels. My advice would be to find a better course. For instance, Weinberg's cosmology textbook has everything you need, but it's no easy read.


Q:

Global variables,c++

I tried many solutions, but can't get my program work.
main.h
short NWMP_acc[3];
short NWMP_gyro[3];

main.cpp
printf_( "%i,%i,%i, g\n", NWMP_gyro[YAW],NWMP_gyro[PITCH],NWMP_gyro[ROLL]);

other.cpp
#include "main.h"
NWMP_gyro[YAW]   = (((buf[3]>>2)<<8) +  buffer[0]);//multiple definition of `NWMP_gyro'

If I change to "extern short NWMP_acc[3];" than I get an error "undefined reference to `NWMP_acc'"

A:

You need both with and without the extern
In your header you need:
extern short NWMP_acc[3];
extern short NWMP_gyro[3];

But in one of your ".cpp" files you still need:
short NWMP_acc[3];
short NWMP_gyro[3];

The reason for this is that the extern keyword can be roughly thought of as meaning "I promise that somewhere in one file there exists an actual real thing that looks like this".

A:

If you declare the array as extern (which you have to if you want a global variable across translation units), you have to define it in exactly one translation unit. So, for example:
// main.h
extern short NWMP_acc[3]; // declare

// main.cpp
#include "main.h"
short NWMP_acc[3]; // define

// other.cpp
#include "main.h"

void foo() {
    std::cout << NWMP_acc[0] << std::endl; //just use, don't define again
}


Q:

How to view the steps of the usort() in PHP?

This is the Example #1 from the php.net usort() page:
<?php
function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
?>

The usort function takes the values within the array as pairs ($a-$b; so this is - 3-2, 2-5, 5-6, 6-1) and moves the $b value depending on whether the cmp() function returns -1, 0 or 1. If it is -1 the $b gets moved down (within a current pair), if it is 0 it stays in the same place and if it is 1 it gets moved up. This is how this is suppose to be working based on the top comment from the php.net manual usort() page.
Is there any way to see how this works step by step (the sorting process)? Am I able to see it or is it only possible to see the final result after the sorting is done? I want to understand fully how this process works.

A:

Using some debug output in your comparison function you can only see the comparisons that PHP does, but can't see intermediate states of the array.
But the algorithm used in usort is well known - it's QuickSort ( Which sort algorithms does PHP's usort apply? ).
You can see its vizualisation at http://www.algomation.com/algorithm/quick-sort-visualization (or just google "quicksort algorithm visualization")


Q:

How to handle turmoil in company's ERGs

There is a policy at my company that says all individuals are welcome to join or attend any ERG (Employee Resource Group), even if they don't belong to that race/gender.
Even though I am not Black, I decided to attend one of the Black Professionals meetings.  Like most Americans, I am sickened by the recent violence and treatment of African Americans, so I wanted to attend to show my support for the group.
When I joined the Zoom call (we're still all working remotely), I was surprised that there was not a single Black individual.  All 25 individuals on the call were white.  (Except for me; I'm half Latino).
After asking around, I finally have pieced things together.  It turns out that this ERG was running smoothly.  But after the Black Lives Matter moved gained national attention, the group became flooded with awkward white individuals who wanted to prove to everyone how they weren't racist.  They would spend the meetings asking strange questions that would make others feel uncomfortable.  Somebody told me that it was eerily similar to the movie Get Out.
One by one, the Black individuals of the group left.  (There is now nobody officially in charge of the group now, but a white woman has taken over as an unofficial president of the group).  Some of the former members have since decided to join the Latino Professionals group.  There is apparently some rumblings in that group that Latino's aren't happy with these changes.
This whole thing is a mess.  Since I am an executive (lower level, but executive nonetheless) as well as a Latino, I have the ability to exert influence make some changes.  But now the question is, what can I do?  How can I help to defuse these tensions and restore these ERGs to their original intention?

A:

...the group became flooded with awkward white individuals who wanted to prove to everyone how they weren't racist. They would spend the meetings asking strange questions that would make others feel uncomfortable.

The best way to get your Black professionals back into the Black Professionals meetings is to reset the expectations of what will be happening there. I don't know how seriously the woman who's unofficially the president takes being in charge but I'm assuming you'll need her cooperation with this. If you can convince the person who used to be unofficially in charge to come back to help, even better.

Announce a return to business as usual: The president should state at the beginning of the next meeting that they understand people wanting to discuss current events but that it doesn't serve the purpose of the ERG and they need to get back to regular topics.

Set an explicit agenda for the next few meetings: I recommend getting some outside speakers to give presentations to the group. The presence of a 3rd party will hopefully make it less likely for the white members to turn the meeting back into awkward Q&A time. If there were specific projects the group was working on before this all blew up, you'll want to wait for some of the old members to return before resuming that work.

Consider some sort of training or workshop that happens outside of this group: If the questions the white employees were asking were mostly, "Would [X] be OK at work or is that racist?", then give them a different venue to ask those questions.

I didn't number these because you might not want or be able to do them in this order. This answer also assumes you won't have strong resistance to getting the group back to doing it's normal thing.


Q:

TFileOpenDialog FileTypes : how to change at runtime

In a TFileOpenDialog I set the FileTypes property to a custom list of files populated by selected files from the current folder.
dlg := TFileOpenDialog.Create( self );
Filter := TStringList.Create();
// ...
// Filter contains the selected files
  if Filter.Count>0 then
    begin
      msg := '';
      for i := 0 to Filter.Count-1 do
          msg := msg + Filter[i] + ';';
      dlg.FileTypes.Clear;
      dlg.FileTypes.Add.DisplayName := '';
      dlg.FileTypes.Add.FileMask := msg;
    end;

It works as desired.
I handle the OnFolderChange event in that I create a new file selection from the newly selected folder. I set the FileTypes property to this new list.
But I observe that the FileTypes property remains unchanged. As a result no files are found.
Am I right to assume that the FileTypes property cannot be changed for the current TFileOpenDialog?

A:

This control is a wrapper around the common item dialog. The documentation for IFileDialog::SetFileTypes says:

This method must be called before the dialog is shown and can only be called once for each dialog instance. File types cannot be modified once the Common Item dialog box is displayed.

So you cannot modify the file types after the dialog has been shown.
FWIW, each time you call FileTypes.Add you are adding a new file type. You need to call FileTypes.Add once per file type.


Q:

Is parseInt() supposed to work like this?

If I write this script :
alert(parseInt("123blahblahblah456"));
I get the alert with the value 123
Ideally, shouldn't the function NOT do anything since it is an invalid integer string?
Similar is the case with parseFloat()

A:

Yes, cf all the anwers. I'd like to add that this is why checking if certain value can be converted to a number, it's better to use Number or just +.
Number("123blahblahblah456"); //=> NaN
Number("123"); //=> 123
+"97.221" //=> 97.221
// if the conversion result needs to be an int
Math.round(Number("123.4567")); //=> 123

Be aware though that Number in some cases (unexpectely) returns 0.
+null   //=> 0
+"  "   //=> 0
+""     //=> 0
+false  //=> 0
+[]     //=> 0

A:

parseInt attempts to parse the string until it finds a non-integer value, at which point it returns whatever it had.
So if the string is:

1234abcd - it returns 1234
1a3f - it returns 1
a14883 - it returns NaN
1.5 - it returns 1
-1.3a - it returns -1

Same with parseFloat except that won't break on a .

1234abcd - it returns 1234
1a3f - it returns 1
a14883 - it returns NaN
1.5 - it returns 1.5
-1.3a - it returns -1.3

A:

Yes: parseInt() is absolutely meant to work like that; to quote the Mozilla Developer Network entry:

The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN. If not NaN, the returned value will be the decimal integer representation of the first argument taken as a number in the specified radix (base). For example, a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal, and so on. For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

It seems that parseInt() is explicitly expecting to take a string and will take the first sequence of numbers (until it encounters an invalid numerical character) and return that as a number of whatever base was specified in the radix parameter.
Incidentally, to reduce errors when parsing the strings passed to parseInt() remember to use the radix parameter, for example:
parseInt('123odod24',10); // for base-10
parseInt('123odod24',16); // for base-16

Reference:

parseInt() at the MDC.


Q:

Fatal error for permissions in Facebook API

I got following error
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in /home/.../third_party/base_facebook.php on line 1106

my function is,
public function isPhotoPermission()
        {
            $facebook = new Facebook();
            $access_token = $facebook->getAccessToken();
            $permissions = $facebook->api("/me/permissions","GET",array('access_token' => $access_token));
            if( array_key_exists('user_photos', $permissions['data'][0]) )
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

that 1106 line is,
1105:  protected function throwAPIException($result) {
1106:    $e = new FacebookApiException($result);
1107:    switch ($e->getType()) { ....

error occurring by following code:
$permissions = $facebook->api("/me/permissions","GET",array('access_token' => $access_token));

Where is the Problem? Thanks for advance.

A:

Are you sure you didn't forget the parameters as for the Facebook() constructor?
$config = array();
$config[‘appId’] = 'YOUR_APP_ID';
$config[‘secret’] = 'YOUR_APP_SECRET';
$config[‘fileUpload’] = false; // optional

$facebook = new Facebook($config);

https://developers.facebook.com/docs/reference/php/
Or perhaps did you initialize your $facebook object somewhere else in the code? In that case, you should:

either pass $facebook to your isPhotoPermission() function in order to get it back,
or set $facebook as global whether it is initialized in another function,
or simply remove the $facebook = new Facebook(); line if $facebook has been defined outside a function (would mean it is already global).


Q:

Imitating specific USB device

I recently got hands on an workout device which has a USB to PC interface and logs workouts on a lousy Windows Application. My intention is to read out the USB and build a custom application for presenting that data.
When connected to a linux machine the device registers in /dev/ttyUSB0, can be seen with lsusb and stty reports the baudrate among other information. I fire up minicom with the stty settings and as soon as the workout is initiated the device sends a series of 41 bytes
I assume that those bytes represent an announcement to the the PC interface.
What I would like to do is to imitate the workout device and send those 41 bytes to the PC interface myself in order to see what the PC side does upon initiation. Is there a way to imitate the device so that the PC software will recognize it?

A:

if the device is /dev/ttyUSB0 it is very likel implementing a virtual COM port, this is USB Communication Device class CDC (ACM).
the operating system knows what driver / kernel module it has to load because when you plug in the device in USB protocol descriptors are exchanged ( the device sends its device descriptor to the host, according to this the host loads the driver / kernel module ), you can see this information with lsusb -v. Specifically the device sends the following descriptors to the host : device descriptor, configuration descriptor, interface descriptor, endpoint descriptor : http://www.beyondlogic.org/usbnutshell/usb1.shtml
for imitating a device you have to write a firmware on a MCU with exaclty these descriptors and additionally with identic VID ( vendor id ) and PID ( product id )
the 41 bytes you receive flow over the virtual COM port and so in RS-232 protocol ( you are able to receive them with minicom ) and so they are above USB level, however they are part of the payload in USB packets. if you have a proprietary driver in windows of your device in windows these 41 bytes are very likely addressed to the driver ( whichs source code you very likely do not have ...). this is very common there are multimeters with RS-232 interface and one has to send a  D = 44 (hex) = 01000100 (bin)  to receive any data
so you can try to sniff the virtual COM port ( RS-232 protocol ) directly using a RS-232 sniffer, i.e. https://www.eltima.com/rs232-sniffer.html
alternatively you can try is to sniff the underlying USB traffic with wireshark ( or usbmon in linux ) and extract the payload from the USB packets to record the communication between the windows driver and ther device
https://ask.wireshark.org/question/36/how-to-capture-usb-packets-please/
https://www.youtube.com/watch?v=EfkC7kmIMt8 ( USB in Wireshark )
https://www.kernel.org/doc/Documentation/usb/usbmon.txt
( https://www.kernel.org/doc/html/v4.13/driver-api/usb/URB.html )


Q:

$(G, \cdot)$ - group such that $|G|<\infty$. $G$ has exactly $2$ subgroups

$(G, \cdot)$ - group such that $|G|<\infty$. $G$ has exactly $2$ subgroups. Prove that order of $a\in G$ is a prime if $a\neq e$ where $e$ is neutral element.
I am stuck. Here is what I got so far:
$G$ has exactly two subgroups that means that the only subgroups are $e$ and $G$.
Let $a^k=e$ and assume that $k$ is not prime, that means $k=p_1 p_2$ where $p_1$ and $p_2$ are prime numbers. Then $a^k=a^{p_1 p_2}=(a^{p_1})^{p_2}=e^{p_2}$.
Now I am stuck because I think that means that it implies that $a^{p_1}=e$ and then I would know what to do, but does it?

A:

You have some work to do here. First off, what is your overall proof technique? What you need to prove, given the assumptions, that if $a\in G$ and $a\neq e$, then the order of $a$ is prime.
You (nearly) correctly observe that under the assumptions, the two subgroups of $G$ are $\{e\}$ (to be careful with the notation, this is not the same thing as $e$) and $G$. (You might note that for these to be different, $\vert G\vert$ must be greater than $1$.)
Now how are you going about proving the if-then result you need to prove? You could attempt a direct proof (assume that $a\in G$ and $a\neq e$ and conclude that the order of $a$ is prime), or a proof by contrapositive or contradiction (assume that $a\in G$ and the order of $a$ is not prime, and conclude that $a=e$ or that $G$ is not finite, or that $G$ has more than two subgroups.)
You begin by assuming that $a^k=e$ where $k$ is not prime, so it looks like you are attempting a proof by contrapositive or contradiction, but this isn’t quite the right assumption, because you should assume that the order of $a$ is not prime, and that’s not the same thing as assuming $a$ raised to a non-prime power is $e$. Do you know the definition of order of an element of a group?
In fact, there are always non-prime values of $k$ for which $a^k=e$. For example, $a^{250\vert G\vert}=e$ for every element $a$ of $G$, so you won’t be able to conclude much about $a$ from that.
You also say that if $k$ is not prime, it is the product of two primes, but this is not true. For example, $12$ is not prime, but it isn’t the product of two primes.


Q:

Show values instead of ids for multiple fields sqlite

How do I resolve user IDs to user names for multiple fields in an SQLite query. I have 2 tables, "Tickets" and "Users". "Tickets" has the user IDs, "Users" links the ID to the user's name. So I have the query below, but how do I show the user names instead of the ID numbers in the "created_by" and "assigned_to" columns.
SELECT tickets.id, tickets.summary, tickets.created_by, tickets.assigned_to
FROM   tickets

I don't think joining is the solution as joining on one field leaves me with a problem with the other.

A:

You could try to join them like this two different alias
SELECT tickets.id, tickets.summary, u1.name, u2.name
FROM tickets
LEFT JOIN users AS u1 ON tickets.created_by = u1.id
LEFT JOIN users AS u2 ON tickets.assigned_to = u2.id


Q:

How to Calculate the average of an Existing list inside Knowledge base of prolog code?

I have been trying for instance to have a list [1,3] and calculate its average inside the code without inputing the least itself. I'm not sure of the correct syntax to make it work, only the first line has a problem since it works perfectly fine if I called average and input the numbers when I run prolog.
average([1,3],X).

average(List, Result) :- sum1(List, Len), sum(List, Sum), Result is Sum / Len.

sum([], 0).

sum([H|T], Sum) :- sum(T, Temp), Sum is Temp + H.

sum1([],0).

sum1([_|B],L):-sum1(B,Ln), L is Ln+1.

A:

Well, you don't want to input list all the time. It means, that you should have predicate something like my_list/1 and use it in your program.
my_list( [1,3] ).

average_easy( List, Avg ) :-
    sum_( List, Sum ),
    length_( List, Length ),
    Avg is Sum / Length.

sum_( [], 0 ).
sum_( [H|T], Sum ) :-
    sum_( T, Temp ),
    Sum is Temp + H.

length_( [], 0 ).
length_( [_|B], L ):-
    length_( B, Ln ),
    L is Ln+1.

main :-
    my_list( X ),
    average_easy( X, Ans ),
    writeln((X, Ans)).

So, what we've got now, is
?- [your_program_name].
% your_program_name compiled 0.00 sec, 64 bytes
true.

?- main.
[1,3],2
true.

Btw, there are length/2 predicate, already built-in in swi-prolog.


Q:

OpenGL frame buffer slow and spontaneously stalls. Can even cause a system crash when used extensively

Apparently frame buffers are fast and the best way to render offscreen to textures or to simply pre-create things.
My game however is not liking them at all. In the current code frame buffers are used often, sometimes each frame, several times. When used the game begins to slow down but not instantly. It seems to take time (Perhaps a built-up memory problem?). In some areas the frame buffer objects do not seem to slow the game down much accept occasionally the game will stall for a few seconds before continuing as normal.
I assume the Frame buffers are the problem because the game is fast in areas where they aren't used.
I'm using python with pyopengl. The OpenGL code is similar to the code in other language so I do not think python knowledge is significantly important.
Some things are rendered directly to the screen, other textures are rendered to other textures which is involved with the Surface class. This resembles pygame which is what I begun my game in before I changed my mind.
Here is the relevant code.
def create_texture(surface):
surface.texture = glGenTextures(1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() #Loads model matrix
glBindTexture(GL_TEXTURE_2D, surface.texture) #Binds the current 2D texture to the texture to be drawn
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) #Required to be set for maping the pixel data
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) #Similar as above
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface.surface_size[0], surface.surface_size[1], 0, GL_RGBA,GL_UNSIGNED_BYTE, surface.data) #Put surface pixel data into texture
if surface.data == None:
    setup_framebuffer(surface)
    c = [float(sc)/255.0 for sc in surface.colour] #Divide colours by 255 because OpenGL uses 0-1
    if surface.background_alpha != None:
        c[3] = float(surface.background_alpha)/255.0
    glClearColor(*c)
    glClear(GL_COLOR_BUFFER_BIT)
    end_framebuffer()
Surface.texture_ready.append(surface)

   def setup_framebuffer(surface):
    #Create texture if not done already
    if surface.texture == None:
        create_texture(surface)
    #Render child to parent
    if surface.frame_buffer == None:
        surface.frame_buffer =  glGenFramebuffersEXT(1)
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, surface.frame_buffer)
    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0)
    glPushAttrib(GL_VIEWPORT_BIT)
    glViewport(0,0,surface._scale[0],surface._scale[1])
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity() #Load the projection matrix
    gluOrtho2D(0,surface._scale[0],0,surface._scale[1])
def end_framebuffer():
    glPopAttrib()
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity() #Load the projection matrix
    gluOrtho2D(0,1280,720,0) #Set an orthorgraphic view
    def draw_texture(texture,offset,size,a,rounded,sides,angle,point):
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity() #Loads model matrix
    glColor4f(1,1,1,float(a)/255.0)
    glBindTexture(GL_TEXTURE_2D, texture)
    if rounded == 0:
        if angle == 0:
            glBegin(GL_QUADS)
            glTexCoord2f(0.0, 0.0)
            glVertex2i(*offset) #Top Left
            glTexCoord2f(0.0, 1.0)
            glVertex2i(offset[0],offset[1] + size[1]) #Bottom Left
            glTexCoord2f(1.0, 1.0)
            glVertex2i(offset[0] + size[0],offset[1] + size[1]) #Bottom, Right
            glTexCoord2f(1.0, 0.0)
            glVertex2i(offset[0] + size[0],offset[1]) #Top, Right
            glEnd()
        else:
            glBegin(GL_QUADS)
            glTexCoord2f(0.0, 0.0)
            glVertex2f(*rotate_coordinate(offset,point,angle)) #Top Left
            glTexCoord2f(0.0, 1.0)
            glVertex2f(*rotate_coordinate((offset[0],offset[1] + size[1]),point,angle)) #Bottom Left
            glTexCoord2f(1.0, 1.0)
            glVertex2f(*rotate_coordinate((offset[0] + size[0],offset[1] + size[1]),point,angle)) #Bottom, Right
            glTexCoord2f(1.0, 0.0)
            glVertex2f(*rotate_coordinate((offset[0] + size[0],offset[1]),point,angle)) #Top, Right
            glEnd()
    else:
        global arc_factors
        arc = [[o*rounded for o in c] for c in arc_factors]
        glBegin(GL_POLYGON)
        if sides % 2:
            for c in arc:
                coordinates = (offset[0] + rounded - c[0],offset[1] + rounded - c[1])
                glTexCoord2f((coordinates[0]-offset[0])/size[0],(coordinates[1]-offset[1])/size[1])
                glVertex2f(*coordinates)
        else:
            glTexCoord2f(0.0, 0.0)
            glVertex2f(*rotate_coordinate(offset,point,angle)) #Top Left
        if sides % 4 > 1:
            for c in arc[::-1]:
                coordinates = (offset[0] + size[0] - rounded + c[0],offset[1] + rounded - c[1])
                glTexCoord2f((coordinates[0]-offset[0])/size[0],(coordinates[1]-offset[1])/size[1])
                glVertex2f(*coordinates)
        else:
            glTexCoord2f(1.0, 0.0)
            glVertex2f(*rotate_coordinate((offset[0] + size[0],offset[1]),point,angle)) #Top, Right
        if sides % 8 > 3:
            for c in arc:
                coordinates = (offset[0] + size[0] - rounded + c[0],offset[1] + size[1] - rounded + c[1])
                glTexCoord2f((coordinates[0]-offset[0])/size[0],(coordinates[1]-offset[1])/size[1])
                glVertex2f(*coordinates)
        else:
            glTexCoord2f(1.0, 1.0)
            glVertex2f(*rotate_coordinate((offset[0] + size[0],offset[1] + size[1]),point,angle)) #Bottom, Right
        if sides > 7:
            for c in arc[::-1]:
                coordinates = (offset[0] + rounded - c[0],offset[1] + size[1] - rounded + c[1])
                glTexCoord2f((coordinates[0]-offset[0])/size[0],(coordinates[1]-offset[1])/size[1])
                glVertex2f(*coordinates)
        else:
            glTexCoord2f(0.0, 1.0)
            glVertex2f(*rotate_coordinate((offset[0],offset[1] + size[1]),point,angle)) #Bottom Left
        glEnd()
def texture_to_texture(target,surface,offset,rounded,rotation,point):
    #Create texture if not done already
    if surface.texture == None:
        create_texture(surface)
    #Render child to parent
    setup_framebuffer(target)
    draw_texture(surface.texture,offset,surface._scale,surface.colour[3],rounded,surface.rounded_sides,rotation,point)
    end_framebuffer()
def texture_to_screen(surface,offset,rotation,point):
    if surface.texture == None:
        create_texture(surface)
    draw_texture(surface.texture,offset,surface._scale,surface.colour[3],surface.rounded,surface.rounded_sides,rotation,point)
    class Surface():
    texture_ready = []
    def __init__(self,size,extra = None):
        self._offset = (0,0)
        self.children = []
        self.blitted = False
        self.last_offset = [0,0]
        self.surface_size = list(size)
        self.colour = [0,0,0,255]
        self.data = None
        self.rounded = 0
        self.parent = None
        self.parent_offset = (0,0)
        self.texture = None
        self.frame_buffer = None
        self._scale = size
        self.background_alpha = None
        self.rounded_sides = 0
    def blit(self,surface,offset,rotation = 0,point = (0,0)):
        texture_to_texture(self,surface,offset,surface.rounded,rotation,point)
        if surface not in self.children:
            self.children.append(surface)
        if surface.parent_offset != offset or not surface.blitted:
            surface.parent_offset = offset
            surface._offset = [offset[0] + self._offset[0],offset[1] + self._offset[1]]
            surface.recursive_offset_change() #Add to the children's offsets
            surface.blitted = True
    def set_background_alpha(self,alpha):
        self.background_alpha = float(alpha)/255.0
    def recursive_offset_change(self):
        for child in self.children:
            child._offset = (self._offset[0] + child.parent_offset[0],self._offset[1] + child.parent_offset[1])
            child.recursive_offset_change()
    def get_offset(self):
        return self._offset
    def fill(self,colour):
        colour = list(colour)
        if len(colour) < 4:
            colour.append(255)
        self.children = []
        self.textures = []
        self.colour = colour
        if self.texture != None:
            glDeleteTextures([self.texture])
            self.data = None
            create_texture(self)
    def get_size(self):
        return self.surface_size
    def get_width(self):
        return self.surface_size[0]
    def get_height(self):
        return self.surface_size[1]
    def round_corners(self,r,sides = 15):
        self.rounded = r
        self.rounded_sides = sides
    def get_rect(self):
        return Rect(self._offset,self.surface_size)
    def scale(self,scale):
        self._scale = scale
        return self
    def __del__(self):
        if self.texture != None:
            glDeleteTextures([self.texture])
        if self.frame_buffer != None:
            glDeleteFramebuffersEXT(1, [int(self.frame_buffer)])
class Game(Surface):
    game_size = None
    first_screen = None
    screen = None
    fs = False #Fullscreen false to start
    clock = None
    resize = True
    game_gap = None
    game_scaled = (0,0)
    title = None
    fps = -1
    enter_fullscreen = False
    exit_fullscreen = False
    scale_to_screen = False
    iconify = False
    on_focus_fullscreen = False
    f_key = False
    fade = 0
    p_key = False
    music_stop = False
    unfade = False
    event_after_fade = -1
    loaded = False
    fade = 255
    unfade = True
    homedir = os.path.expanduser("~")
    fade_screen = False
    keys = []
    events = []
    sections = []
    back_key = False
    transfer_args = ()
    mouse_pos = (0,0)
    def __init__(self,title,game_size,on_exit = sys.exit):
        self.keys = [False] * 323
        self.events = []
        pygame.font.init()
        pygame.mixer.init()
        self.title = title
        self.game_size = game_size
        self.first_screen = (1280,720) #Take 120 pixels from the height because the menu bar, window bar and dock takes space
        glutInit(sys.argv)
        glutInitWindowPosition(0,0)
        glutInitWindowSize(*game_size)
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA)
        glutGameModeString("1280x720:32@60") #720 HD
        glutCreateWindow(title)
        glutSetIconTitle(title)
        self.callbacks()
        self.game_gap = (0,0)
        self.on_exit = on_exit
        self.mod_key = 1024 if sys.platform == "darwin" else 64
        Surface.__init__(self,game_size)
        self.screen_change = True
        self.frames = [time.time()]
        self.fps = 60
        self.last_time = 0
        self.fade_surface = Surface([1280,720])
    def callbacks(self):
        glutReshapeFunc(self.reshaped)
        glutKeyboardFunc(self.keydown)
        glutKeyboardUpFunc(self.keyup)
        glutSpecialFunc(self.specialdown)
        glutSpecialUpFunc(self.specialup)
        glutDisplayFunc(self.game_loop)
        glutIdleFunc(self.game_loop)
        glutMouseFunc(self.mouse_func)
        glutPassiveMotionFunc(self.mouse_move)
        glutMotionFunc(self.mouse_move)
        glViewport(0,0,self.first_screen[0],self.first_screen[1]) #Creates the viewport which is mapped to the window
        glEnable(GL_BLEND) #Enable alpha blending
        glEnable(GL_TEXTURE_2D) #Enable 2D Textures
        glEnable(GL_POLYGON_SMOOTH) #Enable antialiased polygons
        glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST)
        glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity() #Load the projection matrix
        gluOrtho2D(0,1280,720,0) #Set an orthorgraphic view
    def add_section(self,section_object):
        self.sections.append(section_object)
    def mouse_func(self,button, state, x, y):
        self.events.append((state,button,x,y))
    def mouse_move(self,x,y):
        self.events.append((MOUSEMOTION,x - self.mouse_pos[0], y - self.mouse_pos[1]))
        self.mouse_pos = (x,y)
    def keydown(self,char,x,y):
        #300 miliusecond delay, 50 milisecond repeat
        self.change_keys(char,True)
    def keyup(self,char,x,y):
        self.change_keys(char,False)
    def change_keys(self,char,bool):
        char = ord(char)
        #Switch backspace and delete
        if char == 8:
            char = 127
        elif char == 127:
            char = 8
        self.keys[char] = bool
    def specialdown(self,char,x,y):
        if char == GLUT_KEY_UP:
            self.keys[K_UP] = True
        if char == GLUT_KEY_DOWN:
            self.keys[K_DOWN] = True
        if char == GLUT_KEY_LEFT:
            self.keys[K_LEFT] = True
        if char == GLUT_KEY_RIGHT:
            self.keys[K_RIGHT] = True
    def specialup(self,char,x,y):
        if char == GLUT_KEY_UP:
            self.keys[K_UP] = False
        if char == GLUT_KEY_DOWN:
            self.keys[K_DOWN] = False
        if char == GLUT_KEY_LEFT:
            self.keys[K_LEFT] = False
        if char == GLUT_KEY_RIGHT:
            self.keys[K_RIGHT] = False
    def reshaped(self,w,h):
        #Scale game to screen resolution, keeping aspect ratio
        self.screen_change = True
        self.game_scaled = get_resolution((w,h),self.game_size)
        glutReshapeWindow(*self.game_scaled)
        glViewport(0,0,self.game_scaled[0],self.game_scaled[1])
        glutPositionWindow((1280- w)/2,(720 - h)/2)
    def game_loop(self):
        self.section.loop()
        if self.unfade:
            if self.fade == 255:
                play_music(self.section.music)
            if self.fade > 0:
                self.fade -= 5
            else:
                self.music_stop = False
                self.unfade = False
        if self.fade_screen and not self.unfade: #Fade out
            if self.fade == 0:
                sound("/sounds/menu3/fade.ogg").play()
                self.music_stop = True
                pygame.mixer.music.fadeout(850)
            if self.fade < 255:
                self.fade += 5
            else:
                self.fade_screen = False
                self.unfade = True
        if self.fade_screen == False:
            if self.event_after_fade != -1:
                self.section = self.sections[self.event_after_fade]
                self.section.transfer(*self.transfer_args)
                self.transfer_args = ()
                self.event_after_fade = -1
        self.fade_surface.fill((0,0,0,self.fade))
        self.blit(self.fade_surface,(0,0))
        for event in self.events:
            if event[1] == MUSICEND and self.music_stop == False:
                play_music(self.section.music)
        self.events = [] #Remove events
        global draw_texture_time
        #Updates screen properly
        for event in self.events:
            if event.type == QUIT:
                self.on_exit()
        if True:
            if self.keys[K_f]:
                if self.f_key == False:
                    self.f_key = True
                    if self.fs == False:
                        self.enter_fullscreen = True
                    else:
                        self.exit_fullscreen = True
            else:
                self.f_key = False
        if self.on_focus_fullscreen and pygame.display.get_active():
            self.on_focus_fullscreen = False
            self.enter_fullscreen = True
        pixel_data = []
        if self.enter_fullscreen or self.exit_fullscreen:
            for surface in Surface.texture_ready:
                if surface.texture != None:
                    glBindTexture(GL_TEXTURE_2D, surface.texture)
                    glGetTexImage(GL_TEXTURE_2D,0,GL_RGBA,GL_UNSIGNED_BYTE,surface.data)
                    surface.texture = None
                if surface.frame_buffer != None:
                    pixel_data.append((surface,None))
                    glReadPixels(0,0,surface.surface_size[0],surface.surface_size[1],GL_BGRA,GL_UNSIGNED_BYTE,pixel_data[-1][1])
            Surface.texture_ready = []
        if self.enter_fullscreen:
            glutEnterGameMode()
            self.callbacks()
            self.fs = True
            self.enter_fullscreen = False
        elif self.exit_fullscreen:
            glutSetCursor(GLUT_CURSOR_INHERIT)
            self.fs = False
            glutLeaveGameMode()
            self.callbacks()
            self.exit_fullscreen = False
            if self.iconify:
                self.on_focus_fullscreen = True
        if self.enter_fullscreen or self.exit_fullscreen:
            for surface, data in pixel_data:
                surface.frame_buffer =  glGenFramebuffersEXT(1)
                setup_framebuffer(surface)
                glDrawPixels(surface.surface_size[0],surface.surface_size[1],GL_RGBA,GL_UNSIGNED_BYTE,data)
                end_framebuffer()
        if self.iconify:
            pygame.display.iconify() #Minimise
            self.iconify = False
        glFlush()
        glutSwapBuffers() #Flip buffer
        glClear(GL_COLOR_BUFFER_BIT)
        self.frames.append(time.time())
        time_d = (self.frames[-1] - self.frames[-2])
        if time_d < 0.01667:
            time.sleep(0.01667 - time_d)
            self.frames[-1] = time.time()
        self.fps = len(self.frames)/(self.frames[-1] - self.frames[0])
        if self.fps > 60:
            self.fps = 60
        self.frames = [frame for frame in self.frames if (self.frames[-1] - frame) < 1]
        glutSetWindowTitle(self.title + " - " + str(int(self.fps)) + "fps")
    def blit(self,surface,offset,rotation = 0,point = (0,0)):
        if surface.get_offset() != offset or not surface.blitted:
            surface._offset = offset
            surface.recursive_offset_change() #Add to the children's offsets
        surface.blitted = True
        texture_to_screen(surface,offset,rotation,point)
    def transfer_section(self,section,args=()):
        self.transfer_args = args
        self.event_after_fade = section
        self.fade_screen = True

Bravo if anyone can help me with this. I spent ages getting the FBOs to work at all. It's so frustrating that they aren't working properly. If it comes to removing them, it's a nightmare all over again. But I must face whatever needs to be done to make the game fast.

A:

I haven't worked with OpenGL for about 14 years so I'm not much help with that. I'm just looking at the Python code. There's a few things you can do to clean the code up, like use ".width" instead of ".surface_size[0]". You do have a get_width(), but descriptors are your friends. You also have checks for "if self.data == None" but there's no place where the .data field is ever set to anything besides None. Oh, and a minor point - the better form of this test is "if self.data is None".
I'm going on the assumption that you're running out of some sort of resource. I tried to follow the glBindTexture/glDeleteTexture logic but it confused me. Why do you store all your pending surfaces into the class variable Surface.texture_ready list? That is, why isn't it an instance variable?
Your game loop goes through and glBindTexture:s the texture_ready elements, then resets the list to []. But only when entering/exiting full-screen mode. If you don't go to full screen, it seems that texture_ready gets longer and longer.
You might consider using one of the profiling tools to see where most of the time is being spent. Even something as simple as watching the line trace might be enough for you to spot where the slowdown is.
I'm afraid this isn't much help though, as I just don't know OpenGL.


Q:

Manually invoke actionPerformed of a javax.swing.Timer

The following Timer works perfectly.
private static final Timer TICK_HOUR = new Timer(3600000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // ...
    }
});

What I want to do is call the actionPerformed() manually. How can I achieve this?

The question seems unclear to the readers, I'll try to explain more.
Timer does some process hourly. I want to do it whenever I want without interfering the timer's process.

A:

Short answer...
A much simpler (and better designed) solution would be, instead of...
private static final Timer TICK_HOUR = new Timer(3600000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("OK");
    }
});

You should externalise the work the ActionListener does...
private static final Timer TICK_HOUR = new Timer(3600000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        doReallyImportantWorkEveryHour();
    }
});

then you remove the Timer from the equation and you can call doReallyImportantWorkEveryHour when you want and solve the fundamental problem
Long Answer
So, let's start with...
private static final Timer TICK_HOUR = new Timer(3600000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("OK");
    }
});

Creating a Timer this way, automatically registers a ActionListener with the Timer.
You then state:

What I want to do is call the actionPerformed() method inside the timer's ActionListener manually. How can I achieve this?

Which suggest you want try and do something like...
private static final Timer TICK_HOUR = new Timer(3600000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        TICK_HOUR.getActionListeners()[0].actionPerformed(null);
    }
});

This could cause a NullPointerException, but more importantly, this will have an adverse affect on system performance, as there is no way that the ActionListener will know it shouldn't continuously all itself - basically and infinite loop.
IF however, you wanted to, prematurely, trigger the Timers ActionListeners (outside of any registered listeners)
Then yes, you could use...
ActionEvent evt = new ActionEvent(
                TICK_HOUR,
                0,
                TICK_HOUR.getActionCommand(),
                System.currentTimeMillis(),
                0);
for (ActionListener listener : TICK_HOUR.getActionListeners()) {
    listener.actionPerformed(evt);
}

but make sure you're calling them from within the context of the EDT, as that's one of the guarantees that the Timer makes.
A "simpler" solution might be just to use the functionality that is already provide by the Timer itself...
public class ManuallyTimer extends Timer {

    public ManuallyTimer(int delay, ActionListener listener) {
        super(delay, listener);
    }

    public void tigger() {
        ActionEvent evt = new ActionEvent(TICK_HOUR, 0, TICK_HOUR.getActionCommand());
        fireActionPerformed(new ActionEvent(this, 0, getActionCommand(),
                        System.currentTimeMillis(),
                        0));
    }
}


Q:

Wordpress: How to flush cached option value

I am currently working on a plugin, and I am stuck with an issue.
I executed an SQL request on my database through PhpMyAdmin (which I implemented later through a plugin update mechanism), the request looked like this:
UPDATE `wp_options`
    SET `option_value` = replace( `option_value` , 'model', 'ldp_model' )
WHERE `option_name` LIKE 'ldp_container%'

As you can see, I am updating all options value having name beginning by 'ldp_container'. Later in the code execution, when I am retrieving the option value, I am getting a value being false using:
$termId = $term->term_id;
$termMeta = get_option("ldp_container_$termId"); // $termMeta = false

I looked in this issue, and I got to the point where it seems that when I update/create this option, as I used:
update_option("ldp_container_$termID", $termMeta);

instead of
update_option("ldp_container_$termID", $termMeta, false);

The value of this option become part of the alloptions cache. So, retrieving it always return false now, and I do not know how to flush this cache.
Using a plugin update mechanism based on version number, I tried to flush the Wordpress object cache using:
$flush_cache = wp_cache_flush(); // returns true

And the Database query cache too:
$wpdb->flush();

I also tried explicitely deleting those options keys from the cache using a query then looping on results and calling wp_cache_delete:
  $result = $wpdb->get_results(
      "SELECT 'option_name'
       FROM $wpdb->options
       WHERE 'option_name' LIKE '%ldp_container_%';"
    );

    foreach ( $result as $current ) {
      wp_cache_delete($current, 'options');
    }

Still, no luck.
Does anybody have a clue for me here ?
Thanks,
EDIT:
Seems like my error is somewhere else.
After some debugging using Atom and Xdebug, it points out that the issue is with the unserialize method applied to the string retrieved from the database in the file /wp-includes/option.php as follows:
return apply_filters( 'option_' . $option, maybe_unserialize( $value ) );

maybe_unserialize do that:
if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
    return unserialize( $original );
return $original;

The call to the unserialize fails, so it returns false and then the false value is cached...
Using an online unserializer it confirms that the string is not correct, but I do not get why yet.

A:

So, as I assumed my issue was due to the modification in serialized objects I was executing directly on the database. Because of the nature of serialized objects, looking like this:
a:1:{s:9:"ldp_model";s:1651:"{...

The 1651 being the number of characters in the ldp_model string, if you change anything inside this sting, then unserializing using unserialize() will return false, because the actual number of characters is different from the one indicated.
In my case, the solution was to instead of executing a database update of this kind:
$wpdb->query(
   "UPDATE $wpdb->options
    SET `option_value` = replace( `option_value` , 'ldp_', '' );"
);

To use the Options API as follows:
$result = $wpdb->get_results(
  "SELECT `option_name`
   FROM $wpdb->options
   WHERE `option_name` LIKE '%ldp_container_%';"
);

foreach ( $result as $current ) {
  $option = get_option($current->option_name);
  if (!empty($option) && !empty($option['ldp_model'])) {
    $option['ldp_model'] = str_replace('ldp_', '', $option['ldp_model']);
    update_option($current->option_name, $option, false);
  }
}

So that the serialized objects stays correct, and the Options API takes care of serialization and unserialization.
Lots of learning here for me ;-)