text:
Q: How to create qtcreator installer from its source code? I have created Qt creator plugin and used Qt creator source code from git repo. But i could not find how to make installer package for windows at least. If you go to https://www.qt.io/download-open-source/#section-2 , you can see that Qt creator installer are created so that we can install only Qt creator. Qt is using Qt installer framework for creating installers. Where is the script for building Qt creator installer ?

A: Requirement: You need 7zip installed (7z), python (2.7) and IFW.
Answer is based on Windows. you may need slightly different case with linux
My working structure is:
/home
 /Qt5.5.1
 /qt-creator3.6  (Qt creator  source)
 /qtcreator3.6  (Qt creator build)
 /So-ADE
  /So-ADEDebugger   (My plugin)

The script is in /home
This is my script for doing the same thing: Please adapt with your own plug-in directory (Mine is So-ADEDebugger) and file structure.
Use /tmp as a build directory
mkdir c:\tmp
rmdir /s /q c:\tmp\out

Move to my plugin directory, build it
cd So-ADEDebugger
..\..\Qt5.5.1\5.5\mingw492_32\bin\qmake.exe

Add gcc to windows path (in case)
set PATH=%CD%\..\..\Qt5.5.1\Tools\mingw492_32\bin\;C:\Program Files\7-Zip\;%PATH%
..\..\Qt5.5.1\Tools\mingw492_32\bin\mingw32-make.exe

move to qtcreator build directory (shadow build) and install to target directory (/tmp)
cd ..
cd ..\qtcreator3.6
set INSTALL_ROOT=c:\tmp\out
..\Qt5.5.1\Tools\mingw492_32\bin\mingw32-make.exe -j 4 install

Copy Qt windows dll in place
cd ..\So-ADE
xcopy /i/s ..\Qt5.5.1\5.5\mingw492_32\bin\*.dll c:\tmp\out\bin
mkdir c:\tmp\out\bin\plugins
xcopy /i/s ..\Qt5.5.1\5.5\mingw492_32\plugins\designer c:\tmp\out\bin\plugins\designer
xcopy /i/s ..\Qt5.5.1\5.5\mingw492_32\plugins\iconengines c:\tmp\out\bin\plugins\iconengines
xcopy /i/s ..\Qt5.5.1\5.5\mingw492_32\plugins\imageformats c:\tmp\out\bin\plugins\imageformats
xcopy /i/s ..\Qt5.5.1\5.5\mingw492_32\plugins\platforms c:\tmp\out\bin\plugins\platforms
xcopy /i/s ..\Qt5.5.1\5.5\mingw492_32\plugins\printsupport c:\tmp\out\bin\plugins\printsupport
xcopy /i/s ..\Qt5.5.1\5.5\mingw492_32\plugins\sqldrivers c:\tmp\out\bin\plugins\sqldrivers
mkdir c:\tmp\out\lib\vcredist_msvc2013
xcopy /i/s ..\Qt5.5.1\vcredist\vcredist_msvc2013_x86.exe c:\tmp\out\lib\vcredist_msvc2013\
move c:\tmp\out\lib\vcredist_msvc2013\vcredist_msvc2013_x86.exe c:\tmp\out\lib\vcredist_msvc2013\vcredist_x86.exe

and reject the debug one
del /s c:\tmp\out\bin\*d.dll

Now install the plugin in target
cd So-ADEDebugger
..\..\Qt5.5.1\Tools\mingw492_32\bin\mingw32-make.exe -j 4 install

In my plugin i have a copy of qt-creator/dist/installer directory with my custom setup for the installer (optional pass). i copy it back to qt to build the installer with my setup
xcopy /i /s /y installer ..\..\qt-creator3.6\dist\installer
xcopy /i /s /y qt.conf c:\tmp\out\bin
cd ..

in case....
strip c:\tmp\out\bin\* c:\tmp\out\lib\qtcreator\plugins\*

Build the tar for the installer (bindist_installer target of make)
cd ..\qt-creator3.6
set IFW_PATH=C:\Qt\QtIFW2.0.1
..\Qt5.5.1\Tools\mingw492_32\bin\mingw32-make.exe bindist_installer

and finally package it. Changes this with your setup
c:\Python27\python -u .\scripts\packageIfw.py -i "C:\Qt\QtIFW2.0.1" -v 2.0.0 -a "qt-creator-windows-3.6.1-installer-archive.7z" ..\So-ADE\So-ADEdebugger.2.0.0.win


text:
Q: How to decide on dimension fields type When I build my cube, what are the considerations for choosing dimension fields types, for instance customer number should I define it as string or numeric?
Thanks,
Michael

A: If a customer number is a number it should be numerical, there are various types and the best place to start is. http://www.w3schools.com/sql/sql_datatypes_general.asp Then come back with a specific query or test and built a base and show the code/build.

A: I generally put everything in string format.  Date Particularly.  Today your Customer number is a number.  But tomorrow if someone changes source systems and business decisions it could become a string.  So I generally try to setup the Data Warehouse structure to be as accommodating to business changes as possible with the least amount of data warehouse change needed.
I would then look for a data validation process to insure that the Customer Number is a number then if the business changes I can simply switch off that data validation process without changing my database structure or BI that depends on data types.
But I would also say there is no "right" answers here.  It is an engineering decision with advantages and disadvantages what ever direction you go.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Replace function in a price string moves comma to the left at the moment I write a web scraper for Notebooks etc. and want to save the result in a csv File.
My problem now is, when I use price.replace(",", ".") my separator got shifted 1 position left.
e.g.:
price = "379,00€"
price.replace(",", ".")
print(price)

-> "37.900€" in my csv File.
This is the line, where I write it in my CSV File.
f.write(product_brand + "," + product_name + "," + product_price.replace(",", ".") + "\n")

I don't know why this is happening.. I Hope you guys can help me :)

A: You may want to do a currency clean-up before writing the data to a .csv file.
Also, it's advisable to use a csv module to handle the file writing.
Try this:
import csv

data = {
    "price": "379,00€",
    "product_brand": "brand",
    "product_name": "name",
}

def clean_up_currency(d: dict):
    d["price"] = float(data["price"].replace("€", "").replace(",", "."))
    return d

with open('test.csv', 'w') as f:
    w = csv.DictWriter(f, data.keys())
    w.writeheader()
    w.writerow(clean_up_currency(data))

The code outputs:
price,product_brand,product_name
379.0,brand,name


text:
Q: CDI web application not deployed properly on WildFly I'm working with a web application using ejb, cdi, maven, netbeans and wildfly 8.1 server.
Sometimes when I do clean/build, manually remove the content of the server path wildfly-8.1.0.Final/standalone/deployments and then try to run the ear file all works ok but when I load a web page I have the next error:
summary error:
com.mycompany.controller.CarController$Proxy$_$$_WeldClientProxy.getCarType(Unknown Source)

complete error:
16:26:17,215 FATAL [javax.enterprise.resource.webcontainer.jsf.context] (default task-1) /pages/myPage.xhtml @30,87 value="#{myController.carType}": java.lang.IllegalArgumentException: Can not set com.mycompany.ejb.facade.CarsFacadeLocal field com.mycompany.jsf.controller.MyController.carFacade to com.mycompany.ejb.facade.CarFacadeLocal$1909108192$Proxy$_$$_Weld$EnterpriseProxy$: javax.faces.FacesException: /pages/myPage.xhtml @37,87 value="#{myController.carType}": java.lang.IllegalArgumentException: Can not set com.mycompany.ejb.facade.CarFacadeLocal field com.mycompany.jsf.controller.MyController.carFacade to com.mycompany.ejb.facade.CarFacadeLocal$1909108192$Proxy$_$$_Weld$EnterpriseProxy$
    at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:84) [jsf-impl-2.2.6-jbossorg-4.jar:]
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.2.6-jbossorg-4.jar:]
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198) [jsf-impl-2.2.6-jbossorg-4.jar:]
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:130) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449) [shiro-web-1.2.1.jar:1.2.1]
    at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365) [shiro-web-1.2.1.jar:1.2.1]
    at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90) [shiro-core-1.2.1.jar:1.2.1]
    at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83) [shiro-core-1.2.1.jar:1.2.1]
    at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383) [shiro-core-1.2.1.jar:1.2.1]
    at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362) [shiro-web-1.2.1.jar:1.2.1]
    at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125) [shiro-web-1.2.1.jar:1.2.1]
    at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:85) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:61) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:113) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:56) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:45) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:61) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:70) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:240) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:227) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:73) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:146) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:177) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:727) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_72]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_72]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_72]
Caused by: javax.el.ELException: /pages/myPage.xhtml @62,87 value="#{carController.carType}": java.lang.IllegalArgumentException: Can not set com.mycompany.ejb.facade.CarFacadeLocal field com.mycompany.controller.CarController.carFacade to com.mycompany.ejb.facade.CarFacadeLocal$1909108192$Proxy$_$$_Weld$EnterpriseProxy$
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:114) [jsf-impl-2.2.6-jbossorg-4.jar:]
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
    at javax.faces.component.UIOutput.getValue(UIOutput.java:174) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
    at javax.faces.component.UIInput.getValue(UIInput.java:291) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
    at javax.faces.component.UIInput.validate(UIInput.java:988) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
    at javax.faces.component.UIInput.executeValidate(UIInput.java:1249) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
    at javax.faces.component.UIInput.processValidators(UIInput.java:712) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
    at javax.faces.component.UIViewParameter.processValidators(UIViewParameter.java:278) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1258) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1258) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
    at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195) [jboss-jsf-api_2.2_spec-2.2.6.jar:2.2.6]
    at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76) [jsf-impl-2.2.6-jbossorg-4.jar:]
    ... 40 more
Caused by: javax.el.ELException: java.lang.IllegalArgumentException: Can not set com.mycompany.ejb.facade.CarFacadeLocal field com.mycompany.jsf.controller.CarController.carFacade to com.mycompany.ejb.facade.CarFacadeLocal$1909108192$Proxy$_$$_Weld$EnterpriseProxy$
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:368) [jboss-el-api_3.0_spec-1.0.3.Final.jar:1.0.3.Final]
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176) [jsf-impl-2.2.6-jbossorg-4.jar:]
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203) [jsf-impl-2.2.6-jbossorg-4.jar:]
    at com.sun.el.parser.AstValue.getValue(AstValue.java:140) [javax.el-3.0.0.jar:]
    at com.sun.el.parser.AstValue.getValue(AstValue.java:204) [javax.el-3.0.0.jar:]
    at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226) [javax.el-3.0.0.jar:]
    at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109) [jsf-impl-2.2.6-jbossorg-4.jar:]
    ... 52 more
