text:
Q: "LinAlgError: 0-dimensional array given. Array must be at least two-dimensional" BUT I've know I'm passing a 2D argument My first question, so grateful for feedback on how to better help you help me :)
On my Mac (Mojave, 10.14.6 with Python version 3.7.6.final.0), I'm getting the above error.
I've confirmed that my argument matrix has 2 dimensions (8 x 8).
I've worked through the Traceback, and used the relevant argument matrix in each of the subfunctions successfully, but not on the main function "monteCarlo".
BTW, this is code from Marcos López de Prado's "A ROBUST ESTIMATOR OF THE EFFICIENT FRONTIER"
I have made some modifications where the code was outdated (2.*) and some others to help assure myself that I am working with the matrix I expect.
Many, many thanks to the intrepid who care and dare to read through all this.
Below the error message is some of the code and results clipped from Jupyter Notebook.

>
LinAlgError                               Traceback (most recent call last)
<ipython-input-313-a5db76f0dc0a> in <module>
----> 1 monteCarlo(mu0=hist_ann_px_chg, cov0 = CovMatrix, nObs = NumObs, nSims=500, bWidth=.25, minVarPortf = False, shrink=False)
>
<ipython-input-308-b7fbaf4dca14> in monteCarlo(mu0, cov0, nObs, nSims, bWidth, minVarPortf, shrink)
      5         mu1,cov1=simCovMu(mu0,cov0,nObs,shrink)
      6         if minVarPortf:mu1=None
----> 7         if bWidth>0:cov1=deNoiseCov(cov1,nObs*1./cov1.shape[1],bWidth)
      8         w1.loc[i]=optPort(cov1,mu1).values.flatten()
      9         w1_d.loc[i]=optPort_nco(cov1,mu1,int(cov1.shape[0]/2)).values.flatten()
>
<ipython-input-306-062b76320e88> in deNoiseCov(cov0, q, bWidth)
     35 def deNoiseCov(cov0,q,bWidth):
     36     corr0=cov2corr(cov0)
---> 37     eVal0,eVec0=getPCA(corr0)
     38     eMax0,var0=findMaxEval(np.diag(eVal0),q,bWidth)
     39     nFacts0=eVal0.shape[0]-np.diag(eVal0)[::-1].searchsorted(eMax0)
>
<ipython-input-306-062b76320e88> in getPCA(matrix)
     16 def getPCA(matrix):
     17 # Get eVal,eVec from a Hermitian matrix
---> 18     eVal,eVec=np.linalg.eigh(matrix)
     19     indices=eVal.argsort()[::-1] # arguments for sorting eVal desc
     20     eVal,eVec=eVal[indices],eVec[:,indices]
>
<__array_function__ internals> in eigh(*args, **kwargs)
>
~/opt/anaconda3/lib/python3.7/site-packages/numpy/linalg/linalg.py in eigh(a, UPLO)
   1432
   1433     a, wrap = _makearray(a)
-> 1434     _assert_stacked_2d(a)
   1435     _assert_stacked_square(a)
   1436     t, result_t = _commonType(a)
>
~/opt/anaconda3/lib/python3.7/site-packages/numpy/linalg/linalg.py in _assert_stacked_2d(*arrays)
    205         if a.ndim < 2:
    206             raise LinAlgError('%d-dimensional array given. Array must be '
--> 207                     'at least two-dimensional' % a.ndim)
    208
    209 def _assert_stacked_square(*arrays):
>
LinAlgError: 0-dimensional array given. Array must be at least two-dimensional

Below is the function that throws the error when I call with this statement:
monteCarlo(mu0=hist_ann_px_chg, cov0 = CovMatrix, nObs = NumObs, nSims=500, bWidth=.25, minVarPortf = False, shrink=False)

import pandas as pd
from scipy import stats
from pandas_datareader import data as pdr
from pandas.util.testing import assert_frame_equal
import yfinance as yf

yf.pdr_override() # <== that's all it takes :-)

# download dataframe
hist_data = pdr.get_data_yahoo("^GSPC ^VIX ^DJI ^IXIC ^FTSE ^GDAXI ^STOXX50E ^N225", start="2015-01-01", end="2020-01-1")
hist_data = hist_data.iloc[:,0:8]
hist_dly_px_chg = hist_data.pct_change()

NumObs = hist_dly_px_chg.shape[0]
CovMatrix = hist_dly_px_chg.cov()
print(type(CovMatrix)) # data.frame

CovMatrix = np.matrix(CovMatrix) # matrix (8 x 8)
print(type(CovMatrix))
print(CovMatrix.shape)
print(CovMatrix.ndim)
hist_ann_px_chg = hist_dly_px_chg.mean()
print(hist_ann_px_chg*NumObs)

When I make this function call:
print(np.linalg.eigh(CovMatrix))

I get the output I think I would expect, so I can't tell where the disconnect is:

(array([9.76607795e-07, 9.09734518e-06, 1.06092016e-05, 2.18149708e-05,
   7.30351257e-05, 1.16439127e-04, 2.39270121e-04, 7.82633431e-03]), matrix([[-4.82280240e-01, -4.58375572e-01, -5.31172874e-01,
      3.50650316e-02, -4.92673400e-01, -9.94286171e-02,
      1.25967021e-01,  7.37740277e-02],
    [-2.33051153e-02,  3.95717701e-02,  7.84798502e-02,
      8.95759250e-01,  1.02359842e-01, -1.47818043e-01,
      3.93700956e-01,  4.49340838e-02],
    [ 2.54965439e-02, -5.36050910e-01,  4.44240943e-01,
     -3.24298395e-01,  1.74936958e-01, -2.59428034e-01,
      5.54982822e-01,  5.97336351e-02],
    [ 8.28138825e-01, -8.35526265e-02, -1.54346913e-01,
      2.26457229e-02, -5.01976954e-01, -1.04165506e-01,
      1.19382708e-01,  7.60638006e-02],
    [-2.83219910e-01,  4.59584143e-01,  5.09453905e-01,
     -8.28536548e-02, -6.32657429e-01, -1.32770810e-01,
      1.28593449e-01,  8.79835438e-02],
    [ 1.06886068e-03, -7.82137852e-03,  1.94908915e-02,
     -2.38832357e-02, -9.03973958e-02,  9.05732488e-01,
      4.12218925e-01,  2.32359154e-02],
    [-1.33763053e-02,  5.31709637e-01, -4.80196149e-01,
     -2.88561906e-01,  2.10778168e-01, -2.24495845e-01,
      5.52334217e-01,  5.78853425e-02],
    [ 2.25154661e-03,  6.27599544e-04, -3.43348735e-03,
      6.49094855e-04, -1.06569389e-01, -4.16245867e-02,
      1.23854342e-01, -9.85673773e-01]]))

A: In my case, I have to convert the sparse matrix to dense matrix.

A: So who should I believe, you or the computer?
Let's look at the error.  At the lowest level a is the problem array.  Tracing up we see that it is the corr0 array passed to getPCA: getPCA(corr0)
That is created by corr0=cov2corr(cov0), where cov0 is the cov1 passed to deNoiseCov(cov1,...)
mu1,cov1=simCovMu(mu0,cov0,nObs,shrink)

I don't know what cov2corr and simCovMu do.  But since deNoiseCov appears to be your code, I assume you could put some diagnostic prints there, checking shape and dtype.
Since this code is coming from PY2, beware that a number of py2 list creators are generator like in py3.  np.array(range(3)) still works, but many other cases will create scalar (0d) arrays (such as map).
Also the use of np.matrix is old; it's no longer very useful - but it still works (so probably isn't the cause of errors).


text:
Q: Count of elements in lists in two columns within pandas dataframe I need to get the frequency of each element in lists when the list is in a pandas dataframe columns.
it like data.groupby(["element in a","element in b"]).size(),but column 'a' and column 'b' is list.
I need the size of each combination by element in 'a' and b'b'
in data:
        a           b
0   [17, 21, 22]    [zhinan, shejiyuanze, fankui]
1   [17, 21, 23]    [zhinan, shejiyuanze]
2   [17, 21]        [zhinan, shejiyuanze, fankui]
3   [17, 21, 22]    [zhinan, shejiyuanze, fankui]
4   [17, 21]        [zhinan, shejiyuanze, yizhi]

Desired Output:
              17 21 22 23
zhinan        5  5  2  1
shejiyuanze   .  .  .  .
fankui        .  .  .  .
yizhi         .  .  .  .

For example, when a=17 and b=zhinan, the number is 5.when a=17 and b=fankui,the number is 3.when a=23 and b= fankui or b=yizhi the number is 0.
I was wondering if there is a efficient/direct way to do this.
thanks

A: Use explode to explode lists. Remember to reset_index before second explode.
Then use group_by to count number of occurrences.
Finally use unstack to convert Series to Dataframe
df.explode('a').reset_index(drop=True).explode('b').groupby(['b', 'a']).a.count().unstack()

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to replace Data Export Service with Synapse Link for Dataverse We are heavily reliant on the DES as it exists today and have been monitoring developments for the Synapse Link over the past year since the DES deprecation announcement. To date, we have not found a comprehensive guide on how to leverage the Synapse link and pipelines to exactly replicate the capabilities of DES – a service that results in a SQL Server database (serverless / dedicated pools are not sufficiently performant by comparison) that is up to 15 min delayed replication of the dataverse entities configured for export, including the OptionsetMetadata entities. We have considered and tested all of the approaches we can find through the following links but NONE are a true replacements for the DES:
https://powerapps.microsoft.com/en-us/blog/do-more-with-data-from-data-export-service-to-azure-synapse-link-for-dataverse/
https://learn.microsoft.com/en-us/power-apps/maker/data-platform/azure-synapse-incremental-updates
https://learn.microsoft.com/en-us/power-apps/maker/data-platform/azure-synapse-link-pipelines?tabs=synapse-analytics
https://learn.microsoft.com/en-us/power-apps/maker/data-platform/azure-synapse-link-synapse#access-near-real-time-data-and-read-only-snapshot-data
https://powerapps.microsoft.com/en-us/blog/do-more-with-data-from-data-export-service-to-azure-synapse-link-for-dataverse/
Is Synapse Link for Dataverse even capable of replacing Data Export Service. Is there some secret sauce I'm missing here? Microsoft docs seem to only offer limited use cases / preview functionality and not focus on what would be a like-for-like replacement of the existing service.

A: I understand you so well , because we are currently facing the exact same problem.
We have successfully used Synapse Link to export Dataverse data to a Data Lake Storage. Then we effortfully tried to use Data pipelines to sink all the data in an Azure SQL Database, using various data mapping flows, but this al turned to be expensive and an overkill as this would be used for Big Data not for simple export service. As I am not a Data engineer, it was pretty difficult to find the right solution.
Based on our experience, I can tell you we found 2 possible solution that replicate the former DES which gave us no headache.

*

*Use Azure Data Factory, create linked service for Dataverse, thereafter a linked service for SQL Database, and after that, create a simple Copy Activity in ADF pipeline, configure the activity with both linked services, and the SQL will be updated frequently when new data in Dataverse emerge.  Please study the following links: https://learn.microsoft.com/en-us/azure/data-factory/connector-dynamics-crm-office-365?tabs=data-factory as well as https://learn.microsoft.com/en-us/azure/data-factory/tutorial-copy-data-dot-net (Just study the Copy data activity feature, not the entire flow)

*Metada-driven copy. We have not yet implemented this solution but it remains as a backup plan. (https://learn.microsoft.com/en-us/azure/data-factory/copy-data-tool-metadata-driven) As I understand this can be used to copy data from a Data lake to SQL with no major problems, but I have yet to try this solution.

Hope this helps!

A: Serverless SQL seems to be way too slow, qyery performance is like scanning text files... ;) Building another pipeline which pushes data to dedicated SQL pool adds another complex layer and even more delay.
It's also very hard to limit access to Serverless SQL pool as disabling public internet access seems to break Data Verse link and "Allow Azure services and resources to access this workspace" option does not help.
Really expect Microsoft to invest more in this functionality, looks like 3rd parties are joining the party: https://projectum.com/power-hub/


text:
Q: Problems retrieving emails from gmail in Android app I'm using the java mail api built into java to get the mail of a user from their gmail box, most of the code i found in another SO question. And I'm able to pull most of the information i want correctly, like the subject, senders and other info from my mailbox.
Everything works great except when i go to pull the "content" of the message it doesnt always pull the content of the message. Only like 1 in 10 times it works. The other 9 times it just finds "javax.mail.internet.MimeMultipart@40e9c920"
My code is below. I'm printing the output into LogCat to test. Thanks in advance.
Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props, null);
            Store store = session.getStore("imaps");
            store.connect("imap.gmail.com", "Email address here",
                    "password here");
            Folder inbox = store.getFolder("Inbox");
            inbox.open(Folder.READ_ONLY);
            Message messages[] = inbox.getMessages();
            for (Message message : messages)
                Log.d("Email", message + "");
            Message message[] = inbox.getMessages();

                    for (int i = 0; i < 25; i++) {
                        Log.d("From", message[i].getFrom()[0] + "");
                        Log.d("Subject", message[i].getSubject() + "");
                        String content = message[i].getContent().toString();
                        Log.d("content", content + "");

                    }

Edit:
After some additional research I've found it has something to do with reading a multipart email with JavaMail

A: If anyone else has this problem the reason it wasn't working all the time is that when it found multipart messages it was unable to read them. Below is the solution to read multipart emails. I found most of the code on this website.
String s = message[i].getContent() + "";

                    if(s.indexOf("MimeMultipart") != -1){
                        Multipart multipart = (Multipart) message[i].getContent();

                          for (int x = 0; x < multipart.getCount(); x++) {
                          BodyPart bodyPart = multipart.getBodyPart(x);

                          String disposition = bodyPart.getDisposition();
                          //Log.d("disposition", disposition + "");

                          if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) {
                              System.out.println("Mail have some attachment : ");

                              DataHandler handler = bodyPart.getDataHandler();
                              System.out.println("file name : " + handler.getName());
                              } else {
                              System.out.println(bodyPart.getContent());
                              }
                              }
                              System.out.println();

                          }

                    else
                        Log.d("Content", message[i].getContent() + "");

                }

A: Try this,
imap.gmail.com replaced by smtp.gmail.com