Caused by: java.lang.IllegalArgumentException: Can not set com.mycompany.ejb.facade.CarFacadeLocal field com.mycompany.jsf.controller.CarController.carFacade to com.mycompany.ejb.facade.CarFacadeLocal$1909108192$Proxy$_$$_Weld$EnterpriseProxy$
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164) [rt.jar:1.7.0_72]
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:168) [rt.jar:1.7.0_72]
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81) [rt.jar:1.7.0_72]
    at java.lang.reflect.Field.set(Field.java:741) [rt.jar:1.7.0_72]
    at org.jboss.weld.injection.FieldInjectionPoint.inject(FieldInjectionPoint.java:94) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.util.Beans.injectBoundFields(Beans.java:358) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.util.Beans.injectFieldsAndInitializers(Beans.java:369) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.injection.producer.DefaultInjector.inject(DefaultInjector.java:72) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.injection.producer.ResourceInjector.inject(ResourceInjector.java:60) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.injection.producer.DefaultInjector$1.proceed(DefaultInjector.java:66) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:48) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.injection.producer.DefaultInjector.inject(DefaultInjector.java:64) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.injection.producer.BasicInjectionTarget.inject(BasicInjectionTarget.java:90) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:150) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.context.AbstractContext.get(AbstractContext.java:96) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:98) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:78) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
    at com.mycompany.controller.CarController$Proxy$_$$_WeldClientProxy.getCarType(Unknown Source) [classes:]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_72]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_72]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_72]
    at java.lang.reflect.Method.invoke(Method.java:606) [rt.jar:1.7.0_72]
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:363) [jboss-el-api_3.0_spec-1.0.3.Final.jar:1.0.3.Final]
    ... 60 more

That's awful! I can't work...
What's going on?

A: Simply you need to run over the web project and works.
right click over web project-> run


text:
Q: Record video with MediaCodec and MediaMuxer, but the bitrate and framerate are incorrect I wrote a demo to record a video using MediaCodec and MediaMuxer.
I record a video with my demo and use ffprobe to check the video,
the result is as follows:
  Duration: 00:00:06.86, start: 0.000000, bitrate: 723 kb/s
Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 320x240, 619 kb/s, SAR 1:1 DAR 4:3, 30.02 fps, 30 tbr, 90k tbn, 180k tbc (default)
Metadata:
  creation_time   : 2015-06-05 13:19:24
  handler_name    : VideoHandle
Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 96 kb/s (default)
Metadata:
  creation_time   : 2015-06-05 13:19:24
  handler_name    : SoundHandle

It contains video and audio information, I found the audio properties are the same as I set in the source code, but the video properties are not all right.
My video settings source code is as follows:
        MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mWidth, mHeight);
    format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
            MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
    format.setInteger(MediaFormat.KEY_BIT_RATE, 384000);
    format.setInteger(MediaFormat.KEY_FRAME_RATE, 19);
    format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5);
    if (VERBOSE) Log.d(TAG, "format: " + format);
    mVideoEncoder = MediaCodec.createEncoderByType(MIME_TYPE);
    mVideoEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
    mInputSurface = mVideoEncoder.createInputSurface();
    mVideoEncoder.start();

The width and height of the video are right but bitrate and framerate are higher than I set in source code. It results in that the video file size is much larger than
I expected.
Then, I modified my source code to remove audio recording thread and just record the video only. But it didn't make any differences, the bitrate and framerate are also higher.
Who can tell me the reason and give me some advices?
And there is another problem. I record a broken video occasionally which can be played by system player, but the begining of the video is just black and normal image displayed after 1 or 2 seconds. I don't know how to upload file in stackoverflow, I can send the broken video file to anyone who need it.
Is there someone came with this problem?
ADD:
I found another strange thing:
My video encoding config:
private int mWidth = 480;
private int mHeight = 848;
private int mVideoBitrate = 1200 * 1000;

    MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, 480, 848);

    format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
            MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
    format.setInteger(MediaFormat.KEY_BIT_RATE, 1200000);
    format.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
    format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);

but the actual video info is:
  Duration: 00:00:06.01, start: 0.000000, bitrate: 6491 kb/s
Stream #0:0(eng): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 15 kb/s (default)
Metadata:
  creation_time   : 2015-09-30 15:44:18
  handler_name    : SoundHandle
Stream #0:1(eng): Video: h264 (Baseline) (avc1 / 0x31637661), yuv420p, 480x848, 6484 kb/s, SAR 1:1 DAR 30:53, 16 fps, 30 tbr, 90k tbn, 180k tbc (default)
Metadata:
  creation_time   : 2015-09-30 15:44:18
  handler_name    : VideoHandle

A: It looks like your expected frame rate (19fps) doesn't match the actual frame rate (30fps).  The encoder is attempting to meet the bit rate requirements for frames submitted at 19fps, but they're coming in faster, so it misses and the actual bit rate is higher.  I'm assuming the 30fps value is determined from the actual presentation time stamps in the video file, which are set by the presentation time stamps passed into MediaMuxer.  If you want 19fps video, you need to generate time stamps that are (1000/19) milliseconds apart.
If your input video is 30fps, you will need to drop frames during the encoding process to get to 19fps.  MediaCodec does not drop frames for you -- it encodes everything you pass in.
I don't know why you'd be getting a broken section at the start of the video.


text:
Q: Error1053 trying to start postgres as service on windows I installed postgres on windows7 and tried to start the service through control panel. It produces error 1053.
When I try to run postgres.exe from command line, I get this message:
C:\Program Files (x86)\PostgreSQL\9.0\bin>postgres.exe
2011-07-24 14:02:29 IST LOG:  could not create file "postmaster.opts": Permission denied

The default data directory is
C:\Program Files (x86)\PostgreSQL\9.0\data

I have set the PGDATA env variable to the above directory.
Also, I have edited the pg_hba.conf file in that directory to add a new line as below:
local   all postgres    ident  sameuser

I tried to start the service with postgresql server allowed (both private and public networks ticked) in Windows Firewall, and when that didn't solve the problem, turned off the firewall for both public and private networks..
Still the service cannot be started. I tried disabling the AVG resident shield. None of these worked.
Any idea what to do?

update:
I tried this:
C:\Program Files (x86)\PostgreSQL\9.0\bin>pg_ctl restart
pg_ctl: PID file "C:/Program Files (x86)/PostgreSQL/9.0/data/postmaster.pid" does not exist
Is server running?
starting server anyway
server starting

C:\Program Files (x86)\PostgreSQL\9.0\bin>2011-07-24 16:12:57 IST LOG:  could not create file "postmaster.opts":

Still no luck.
As for the logs, I found 2 txt files in folder data/pg_log. They contain logs of events immediately after installation, not my later attempts at starting postgres. I have put it here.
In windows event viewer, I get a series of error event entries like http://pastebin.com/K6jUPPAy. All of them contain messages similar to:
2011-07-24 12:46:44 IST FATAL:  could not access status of transaction
0 2011-07-24 12:46:44 IST DETAIL:  Could not open file
"pg_notify/0000": Permission denied.

If there are any other logs, please tell me where I can find them.

A: This is just a guess, but maybe PostgreSQL directory is set to be read-only. Read this post for more.

A: I just had the same error and in my case it was because I allocated too much memory (sort_mem and shared_buffers) to posgresql and somehow that prevented from starting. I just had to go back and replace posgresql.conf with the factory-default file.
Good luck


text:
Q: solution regarding slow process from AsyncTask while loading lots images from sdcard Good day all, i have a load of images i want to display from an sdcard to a gridview. I have followed the tutorial to do this in the is link:
http://mihaifonoage.blogspot.com/2009/11/displaying-images-from-sd-card-in.html
everything works great apart the fact that when the images become a lot, it becomes really slow to populate it and scrolling is also very slow. i have tried editing the code to use the ViewHolder method but still no luck.
now, i also have used populated the images in a custom ListView without using the AsyncTask and it appears to process it faster. yeah common sense would be to just use the faster method but want to clarify somethings first. so i am asking:

*

*is it that AsyncTask can be really slow in some cases and not ideal or thus the fact that am using a Gridview or Listview have something to do with it? any reason why?  am asking this cause AsyncTask always seem to get very good favourism.

*Any Other way, solutions or tips that i can make this process faster?..
Note: i would have posted my code, but its the same things as the link only that i don't use the getThumbnails() in the MediaStore query.  Thanks in advance.
here is part what i get for the logcat output when its loading the images:
10-07 19:42:54.072: DEBUG/dalvikvm(20291): GC_EXPLICIT freed <1K, 48% free 2886K/5511K, external 1574K/14018K, paused 28ms

10-07 19:42:54.092: DEBUG/dalvikvm(20291): GC_EXPLICIT freed <1K, 48% free 2918K/5511K, external 1574K/14018K, paused 25ms

10-07 19:42:54.122: DEBUG/dalvikvm(20291): GC_EXPLICIT freed <1K, 48% free 2918K/5511K, external 1574K/14018K, paused 25ms

10-07 19:42:54.142: DEBUG/dalvikvm(20291): GC_EXPLICIT freed <1K, 48% free 2918K/5511K, external 1574K/14018K, paused 24ms

10-07 19:42:54.172: DEBUG/dalvikvm(20291): GC_EXPLICIT freed <1K, 48% free 2918K/5511K, external 1574K/14018K, paused 25ms

10-07 19:42:54.202: DEBUG/dalvikvm(20291): GC_EXPLICIT freed <1K, 48% free 2918K/5511K, external 1574K/14018K, paused 25ms

10-07 19:42:54.232: DEBUG/dalvikvm(20291): GC_EXPLICIT freed <1K, 48% free 2918K/5511K, external 14018K/14018K, paused 28ms

10-07 19:42:54.252: DEBUG/dalvikvm(20291): GC_EXPLICIT freed <1K, 48% free 2918K/5511K, external 14018K/14018K, paused 24ms

10-07 19:42:54.282: DEBUG/dalvikvm(20291): GC_EXPLICIT freed <1K, 48% free 2918K/5511K, external 14018K/14018K, paused 24ms

10-07 19:42:54.302: DEBUG/dalvikvm(20291): GC_EXPLICIT freed <1K, 48% free 2918K/5511K, external 14018K/14018K, paused 25ms

10-07 19:42:54.332: DEBUG/dalvikvm(20291): GC_EXPLICIT freed <1K, 48% free 2918K/5511K, external 14018K/14018K, paused 25ms

10-07 19:42:54.362: DEBUG/dalvikvm(20291): GC_EXPLICIT freed <1K, 48% free 2918K/5511K, external 14018K/14018K, paused 25ms

A: It is slow because in fact you are still using one single thread (i.e. one AsyncTask.execute() call) download all images in sequence (i.e. loop all image download in your doInBackground() implementation). Yes, this is the way that google suggested how to use AsyncTask.
By calling several AsyncTask.execute() will probably speed you up, this gives you several thread running simultaneously and managed by underlying thread pool (before API level 11, this thread pool is non accessible). of cause, you need somehow split your download task into several piece and feed each piece into each AsyncTask.execute():
for (DownloadTask task : tasks) {
  new AsyncTask.execute();
}

Check out here for more information.

A: The right way to speed this up would be to use a image cache. Google has a guide for an easy implementation right here:


text:
Q: Hive timestamp ISO to UTC conversion I have strings with ISO 8601 timestamps like 2016-03-07T10:02:37.820+01:00 and I would like to convert them to UTC time. The built-in to_utc_timestamp (AFAIK) only takes time zone names (e.g. PST, CET) and not the offsets. At least I tried and failed. Is there an elegant way to achieve this in Hive?