text:
Q: Getting Error during Angular Production Build When I was preparing project to publish, I get this error. Can someone tell me how can i fix this?
ERROR in ./node_modules/angular2-jwt/angular2-jwt.js
Module build failed: Error: Debug Failure. False expression.
    at getJSDocTags (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@angular-devkit\build-optim
er\node_modules\typescript\lib\typescript.js:13197:22)
    at getFirstJSDocTag (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@angular-devkit\build-o
imizer\node_modules\typescript\lib\typescript.js:13205:24)
    at Object.getJSDocTypeTag (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@angular-devkit\b
ld-optimizer\node_modules\typescript\lib\typescript.js:13154:19)
    at checkParenthesizedExpression (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@angular-de
it\build-optimizer\node_modules\typescript\lib\typescript.js:45628:56)
    at checkExpressionWorker (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@angular-devkit\bu
d-optimizer\node_modules\typescript\lib\typescript.js:45676:28)
    at checkExpression (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@angular-devkit\build-op
mizer\node_modules\typescript\lib\typescript.js:45609:42)
    at checkBinaryLikeExpression (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@angular-devki
build-optimizer\node_modules\typescript\lib\typescript.js:45155:29)
    at checkBinaryExpression (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@angular-devkit\bu
d-optimizer\node_modules\typescript\lib\typescript.js:45147:20)
    at checkExpressionWorker (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@angular-devkit\bu
d-optimizer\node_modules\typescript\lib\typescript.js:45702:28)
    at checkExpression (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@angular-devkit\build-op
mizer\node_modules\typescript\lib\typescript.js:45609:42)
    at checkExpressionCached (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@angular-devkit\bu
d-optimizer\node_modules\typescript\lib\typescript.js:45457:38)
    at getTypeOfExpression (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@angular-devkit\buil
optimizer\node_modules\typescript\lib\typescript.js:45577:28)
    at checkDeclarationInitializer (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@angular-dev
t\build-optimizer\node_modules\typescript\lib\typescript.js:45469:24)
    at getTypeForVariableLikeDeclaration (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@angul
-devkit\build-optimizer\node_modules\typescript\lib\typescript.js:30738:28)
    at getWidenedTypeForVariableLikeDeclaration (D:\Visual Studio\asp.net\mean_blog\client\node_modules
angular-devkit\build-optimizer\node_modules\typescript\lib\typescript.js:30961:24)
    at getTypeOfVariableOrParameterOrProperty (D:\Visual Studio\asp.net\mean_blog\client\node_modules\@
gular-devkit\build-optimizer\node_modules\typescript\lib\typescript.js:31062:28)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! blog@0.0.0 build: `cd client && ng build --prod && cd .. && node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the blog@0.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Yashdeep Raj\AppData\Roaming\npm-cache\_logs\2018-07-06T19_43_30_221Z-debug.log

I have fixed some error, but these are about module and I know nothing about these error.

A: I resolved this issue using @auth0/angular-jwt with angular 6. You first need to uninstall angular2-jwt completely:
npm uninstall angular2-jwt --save

Then you can run:
npm install @auth0/angular-jwt

Only these two command lines helped me. All the best.

A: I solve the issue, actually I was using the angular2-jwt(Deprecated) along with @auth0/angular-jwt. Which was causing issue. So I uninstalled the angular2-jwt update code with @auth0/angular-jwt and Everything start working fine.


text:
Q: Как вы нашли работу? Я вот-вот получу диплом бакалавра и уже хочется не штаны просиживать в аудиториях, а какой-то практический опыт получать. Как вы нашли свою первую работу?
A: А я вот на 3 курсе подрабатывал в разных компаниях тестировщиком ПО,
потом год не работал.
Полноценно, на постоянной основе стал трудиться только на 5 курсе
устроившись на кафедру,теперь вот 3-ий год на Java программирую.
Должен сказать что поднабрался опыта - спасибо родному электротехническому университету.
Теперь остался в аспирантуре. Пошли интересные исследовательские проекты.

P.S.
Зря некоторые критикуют Российскую науку ведь всё зависит от нас самих.
По мне так лучше в российской организации работать, т.к. на дядю Сема
трудиться слишком много желающих.
А кто о своей собственной стране думать будет если не мы?
A: Так же как и многие другие. В конце второго курса написал резюме и послал в кучу мест. Много где меня послали куда подальше, так как опыта работы не было и режим работы мой был неясный.. но в одном месте взяли. И понеслась :)
A: Разослал ссылки на свою страницу на LinkedIn. Через 3 собеседования устроился на работу которая меня устраивала.
A: Я вобще поздно спохватилась. Закончила универ и тогда только начала искать работу. Полгода металась с одного места на другое: везде заключала договора. Если что-то не устраивало - тут же начинала искать работу снова. Особого выбора, правда, не было: куда брали, туда и шла. Таким макаром побывала продавцом-консультантом в компьютерном отделе и программистом на нескольких предприятиях. Хотелось программировать, но обычно под словом "программист" работодатель подразумевал одмина-эникейщика. А то бывало и сразу отказывали либо из-а того, что нету опыта, либо вовсе из-за того, что я девушка). И так продолжалось, пока не нашла работу по душе. Теперь тружусь веб-программистом и очень рада, что нашла эту работу. Наверное, не часто человек может похвастаться, что ему нравится ходить на работу и он там занимается любимым делом))
A: Я начал работать на 2м курсе, на 3м был уже на постоянной основе. В последнее время правда уже скорее ищут меня чем ищу я, но это выстрадано долгим построением репутации.
A: :)))
17 лет - Лето на дворе - жара...Рещил пойти на работу работать, но куда - не знал :)))
И тут открыл сайт местного провайдера где черным по Русскому было написано "Срочно требуется работник в ТП".
Труда пройти собеседование не составило (я на то время был админ нашей Дом. сетки, так что то, что у меня спрашивали - мне было знакомо).....
Оттуда и все понеслось :)
A: Я получил работу когда был второй раз на 1м курсе. В группе выдали анкеты, я сразу понял по вопросам для чего она. Таким образом я стал сисадмином на кафедре, через пол года это стало моей официальной работой с зарплатой.
A: Пошел на собеседование в 1С и веб-студию. В первой предложили бесплатное обучение, с последующим трудоустройством. В веб-студии: работу )
Так вот стал веб-разработчиком.
A: Первая моя работа тоже была поздно, после окончания универа. Немаленькая организация, неплохая зарплата, неплохое занятие. Но и вправду говорится, что работа должна приносить удовольствие, ну или хотя бы удовлетворение. Неплохая оплата не смогла компенсировать скуку и стресс. В итоге через полгода новая работа: программирование под iOS. Устраивает все, кроме зарплаты. Но так получилось, что моральное удовлетворение важнее зарплаты :) В университете было заблуждение, что не важно, какая работа, главное, чтобы хорошо платили...
A: Получил работу на втором курсе. На кафедре порекомендовали меня в информационный отдел, после чего я устроился там работать. Сначала на маленькую з/п для опыта, лаборантом. Потом поднялся до ведущего программиста, опыт набрал неплохой для того времени.
A: Написал прогу - некий аналог ГИСа, увидели какие-то буржуины - пригласили к себе и понеслось...
A: Так получилось, что компьютер у меня дома появился еще в конце 80-х (отец был программистом в каком-то сверхсекретном НИИ, но ему удалось принести домой "списанный" ЕС-1840), когда понятие компьютер (да и ЭВМ) было незнакомо народу, да и вообще не вызывало никакого интереса у одноклассников и друзей. С него началось изучение ДОС, Бейсика и Паскаля. Потом были тяжелые годы, связанные с переделом СССР, годы бесперспективности и застоя. Уже учась в институте, начал подрабатывать на складе в фешенебельном ресторане - зарабатывал свои деньги, но самое главное - получил бесценный опят работы в коллективе, научился делопроизводству, ответственности, несмотря на то, что профессия была далеко не той, о которой мечтал. Все эти годы компьютер был рядом со мной дома (уже не ЕС-1840) и я довольно много времени уделял обучению и практике, хотя даже в те времена бухгалтерия ресторана обходилась без компьютера, и лишь потом директор принес первый в истории DX486-ой с Windows 95, который поручили мне, чтобы обучить бухгалтера работать с Excel.
Так получилось, что мне посчастливилось познакомиться с мои ровесником, который работал в рекламном агентстве, куда я был принят. Спустя полгода я уже профессионально работал в Corel и имел свои собственные работы в виде плакатов и 3D-инсталляций, развешанных по городу, а также брошюр и прочей рекламной атрибутики. Но с рисованием и дизайном я не дружил с детства, поэтому я знал, что это не моя сфера, где я был сугубо техническим исполнителем, но никак не креативным работником. Забыл упомянуть: я всегда увлекался электроникой и радиотехникой. Поэтому однажды подал свое резюме в компанию Ericsson, был вызван на собеседование, но принят не был (какой-то иностранец почему-то спросил меня, знаю ли я С++, хотя, как позже выяснилось, это не имело отношения к работе вообще, а будущие коллеги впоследствии сказали, что спросить это у меня его подтолкнул тот факт, что у одного из сотрудников на столе лежала книга по С++, которую этот иностранец принял за учебник технологии, которая якобы использовалась в их офисе). Спустя год я опять повторил попытку, прошел собеседование с другим уже начальством и был принят. Ericsson обслуживал местного оператора мобильной связи, но спустя пару лет, после реформирования контракта между компаниями, я с несколькими сотрудниками перешли работать в саму компанию - мобильный оператор, где и работаю на сегодняшний день уже более 10-ти лет.
Вот такая вот история со получением работы. Я считаю, что если хотеть - то добиться можно всего. Главное - не опускать руки и учиться, учиться и еще раз учиться.
A: Поздно спохватились конечно. Теперь главное адекватно понимать свои возможности. Не гнаться за большой зарплатой Идти туда, где сможете набраться опыта. Сейчас для вас главное не зарплата, а опыт.
A: Когда я ещё не был программистом (по первому образованию я агрохимик), я вообще листовки в пробках раздавал. Первый раз устроился работать программистом под конец магистратуры, когда заканчивал соответствующую переподготовку. Впечатления такие: поначалу проще устроиться туда, где занимаются какой-нибудь экзотикой и готовы ей обучать.
A: На 3-ем курсе пришел дядька с фирмы, спросил кому нужна работа, прошел собеседование у него, так и устроился на программиста )
A: Взломал "Счастливого фермера" Вконтакте и понеслось....увлекся web программированием и web дизайном. В данный момент помогаю своему учебному заведению с сайтом. - "Работа за уважение":)
A: В начале первого курса института пошел на собеседование на android developer и прошел, так как я после техникума у меня диплом младшего специалиста и соответственно 20 лет за плечами) до этого интересовался разработкой под дроид и когда пришел на собеседование без проблем ответил на вопросы и прошел.

A: Курсе на 3-ем, одногруппник предложил сверстать дизайн и подработать. В то время я ничего об этом не знал. Ну и понеслось :)
Через зарубежную биржу труда вышел на заказчика из своего города, который после разовых работ, пригласил к себе в веб-студию.
A: Нашёл свою первую работу на 3-м курсе.
До этого изучал java и android , пытался писать свои приложения.
Друг уже устроился летом iOS разработчиком и пригласил меня. В итоге успешно выполнив задание я стал работать android разработчиком.
A: Студент, в конце первого курса заполнил резюмешку на сайте вакансий, и все теперь работаю, получаю опыт ( веб разработка ) =)


text:
Q: JQuery click of input button not firing I've looked on the forum and my question is a duplicate of Button click event not firing in jQuery, except my code already matches the given answer.
I've stripped this down for you guys anyway, and can confirm that links with a class of disabled do not fire, so this proves the document ready and Jquery library are correct.
Javascript
$(document).ready(function () {
  // Prevents links from firing
  $('a.disabled').click(function (e) {
    e.preventDefault();
  });

  // Handles search
  $("#btnTreeSearch").click(function () {
    alert("click search fool!");
  });
});

Html
<input type="submit" value="btnTreeSearch" />

Any clues?

A: You need to assign id to input to use id selector
Live Demo
Html
<input type="submit" id="btnTreeSearch" value="btnTreeSearch" />

Javascript
 $("#btnTreeSearch").click(function () {
     alert("click search!");
 });

A: Change value="btnTreeSearch" to id="btnTreeSearch".


text:
Q: How to typescript `this` when it is dynamic? I'm converting a series of JavaScript projects to typescript, and a common paradigm that I've used has been the following:
abstract class A {
    static create (…args) {
        return new this(…args)
    }
    /* a bunch of things */
}

class B extends A {
    a: number
    b: string
    constructor(a: number, b: string) {
        super()
        this.a = a
        this.b = b
    }
    /* a bunch of things */
}

class C extends A {
    /* a bunch of things */
}

Which offers the compelling syntactic sugar of require('module').B.create().
I cannot figure out how to make this valid typescript.
Additional complexity, is that consumers of the package may also extend class A too, so I am not aware of all the extensions at the time of authorship.

With:
abstract class A {
    static create<T extends typeof A>(this: T, ...args: any): T {
        const Klass = this
        const instance = new Klass(...args)
        return instance
    }
}

class B extends A {
    a: number
    b: string
    constructor(a: number, b: string) {
        super()
        this.a = a
        this.b = b
    }
}

class C extends A { }

I get the error:

[ts] Cannot create an instance of an abstract class. [2511]

With the following, that omits the abstract for debugging:
class A {
    static create<T extends typeof A>(this: T, ...args: any): T {
        const Klass = this
        const instance = new Klass(...args)
        return instance
    }
}

class B extends A {
    a: number
    b: string
    constructor(a: number, b: string) {
        super()
        this.a = a
        this.b = b
    }
}

class C extends A { }

I get an error about the variable arguments:

[ts] Expected 0 arguments, but got 1 or more. [2556]

With:
type StaticThis<T> = { new(): T };

abstract class A {
    static create<T extends typeof A>(this: StaticThis<T>, ...args: any): T {
        const Klass = this
        const instance = new Klass(...args)
        return instance
    }
}

class B extends A {
    a: number
    b: string
    constructor(a: number, b: string) {
        super()
        this.a = a
        this.b = b
    }
}

class C extends A { }

I solve the abstract error, but keep the arguments error:

[ts] Expected 0 arguments, but got 1 or more. [2556]

With:
interface Factory<T> {
    new(...args: any[]): T
}

abstract class A {
    static create<T extends A>(this: Factory<T>, ...args: any): T {
        return new this(...args)
    }
}

class B extends A {
    a: number
    b: string
    constructor(a: number, b: string) {
        super()
        this.a = a
        this.b = b
    }
    foo() {

    }
}

class C extends A {
    bar() {

    }
}

It works as expected, however Visual Studio Code autocompletes B.create to B.create(this), which may be a seperate bug.

A: I think a minor modification to the code alluded to in the relevant issue will also give you the proper constructor argument checking for each subclass, at least since TypeScript 3.0 introduced generic rest parameters:
type StaticThis<Args extends any[], T> = { new(...args: Args): T };

abstract class A {
  public static create<Args extends any[], T extends A>(
    this: StaticThis<Args, T>,
    ...args: Args
  ): T {
    const Klass = this
    const instance = new Klass(...args)
    return instance
  }
}

class B extends A {
  a: number
  b: string
  constructor(a: number, b: string) {
    super()
    this.a = a
    this.b = b
  }
}

class C extends A { }

const b = B.create(1, "b"); // okay
const c = C.create(); // okay
const badB = B.create(2, 3); // error, type '3' not assignable to type 'string';
const badC = C.create(4); // error, expected 0 arguments
const badA = A.create(); // error, can't use abstract class here

I'm kind of not sure about why you'd rather jump through these hoops instead of just using new on the subclasses, but you probably have your reasons.
Hope that helps.  Good luck!

A: File 1 =>
 export namespace Shapes {
        export namespace Polygons {

            export class A {
                static create <T extends A>(): T {
                    return <T>new this();
                }

                sayHi(){
                    console.log('Hi')
                }
            }

            export class B extends A{
                sayHiFromB() {
                    console.log('Hi From B');
                }
            }
        }
    }

File 2 =>
import * as myImport from './testing';

    const myInstanceA = myImport.Shapes.Polygons.A.create();
    myInstanceA.sayHi();

    const myInstanceB = myImport.Shapes.Polygons.B.create<myImport.Shapes.Polygons.B>();
    myInstanceB.sayHi();
    myInstanceB.sayHiFromB();

Result =>


text:
Q: Parsing MagTek EMV TLV I'm working with a MagTek DynaPro in a project to read credit card data and enter it into an accounting system (not my first post on this project). I've successfully leverage Dukpt.NET to decrypt MSR data, so that's been good (https://github.com/sgbj/Dukpt.NET). So I started working on getting the EMV data, and I've used the following MagTek document for TLV structure reference: https://www.magtek.com/content/documentationfiles/d99875585.pdf (starting at page 89). However, I'm having trouble reading the data.
I tried using BerTlv.NET (https://github.com/kspearrin/BerTlv.NET) to handle parsing the data, but it always throws an exception when I pass the TLV byte array to it. Specifically, this is what I get:
System.OverflowException : Array dimensions exceeded supported range.

I've also tried running the data through some other utilities to parse it out, but they all seem to throw errors, too. So, I think I'm left with trying to parse it on my own, but I'm not sure about the most efficient way to get it done. In some instances I know how many bytes to read in to get the data length, but in other cases I don't know what to expect.
Also, when breaking some of the data, I get to the F9 tag, and between it and the DFDF54 tag the hex reads as 8201B3. Now, the 01B3 makes sense considering  the leading two bytes for full message length are 01B7, but I don't understand the 82. I can't assume that's the tag for "EMV Application Interchange Profile" since that's listed under the F2 tag.
Also, there's some padding of zeros (I think up to eight bytes worth) and four bytes of something else at the end that are excluded from two-byte message length at the very beginning. I'm not certain if that data being passed into parsers is causing a problem or not.

A: Refer the spec screenshot 1, as per EMV specs you are supposed to read the tags like below.
Eg tag 9F26 [1001 1111] the subsequent byte is also tag data - [0010 0110]
But when it is 9A [1001 1010], tag data is complete, length follows.

The spec also says to check the bit 8 of second byte of tag to see whether a third byte of tag follows like below, but practically you will not require it.

In real life you know upfront the tags you will encounter, so you parse through the data byte by byte, if you get 9F you look for the next byte to get the full tag and then next one byte of length, and if it is 9A, the next byte is length.
Note that length is also in Hex, which mean, 09 means 9 bytes, where as 10 means 16 bytes. For 10 bytes it is 0A.
I now bless you to fly!!

A: While @adarsh-nanu's answer provides the exact BER-TLV specs I believe what @michael-mccauley was encountering was MagTek's invalid usage of TLV tags.  I actually stumbled through this exact scenario for the IDTech VIVOpay where they also used invalid tags.
I rolled my own TLV parsing routines and I specifically called out the non-conforming tags to force set a length when not in BER-TLV conformance.  See example code below:
int TlvTagLen(uchar *tag)
   {
   int len = 0;            // Tag length

   // Check for non-conforming IDTech tags 0xFFE0 : 0xFFFF
   if ((tag[0] == 0xFF) &&
       ((tag[1] >= 0xE0) && (tag[1] <= 0xFF)))
      {
      len = 2;
      }

   // Check if bits 0-4 in the first octet are all 1's
   else if ((tag[len++] & 0x1F) == 0x1F)
      {
      // Remaining octets use bit 7 to indicate the tag includes an
      // additional octet
      while ((tag[len++] & 0x80) == 0x80)
         {
         // Include the next byte in the tag
         }
      }

   return len;
   }


text:
Q: Krull dimension of $A[x]/\langle x^2 + 1 \rangle$
Consider any noetherian ring $A$ and the polynomial ring $A[x]$. Consider the quotient ring $A[x]/\langle x^2+1\rangle$. Is the dimension of this quotient ring equal to dimension of $A$ (i.e. dimension of $A[x] - 1$)?

If there is a chain of ideals in $A[x]$ given by $P_0[x] \subseteq P_1[x] \cdots, P_r[x] \subseteq P_r + \langle x \rangle$. This chain will still be prime in the quotient ring?

A: The ring extension $A\subset A[x]/(x^2+1)$ is integral ($x$ is a root of the monic polynomial $t^2+1\in A[t]$), so $\dim A=\dim A[x]/(x^2+1)$.
Remark. You can replace $x^2+1$ by any monic polynomial.


text:
Q: Computing conjugacy between two elements of $\mathrm{SL}_2(\mathbb{Z})$ The conjugacy classes of $\mathrm{SL}_2(\mathbb{Z})$ are well characterized (see, e.g., this question). Assuming two matrices $A, B \in \mathrm{SL}_2(\mathbb{Z})$ are conjugate, is there a way to compute their conjugacy, i.e. construct a matrix $C \in \mathrm{SL}_2(\mathbb{Z})$ such that $A C = C B$?

A: If you have access to a soft as Maple , Mathematica or Sage, you can proceed as follows. Let $A,B\in \mathrm{SL}_2$ be conjugate.
Step 1. Using a Grobner basis library, you solve the equation in $X=\begin{pmatrix}a&b\\c&d\end{pmatrix}$ $XB-AX=0,\det(X)=1$ ($5$ equations in the $4$ unknowns $(a_{i,j}))$.
Since the dimension of the algebraic set of the solutions is $1$, you group the unknowns into 2 blocks, for example $(a,b)$ and $(c,d)$. In this way , you obtain $3$ equations, the first $2$ of degree $1$ and the last one, denoted by (*), is a quadratic function of $(c,d)$ ($uc^2+vd^2+wcd+t=0$). The calculation must be instantaneous with $70$ digits; otherwise change the couples of unknowns.
Step 2. You solve (*); you can do that on line here
https://www.alpertron.com.ar/QUAD.HTM
This type of equations admits an infinity of solutions except for example if we consider the equation $x^2+y^2+1=0$ which, I think so, does not have many solutions.
We obtain one or several primitive solutions and also one or several recursive solutions starting with primitive solutions. With $70$ digits, the time of calculation is $20"$.
Step 3.  The problem is that the first $2$ equations have the form: $pa+qb=r(c,d),p_1a+q_1b=r_1(c,d)$; then the solution obtained in the last equation must kill the denominator $pq_1-p_1q$.
Fortunately, in all the tests I carried out, a primitive solution was suitable. I don't know if this is general or at least generic; however, if not, then we have to use the recurrence formulas.
That follows is an example:


text:
Q: Specifying a set of prioritized namespaces for finding API controllers? Fact: the current VS.2015 templates the authorization implementation differs dramatically between a WebAPI project and an MVC project.
Fact: My project has both MVC and WebAPI 2.0 components
Requirement: Identity 2.0 authorization for both WebAPI and MVC controllers
Wish: I want both controllers to be named Account but one in the Controllers namespace and the other in Controllers.Api, thus avoid renaming one of the controllers.
knowing that and that apparently the only way is to merge both Identity/Authorization implementations into one project, it would mean I need two account controllers and two sets of account-related models.
In the MVC MapRoute (RouteConfig.cs) one can specify the namespaces for the MVC controllers. But since I am going to have two account controllers (one for API the other for MVC) I plan to put the API Account controller in MyNamespace.Controllers.Api and leave the MVC on MyNamespace.Controllers. But On the WebApiConfig.cs file the HttpRoute method seems to have no parameter to configure the namespace, that means it would find the AccountController used in MVC rather than the one it needs isn the .Api subnamespace.
Is there a way to tell the WebAPI route to look for its controllers in the Controllers.Api namespace rather than the Controllers namespace?
As I stated, I do not want to rename one of the controllers unless absolutely necessary.


text:
Q: PPTP connection fails during handshake A user located on the other side of the planet has troubles connecting to our PPTP VPN. The VPN is a regular windows server 2003 VPN and works fine for most users from the US, but for this specific person, it doesn't connect at all.
The login window hangs on "verifying username/password" and dies after ~30 seconds.
I took a network trace on the server side, and this is what I see. 10.250.10.10 is the internal IP of the server, 121.X.X.255 is the public IP of the user.

Apparently there is no new network equipment on the user side, and definitely nothing has changed on the server side.
Any idea on how to diagnose this ?

A: I don't see an ACK from the client to the server's SYN-ACK. Here's a snippet of a Microsoft Network Monitor capture from my workstation to an internal RRAS server. You can clearly see the TCP three way handshake occurring before any PPTP negotiation takes place. If the client ACK to the server's SYN-ACK isn't taking place then I'd say that's where the problem is.

EDIT
Using Wireshark on the server this time, I see the same thing as you when looking at the conversation flow. There is a slight difference as evidenced in the below screen shot. There are 3 Set-Link-Info control messages in my capture as opposed to the 1 in your capture. My guess is that the server and client are failing to negotiate the connection parameters. Beyond that I have no clue. Sorry I couldn't be of more help.

A: NAT = Network Address Translator (device) or Network Address Translation (concept) depending on context.
PAT = Port Address Translator (device) or Port Address Translation (concept) depending on context
This problem is very common when either end (client or server) is behind a NAT/PAT boundary that does not support the PPTP+GRE protocol -- or does not support it well.
In the realm of PPTP, TCP/1723 is a simple control channel whose sole purpose is to bring up a Microsoft specific secondary GRE (IP/47) tunnel. This GRE tunnel contains encapsulated PPP frames and is used for negotiating authentication, encryption, and passing actual data.
Not all NATs (firewalls, routers, appliances) support passing the secondary GRE tunnel to clients/servers.  The PPTP VPN client will appear to connect, get to a "Verifying Username and Password" message and hang there.  The "Verifying Username and Password" stage requires the GRE tunnel to be functional.
Some NATs/PATs may support a single PPTP+GRE for a single user behind the NAT/PAT, but a second PPTP+GRE from either the same user or a different user behind the NAT/PAT can fail.  I have seen many kinds of spectacular failures with PPTP+GRE through NAT/PAT with both consumer, business, and enterprise grade NATs/PATs
In your specific case -- if other users can connect to your RRAS fine using PPTP+GRE, but this single user cannot -- it is likely the NAT/PAT boundary on that user's network.
Be prepared to spend a lot of time diagnosing this problem if this particular user has substandard Internet and edge hardware -- especially if it is from a provider performing Carrier Grade NAT (CGN).
If you can gain access to the user's PC and run Wireshark on their PC while trying to connect and look for GRE datagrams both to and from the RRAS server.  If the GRE tunnel is failing you will likely see a GRE datagram destined for the RRAS server public IP, but not see a return GRE datagram from the RRAS server public IP.
If this is the case the concern is upstream from the PC.  Look at all upstream NATs/PATs to ensure they support PPTP+GRE fixup/passthrough/inspection or whatever that vendor calls it.  Know that some vendors, despite "support" for PPTP+GRE, only support it in limited manners -- as described earlier.  Cisco ASA's and PIX's have had rather excellent support for PPTP+GRE fixup/inspection for quite a while -- usually not enabled by default.
Running PPTP, L2TP, and IPsec VPN's through NAT/PAT are all rather problematic unless care is taken to overcome the NAT/PAT.  About the only VPN tech that can penetrate NAT/PAT rather easily is SSL/TLS based VPN's -- in my experience.


text:
Q: Best way to create draw with limitation I'm writing a program to automatically make the draw for a competition. There are four objects: Debate Judge School Team Each Debate has two teams and a judge. Each team participates in three debates.
With this, there are the following rules: 1) A team cannot face someone from their same school 2) A team cannot face another team from the same other school (As in if they play a team from a school once, they cannot play again against someone from that school) 3) A judge cannot come from the same school as a team they are judging.
So how would I create a draw? A draw looks like a table (I just need the data, but when you write it it looks like this) with a column for judges and then three other columns for each round of debates (the three debates each team participates in).
Right now I'm basically choosing a random team, finding an opposing team that hasn't played the school of the first team before and doesn't come from the same school and then finding a judge from neither of those schools. Then I do the same thing until I have all the debates. The problem is the program sometimes gets into ruts where there is no other team/judge that fits.  A human would then shift things around and try to find a way to move other judges around to figure it out, but how can I do that with a program. If I run the program again it figures it out just because it's random which teams it chooses for what. Basically, I'm wondering what the best solution is to the problem?

A: Sounds like a good candidate for using the knapsack problem algorithm.  You may want one of the multi-variant extensions (also listed in that Wikipedia reference), but ultimately it's the same algorithm.  You could have a look at one of my recent answers for a very similar problem domain.
The bad news is that this is an NP-hard problem.  Loose translation: you'll never find a perfect algorithm to solve the issue.  However, if you're willing to use some "cheats" then you can generate an algorithm that will reliably complete.  The cheats aren't that big of a deal in this case; you just need to constrain the starting parameters in order to allow the algorithm to converge upon a solution.  And it's not like you need true randomness for setting up the draw, you just need to make sure the participants are able to compete against as wide of a range of other participants as reasonably possible.

A: I think you're close.  The trick is to start with the first team ('first' can be defined any way you want, including random) and make a list of all the available other teams, in some order.  Pair up the first team with the first of the available other teams.  Now look make a list of the available judges (again in some order), and pick the first available judge.
Repeat the above for the next set.  At some point you won't have any second team to pick, or you'll be out of judges.  At that point you need to "backtrack" - unwind one of your previous decisions and move on to the next.
For example, when you select team A, your choices are (B and C).  You select B and move on.  Later you discover that B was an unfortunate choice, so you revisit that choice and select C instead.
The idea is called Depth First Search.  It's a lot easier than the Wikipedia page makes it out to be.
I'd handle your challenge by assigning each team a random number then use that number for sorting them whenever I'm looking for the "next available" team or judge.  That way you'd get your random pairings and a way to backtrack and unwind.  (The goal is to correctly select the correct teams and judges in such an order that you get all the pairings you need, subject to the contest rules constraints).
The only time you use Random() is when you're setting up the data.  The algorithm shouldn't use it.

A: As it's Saturday, and my thinker is currently broken, I'll take the lazy way out. Count iterations without a match found. If they get above an arbitrary number, dump your result set and start over.
It's a kludge fix, but it will address the never-ending rut issue.


text:
Q: Does the bearer token sent in Auth0's /userinfo api endpoint ever expire? We have Auth0 set up with their Lock widget v11 using Implicit Flow in our SPA. We have JWT expiration set to 15 minutes in the Application settings in Auth0 admin portal and we use Silent Authentication in our web app to get a new token periodically.
That flow is working fine and the tokens expire as they should. Our issue is with the userinfo endpoint. The Auth0 Lock widget is doing XHR requests to the userinfo endpoint internally. During a security screening it was discovered that if such a request is recorded by us and then requested again in Postman several hours later the endpoint still responds with user details such as name and email. The bearer token sent in that request is not the same as the one issued with the 15 min expiration time.
This is a security issue for us since it is possible to get basic user info long after the user chose to log out.
In the Auth0 admin portal I have tried setting "Inactivity timeout"/"Require log in after" under Tenant Settings > Advanced to 1 minute. I also tried lowering "JWT expiration" under Application settings. None of these settings is affecting the userinfo request which still responds with user details.
Example of a request to the userinfo endpoint:
GET https://<tenant>.eu.auth0.com/userinfo

Request headers:
Authorization:Bearer <some token with length of 32>

Example of the response:
{
    "sub": "auth0|xxxxxxxxxxxxxxxxxx",
    "nickname": "John",
    "name": "John Doe",
    "picture": "xxxxxxxxxxxx",
    "updated_at": "2019-08-29T12:32:39.352Z",
    "email": "user@example.com",
    "email_verified": true
}

Is there any setting that governs the expiration of the bearer token sent to userinfo? Should it not have the same expiration as the application JWT expiration setting?

A: Unfortunately that token expiration is set for the endpoint and cannot be changed. This doc provides an answer.
https://auth0.com/docs/tokens/guides/access-token/set-access-token-lifetime#access-token-lifetime-for-the-oidc-user-profile-endpoint


text:
Q: JS Joi Validation fails on string length After spending almost 2 days to investigate why the validation is not working, I've got to a point. Basically I found out that if my string has more than 40 chars, the validation will fail. If it has 40 or bellow it will work.
So now I am using validator.joi.string() but I also try to fix this issue with : validator.joi.string().min(0).max(500) but it doesn't seem to work.
Any solution to this?

A: Just was testing. Sorry for the wrong formatting.
But It does work fine.
const Joi = require('@hapi/joi');

const schema = Joi.object({
    username: Joi.string()
        .min(3)
        .max(100)
        .required(),
})

schema.validate({ username: 'abc' });
// -> { value: { username: 'abc' } }

schema.validate({});
// -> { value: {}, error: '"username" is required' }

// Also -

async function run(){
  const value = await schema.validateAsync({ username: 'abcedeedsdsd sfdfghgdf sgfdghsfdsfdjgsfdgs shgdfshgdbshgdf sdhghsjfgfkhgj' });
  console.log(value)
}

run();


text:
Q: How make Swagger-UI work in a Play application I've just integrated Swagger into my Play application and it works – http://localhost:9000/api-docs/ returns the api doc in JSON format.
Now I'd like to use Swagger-UI... and I've copied the distro to myApp\public as suggested in the README file, but no way to make it work – the documentation seems to be a bit outdated.
I've tried to add this to conf\routes...
GET  /swagger-ui    staticDir:public/swagger-ui

... but it doesn't work and I always get the following error message:
Controller method call expected

The content of directory public/swagger is here.
Thanks.

A: Just added the following route to file routes:
GET /swagger-ui/*file  controllers.Assets.at(path = "/public/swagger-ui", file)

I hope it helps.


text:
Q: Why do deactivated layers still appear in the Processing Modeler's wizard in QGIS? I'm quite new to the graphical modeler of QGIS (version 3.10.1). It's a great tool, still, something has been bugging me for a while. I've created a fairly long model, saving the outputs of some tools as shapefiles as I need them for further analysis.
I use these newly generated shapefiles later in the model (inputed as vector layers), but have deactivated them when running the first block of my model where they are not needed (I don't launch everything at the same time as I have very big datasets and crashes often occur).
Still, in the computing wizard, it is still required to select these newly generated shapefiles, or shapefiles which will be generated further down in the model. I can't launch the model without them. What's the point of deactivating a layer and still needing to compute it in the drop down banners in the wizard? I've looked around for a related question, couldn't find an answer.

A: To start with, there is no such thing as stupid questions.
If you feel that there must be an option not to have those layers appear in the list, you can make a feature request here. The developers might agree and add that in their pipeline.

A: If I understand correctly, you save the outputs for every tool to disk or maybe you simply assign them an output name but keep them in memory. You could simply forego generating an output layer. You can still use the product of the tool in subsequent steps without having to choose any indermediate layer.
For example, in the following screenshot, almost all processing tools could output a layer, but I simply skipped saving them. The tool's output is used in the next tool, but when the entire model finishes running, only the last layer is saved and, when you run the model, is the only one that needs to be specified a path (or not if you want to keep it as a virtual layer).


text:
Q: How to use ImageRect images into movieclip in corona sdk? In my game i have to use movie clip. it runs perfect in iphone.when i use 4x images.it will not working properly.how to use imagerect image into movieclip.

A: I used newest movieclip.lua file.my problem solved.


text:
Q: Promise inside Observable in Angular 7+ I have a problem that I can't solve.
In the ngOnInit event I observe the url parameter. This parameter corresponds to a folder in firebase-storage. That way when loading I get a list of folders and/or files inside that folder that is being informed and storing it inside listReferences variable which is of type Reference[].
Here is the code:
ngOnInit() {
  this.route.params
    .subscribe(params => {
      this.getFiles(params.ref).subscribe(
        (listReferences) => {
          this.listReferences = listReferences;
        }
      );
    }
  );
}

getFiles(folder: string) {
  return this.storage.ref('/' + folder).listAll()
  .pipe(
    map((data) => {
      return data.items;
    })
  );
}

It turns out that for each item in the listReferences array I need to access the getDownloadUrl() or getMetadata() method which are promising and I am unable to retrieve the values for each item in the array. How should I proceed in this case? How best to do this?
Basically I am following the information contained in the reference guide.
https://firebase.google.com/docs/reference/js/firebase.storage.Reference

A: How about using ForkJoin as follows:
ngOnInit() {
  this.route.params
    .pipe(
      mergeMap(x => this.getFiles(x.ref)),
      mergeMap((listReferences: { getDownloadUrl: () => Promise<string> }[]) => {
        return forkJoin(listReferences.map(x => x.getDownloadUrl()))
      })
    )
    .subscribe(x =>  this.urls = x)
}


text:
Q: Django - field of language choices I want to let users choose from languages they speak. Is there a Django built-in list of languages or should I get list of languages from another source?
For now:
class UserProfile(models.Model):
    languages = models.ManyToManyField(Language)

class Language(models.Model):
    shortcut ...
    name ...

The languages field should only be able to list all languages user can speak.

A: There's the django-language-field. Unfortunately, it's sorted by the language code instead of the language name.

A: Django doesn't have a build-in list of lenguages! You have to get your list of lenguages from other source! For example you might see: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes


text:
Q: Laravel 5 and AJAX I want to display a partial form using ajax when I select the client name. So far I have managed to fetch data from database using this:
<script>
  $('#client').change(function(){
    var client = $(this).val();
    var host = "{{URL::to('/')}}";
    var url = host + '/newinvoice/' + client;
    $.ajax({
      url: url,
      type: 'GET',
      beforeSend: function(){
        $('.client_services').html('Loading...');
      },
      success: function(data){
        $('.client_services').html(data);
      }
    });

    return false;
  });
</script>

Here is my Controller.
public function getClientServices(Client $client) {
  return json_encode($client->client_service()->get());
}

So instead of $('.client_services').html(data); I want to display text inputs depending on the number of available services for that particular client.
I don't know how to do that.
The above snippet returns results like:
[{"id":1,"client_id":1,"service_id":1,"frequency":90,"deleted_at":null,"created_at":"2015-04-15 10:20:33","updated_at":"2015-04-15 12:22:48"},{"id":2,"client_id":1,"service_id":1,"frequency":0,"deleted_at":null,"created_at":"2015-04-15 13:10:41","updated_at":"2015-04-15 13:24:41"},{"id":3,"client_id":1,"service_id":1,"frequency":180,"deleted_at":null,"created_at":"2015-04-15 13:58:39","updated_at":"2015-04-15 15:34:46"}]

I'm interested on id only.
What I want to do after that is enter the charges for that particular service for that particular client.
I hope I am clear.

A: Build a partial view "_clientservice" with the final html structure you want to inject.
In your controller:
public function getClientServices(Client $client)()
{
    $clientService = $client->clientService()->get();
    return \Response::json(['html' => view('_clientservices', compact('clientService'))->render()]);
}

and then:
<script>
  $('#client').change(function(){
    var client = $(this).val();
    var host = "{{URL::to('/')}}";
    var url = host + '/newinvoice/' + client;
    $.ajax({
      url: url,
      type: 'GET',
      beforeSend: function(){
        $('.client_services').html('Loading...');
      },
      success: function(data){
        $('.client_services').html(data.html);
      }
    });

    return false;
  });
</script>


text:
Q: Save tkinter canvas for reimport and add-ons Strangely worded but a rather potential strange situation.
I'm plotting on a canvas a massive number of lines, err points in some cases.  This plotting goes beyond the edge of the screen...by the time all the data is included at a decent, usable resolution it would probably be in the area of 10,000-20,000x10,000-20,000 pixels...maybe bigger than that even.  In the current situation where I'm only displaying maybe 1-2% of the data to the screen it takes 30 seconds to create the graph.  I got to thinking this morning that maybe my best bet given how much more data is going to be presented before everything is said and done would be to create an initial graph and save the image and then display the image since it should be much quicker to display the image of the graph already created/saved then to create it each and every time I run the program.
I started doing some research into the idea this morning and have run into a few problems and questions to help me decide if this is a good idea or not.
When I try to
from PIL import Image, ImageTk

I get the error message that it cannot import ImageTk
If I try
import PIL

I get no errors.  I'm using Linux and Python 3.4.3.  Since several of the ideas involve ImageTk, how do I correct the importing problem?
Edit:
Also when I try
from PIL import ImageGrab
I get the error no module named _grabscreen.  Since that falls under PIL shouldn't it have been installed with PIL?
I know I would still need to install pyscreenshot to try the one technique I've seen presented here on SO.
Do any of these methods save the full canvas or only what you see on the physical screen. I would be wanting to save everything which is a much larger image then the physical screen display?
After saving the image and bringing it back up would I still be able to scroll around the image with tkinter?  As well, would I be able to add extras to the image, in terms of adding points of interest to the image(this would be a road map image).
So far I've only ever used tkinter for line graphs and not anything else so I don't have the experience to know the limitations versus what I might be wanting to do.
I have a few other ideas of how I might be able to handle the problem but none of the other ideas are as fast as this idea would be.
I just to need to get an idea as to what the limitations are to decide if I want to try to go any further with testing this idea out or not.
Thanks.


text:
Q: paperjs - How to apply brightness/contrast like effects on the raster image? I have tried to apply the image adjustment options using paper.js, but it will only apply to the fillcolor.
Does anyone know how to apply brightness, contrast or other image adjustments to the raster image?
For example:
var url = 'http://images.com/q.jpg';
var raster = new paper.Raster(url);
raster.brightness = .5;

Are there any pre-defined functions available for image adjustment in paper.js?

A: Nope, but you can play with blend modes or opacity.
I would advise using specialized WebGL libraries like glfx or webgl-filter for image effects (I didn't try them, but they seem powerful).

A: function reDrawImage(lightness = 10,contrast = 1.5) {
  const raster = paper.project.activeLayer.children[0] as paper.Raster
  const ctx: CanvasRenderingContext2D = currentRaster.getContext(true)
  const imageData = ctx.getImageData(0, 0, currentRaster.width, currentRaster.height)
  for (let i = 0; i < imageData.data.length; i += 4) {
    imageData.data[i] = saturate_cast(imageData.data[i] * (contrast + lightness));
    imageData.data[i+1] = saturate_cast(imageData.data[i+1] * (contrast + lightness));
    imageData.data[i+2] = saturate_cast(imageData.data[i+2] * (contrast + lightness));
  }
  raster.setImageData(imageData, new Point(0, 0))
}

function saturate_cast(num: number) {
  if (num > 255) {
    return 255
  }

  if (num < 0) {
    return 0
  }

  return num
}


text:
Q: Keycloak - how to get service account roles in client credentials access token I want a backend app to use another backend service's API, and control per app what it is authorized to call on the backend service. I am using OAuth 2.0 client credentials flow and Keycloak as the authorization server.
I expect roles defined for the backend service and set for the backend app to appear in the access token I request from Keycloak. But the only thing I can manage to appear, are realm level client scopes.
I tried the following (I don't expect to need all of this, but I wanted to try anything that made a little sense):

*

*created realm Test

*added client scope on the realm (realm-clientscope1)

*added roles on the realm (realm-role1, realm-role2)

*define client "backend-service", made this a "bearer-only" client since it doesn't have to authorize itself to other services

*create roles on this client (backendservice-role1, backendservice-role2, backendservice-role3-comp)

*define client "backend-app", made this a confidential client, with service account enabled

*added role on this client (backendapp-role1)

*assigned realm-clientscope1 as a default scope

*on the scope tab (backend-app Scope Mappings), turned off "Full Scope Allowed", assigned realm-role1, realm-role2, and client roles backendservice-role1, backendservice-role2, backendservice-role3-comp

*assigned service account roles with the same roles as on the scope tab (realm-role1, realm-role2, and client roles backendservice-role1, backendservice-role2, backendservice-role3-comp)

After all this, I used Postman to get an access token for grant_type client-credentials. The only thing on the access token is the realm scope "realm-clientscope1".
Why all these options to set service account roles, etc. If they don't show up?
I assume I am misunderstanding how roles are used, but I can't find a proper explanation either.
To try and cover all bases, I also turned on Authorization Enabled on the "backend-app" client, and  under authorization, tried to define authorization scopes, policies and permissions that made some sense.
This too, did not result in any more authorization info appearing on the access token.
The last thing I tried, is changing my "backend-service" app from "bearer-only" to "confidential" with Service Accounts Enabled. This also did not make a difference (as expected).
Keycloak version is 15.1.0 (thanks for asking, dreamcrash).

A: A little late, but I hope that it can be helpful to someone having the same problem.
Basically, it's necessary go to Client scopes tab, and add roles to default scope.
Notice that desired role must be setted in both Scope and Service account roles tabs or it can be setted Allow full scope in Scope tab, and then just set the desired role in Service account roles tab.
EDIT: I forgot to say these configurations must be set in client.

So, in my JWT token, I can see the role:


text:
Q: MySQL Returning Unique combinations from many tables this is my first post so please be kind.
I am trying to get to grips with SQL, using MySQL, I am having trouble returning unique results from queries where there are more than 2 tables. 2 tables is OK as I can use a not equals in the where clause to create unique vales.
Can someone explain the concept of how to do this for 3 or more tables.  Here is an example of what I am trying to do.
Table1     Table2     Table3

Number     Number     Number
1           1          1
2           2          2
3           3          3
4           4          4

When I run my query I will get 1,2,3 and 1,3,2. All I need is one of the possible results.
With 4 numbers there are a total of 24 combinations from the 3 tables. However I only want the unique combinations which is 4 combinations i.e.[1,2,3],[1,2,4],[1,3,4],[2,3,3].
The SQL that I have is
SELECT Table1.Number,Table2.Number, Table3.Number
    FROM  Table1,Table1 AS Table2,Table3
    WHERE
        Table1.Number <> Table2.Number and  Table1.Number <> Table3.Number
    GROUP BY Table1.Number , Table2.Number , Table3.Number
    HAVING Table1.Number <> Table2.Number
        AND Table1.Number <> Table3.Number
        AND Table2.Number <> Table3.Number;

What I am trying to do is de-duplicate all variances of the 3 numbers chosen.


text:
Q: Distributing 2 different kinds of identical objects into 4 distinct groups The question is like this:

In how many ways can 13 chocolate-chip cookies and 8 jelly donuts be
  distributed among four  children that each child gets at least one
  cookies and one donuts?

The model answer of this question is:
${9+4-1 \choose 4-1}{4+4-1 \choose 4-1} = {12 \choose 3}{7 \choose 3} = 7700$
However, I cannot understand why using generating function method does not work:
$((x+x^2+...+x^{13-3})(x+x^2+...+x^{8-3}))^4$
where $13-3$ means every kid can at most get $10$ cookies as each of the others 3 kids need to get at least one.
With this method, I get an answer of $52020$ ways to do this.
So what is wrong with this method? I am really confused. Could anyone explain this to me?
Thanks in advance :D

A: Your generating function is a product of $8$ factors, and the products of terms making $x^{21}$ include things like this:
$$x^1x^2x^3x^4x^5x^4x^1x^1=x^{21}\ .$$
The interpretation of this is that the children receive $1,2,3,4$ cookies and $5,4,1,1$ donuts, which is clearly not a valid solution to the problem.

A: Expanding the comment of the OP on the answer of @David, you can use this generating function
$$f(x,y)=((x+x^2+...+x^{13-3})(y+y^2+...+y^{8-3}))^4$$
and after search the coefficient for $x^{13}y^8$.
Anyway see that you have 2 independent distributions combined into one: the distribution of chocolate and the distribution of donuts.


text:
Q: SELECT MAX DATE when records have identical dates I have  table with many rows that have the same date. I want to query the max (latest) data but if the dates are the same, only return one. It doesn't matter which record but I could use the latest (GID).
I currently have this to to get the latest date:
SELECT ProjectNum,DateSaved,FilePath ,GID
FROM dbo.master_m_table
AS [alldata]
WHERE DateSaved = (
        SELECT MAX(DateSaved)
        FROM dbo.master_m_table
        WHERE FilePath = [alldata].FilePath)

But if there are two identical dates then it will return both.

*

*edited -

to better explain my question here is the data:
ProjectNum  DateSaved   FilePath    GID
12345   01.01.2015             a    1
12345   01.01.2015             a    2
12345   01.01.2015             a    88
12345   01.01.2015             c    104
12345   25.01.2015             c    101
12345   25.01.2015             c    68

...and I want the latest date unless the dates are the same and then I want the max GID.
example result:
ProjectNum  DateSaved   FilePath    GID
12345       01.01.2015         a    88
12345       25.01.2015         c    101

A: Looks like you're looking for this:
SELECT ProjectNum,DateSaved,FilePath,GID
FROM (
  select
    ProjectNum,DateSaved,FilePath,GID,
    row_number() over
        (partition by FilePath order by DateSaved desc, GID desc) as RN
  from dbo.master_m_table
) X
where RN = 1

Row number will create numbers for the rows, for each FilePath separately, and order it first by DateSaved and then GID descending and then outer part will then only pick the rows with number 1. You might also need ProjectNum in partition by part.
Example in SQL Fiddle

A: Just use top and order by:
select top 1 t.*
from dbo.master_m_table t
order by t.datesaved desc;

If you wanted all of them, you can use with ties.
I'm not sure what you mean by "the latest GUID".  You can add more columns to the order by to handle ties.

A: try this
SELECT top 1 ProjectNum,DateSaved,FilePath ,GID
FROM dbo.master_m_table
AS [alldata]
order by DateSaved desc, GID desc

or
SELECT top 1 ProjectNum,DateSaved,FilePath ,GID
FROM dbo.master_m_table
AS [alldata]
WHERE DateSaved = (
        SELECT MAX(DateSaved)
        FROM dbo.master_m_table
        WHERE FilePath = [alldata].FilePath)
order by GID desc


text:
Q: Как вставить данные из 2 связанных таблиц чтобы сохранилось их связь через ID (PK, FK) Есть главная таблица Producers и подчиненная Goods.
***************
***Producers***
***************
producer_id prmary key,
Producer_Name

************
***Goods****
************
Id Primary key,
producer_id Foreign key,
Good_Name

С помощью IBEXPERT вытащил данные из Producer но когда скрипт вставит в новую таблицу их связь потеряется. Если, например, в Producer ест такие данные:
PRODUCER_ID PRODUCER_name
41           AAA
42           BBB
43           CCC

после вставки данных sql-скриптом в таблице PRODUCERS новой бд
INSERT INTO PRODUCER (PRODUCER_ID, PRODUCER_name) VALUES (41, 'AAA');

генератор  присваивает производителю 'AAA' ID вместо 41 новое значение 1, 'BBB'-ID 2, 'CCC'- ID 3 и т.д., а в подчиненной таблице правильно присваивается 41,42,43. т.е. целостность данных нарушается?! (см. скрин).
Как в IBEXPERT вытащить данные из обойх таблиц так чтобы не потерять их связь через Producer_id?
UPDATE:
Когда включил галочку "Extract All" и читает все данные  из обоих таблиц потом всё  правильно вставляет в новых таблицах, ID главной таблицы правильно сохраняется(41-ый ID для "AAA".42-ой для "BBB" и т.д. или как на скрине, 50-ый ID правильно присваивается "222"). Как, не могу понять!
Ведь в первую очередь создаются новые домены и генераторы, потом таблицы, потом вставляет записи, потом создаются внешние ключи и потом создаются триггеры. Пока записи вставляется и потом заработают триггеры?! Как и на каком этапе обеспечивается целостность данных? Если одинокая таблица тогда генератор игнорирует мой ID и инкрементирует последный ID,  а если связанные таблицы тогда...?


text:
Q: Re-use PHP SOAP connection if already created? How do I  in the easiest way re-use the SOAP connection if it has already been created?
The soap connection function could in many cases be run multible times duing one PHP page load so there is not need to re-create the connection if it has been created - it just needs to be re-used.
(And sometimes it is not even run at all because it is not needed so it would be a waste of time calling it in the beginning of all PHP page. The function only needs to be run it there is a need to connect.)
I know that there other solutions for this problem (when I google it) but I did not manage to understand them. I tried a lot of things but they did not work for me. I even tried storing the SOAP object in a session so the next PHP page that was loaded could re-use the soap connection (from the previous PHP load) but it did not work eighter.
The best solution is that the connection is remembered for all PHP pages loads in a browser session and the next best solution is that it remembered for the current PHP page load.
Here is my code:
protected static function Economic_API() {

    static $client;

    $settingsOld = Settings::GetOld();

    try {
        $client = new SoapClient("https://api.e-conomic.com/secure/api1/EconomicWebservice.asmx?WSDL", array("trace" => 1, "exceptions" => 1));
        $client->ConnectWithToken(array(
            'token' => $settingsOld->economic_token_secret,
            'appToken' => $settingsOld->economic_token_app
        ));
    }
    .
    .
    .

UPDATED CODE:
class EcoAPI {

static $client;

static public function getClient() {

    if (empty(self::$client)) {
        self::initClient();
    }

    return self::$client;
}

static private function initClient() {

    $settingsOld = Settings::GetOld();
    self::$client = new SoapClient("https://api.e-conomic.com/secure/api1/EconomicWebservice.asmx?WSDL", array("trace" => 1, "exceptions" => 1));
    self::$client->ConnectWithToken(array('token' => $settingsOld->economic_token_secret, 'appToken' => $settingsOld->economic_token_app));

}
}

And call it by:
$result = EcoAPI::getClient()->Account_FindByNumber(array('number' => intval($accountID)));

A: perhaps you could try using a class instead of a function. The connection will be living in your class instance while the public function getClient() is available for the application to use the soapClient connection.
class Economic_API {

     private $client;
     private $token;
     private $appToken;

     public function __construct($token, $appToken){
         $this->token = $token;
         $this->appToken = $appToken;
     }

     private function initClient() {
         $this->client = new SoapClient("https://api.e-conomic.com/secure/api1/EconomicWebservice.asmx?WSDL", array("trace" => 1, "exceptions" => 1));
         $this->client->ConnectWithToken(array(
             'token' => $settingsOld->economic_token_secret,
             'appToken' => $settingsOld->economic_token_app
         ));
     }

     /**
      * @returns SoapClient
      */
     public function getClient() {
         if($this->client === null) {
             $this->initClient();
         }
         return $this->client;
     }
}
$token = '123';
$appToken = "abc"
$economicApi = new Economic_API($token, $appToken);

$economicApi->getClient()->YourSoapFunction();


text:
Q: Saving multiple Athena queries using a template Here is a template that works correctly and saves a query to Athena. But how do I save more than 1 query in a single template?
{
  "Resources": {
    "AthenaNamedQuery": {
      "Type": "AWS::Athena::NamedQuery",
      "Properties": {
        "Database": "swfnetadata",
        "Description": "A query that selects all aggregated data",
        "Name": "MostExpensiveWorkflow",
        "QueryString": "SELECT workflowname, AVG(activitytaskstarted) AS AverageWorkflow FROM swfmetadata WHERE year='17' AND GROUP BY workflowname ORDER BY AverageWorkflow DESC LIMIT 10"
      }
    }
  }
}

A: Just stick another resource in the template:
{
  "Resources": {
    "AthenaNamedQuery": {
      "Type": "AWS::Athena::NamedQuery",
      "Properties": {
        "Database": "swfnetadata",
        "Description": "A query that selects all aggregated data",
        "Name": "MostExpensiveWorkflow",
        "QueryString": "SELECT workflowname, AVG(activitytaskstarted) AS AverageWorkflow FROM swfmetadata WHERE year='17' AND GROUP BY workflowname ORDER BY AverageWorkflow DESC LIMIT 10"
      }
    },
  "AnotherAthenaNamedQuery": {
      "Type": "AWS::Athena::NamedQuery",
      "Properties": {
        "Database": "swfnetadata",
        "Description": "Another query",
        "Name": "AnotherQuery",
        "QueryString": "SELECT 1"
      }
    }
  }
}


text:
Q: php MySQL processing data on different servers I have a php script that will typically retrieve around 200 records in a single MySQL query (Database A) and, as it processes each record returned by the query,  it needs to look up a value in another database (Database B) - typically 500 records.
Which is the best way to do this ? - either a separate query to Database B for each fetched record in the Database A query loop or to pull all the values from Database B  into an array with a single query and then read the required value from the array in the row fetching loop. Or is there any better way ?  Any guidance here much appreciated.  Thanks.

A: I would read first all records from B into an array.
Next read the records from A and perform a lookup on the array created from B.


text:
Q: Dividing before and after integration give different results I'm having a physics exercise, but the question is more of math.
Assuming I have the following constants: $m_1, m_2, \alpha, V_0$ and two variables: $v, t$. (v as velocity).
I reach the following equation, and I wish to extract $v(t)$ out of it:
$$ (m_1+m_2-\alpha\cdot{t})dv=(\alpha\cdot{V_0})dt$$
Usually the lecturer does the following trick in order to get $v(t)$:
$$dv = \frac{\alpha\cdot{V_0}}{{m_1+m_2-\alpha\cdot{t}}}dt$$
$$\int_{0}^{v}{dv} = \int_{0}^{t}{\frac{\alpha\cdot{V_0}}{{m_1+m_2-\alpha\cdot{t}}}dt}$$
$$v = V_0 \cdot ln(\frac{m_1+m_2}{m_1+m_2-\alpha\cdot{t}})$$
And that's the correct result.
But why when I decide not to divide before integration gives me a total different result?
$$ (m_1+m_2-\alpha\cdot{t})dv=(\alpha\cdot{V_0})dt$$
$$\int_{0}^{v}(m_1+m_2-\alpha\cdot{t})dv = \int_{0}^{t}(\alpha\cdot{V_0})dt$$
$$(m_1+m_2-\alpha\cdot{t}) v = (\alpha\cdot{V_0})t$$
$$v = \frac{\alpha\cdot{V_0}}{m_1+m_2-\alpha\cdot{t}}$$
It's completely different.
How do this difference occur, and how can I know what the rules are?
Thank you.

A: You're solving a differential equation by separating the variables, but that technique is only valid if you actually separate the variables, and get all the $v$s on one side and all the $t$s on another side.
You're not doing that; instead you create the integral
$$ \int_0^v (m_1 + m_2 - \alpha t)\,dv $$
which contains both a $t$ and a $v$.
In the unknown solution to the differential equation you're trying to discover something about (say, a formula for it), $t$ and $v$ depend on each other in some particular way -- they're not independent of each other. But when you evaluate the above integral you're deciding to forget about that and treat $t$ as a constant, independent of $v$. Therefore you have no reason to expect that the outcome of the integral will match the integral to its right,  because you're pretending that the $t$ everywhere on the curve is equal to the final $t$ instead of varying with $v$.


text:
Q: converting cvs repositories to git How to convert a CVS repository to a git repository?

*

*I have tried using git cvsimport command like this:
git cvsimport -v -d :pserver:thillaiselvan@(my_cvs_server_root) -r cvs -k (module_name)

*But the process stalls in the middle for minutes with this message:
cvs [rlog aborted]: could not chdir to file_name_config: Permission denied

*Despite that a directory is created with .git but shows fatal error when trying to check git log:
git log
fatal: bad default revision 'HEAD'

*On checking the status:
git status
On branch master
Initial commit
nothing to commit (create/copy files and use "git add" to track)

A: I use git --bare cvsimport -d:local:/cvsroot/$PROJECT -v -k -m -i -A Authors -o master $PROJECT to import cvs project from the local repository (or mirror) into a local bare git repository that is suitable for being exposed to remote developers. This can do incremental updates if you are still using CVS as the primary repository.
However you should also look at cvs2git as this can be better sometimes but is more appropriate for a one-off conversion to git. cvsimport can have trouble with vendor branches so it is important to very carefully check your newly imported repository. In both cases it can take a long time for large repositories (possibly hours on a slower machine with a 10year old cvs repository).


text:
Q: Does removeChildAt() clear up cpu resources? I am loading/unloading several swfs from one main swf. When I load a new swf I do something like this:
contentContainer.addChild(the new swf); //add the new swf
contentContainer.swapChildrenAt(0,1);
contentContainer.removeChildAt(1); //remove the previous swf

My question is, when I removeChildAt(), does the old swf keep "playing" and keep taking up cpu resources? How can I kill it completely? If there is audio or video in the old swf, it seems to keep playing even after it is removed.

A: try with Loader.unloadAndStop()

A: You might want to try something like:
var mc:MovieClip = contentContainer.removeChildAt(1) as MovieClip;
mc.stop();

or make some public stop() methods on the movies embedded in the unloaded swf. (ref)
You'll probably need some variation on this.
Also, if you are able, you could also have the child swfs listen for the Event.ADDED_TO_STAGE, Event.REMOVED_FROM_STAGE events. It might make more sense to have them control themselves in this sense rather than relying on the parent container to stop them.


text:
Q: Apply function along axis over two numpy arrays - shapes not aligned I'm probably not seeing something obvious here but don't believe np.apply_along_axis or np.apply_over_axes is what I'm looking for.  Say I have the following two arrays:
arr1 = np.random.randn(10, 5)
arr2 = np.random.randn(10, )

And the following function:
def coefs(x, y):
    return np.dot(np.linalg.inv(np.dot(x.T, x)), np.dot(x.T, y))
    # the vector of coefficients in a multiple linear regression

Calling this on arr1 and arr2 works smoothly as it should:
coefs(arr1, arr2)
Out[111]: array([-0.19474836, -0.50797551,  0.82903805,  0.06332607, -0.26985597])

However, suppose instead of the 1- or 2d arrays I have two 3d arrays:
arr3 = np.array([arr1[:-1], arr1[1:]])
arr4 = np.array([arr2[:-1], arr2[1:]])

As expected, if I apply the function here I get
coefs(arr3, arr4)
Traceback (most recent call last):

  File "<ipython-input-127-4a3e7df02cda>", line 1, in <module>
    coefs(arr3, arr4)

  File "<ipython-input-124-7532b8516784>", line 2, in coefs
    return np.dot(np.linalg.inv(np.dot(x.T, x)), np.dot(x.T, y))

ValueError: shapes (5,9,2) and (2,9,5) not aligned: 2 (dim 2) != 9 (dim 1)

...because NumPy is treating each array as an object as it should.  What I want to do instead is apply the coefs() function to each of the 2 elements along the 0 axis of the arrays, element-wise.  Here's a crude way of doing this:
tgt = []
for i, j in zip(arr3, arr4):
    tgt.append(coefs(i, j))

np.array(tgt)
Out[136]:
array([[-0.34328006, -0.99116672,  1.42757897, -0.06687851, -0.44669182],
       [ 0.44494495, -0.58017705,  0.75825944,  0.18795889,  0.4560851 ]])

My question is, is there a more efficient and pythonic way of doing this than using zip and iterating over, as above?  Basically, given two input arrays of shape (2, n, k) and (2, n), I want the array that is returned to be of shape (2, k).  Thanks.

A: For generic shaped 3D and 2D arrays - arr3 and arr4, we can use some np.einsum magic to have a vectorized solution, like so -
dot1 = np.einsum('ijk,ijl->ikl',arr3,arr3)
dot2 = np.einsum('ijk,ij->ik',arr3,arr4)
inv1 = np.linalg.inv(dot1)
tgt_out = np.einsum('ijk,ij->ik',inv1, dot2)

Runtime test
Approaches -
def org_app(arr3, arr4):
    tgt = []
    for i, j in zip(arr3, arr4):
        tgt.append(coefs(i, j))
    return np.array(tgt)

def einsum_app(arr3, arr4):
    dot1 = np.einsum('ijk,ijl->ikl',arr3,arr3)
    dot2 = np.einsum('ijk,ij->ik',arr3,arr4)
    inv1 = np.linalg.inv(dot1)
    return np.einsum('ijk,ij->ik',inv1, dot2)

Timings and verification -
In [215]: arr3 = np.random.rand(50,50,50)
     ...: arr4 = np.random.rand(50,50)
     ...:

In [216]: np.allclose(org_app(arr3, arr4), einsum_app(arr3, arr4))
Out[216]: True

In [217]: %timeit org_app(arr3, arr4)
100 loops, best of 3: 4.82 ms per loop

In [218]: %timeit einsum_app(arr3, arr4)
100 loops, best of 3: 19.7 ms per loop

Doesn't look like einsum is giving us any benefits here. This is expected because basically einsum is fighting it out against np.dot, which is much better at sum-reduction and even though we are using it in a loop. The only situation/case in which we can give np.dot a fight is when we loop enough and that should make einsum competitive. We are looping for times equal to the length equal of the first axis of the input arrays. Let's increase it and test again -
In [219]: arr3 = np.random.rand(1000,10,10)
     ...: arr4 = np.random.rand(1000,10)
     ...:

In [220]: %timeit org_app(arr3, arr4)
10 loops, best of 3: 23 ms per loop

In [221]: %timeit einsum_app(arr3, arr4)
100 loops, best of 3: 9.1 ms per loop

einsum definitely winning on this one!
This related post on the fight between np.einsum and np.dot is worth a look.
Also, note that if we need to use the loop based approach, we should look to initialize the output array and then assign the output values from coefs into it rather than appending, as the latter is a slow process.


text:
Q: primefaces `I keep getting this error addAddress:states: Validation Error: Value is not valid when using <p:selectOneMenu. I tried using the id and got rid of the converter, its doing the same. I tried debugging. Found that the converted is running twice and the last time it is checking blank value and returning null/false. What am I doing wrong? If need any more details let me know?
Code is as follows
Converter
    @FacesConverter(value = "statemasterconverter", forClass = Statemaster.class)
public class StateConverter implements Converter {
    public String getAsString(FacesContext context, UIComponent component,
            Object value) {
        return ConversionHelper.getAsString(value);
    }

    public Object getAsObject(FacesContext context, UIComponent component,
            String value) {
        return ConversionHelper.getAsObject(Statemaster.class, value);
    }
}

Conversion Helper
public final class ConversionHelper {

    private ConversionHelper() {
    }

    @SuppressWarnings("unchecked")
    public static <T> T getAsObject(Class<T> returnType, String value) {
        BigDecimal id = BigDecimal.ZERO;
        if (returnType == null) {
            throw new NullPointerException(
                    "Trying to getAsObject with a null return type.");
        }
        if (value == null) {
            throw new NullPointerException(
                    "Trying to getAsObject with a null value.");
        }

        try {
            id = BigDecimal.valueOf(Long.parseLong(value));
        } catch (NumberFormatException nfe) {
            return null;
        }

        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            T r = (T) session.load(returnType, id);
            if (r != null)
                Hibernate.initialize(r);
            return r;
        } catch (HibernateException e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
        return null;
    }

    public static String getAsString(Object value) {
        if (value instanceof Gendermaster) {
            Gendermaster result = (Gendermaster) value;
            return String.valueOf(result.getGenderid());
        } else if (value instanceof Salutationmaster) {
            Salutationmaster result = (Salutationmaster) value;
            return String.valueOf(result.getSalutationid());
        } else if (value instanceof Countrymaster) {
            Countrymaster result = (Countrymaster) value;
            return String.valueOf(result.getCountryid());
        } else if (value instanceof Statemaster) {
            Statemaster result = (Statemaster) value;
            return String.valueOf(result.getStateid());
        }
        return null;
    }
}