A: One way is, you can write a Hive UDF for time format conversion.
Another way is, convert ISO timestamps to seconds using unix_timestamp and then use to_utc_timestamp
 TO_UTC_TIMESTAMP(UNIX_TIMESTAMP(T.date, "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'") * 1000, '<timezone>')


text:
Q: Does AWS offer Websites or only Virtual Servers? Azure has the concept of websites which offer the user no OS maintenance. I only seem to see Virtual Machines available on AWS? What am I missing?
I am interested in deploying nodejs express apps, but don't want to manage vm's. In azure the equivalent in an azure website.

A: Presently, I don't think there's a convenient, out-of-the-box nodejs deployment on AWS.  You will have to setup and manage that VM.
Correction (Update):
AWS does have a nodejs deploy via Elastic Beanstalk.
Edit:
After looking over joynet's really nice wiki on node-hosting they list awsbox - which looks to make it easier, but you'll still have to do some work starting up the VM and accessing it.


text:
Q: Mean of two numbers by infinite sequences Consider two numbers $a$ and $b$, and the following sequence alternating between even and odd positions:
$$
a+2b+3a+4b+5a+6b\ldots,
$$
If we ''normalize''
$$
\frac{a+2b+3a+4b+\ldots}{1+2+3+4+\ldots},
$$
it turns out this ratio approaches the mean value of $a$ and $b$: $(a+b)/2$. In general
$$
\frac{a+2^n b+3^n a+4^n b+\ldots}{1^n+2^n+3^n+4^n+\ldots}=\frac{a+b}{2}
$$
for $n\geq1$. However if we use exponential functions instead powers:
$$
\frac{m^1 a+m^2 b+m^3 a+m^4 b+\ldots}{m^1 +m^2 +m^3 +m^4 +\ldots}
$$
for some $m>1$, this ratio oscillates and does not approach any number.
Could someone explain why convergence to the mean is obtained by using sequences of powers, and the ratio diverges for sequences of exponentials?

A: To give an evaluation, to make more rigourous, in the first case we have
$$1^n+2^n+3^n+4^n+\ldots+k^n\sim \frac{k^{n+1}}{n+1}$$
$$a+2^n b+3^n a+4^n b+\ldots+k^nb\sim a\left(\frac{k^{n+1}}{n+1}-2^n\frac{k^{n+1}}{(n+1)2^{n+1}}\right)+2^nb\frac{k^{n+1}}{(n+1)2^{n+1}}=$$$$=\frac12(a+b)\frac{k^{n+1}}{n+1}$$
and therefore
$$\frac{a+2^n b+3^n a+4^n b+\ldots+k^nb}{1^n+2^n+3^n+4^n+\ldots+k^n}\sim \frac{\frac12(a+b)\frac{k^{n+1}}{n+1}}{\frac{k^{n+1}}{n+1}}\to \frac{a+b}{2}$$
On the other hand for $m\neq 1$
$$m^1 +m^2 +m^3 +m^4 +\ldots+m^k =\frac{m^{k+1}-m}{m-1}$$
$$m^1 a+m^2 b+m^3 a+m^4 b+\ldots+m^kb\sim a\left(\frac{m^{k}-m}{m-1}-\frac{m^{k}-m^2}{m^2-1}\right)+b\frac{m^{k+2}-m^2}{m^2-1}=$$
$$=a\frac{m^{k+1}-m}{m^2-1}+b\frac{m^{k+2}-m^2}{m^2-1}$$
and therefore
$$\frac{m^1 a+m^2 b+m^3 a+m^4 b+\ldots+m^kb}{m^1 +m^2 +m^3 +m^4 +\ldots+m^k}\sim \frac {a+bm} {m+1}$$
but for
$$m^1 a+m^2 b+m^3 a+m^4 b+\ldots+m^ka$$
we would obtain
$$\frac{m^1 a+m^2 b+m^3 a+m^4 b+\ldots+m^ka}{m^1 +m^2 +m^3 +m^4 +\ldots+m^k}\sim \frac {am+b} {m+1}$$