the xhtml code
                    <p:row>
                        <p:column>
                        Country
                    </p:column>
                        <p:column>
                            <p:selectOneMenu id="country"
                                value="#{customerBean.country.countryid}" required="true">
                                <f:selectItem itemLabel="Select Country" itemValue="" />
                                <f:selectItems value="#{customerBean.countrydropdown}"
                                    var="countrymaster"
                                    itemLabel="#{countrymaster.countryname} - #{countrymaster.countrycodeNn}"
                                    itemValue="#{countrymaster.countryid}" />
                                <p:ajax update="states"
                                    listener="#{customerBean.updateStates()}" />
                            </p:selectOneMenu>
                        </p:column>
                    </p:row>
                    <p:row>
                        <p:column>
                        State
                    </p:column>
                        <p:column>
                            <p:selectOneMenu id="states" required="true"
                                value="#{customerBean.state}" converter="statemasterconverter">
                                <f:selectItem itemValue="" itemLabel="Select State" />
                                <f:selectItems value="#{customerBean.statedropdown}"
                                    var="statemaster"
                                    itemLabel="#{statemaster.statename} - #{statemaster.statecode}"
                                    itemValue="#{statemaster}" />
                            </p:selectOneMenu>
                        </p:column>
                    </p:row>

                        <p:commandButton id="saveBtn" value="Save Salutation"
                            update="msgs"
                                style="float: left;" icon="ui-icon-disk"
                                actionListener="#{customerBean.saveAddress()}" ajax="true" />
                        </p:column>

A: Use event="valueChange" in Ajax. and try to updated whole form by update="@form".
if above code is not work then try update=":id:id" update tag search id within the tag.
let consider this code.
<h:form id="myForm">
    <h:sometag id="ineer1">
        <p:ajax update="ineer3"/>// it is **not work**
        <p:ajax update=":myForm:ineer2:ineer2"/>// it is **work**
    </h:sometag>
    <h:sometag id="ineer2">
        <h:someoutfield id="ineer3"/>
     </h:sometag>
<h:/form>

it is working at my end if not work then let me know.
Happy to help :)


text:
Q: Wordpress custom wp-cron class doesn't firing the scheduled handler So, we use the Bedrock to help to code our products and I need to build a generic class to handle custom cronjobs.
This is the base cronjob class:
<?php
namespace namespace\to\the\class;

abstract class CronHelper extends AbstractHelper {

    /** Declare all attributes and other methods */

    /**
     * Setup the custom cronjob
     */
    protected function init() {
        $this->setAlias(DEFAULT_CRON_ALIAS);
        $this->setInterval(DEFAULT_CRON_INTERVAL);
        $this->setDisplay(DEFAULT_CRON_DISPLAY);
    }

    /**
     * Start the cronjob
     */
    public function start() {
        add_filter('cron_schedules', array($this,'customInterval'));
        add_action($this->getAlias(), array($this,'runner'));

        if (! wp_next_scheduled($this->getAlias())) {
            wp_schedule_event(time(), "{$this->getAlias()}_interval", $this->getAlias());
        }
    }