A: Some thoughts; not sure if this fully answers "why" but an attempt:
The difference in coefficients of $a$ and $b$ goes roughly like the last coefficient term (whichever one's ahead is ahead by around that much). In the polynomial case this difference becomes small relative to the sums; in the geometric case, this stays large.
This is because last term of a geometric sequence with ratio $m > 1$, no matter how long, is a constant fraction of its sum. But for a polynomial sequence, eventually the last term becomes a vanishingly small fraction of the sum.

More formally: consider a sequence of positive reals $c_1, c_2, \dots$ (may be geometric, polynomial, whatever). We're interested in
$$\frac{c_1a + c_2b + c_3a + \dots}{c_1 + c_2 + c_3 + \dots}$$
Or more precisely, let the partial sum $s_k = \sum_{1 \le i \le k} c_i$. Let the sum of odd terms $o_k = \sum_{1 \le 2i-1 \le k} c_{2i-1}$ and the sum of even terms $e_k = \sum_{1 \le 2i \le k} c_{2i} = s_k - o_k$. We're interested in
$$\lim_{k \rightarrow \infty} \frac{o_k a + e_k b}{s_k}$$
Now we can observe this converges for all $a, b$ if and only if $\frac{o_k}{s_k}$ converges.
So the question is: for what kinds of sequences does $\frac{o_k}{s_k}$ converge?
Don't have a nice full answer to this.
But we're more interested in the case when $c_i$ increases it seems, so let's restrict ourselves to that case. Hereafter $c_i$ are increasing.
In this case, we can say the following (the formal version of the above)
Claim:
(i) if $\frac{c_k}{s_k} \rightarrow 0$ then $\frac{o_k}{s_k} \rightarrow \frac{1}{2}$.
(ii) if $\frac{o_k}{s_k} \rightarrow L$ then $L = \frac{1}{2}$ and $\frac{c_k}{s_k} \rightarrow 0$.
Proof of claim:
Observe first that $\frac{o_k}{s_k} \rightarrow L$ if and only if $\frac{o_k - e_k}{s_k} \rightarrow 2L-1$. In particular $\frac{o_k}{s_k} \rightarrow \frac{1}{2} \Leftrightarrow \frac{o_k - e_k}{s_k} \rightarrow 0$
(i) Assume $\frac{c_k}{s_k} \rightarrow 0$. Because the $c_i$ are increasing and positive: when $k$ is odd, $0 \le o_k - e_k \le c_k$. When $k$ is even $0 \le e_k - o_k \le c_k$. So $\left|\frac{o_k - e_k}{s_k}\right| \le \frac{c_k}{s_k}$ for all $k$, hence $\left|\frac{o_k - e_k}{s_k}\right| \rightarrow 0$.
(ii) Assume $\frac{o_k}{s_k} \rightarrow L$. We have $\frac{o_k - e_k}{s_k} \rightarrow 2L-1$. But as in (i) we have $o_k - e_k \ge 0$ for odd $k$ and $o_k - e_k \le 0$ for even $k$. So we must have $2L-1 = 0 \Rightarrow L = 1/2$.
Now let's try to upper bound $\frac{c_k}{s_k}$ in terms of $|\frac{o_k - e_k}{s_k}|$.
For any odd $k$, $(e_{k-1} - o_{k-1}) + (o_k - e_k) = o_k - o_{k-1} = c_k$. Both those terms are positive, so we have that either $\frac{c_k}{2} \le e_{k-1} - o_{k-1} = |o_{k-1} - e_{k-1}|$ or $\frac{c_k}{2} \le o_k - e_k = |o_k - e_k|$. This also holds for even $k$ and can be shown similarly.
So we have
$$c_k \le 2\left(\max \{|o_{k-1} - e_{k-1}|, |o_k - e_k|\}\right)$$
Divide both sides by $s_k$, and we see that the RHS goes to 0 and hence $\frac{c_k}{s_k} \rightarrow 0$ $\square$.

Applied to polynomial case: so we have $c_1, c_2, \dots = 1^n, 2^n, \dots$. Let's lower bound $s_k$ by some multiple of $k^{n+1}$. Very roughly, note that for say $k \ge 4$,
$$s_k = \sum_{i=1}^k i^n \ge \sum_{i \ge k/2} i^n \ge \sum_{i \ge k/2} \left(\frac{k}{2}\right)^n \ge \lfloor \frac{k}{2} \rfloor \left(\frac{k}{2}\right)^n \ge \frac{k}{4}\left(\frac{k}{2}\right)^n = \frac{k^{n+1}}{2^{n+2}}$$
And so $\frac{c_k}{s_k} \le \frac{2^{n+2}}{k} \rightarrow 0$ as $k \rightarrow \infty$.
From the claim, this means $\frac{o_k}{s_k} \rightarrow \frac{1}{2}$ and so the sequence of fractions $\frac{o_ka + e_kb}{s_k}$ approaches $\frac{a+b}{2}$ as expected.
Geometric case: By the formula for sum of geometric series, we can show that $\frac{c_k}{s_k} = \frac{m^{k-1}}{(m^{k} - 1)/(m - 1)} \ge \frac{m-1}{m}$; hence it cannot go to 0. By the claim, the series of fractions diverges.
[More specifically I think it can be shown that $\frac{o_k}{s_k}$ oscillates between $\frac{1}{m+1}$ and slightly larger than $\frac{m}{m+1}$, using the facts that for even $k$, $e_k = mo_k$ and for odd $k$, $o_k = me_k + c_1$]


text:
Q: Problem with the mdadm Raid 5 array on Linux I have a big problem here:
Until a week ago everything worked perfectly with my mdadm array. I then let it shut down for a week and only now started it up again. Shortly afterwards, I noticed a first problem: the LED was not lit on one of my 3 500GB hard drives. So far, not bad. Then I went in via SSH and then found out: my raid was broken.
    pi@raspberrypi:~ $ sudo mdadm --detail /dev/md0
/dev/md0:
           Version : 1.2
     Creation Time : Sat May  2 18:51:06 2020
        Raid Level : raid5
     Used Dev Size : 488251904 (465.63 GiB 499.97 GB)
      Raid Devices : 3
     Total Devices : 1
       Persistence : Superblock is persistent

       Update Time : Fri May 21 13:46:39 2021
             State : active, FAILED, Not Started
    Active Devices : 1
   Working Devices : 1
    Failed Devices : 0
     Spare Devices : 0

            Layout : left-symmetric
        Chunk Size : 64K

Consistency Policy : unknown

              Name : raspberrypi:0  (local to host raspberrypi)
              UUID : 23f436a0:c3f13920:01784b25:b4581c36
            Events : 48112

    Number   Major   Minor   RaidDevice State
       -       0        0        0      removed
       -       0        0        1      removed
       -       0        0        2      removed

       -       8       33        1      sync   /dev/sdc1
pi@raspberrypi:~ $ cat /proc/mdstat
Personalities : [raid6] [raid5] [raid4]
md0 : inactive sdc1[4]
      488254584 blocks super 1.2

unused devices: <none>
pi@raspberrypi:~ $ lsblk
NAME        MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda           8:0    0 465,8G  0 disk
└─sda1        8:1    0 465,8G  0 part
sdb           8:16   0 465,8G  0 disk
└─sdb1        8:17   0 465,8G  0 part
sdc           8:32   0 465,8G  0 disk
└─sdc1        8:33   0 465,8G  0 part
mmcblk0     179:0    0  14,9G  0 disk
├─mmcblk0p1 179:1    0   256M  0 part /boot
└─mmcblk0p2 179:2    0  14,6G  0 part /

This should not be like that. / dev / sda, / dev / sdb and / dev / sdc should be yours in the array. I thought about it and it looks like 2 hard drives have failed at the same time (in retrospect I think the LED is always off when there is no activity) and now the array cannot be rebuilt. If I reboot with only 2 hard drives, this is what comes out:
    pi@raspberrypi:~ $ sudo mdadm --detail /dev/md0
/dev/md0:
           Version : 1.2
        Raid Level : raid0
     Total Devices : 2
       Persistence : Superblock is persistent

             State : inactive
   Working Devices : 2

              Name : raspberrypi:0  (local to host raspberrypi)
              UUID : 23f436a0:c3f13920:01784b25:b4581c36
            Events : 48112

    Number   Major   Minor   RaidDevice

       -       8       17        -        /dev/sdb1
       -       8        1        -        /dev/sda1
pi@raspberrypi:~ $ cat /proc/mdstat
Personalities :
md0 : inactive sdb1[4](S) sda1[0](S)
      976509169 blocks super 1.2

unused devices: <none>
pi@raspberrypi:~ $ lsblk
NAME        MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda           8:0    0 465,8G  0 disk
└─sda1        8:1    0 465,8G  0 part
sdb           8:16   0 465,8G  0 disk
└─sdb1        8:17   0 465,8G  0 part
mmcblk0     179:0    0  14,9G  0 disk
├─mmcblk0p1 179:1    0   256M  0 part /boot
└─mmcblk0p2 179:2    0  14,6G  0 part /

I rebooted the Pi and now this is coming out and I'm even more confused (it should be a Raid 5 array)
pi@raspberrypi:~ $ lsblk
NAME        MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda           8:0    0 465,8G  0 disk
└─sda1        8:1    0 465,8G  0 part
sdb           8:16   0 465,8G  0 disk
└─sdb1        8:17   0 465,8G  0 part
sdc           8:32   0 465,8G  0 disk
└─sdc1        8:33   0 465,8G  0 part
mmcblk0     179:0    0  14,9G  0 disk
├─mmcblk0p1 179:1    0   256M  0 part /boot
└─mmcblk0p2 179:2    0  14,6G  0 part /
pi@raspberrypi:~ $ cat /proc/mdstat
Personalities :
md0 : inactive sda1[0](S) sdc1[4](S) sdb1[3](S)
      1464762761 blocks super 1.2

unused devices: <none>
pi@raspberrypi:~ $ sudo mdadm --detail /dev/md0
/dev/md0:
           Version : 1.2
        Raid Level : raid0
     Total Devices : 3
       Persistence : Superblock is persistent

             State : inactive
   Working Devices : 3

              Name : raspberrypi:0  (local to host raspberrypi)
              UUID : 23f436a0:c3f13920:01784b25:b4581c36
            Events : 48112

    Number   Major   Minor   RaidDevice

       -       8       33        -        /dev/sdc1
       -       8       17        -        /dev/sdb1
       -       8        1        -        /dev/sda1

I hope that someone will know how to get the array back together, since the data on all hard drives should still be there.
I do have a backup, but some data on the Raid isn't present on my backup.
Kind regards,
Elytronn


text:
Q: What is the nature of an empty array in C? I have the following code:
#include <stdio.h>

int main(void) {
    int array[0];
    printf("%d", array);
    return 0;
}

As we know, an array always points to its first item, but we don't have items in this example, but this code produces some memory address. What does it point to?

A: An array of size 0 is considered a constraint violation.  So having such an array and attempting to use it triggers undefined behavior.
Section 6.7.6.2p1 of the C standard regarding constraints on Array Declarators states:

In addition to optional type qualifiers and the keyword static, the [ and ] may delimit an expression or *. If they delimit an expression (which specifies the size of an array), the expression shall have an integer type.  If the expression is a constant expression, it shall have a value greater than zero.  The element type shall not be an incomplete or function type.   The  optional  type  qualifiers  and  the  keyword static shall  appear  only  in  a declaration  of  a  function  parameter  with  an  array  type,  and  then  only  in  the  outermost array type derivation

GCC will allow a zero length array as an extension, but only if it is the last member of a struct.  This is an alternate method of specifying a flexible array member which is allowed in the C standard if the array size is omitted.


text:
Q: Issues with seemingly fine cron files in /etc/cron.d/ on Debian/Ubuntu I've noticed jobs in /etc/cron.d/ not running, the odd thing is that X amount will run but then the rest won't.
I've read comments from people about not using a '.' in the filenames, none of my files have any dots in them.
I've also read that you should always place a blank line at the end of each file, but that didn't seem to make any difference.
In the end I stripped out ALL comments from every single file in /etc/cron.d/, this made all jobs run correctly.
Cron was not putting any errors messages in to /var/log/syslog or /var/log/messages, there is no /var/log/cron(d).log
Has anyone encountered anything like this before? If so is there a solution for commenting without it causing problems?

A: Use # at the beginning of the line to comment.
Crontabs are not supposed to have a blank line at the end - maybe they accept it in recent releases(?) but for a long time is was causing problem.
Usually a mail is sent to the crontab owner with the output / problems. If the crontab belongs to root, you should open its mailbox.

A: Quick update to the above comments
@Dennis - They all ran without any issues.
@Richard - All fines contained Unix line endings, if any of my developers used Windows line endings they would feel my ban hammer instantly.
There was no output or problems because the cron files simply did not run. Checking mailboxes was one of my first ideas.
Adding a simple - echo "file ran" > /root/cron-has-worked  - to a job confirmed that it was not working, also sitting and watching /var/log/syslog in one shell and top in another confirmed cron jobs not running.
Thank you for the comment about using # but I do know how to comment cron files. =P


text:
Q: Gerar relatório IReport / Jasper Report contendo 2 páginas (com 3 colunas cada) em uma mesma folha em modo paisagem estou fazendo um relatório para um cliente e não estou conseguindo montá-lo de acordo com a sua necessidade. O que ele precisa é gerar um PDF de folha A4 no modo paisagem, contendo cada folha duas páginas (ímpar e par), e cada página com 3 colunas.
Já pesquisei em vários fóruns (tanto aqui no GUJ quanto em outros) mas em nenhum consegui encontrar algo para me ajudar com esta resolução, e já estou atrasado com a entrega deste software, onde só falta este relatório dos produtos.
Para exemplificar melhor, estou enviando neste post a imagem do resultado que preciso.
Por favor pessoal, alguém conhece e/ou já precisou gerar um relatório de duas páginas em 1 mesma folha? As 3 colunas eu consigo gerar, porém somente em 1 página.
Se tiverem alguma idéia, ou também até sugestão de outra maneira para gerar, serão muito bem vindas, pois minhas possibilidades estão muito próximas de esgotadas, por isso preciso e muito da ajuda de vocês.
Estou usando IReport versão 5.6.0
Obrigado!

A: Achei essa thread discutindo mais ou menos o mesmo problema que o seu. O curioso é que a resposta do Staff da Jasper foi na linha do meu comentário na sua pergunta. =]
Vou copiar o código que foi postado lá com alguns poucos comentários meus. Não testei aqui, mas parece fazer sentido no universo que conheço do JasperReports:
//Começa configurando o relatório normalmente!
JasperDesign jd = JRXmlLoader.load(ResourceUtils.getFile(getFileResourcesJRXML("myjasper_A5.jrxml")));
JasperReport jrRH02 = JasperCompileManager.compileReport(jd);
jp = JasperFillManager.fillReport(jrRH02, data, dataSource);

getResponse().setContentType("application/pdf");
ServletOutputStream outputStream = getResponse().getOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JRPdfExporter exporter = new JRPdfExporter();
exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT, jp);
exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM, baos);
exporter.exportReport();

//Não entendi porquê ele fez isso...
exporter.reset();
exporter = null;
System.gc();

//Aqui é onde a hackeada começa:
Document document = new Document();
//Define as dimensões da página no braço
document.setPageSize(new Rectangle(jp.getPageWidth(), jp.getPageHeight() * 2)); // This is because A4 Size == 2 * A5
//lê os dados do relatório originalmente produzido (páginas separadas)
PdfReader pdfReader = new PdfReader(baos.toByteArray());
//cria um novo escritor de PDF usando a configuração acima
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();
//Faz um loop que lê as páginas do relatório inicial
// e coloca no relatório novo
//Estranhamente ele deixou a definição do loop incompleto,
// não deve ser difícil completar...
for(int i = 1; i ...){
    document.newPage();
    PdfImportedPage page = writer.getImportedPage(pdfReader, i);
    cb.addTemplate(page, 0, 0);
    cb.addTemplate(page, 0, jp.getPageHeight());
}
outputStream.flush();
document.close();

A: Neste caso eu faria o seguinte:
Na paisagem A4 colocaria 2 SubReports com 400 pixels cada devidamente configurado as sobras do tamanho, e no meio vi que tem uma linha vertical, pois bem, adicione uma linha vertical.
Configurar os SubReports tanto no Ireport/JasperStudio e em código, dividindo minha exibições em duas lista(Uma para cada SubReport) para não haver redundância.


text:
Q: Gradle Build Failing Due to Gradle Version I Do Not Have and Source 8 I am trying to build and run a project I am getting theses errors / warnings. The docs say that it needs JVM 10 and Gradle 6:
D:\GIT\geo\spring-boot>.\gradlew  bootRun