    /**
     * The custom interval builder
     *
     * @return array The custom interval setup
     */
    public function customInterval() {
        $scheduler["{$this->getAlias()}_interval"] = array('interval' => $this->getInterval(),'display' => $this->getDisplay());
        return $scheduler;
    }

    /**
     * The scheduler implementation function
     */
    protected abstract function runner();
}

What you guys should know:

*

*AbstractHelper is a Singleton class

*I suppressed the getters/setters

*The method start() is fired on every page load of our site

This is one implementation of the CronHelper class:
<?php
namespace namespace\to\the\class;

class TestCron extends CronHelper {

    protected function runner() {
        // Try to print something on the nginx's error logs
        error_log('Running inside the class TestCron');
        // Create a random file just for testing
        $file = fopen('./cronjob.txt', 'w');
        fwrite($file, sprintf('Hello World [%d]', time()));
        fclose($file);
    }
}

And this is how I'm instantiating everything, remember this piece of code is executed every time:
<?php
/** A lot of code above ... */

// Start the Test Cronjob
TestCron::getInstance()->setAlias('test_cron')
    ->setDisplay('Test Cronjob')
    ->setInterval(5) // Fire every 5 seconds
    ->start();

/** A lot of code below ... */

And every time I load the page and navigate through the site nothing happens. I was wondering what am I doing wrong?!
Thanks for helping!

A: I finally discover what was going on with my code. And I just let it here for future similar doubts.
The solution is: instead of using a protected method, use a public method for your runner() wannabe function.


text:
Q: How to send Ctrl+Alt+F1 (and other special keystrokes) to X window? When I press Ctrl+Alt+F{1..12}, it switches me to other virtual terminal.
Even xte "keydown Control_L" "keydown Alt_L" "key F1" "keyup Alt_L" "keyup Control_L" leads to switching to vt instead of sending that keys to focused window.
Use cases of this includes (but not limits to) sending special keystrokes to VNC or virtualization clients to be handled by clinet/guest system instead of the host one. Sometimes (like in VirtualBox) applications explicitly map some special alternative keystroke to that special ones (like Ctrl+Alt+Del or Ctrl+Alt+Backspace in VirtualBox), but I want clean and universal solution.

A: Let's call Ctrl+Alt+Fx (where Fx is one of function buttons: F1, F2, F3...) srvr keys.
There is a way to disable/enable srvr keys on the fly. By disabling I mean that X11 do not swallow them, but passes to window manager (kwin in kde).
For diabling srvr keys, you run setxkbmap -option srvrkeys:none
For enabling srvr keys, you run setxkbmap -option
To check if srvr_ctrl(no_srvr_keys) flag is enabled, run setxkbmap -print | grep xkb_symbols
In kde there is possibility to perform window actions (for example, execute some command when window gets or looses focus). So you can automatically disable srvr keys when your special application window is focused, and automatically enable them back when it looses focus. It is universal solution. Useful for such applications as TeamViewer, VirtualBox, Chrome Remote Desktop, ipkvm viewer, krdc and so on.
If you interested, here is my script that I use for this thing: https://github.com/Ashark/aten-ip8000/blob/master/srvrkeys

A: For VirtualBox, try the key combination REL + F1. Here, REL is the key used to release the mouse grab in the VirtualBox window, usually right Ctrl or Alt key.

A: It is not possible to send Ctrl+Alt+F[1..12] because the virtual terminals are seperate from the desktop that the VNC is connected to.


text:
Q: How to set certain number of listener on one server and no listener on other server for same queue in spring amqp as we can not set 0 concurrency? I have setup listeners on reply queues, I want those to be only on master (from where messages are queued) and other servers should have no listeners to reply queue. They should have listeners to all other queues.
Spring AMQP doesn't allow to set listener concurrency to be set to 0. So I cant set 0 listners to reply queue on slave servers.
How do I set 0 concurrency on slave servers for reply queues ?

A: I could do it using spring profiles. I just added "master" profile to all listener beans and activated master profile only on master server.
Few nice articles to begin with using profiles
http://diarmuidmoloney.wordpress.com/2012/04/07/spring-environments/
http://maciejwalkowiak.pl/blog/2012/03/27/spring-3-1-profiles-and-tomcat-configuration/

A: Use auto-startup="false" and only start() the container that you want to listen.