> Task :compileJava FAILED
D:\GIT\geo\spring-boot\src\main\java\module-info.java:1: error: modules are not supported in -source
8
module Geo {
^
  (use -source 9 or higher to enable modules)
1 error

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileJava'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more
log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.2.2/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 1s
1 actionable task: 1 executed

I see this message: use -source 9 or higher to enable modules
However, it looks like it am using java 10
D:\GIT\geo\spring-boot>java -version
openjdk version "10" 2018-03-20
OpenJDK Runtime Environment 18.3 (build 10+44)
OpenJDK 64-Bit Server VM 18.3 (build 10+44, mixed mode)

I also see this message: Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
But it looks like I am using Gradle 2.2
D:\GIT\geo\spring-boot>.\gradlew -v

------------------------------------------------------------
Gradle 6.2.2
------------------------------------------------------------

Build time:   2020-03-04 08:49:31 UTC
Revision:     7d0bf6dcb46c143bcc3b7a0fa40a8e5ca28e5856

Kotlin:       1.3.61
Groovy:       2.5.8
Ant:          Apache Ant(TM) version 1.10.7 compiled on September 1 2019
JVM:          10 ("Oracle Corporation" 10+44)
OS:           Windows Server 2016 10.0 amd64

A: You need to set the version in your build script
compileJava {
    options.release = 10
}

https://docs.gradle.org/6.8.1/userguide/building_java_projects.html#sec:java_cross_compilation


text:
Q: Union of cell array of cells I'm looking for the way to do the union of two cell arrays of cell arrays of strings. For example:
A = {{'one' 'two'};{'three' 'four'};{'five' 'six'}};
B = {{'five' 'six'};{'seven' 'eight'};{'nine' 'ten'}};

And I'd like to get something like:
C = {{'one' 'two'};{'three' 'four'};{'five' 'six'};{'seven' 'eight'};{'nine' 'ten'}};

But when I use C = union(A, B) MATLAB returns an error saying:

Input A of class cell and input B of class cell must be cell arrays of strings, unless one is a string.

Does anyone know how to do something like this in a hopefully simple way? I'd greatly appreciate it.
ALTERNATIVE: A way to have a cell array of separated strings in any other way than a cell array of cell array of strings would be also useful, but as far as I know, it's not possible.
Thank you!

A: C=[A;B]
allWords=unique([A{:};B{:}])
F=cell2mat(cellfun(@(x)(ismember(allWords,x{1})+2*ismember(allWords,x{2}))',C,'uni',false))
[~,uniqueindices,~]=unique(F,'rows')

C(sort(uniqueindices))

What my code does: it builds up a list of all words allwords, then this list is used to build up a matrix which contains the correlation between the rows and which word they contain. 1=Match for first wird, 2=Match for second word. Finally, on this numeric matrix unique can be applied to get the indices.
Including my update, now the 2 words per cell is hardcoded. To get rid of this limitation it would be neseccary to replace the anonymous function (@(x)(ismember(allWords,x{1})+2*ismember(allWords,x{2}))) with a more generic implementation. Probably using cellfun again.

A: Union doesn't seem like compatible for cell arrays of cells. So, we need to look for some workaround.
One approach would be to get the data from A and B concatenated vertically. Then, along each column assign each cell of strings an unique ID. Those IDs can then be combined into a double array that opens up the possibility of  of using unique with 'rows' option to get us the desired output. This is precisely achieved here.
%// Slightly complicated input for safest verification of results
A = {{'three' 'four'};
    {'five' 'six'};
    {'five' 'seven'};
    {'one' 'two'}};

B = {{'seven' 'eight'};
    {'five' 'six'};
    {'nine' 'ten'};
    {'three' 'six'};};

t1 = [A ; B] %// concatenate all cells from A and B vertically
t2 = vertcat(t1{:}) %// Get all the cells of strings from A and B

t22 = mat2cell(t2,size(t2,1),ones(1,size(t2,2)));
[~,~,row_ind] = cellfun(@(x) unique(x,'stable'),t22,'uni',0)
mat1 = horzcat(row_ind{:})

[~,ind] = unique(mat1,'rows','stable')
out1 = t2(ind,:) %// output as a cell array of strings, used for verification too
out = mat2cell(out1, ones(1,size(out1,1)),size(out1,2)) %//desired output

Output -
out1 =
    'three'    'four'
    'five'     'six'
    'five'     'seven'
    'one'      'two'
    'seven'    'eight'
    'nine'     'ten'
    'three'    'six'


text:
Q: Algorithmically computing bounds on multiple integrals I have been wrestling with the following problem for several reasons:

Integrate $\sqrt{x^2+y^2+z^2\,}$ over the region $x^2+y^2+z^2 \le 1$.
My first question was: How do I set up the integral?
This was answered really clearly and I understand the form of the triple integral in both cartesian and spherical coordinates. What concerns me the most now is how the integrating region is transformed from one set to another in a methodical fashion.
I know that because in this case, the integrating region is a sphere, then the bounds for the spherical coordinates are trivial to find. However, what if I had to integrate the same function over the region
$$\{\ (x,y,z):\quad 0\le x\le 1,\quad -1/3 \le y \le \sqrt{1-x^2\,},\quad 0 \le z \le \sqrt{1-x^2-y^2\,}\ \}\ ?$$
That is just an example, my problem is not with spherical coordinates or with the integral at hand, but with the apparent over-reliance on intuition that will not be available to me if I ever have to deal with higher dimensions or regions that are not triangles or squares or spheres. Is there a method, no matter how tedious, that can be used to determine the region in the transformed space and therefore the new integral bounds?


text:
Q: FIltering a data set in excel vba and pasting results into different tabs that are named based on filter I am trying to filter a data set in tab "Expiring Contracts", filtered on column B (this data set can increase or decrease based at any point). The different filters come from tab "Inputs" which can change overtime (increase or decrease). I am trying to paste the results of the filter to separate tabs that are named exactly like the list, BUT I want to paste the values on the next available (blank) cell. This is what I have now:
Sub ParseList2()

    Dim uwname As String
    Dim lastrowUW As Long
    Dim lastrow As Long
    Dim N As Range

    lastrowUW = Sheets("Inputs").Cells(Rows.Count, "H").End(xlUp).Row

    For Each N In Sheets("Inputs").Range("H2:H" & lastrowUW).Cells
        uwname = N.Text
        Sheets("Expiring Contracts").Range("$A:$AA").AutoFilter Field:=2,
            Criteria1:=N
        lastrow = Columns(2).Find("*", SearchDirection:=xlPrevious).Row
        Range("A2:AA" & lastrow).SpecialCells(xlCellTypeVisible).Select
        Selection.Copy
        Sheets(uwname).Select
        lastrow = Columns(2).Find("*", SearchDirection:=xlPrevious).Row + 1
        Range("A" & lastrow).Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False
    Next N

    Sheets("Expiring Contracts").AutoFilterMode = False

End Sub

This worked thanks to some comments below!
Sub ParseList2()

Dim uwname As String
Dim lastrowUW As Long
Dim lastrow As Long
Dim N As Range
Dim rng As Range

lastrowUW = Sheets("Inputs").Cells(Rows.Count, "H").End(xlUp).Row

For Each N In Sheets("Inputs").Range("H2:H22").Cells
uwname = N.Value
Sheets("Expiring Contracts").Range("$A:$AA").AutoFilter Field:=2,
Criteria1:=uwname
'lastrow = Columns(2).Find("*", SearchDirection:=xlPrevious).Row + 1
Range("A2:AA99999").SpecialCells(xlCellTypeVisible).Select
Selection.Copy
Sheets(uwname).Select
lastrow = Columns(2).Find("*", SearchDirection:=xlPrevious).Row + 1
Range("A" & lastrow).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Range("A1").Select
Sheets("Expiring Contracts").Select
Sheets("Expiring Contracts").AutoFilterMode = False
Range("A1").Select
Next N
Sheets("Expiring Contracts").Select
Sheets("Expiring Contracts").AutoFilterMode = False
Range("A1").Select
End Sub

A: What you are attempting to do using VBA can very easily be accomplished using PivotTables and Slicers. Turn your source data into an Excel Table, make a PivotTable out of it, put the PivotTable in the Inputs tab, set up a Slicer on the field you want to filter on, put the other fields of interest in the PivotTable as row fields, and you're done. No code necessary. Let the application do the work for you.


text:
Q: Virtual Host Joomla and MAMP I have been trying for some time now to set up a virtual host for the new Intranet we are putting in at my organization. It is on a separate server from the one running our website. I have set up the Intranet using MAMP and Joomla on a Mac OSX 10.5.8 machine.
I have followed several tutorials and solutions including Virtual Host X but nothing seems to work.
I am able to get the virtual host to work on the local machine but nothing outside of that.
Here is an example of my hosts file.
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1            localhost
127.0.0.1           staff.mysite.org
255.255.255.255 broadcasthost
::1                 localhost
fe80::1%lo0         localhost

The end of my httpd.conf file looks like this. There are two includes. The first was my original attempt to set up a virtual host. The second created by Virtual Host X
NameVirtualHost *:80

Include /Applications/MAMP/conf/apache/vhosts.conf

Include /private/etc/apache2/extra/httpd-vhosts.conf

Here is my vhosts.conf file.
<VirtualHost *:80>
ServerName staff.mysite.org
DocumentRoot /Applications/MAMP/htdocs/joomla/
DirectoryIndex index.php index.html index.cgi
<Directory /Applications/MAMP/htdocs/joomla/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
</VirtualHost>

Here is the httpd-vhosts.conf file.
NameVirtualHost *:80
Listen 9000

<Directory "/Applications/MAMP/htdocs/joomla/">
Allow From All
AllowOverride All
</Directory>
<VirtualHost *:80>
ServerName "staff.mysite.org"
ServerAlias "www.staff.mysite.org"
DocumentRoot "/Applications/MAMP/htdocs/joomla"
</VirtualHost>

<VirtualHost *:9000>
DocumentRoot "/Applications/MAMP/htdocs/joomla"
</VirtualHost>

I read on the Joomla support site that you have to make a change to the $mosConfig_live_site variable in the configuration.php file, but when I make the suggested change it still does not work and I can no longer view the site on the local machine.
Is there something I am missing here?
Please help if you can. Thanks!

A: your missing some DNS configuration
you need to have a dns record that will translate staff.mysite.org into the IP address of your server, if you are running internal dns then this is no problem, and it totally depends on your local dns configuration, 2 examples:
if your running a firewall like pfsense with dns forwarding, you can setup a single dns record that will send staff.mysite.org to the IP of your intranet server
if however you are running standard dns servers like Apple's or Windows DNS then you will have to locally create the zone for the whole domain and replicate the current values found on the internet and then add the staff subdomain with the local IP.


text:
Q: Android-Stripe add missing parameters while account creating I was trying to implemented stripe payment gateway. Every thing is going fine. I was able to create connected account for the user in my stripe dashboard, but the problem is I'm missing following parameter

*

*Website

*SSN

*Industry

Now I want to know how to add these parameters while creating account.
I have add the screen shot from stripe dashboard and here is the code:
 Map<String, Object> dob =
                    new HashMap<>();
            dob.put("day", "12");
            dob.put("month", "1");
            dob.put("year", "1991");
            Map<String, Object> address =
                    new HashMap<>();
            Map<String, Object> address_pram =
                    new HashMap<>();
            address_pram.put("city", "Baton Rouge");
            address_pram.put("line1", "1 Calais Ave");
            address_pram.put("postal_code", "70806");
            address_pram.put("state", "Louisiana");
            address.put("address", address_pram);
            address.put("dob", dob);
            address.put("email", "ahmad@example.com");
            address.put("first_name", "ahmad");
            address.put("last_name", "bajwa");
            address.put("phone", "+12015551023");
            //address.put("website", "www.goldenkeystone.com");
            //address.put("industry", "");
         //   address.put("ssn", "000000000");
            Map<String, Object> acceptance =
                    new HashMap<>();
            acceptance.put("date", System.currentTimeMillis() / 1000L);
            acceptance.put("ip", ipString);
            Map<String, Object> cardPayments =
                    new HashMap<>();
            cardPayments.put("requested", true);
            Map<String, Object> transfers = new HashMap<>();
            transfers.put("requested", true);
            Map<String, Object> capabilities =
                    new HashMap<>();
            capabilities.put("card_payments", cardPayments);
            capabilities.put("transfers", transfers);
            Map<String, Object> params = new HashMap<>();
            params.put("type", "custom");
            params.put("country", "US");
            params.put("tos_acceptance", acceptance);
            params.put("business_type", "individual");
            params.put("individual", address);
            params.put("capabilities", capabilities);
            Account account = Account.create(params, requestOptions);

Note: If still question is unclear, I would be glad if you add your contribution.

A: That data and other sensitive information would be collected by Stripe during the onboarding via Account Links: stripe.com/docs/connect/connect-onboarding
It's not something that you can pass to the Accounts API. See here for more information: https://stripe.com/docs/connect/collect-then-transfer-guide?platform=web#create-an-account-link


text:
Q: android: app start more slowly after size grown My app is about 10M in size. It start quickly.
Recently, for some reason, my app include a library project which has little java code and a very large dynamic library about 60M. And then, my app start with a full screen white and go into my first Activity after about five second.
However I don't load the large lib when start, instead I load it when I use the feature.
Why so slowly? Isn't Android load dynamic library into RAM when I call System.loadLibrary() ?
How should I do to shorten the time of start-up?


text:
Q: How can one parallelize geopandas "to_file" function I am trying to implement a parallelized function for Geopandas that takes a single vector data (i.e.: a Shapefile containing a Multipolygon data type), and converts it to a standard celular grid with cell x and y sizes defined by the user.
As this function may result in serious Memory issues (i.e.: caused by too high spatial resolution), I was wondering whether it would be possible to save the data iteratively in the given destinated file. That way, as each parallel process runs the "GRID" function, the same process can save the data iteratively in appended mode. That way, I believe that one wouldn't have Memory issues.
Here is my "SHP_to_GRID_Function". Note that the code below still requires that the whole data generated by the multiprocessing be handled by memory directly (so overflow is more than certain for large datasets).
import pandas as pd
import numpy as np
import geopandas as gpd
from shapely.geometry import Polygon
from multiprocessing import Pool
import os
from functools import partial

def info(title):
    print(title)
    print('module name:', __name__)
    print('parent process:', os.getppid())
    print('process id:', os.getpid())

def parallelize_df(gdf, func, n_cores, dx=100, dy=100, verbose=False):

    Geometries= gdf.loc[:, 'geometry'].values

    pool = Pool(processes=n_cores)
    func_partial=partial(func, dx, dy, verbose) # prod_x has only one argument x (y is fixed to 10)

    results = pool.map(func_partial, Geometries)

    pool.close()
    pool.join()

    print(np.shape(results))

    GRID = gpd.GeoSeries(np.array(results).ravel())

    print("GRID well created")

    return GRID

def generate_grid_from_Poligon(dx=100, dy=100, verbose=False, polygon=None):
    if verbose == True:
        info('function parallelize_df')
    else:
        None

    xmin,ymin,xmax,ymax = polygon.bounds

    lenght = dx
    wide = dy

    cols = list(np.arange(int(np.floor(xmin)), int(np.ceil(xmax)), wide))
    rows = list(np.arange(int(np.floor(ymin)), int(np.ceil(ymax)), lenght))
    rows.reverse()

    subpolygons = []
    for x in cols:
        for y in rows:
            subpolygons.append( Polygon([(x,y), (x+wide, y), (x+wide, y-lenght), (x, y-lenght)]) )

    return subpolygons

def main(GDF, n_cores='standard', dx=100, dy=100, verbose= False):
    """
    GDF: geodataframe
    n_cores: use standard or a positive numerical (int) value. It will set the number of cores to use in the multiprocessing

    args: (dx: dimension in the x coordinate to make the grid
            dy: dimenion in the y coordinate to make the grid)

    """

    if isinstance(n_cores, str):
        import multiprocessing
        N_cores = multiprocessing.cpu_count() -1

    elif isinstance(n_cores, int):

        N_cores =n_cores

    GRID_GDF = parallelize_df(GDF, generate_grid_from_Poligon, n_cores=N_cores, dx=dx, dy=dy, verbose=verbose)

    return GRID_GDF

I thank you for you time,
Sincerely yours,
Philipe Leal

A: I finally have come across a solution for my question. It is not perfect, since it requires several writing processes and one final concatenation process over all temporary files created during the run.
Feel free to suggest alternatives.
Here is the solution I found.
import numpy as np
import geopandas as gpd
import pandas as pd
from shapely.geometry import Polygon
from multiprocessing import Pool, Lock, freeze_support
import os
from functools import partial
import time

def info(time_value):

    print('module name:', __name__)
    print('parent process:', os.getppid())
    print('process id:', os.getpid())
    print("Time spent: ", time.time() - time_value)

def init(l):

    global lock

    lock=l

def Data_Arranger(to_filename):

    """This function concatenates and deletes temporary files. It is an arranger
        of the multicessing data results"
    """

    Base = os.path.join(os.path.dirname(to_filename), 'temp')

    Strings = [file for file in os.listdir(Base)]

    Strings = [os.path.join(Base, S) for S in Strings]

    if not os.path.exists(os.path.dirname(to_filename)):
        os.mkdir(os.path.dirname(to_filename))

    Sq = [S for S in Strings if S.endswith('.shp')]

    gpd.GeoDataFrame(pd.concat([gpd.read_file(sq1) for sq1 in Sq]), crs=GDF.crs).to_file(to_filename)

    for sq1 in Sq:
        os.remove(sq1)

    import shutil

    shutil.rmtree(Base, ignore_errors=True)

def parallelize_df(gdf, func, n_cores, dx=100, dy=100, verbose=False, to_filename=None):

    Geometries= gdf.loc[:, 'geometry'].values
    crs = gdf.crs

    pool = Pool(processes=n_cores, initializer=init, initargs=(Lock(), ) )

    func_partial=partial(func, dx, dy, verbose, to_filename, crs) # prod_x has only one argument x (y is fixed to 10)

    pool.map(func_partial, Geometries)

    pool.close()
    pool.join()

def generate_grid_from_gdf(dx=100, dy=100, verbose=False, to_filename=None, crs=None, polygon=None):
    if verbose == True:
        info(time.time())
    else:
        None

    xmin,ymin,xmax,ymax = polygon.bounds

    lenght = dx
    wide = dy

    cols = list(np.arange(int(np.floor(xmin)), int(np.ceil(xmax)), wide))
    rows = list(np.arange(int(np.floor(ymin)), int(np.ceil(ymax)), lenght))
    rows.reverse()

    subpolygons = []
    for x in cols:
        for y in rows:
            subpolygons.append( Polygon([(x,y), (x+wide, y), (x+wide, y-lenght), (x, y-lenght)]) )

    lock.acquire()

    print('parent process: ', os.getppid(), ' has activated the Lock')
    GDF = gpd.GeoDataFrame(geometry=subpolygons, crs=crs)

    to_filename = os.path.join(os.path.dirname(to_filename), 'temp',  str(os.getpid()) + '_' + str(time.time()) + '.' + os.path.basename(to_filename).split('.')[-1])

    if not os.path.exists(os.path.dirname(to_filename)):
        os.mkdir(os.path.dirname(to_filename))

    try:
        print("to_filename: ", to_filename)
        GDF.to_file(to_filename)
    except:
        print("error in the file saving")
    lock.release()

    print('parent process: ', os.getppid(), ' has unlocked')

def main(GDF, n_cores='standard', dx=100, dy=100, verbose= False, to_filename=None):
    """
    GDF: geodataframe
    n_cores: use standard or a positive numerical (int) value. It will set the number of cores to use in the multiprocessing

    dx: dimension in the x coordinate to make the grid
    dy: dimenion in the y coordinate to make the grid)
    verbose: whether or not to show info from the processing. Appliable only if applying the function not
            in Windows (LINUX, UBUNTU, etc.), or when running in separte console in Windows.

    to_filename: the path which will be used to save the resultant file.
    """

    if isinstance(n_cores, str):
        import multiprocessing
        N_cores = multiprocessing.cpu_count() -1

    elif isinstance(n_cores, int):

        N_cores =n_cores

    parallelize_df(GDF, generate_grid_from_gdf, n_cores=N_cores, dx=dx, dy=dy, verbose=verbose, to_filename=to_filename)
    Data_Arranger(to_filename)

    ####################################################################################

if "__main__" == __name__:
    freeze_support()
    GDF = gpd.read_file("Someone's_file.shp")

    to_filename = "To_file_directory/To_file_name.shp"

    dx = 500 # resampling to 500 units. Ex: assuming the coordinate reference system is in meters, this function will return polygons of the given geometries in 500m for the longitudinal dimension.

    dy = 500 # same here. Assuming CRS is in meters units, the resultant file will be have polygons of 500m in latitudinal dimension

    main(GDF, dx=dx, dy=dy, verbose=True, to_filename=to_filename)

I thank you for your time.
Philipe Leal


text:
Q: Confining colorful background to the area of an equation in rmarkdown I would like to add a colorful background to equations. I have tried the code below, but, unfortunately, the colorful background expands to the margins instead of being confined to the equation. Could someone please help me?
---
title: "Untitled"
output: html_document
---

Some text

$$Y = \beta_0 + \beta_ 1 X_1 + \ldots + \beta_n X_n.$$

A: You can do this with a CSS style.  Put this into your document, or in a separate CSS file included in the YAML header:

That will make all of your MathJax code have a yellow background.  If you only want display equations to have it, use

And if you only want one particular equation to have the colouring, then you should use a more specific selector, e.g.

where you would put in #MathJax-Element-2-Frame for the second equation, etc.  With lots of equations this could be tedious, so you could add a class to the ones you want to highlight and select those,
e.g.

This one is regular:
$$Y = \beta_0 + \beta_ 1 X_1 + \ldots + \beta_n X_n.$$

This one is highlighted:

$$Y = \beta_0 + \beta_ 1 X_1 + \ldots + \beta_n X_n.$$

According to the comments, Bookdown may need you to request HTML-CSS rendering, which can be done with the right mouse click on one of the equations, and following the menus to Math Settings | Math Renderer | HTML-CSS.

A: A DIV is a block element by default.
A SPAN is an inline element.
Try this:

$$Y = \beta_0 + \beta_ 1 X_1 + \ldots + \beta_n X_n.$$

The padding controls the amount of color around the equation.


text:
Q: Android: Offset ImageView in Center slightly
We say that the following image is in the center. To do this I use the following code.
<RelativeLayout
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="10"
    android:orientation="vertical" >
    <ImageView
        android:src="@drawable/logo"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>

It has been working for a deadcenter positioning. I would like to do the following, and just offset it slightly upwards. As you see I do not want the image to cross the center line (I know how to fix that by adding an invisible view).

A: Found a post giving me another hint at the fake view idea, making the fake view 100dp long, the bottom padding of the fake view 100dp long (so it would be pushed down) then aligning my views bottom with the bottom of the fake view, perfect.
<RelativeLayout
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="10"
    android:orientation="vertical" >
    <View
        android:id="@+id/anchor"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        android:paddingBottom="100dp" />

    <ImageView
        android:src="@drawable/logo"
        android:layout_alignBottom="@id/anchor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>


text:
Q: Why is curvature quadratic? In my textbook, it describes the hessian being the local quadratic of the optimization landscape. The hessian is synonymous with curvature.
I'm wondering why curvature is quadratic?

A: The Hessian is not synonymous with curvature. The quadratic (involving Hessian) is the lowest order term in a multivariate Taylor series expansion which captures any curvature. Higher order terms than quadratic (Hessian) are not usually used in optimization.  But higher order methods can be used in optimization, and sometimes are.

A: Slope is obtained by first differentiation... like with differential  operator $D$. Curvature is obtained by second  differentiation, like with the operator $D^2$.
Second order terms and their products like $rt-s^2$ in Hessian vanish for flat planes and the like. It is positive for positive (double or Gauss) curvature surfaces and negative for negative curvature surfaces. Hessian indicates sign of curvature.


text:
Q: What is the best way to use C# try/catch/finally to behave like if/else? I am trying to set up try/catch/finally to behave like if/else. I am not sure of the most elegant way to do this simple thing.
public bool login()
{
bool isLoggedIn = false;
if (connectToServer(Path,username,password) ) // if successful
  {
     isLoggedIn = true;
  }
  else
  {

  }

return isLoggedIn;
}

Here is what I attempted with Exceptions.
public bool login()
{
 bool isLoggedIn = false;

 try{
    connectToServer(Path,username,password)
    isLoggedIn = true;
  }
  catch(myConnectionException ex)
  {

  }

return isLoggedIn;
}

the 2nd line "isLoggedIn" is going to get executed although the previous line raises an exception upon failure.  My thinking is to ask "if an exception was thrown, I don't want that line to be executed.  Can I (should I) access the exception object at this point to test? (or is it out of scope?) I am a former C coder so I am trying to "keep it c#" to do a simple thing. I just want to perfect my skills and be in line with "best practices".
Thanks
DTM

A: What would be wrong with doing something like this?
bool isLoggedIn = false;

try
{
    isLoggedIn = connectToServer(Path, username, password);
}
catch (ExceptionType1 ex1)
{
    //Recover from this exception type.
}
catch (ExceptionType2 ex2)
{
    //Recover from this exception type.
}

Exceptions aren't a "replacement" for if statements. They're for handling error conditions, if one should occur, and using them to control the flow of an application is certainly not advisable. At the very least they're slow, and using them to control flow may hide actual real errors from you when you may actually want the application to fail.
EDIT:
As @Anthony Pegram mentions in the comment below, dealing with all exception types in a single catch block is bad practice (something I'm guilty of all too often), since it also hides exceptions from you that you might actually want to handle specifically.

A: No it won't get executed. However, this is bad practice as there is a costly context-switch to handle the exception. You should only use exceptions in exceptional cases.
I would consider combining the two approaches.

A: connectToServer should throw a myConnectionException if it wasn't successful

A: I would highly recommend moving the try/catch block to connectToServer. You should never control program flow with exceptions, as mentioned the context switch is horrible overhead.
Have connectToServer always return true or false (have it internally catch it's errors and return false). and simply:
return connectToServer(Path,username,password);

A: In this simple example the
isLoggedIn = true;

is not reached if an exception is thrown so it is still false (as initialized) if the connection call throws an exception. Even if it is not a catched exception type the part of setting isLoggin to true will never be reached.
As mentioned before: Don't use exception instead of if/then/else or switch/case. If your code has more method calls after setting the isLoggedIn to true then you should reset this to false because in the catch because this will be the returned result.
By the way, there is no difference in the rule of using exceptions in c# or i c++. This seems common to both languages.

A: This will work, but should not be done. Your best bet would be to code it as :
public bool login()
{
    return connectToServer(Path,username,password);
}

Short and sweet. Exceptions are very bad to use except in exceptional cases. Of course, if you want to pick up the connectToServer exceptions then you can use something like:
public bool login()
{
    try
    {
        return connectToServer(Path,username,password);
    }
    catch(exception ex)//or the specific exception you are after
    {
        return false;
    }
}

meaning that the exceptional occasion of the failure will be picked up by the exception, but most of the time the exception will not be called.


text:
Q: Protractor "Error while waiting for Protractor to sync with the page" browsing Angular site I'm trying to follow the Protractor's tutorial on Protractors official site but I can't even complete the step 0.
I'm using protractor & webdriver-manager in version 6.0.0. My SO is Linux (Ubuntu 18.06) and my Chrome is the latest available (73.0.3683.86).
After installing protractor I had to downgrade the chromedriver installed by default as it expected me to have Chrome 74. I downgraded it by executing webdriver-manager --versions.chrome 73.0.3683.68.
After that, I have been following the step 0 of the tutorial. I have the configuration.js file and the test-spec.js files as follow:
configuration.js
 exports.config = {
      seleniumAddress: 'http://localhost:4444/wd/hub',
      specs: ['test-spec.js']
    };

test-spec.js
describe('Protractor Demo App', function() {
    it('should have a title', function() {
        browser.get('http://juliemr.github.io/protractor-demo/');
        expect(browser.getTitle()).toEqual('Super Calculator');
    });
});

When I run protactor protractor configuration.js I'm getting the following error:
[15:15:13] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
DEPRECATION: Setting randomizeTests directly is deprecated, please use the random option in `configure`
DEPRECATION: Setting specFilter directly on Env is deprecated, please use the specFilter option in `configure`
Started
F

Failures:
1) Protractor Demo App should have a title
  Message:
    Expected [object Promise] to equal 'Super Calculator'.
  Stack:
    Error: Expected [object Promise] to equal 'Super Calculator'.
        at
        at UserContext. (/home/srubio/Escritorio/Protractor/test-spec.js:5:32)
        at

1 spec, 1 failure
Finished in 0.009 seconds
/home/srubio/n/lib/node_modules/protractor/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:3190
        throw arguments[0];
        ^

Error: Error while waiting for Protractor to sync with the page: "both angularJS testability and angular testability are undefined.  This could be either because this is a non-angular page or because your test involves client-side navigation, which can interfere with Protractor's bootstrapping.  See http://git.io/v4gXM for details"
    at ProtractorBrowser. (/home/srubio/n/lib/node_modules/protractor/built/browser.js:354:27)
    at Generator.next ()
    at fulfilled (/home/srubio/n/lib/node_modules/protractor/built/browser.js:4:58)
    at processTicksAndRejections (internal/process/next_tick.js:81:5)

A: Updating this answer
Protractor version 6.0 uses selenium version 4 which is the first selenium version to drop support for the control flow. The control flow was what allowed Protractor to execute code like
browser.get('http://google.com');
expect(browser.getTitle()).toEqual('Super Calculator');

in a synchronous manner.
The control flow was used until now in order to handle the asynchronous nature of webdriverJS's promises in a user-friendly manner. Once the es8 async/await style of promise handling became supported however the decision was made to deprecate the control flow and advise users to leverage async/await going forward.

original answer
6.0 is the latest version of Protractor, I believe it was released 3 days ago (around 22/March/19), and it drops support for the control flow which was previously enabled by default. Apparently the tutorial documentation has not been updated to reflect this however and I believe this is why you are seeing this issue.
Going forward you will need to use the async/await syntax (which is actually much more readable and easy to use in my opinion)
Try the following code:
configuration.js
exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['test-spec.js']
};

test-spec.js
describe('Protractor Demo App', function() {
    it('should have a title', async function() {
        await browser.get('http://juliemr.github.io/protractor-demo/');
        expect(await browser.getTitle()).toEqual('Super Calculator');
    });
});

Update:
If you try adding SELENIUM_PROMISE_MANAGER: true, to your configuration.js that may allow you to proceed with the demo as it is written.


text:
Q: Cant resolve linker error using templates by not adding function to the header I have this function defined in header:
template<typename T>
void GfxDevice::BindConstantBuffer(unsigned int stage, GfxConstantBuffer<T>* constantBuffer, unsigned int binding)
{
    GfxBufferResource* bufferResource = constantBuffer->GetBufferResource();
    if (!bufferResource->Initialized())
        bufferResource->Initialize();

    BindConstantBuffer(stage, bufferResource->GetBuffer(), binding);
}

I get linker error because compiler won't link Initialize() function that is defined in .cpp file. Is there any way of resolving that and that Initialize() stay in the cpp?

A: Ok, I was just being stupid by frustration that template programming gave me :)
The solution is not that complicated i just needed to pass GfxBufferResource* in the BindConstantBuffer instead of doing that stuff in template function.
So solution:
    template<typename T>
void GfxDevice::BindConstantBuffer(unsigned int stage, GfxConstantBuffer<T>* constantBuffer, unsigned int binding)
{
    BindConstantBuffer(stage, constantBuffer->GetBufferResource(), binding);
}

and make BindConstantBuffer in GfxDevice that will receive GfxBufferResource and do it there.


text:
Q: Pointer to QVector of pointers I  have a pointer to the QVector of pointers. I need to pass "trigger" as a reference.
I have this in header:
public:
    QVector<Trigger*>* triggers;

What do I have to input where ??? are (triggers[i] is not ok):
void FastViveLoop::solveTriggers()
{
    for(int i = 0; i < triggers->count(); ++i)
    {
        bool on, off;
        on = checkOn(???);
    }
}

bool FastViveLoop::checkOn(Trigger &trigger)
{

    return false;
}

A: I don't like that you are storing a QVector as a pointer,
this is not how this class should be used.
But since you are, there's an easy way to solve your issue.
void FastViveLoop::solveTriggers()
{
    for(auto item : (*trigger))
    {
        bool on, off;
        on = checkOn(item);
    }
}

Use use the range-based for with the value of the QVector.


text:
Q: How do I configure npm packages using a package list? Like Bower I'm a big fan of bower. I don't need to put a stack of packages in my repository, I just commit bower.json each time and I'm done.
So my question really is, can I make npm read from a json file in the same way that bower does?

A: npm has package.json. This file has dependencies and devDependencies parts. You can use this file similar to bower.json.
npm install

will install necessary dependencies to your project's node_modules directory.
See sample package.json below.
{
  "name": "SampleMobileApp",
  "version": "0.0.1",
  "description": "Sample App",
  "dependencies": {
    "grunt": "~0.4.2",
  },
  "devDependencies": {
    "grunt": "~0.4.2",
    "grunt-contrib-jshint": "~0.8.0",
    "grunt-open": "~0.2.3",
    "grunt-contrib-copy": "~0.5.0",
    "grunt-bowercopy": "~0.7.1",
    "grunt-contrib-watch": "~0.5.3",
    "grunt-phonegap": "~0.12.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "grunt",
    "javascript"
  ],
  "author": "Atilla Ozgur",
  "license": "MIT",
}

dependencies are your runtime dependencies that your users need to download while devDependencies are your developer dependencies like your test runtime, grunt helper packages etc.


text:
Q: Updating Rails view from JS using remote = true I have this code in a Rails view:
(a little simplified to fit in a question)
<%= link_to "FAV", :action => 'make_fav',
    remote: true,  data: {old_state: "NOTFAV",
    product: product.id} %>

which works and calls a method "make_fav" in my controller. This methods updates the database and sets an instance variable @newstate = "FAV"
in make_fav.js.erb I can see that this instance variable is set
<% puts "Newstate is #{@newstate}" %>

in my index.html.erb, I have
<td id='<%= "favourite-#{product.id}" %>' >
  <% if current_user.products.exists?(product.id) %>

  <% else %>

  <% end %>

Now how should I (in make_fav.js.erb) update the td with id "favourite-#{product.id}" to reflect the @newstate variable?
I have tried things like
<% @key = "#favourite-#{@product.id}" %>
<% x = "" %>

$('<%= @key %>').html("<%= escape_javascript (x) %>");

but as you can see, I'm at a loss when it comes to javascript...
Basically, I want to update the  content to

if @newstate is "FAV", and else

I feel like I'm close, but would appreciate any help!
Also, if there is a better/more "railsy" way of doing it, I would like to hear about it.

A: Your reasoning is not too far from the solution. It seems like you are correctly calculating the id of the element you want to find, but you want to update the i element within that ID. So a small change on your make_fav.js.erb could do the trick. Try changing to:
(function() {
  var id = "#favourite-<%= @product.id %> i";
  if ($(id).hasClass('fa-star-o')) {
    $(id).addClass('fa-star').removeClass('fa-star-o');
  } else {
    $(id).addClass('fa-star-o').removeClass('fa-star');
  }
})();

In this solution, we first define the selector of the i you want to find (which is the i within the favourite-id and swap the class (if it was fa-star it goes to fa-star-o and vice versa).
Note that instead of using $(id).hasClass('fa-star-o') in that condition, you should use the new state of the data (I just didn't know how it'd look like your particular case), but the make_fav.js.erb could look like:
(function() {
  var id = "#favourite-<%= @product.id %> i";
  <% if current_user.products.exists?(product.id) %>
    $(id).addClass('fa-star').removeClass('fa-star-o');
  <% else %>
    $(id).addClass('fa-star-o').removeClass('fa-star');
  <% end %>
})();

That would be the preferred way, because you're not relying on the state of UI, but on the state of the data.


text:
Q: How to configure Vim so that CapsLock is only enabled in INSERT mode I want to disable Capslock functionality in Visual Mode. How can I do that?
Ex:

*

*In Insert Mode, Capslock=On, A should print A.

*In Visual Mode, Capslock=On, A should trigger append text after cursor (not append text to end of current line)

A: What did you mean by "append to next character" in visual selection?
In your vimrc file or vim session, do following (for command mode):
:map A a

If you just meant that selection should be ended and you must be able to append characters at end of the current position, do:
:map A Ctrl+VEsca
Bingo!


text:
Q: How to only show files with custom extension in file chooser on Android? I've seen the same question posted here: Android - how to only show(or able to select) files with a custom extension when calling "file selector" using Intent.ACTION_GET_CONTENT but they did not manage to solve it.
I want to force the user to pick a file with a custom extension .xyz from the file chooser. The intent is created something like this:
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = <what goes here?>

Is that possible to do?
If not, is there any alternative - like searching through the external storage to find all files with that file ending and return the data (collection of files) in the same manner an intent would do?


text:
Q: Show explicitly $X \to CX$ is Cofibration Let $X$ be topological space and
$$CX:=(X\times [0;1]) / (X \times \{0\})$$
it's cone. $X$ can via identification $X \cong X \times \{1\}$ be enbedded into $CX$.
I wan't to show explicitely that $i:X \to CX$ is a cofibration by writing concretely the morphism $$m: CX \to Y^I$$
commutating with the morphisms in following diagram:
$$
\require{AMScd}
\begin{CD}
X  @>{H}  >> Y^I   \\
@VViV  @VVev_0V   \\
CX @>{f}>> Y
\end{CD}
$$
Indeed I know that there are a lot of ways to show implicitely that $i$ is a cofibration.
But here I'm interested in the concrete shape of the map $m$.

A: To set conventions: I will define $CX = X\times I /X\times \{0\}$, I will identify $X \cong X\times \{1\} \subset CX$. We define a retraction $r: CX \times I \to (X\times I) \cup (CX \times \{0\})$ as follows:
$$r(((x,s),t))=
\begin{cases}
((x,1), t-2 +2s) & \text{if}\ \ \  1-\frac{1}{2}t\le s \le 1\\
((x, \frac{2s}{2-t}),0)& \text{if}\ \ \  0 \le s \le 1-\frac{1}{2}t
\end{cases}$$
It is necessary to check that the function is well defined, though in that case it is clearly continuous. One also needs to check that it is a retraction.
Doing the case of $X = \{*\}$ by drawing a picture of a square and visualizing the retraction onto the left and top edge gives the idea for the formulas.
There is a more sophisticated approach to this type of thing using NDR pairs, and it is fairly easy to prove that $(CX, X)$ is an NDR pair. One advantage is it works out such formulas behind the scenes.
Finally, once you have obtained $r$, how do you obtain $m: CX\to Y^I$? First, note that $H: X\to Y^I$ defines by duality a map $H':X\times I \to Y$ given by $H'(x,t) = H(x)(t)$. The map $f: CX\to Y$ can be viewed as a map $f': CX\times \{0\} \to Y$ in the obvious way, by identification. Thus, we obtain a map $H'\cup f' : (X\times I) \cup (CX \times \{0\}) \to Y$, which agrees on the overlap by the commutativity of your diagram above. Therefore, $H'\cup f'$ is continuous. Now, define $m': CX\times I \to Y$ by $m' = (H'\cup f') \circ r$. The dual map $m: CX \to Y^I$ is the map $m$ you seek. For clarity, the map $m$ is defined by $m((x,s))(t) = m'((x,s),t)$. Hopefully, this clarifies the connection between the retraction and the lifting problem above.


text:
Q: D3 and angularjs radio button intergation I want to add few radio button like shown below in the legend of my this http://jsfiddle.net/nikunj2512/phsdeq4v/ D3 chart. So that when i click on any radio button it should call the function defined in the controller to fetch the data and then update the chart.

Also, this date should be customize-able, so that i can pass something like config while calling the d3Chart directive and according to my config, code should add appropriate number of radio buttons.
My problems:
1) get the value of the clicked radio button and pass the value of selected radio button & call a appropriate function in the controller?
Please anyone has any idea how to achieve this?

A: Please check this link..iCheck
U can easily integrate with angulerjs using directives. Pls check below ex.
angular.module('test').directive('icheck', ['$timeout', '$parse',function($timeout, $parse) {
return {
    require: 'ngModel',
    link: function($scope, element, $attrs, ngModel) {
        return $timeout(function() {
            var value = $attrs['value'];
            $scope.$watch($attrs['ngModel'], function(newValue){
                $(element).iCheck('update');
            })

            $scope.$watch($attrs['ngDisabled'], function(newValue) {
                $(element).iCheck(newValue ? 'disable':'enable');
                $(element).iCheck('update');
            })

            return $(element).iCheck({
                checkboxClass: 'icheckbox_square-green',
                radioClass: 'iradio_square-green'
            }).on('ifChanged', function(event) {
                if ($(element).attr('type') === 'checkbox' && $attrs['ngModel']) {
                    $scope.$apply(function() {
                        return ngModel.$setViewValue(event.target.checked);
                    });
                }
                if ($(element).attr('type') === 'radio' && $attrs['ngModel']) {
                    return $scope.$apply(function() {
                        return ngModel.$setViewValue(value);
                    });
                }
            });
        });
    }
};

}]);
and use it in UI like..
<input type="checkbox" icheck name="Check" ng-model="checkConfig" ng-change="updateMode()"/>


text:
Q: In boost::posix_time, how to construct time_duration from volatile time_duration? I'm trying to compile this code:
#include <boost/date_time.hpp>
using boost::posix_time::time_duration;
int main()
{
  volatile time_duration t0;
  time_duration t1 = t0;
  return 0;
}

With this command:
g++ test01.cpp -std=c++11 -I /boost_1_55_0/ -o test01

And I get this error:

test01.cpp:6:22: error: no matching function for call to 'boost::posix_time::time_duration::time_duration(volatile boost::posix_time::time_duration&)

I'm using gcc 4.8.2; any idea how to fix this?

A: This is due to a GCC bug. Workaround it like so:
volatile time_duration t0;
time_duration t1 = const_cast<time_duration&>(t0);

It works because const_cast can remove volatility as well as constness. I'm not sure how strictly safe this is, mind you.
An alternative fix is to get rid of the volatile in the first place; it very rarely serves any purpose nowadays.


text:
Q: Android App compiled on AOSP can't be installed in lower sdk-version emulator I downloaded the newest source code of Android form git,
and I managed to compile the source code and made a SDK and a emulator with the verison AOSP.
Then I tried to modified the source code of LatinIME the input-method and managed to compile and run on the emulator compiled along with the code of version AOSP.
Then I want to install the apk to my phone whose sdk-version is 2.2, and the error appeared to say my sdk-version is too low.
I'm sure I've add the <uses-sdk android:minSdkVersion="8" /> in the manifest node in AndroidManifest.xml , but it still needs the AOSP version to install.
Is that means I will have to repo the 2.2 version source code to compile the apk so it can fit my phone?

A: OK, I'm answering my own question again, I can't understand why my questions always rarely answered.
However I searched the whole Internet and can find a answer, but in luck I saw this:
version_defaults.mk of API Key 7
I simply replaced the android/build/core/version_defaults.mk in my downloaded code tree and re-compiled the module, and it worked!
Thought I don't know if it will work all modules in the source code, but however my IME works good.

A: Why have you added in the manifest the min sdk version? I don't think you have added features compatible only for froyo or newer.
The original manifest http://www.google.com/codesearch/p?hl=it#cZwlSNS7aEw/packages/inputmethods/LatinIME/java/AndroidManifest.xml&q=latinime&d=2
deos not have a min sdk version. Try to remove it.


text:
Q: How do I read data from a Json file discord.py How do I read data from a json file in a pyhton file
json file:
    {
        "bot-token": "BotTokenHere",
        "OwnerDiscordName": "UsernameAndTag"
    }

I'm trying to get data from a file called config.json and put it into a python variable the python file is call bot.py

A: You have to load the file content through json lib:
import json
with open("config.json") as f:
    data = json.load(f)

Then you can acess the items by dict indexing:
token = data["bot-token"]


text:
Q: How to dynamically add multiple values to a single key in HashMap? I want to add multiple card values to a distinct single key in HashMap at run time
if i give an input like this
s 2
d 5
s 3
d 7
s 4

it should give an output like
s 2 3 4
d 5 7

A: Hint: For this you need to use ArrayList as values and String as keys in HashMap. Here is an example:
HashMap<String, ArrayList<Integer>> myMap = new HashMap<>();
ArrayList<Integer> list = new ArrayList<>();
list.add(2);
list.add(3);
list.add(4);
myMap.put("s", list);

If there are n key, then to dynamically add values to each key, you can do following:
//1. Get the value (list here) for the key you want to add new values.

ArrayList<Integer> myList =  myMap.get("s");

//2. Check if myList is null
if(myList==null){
    myList = new ArrayList<Integer>();
}

//3. Now add the values to this list.

myList.add(5);

A: if you don't wanna get your hands dirty and instead rely on bulletproof 3rd party library classes check the following classes, that should do the work:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/MultiValueMap.html
https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/MultiValueMap.html
https://google.github.io/guava/releases/21.0/api/docs/com/google/common/collect/Multimap.html