text:
Q: Universally skip validation params on required inputs How to make some button which can skip web required validation(but still I want to process all data, so immediate and so on cannot be true).
Important is that it must be universal. At the moment I am using in every required field condition with some request param. Code example below

   <f:param name="onlySave" value="true"/>

This solution is fine cause I can in every page just add this param to button and it skips validation, but when my save button not making any redirect, in case of failed some java validation in save method, I am just adding some message without redirect and then I lost all required styles from inputs.
Is there any possibility to set onlySave param to null in save method when validation failed or maybe some better solutions?
Edit: Balus answer great, but with bean validation like:
@Pattern(regexp = "^([^0-9]*)$", message = "only non numbers")
String field;

It processes to bean all data beyond that field. The best would be ignore only required field property, not validation etc.
Edit2:

        <cc:insertChildren/> --here component with componentId

A: Please see below modified code for required fields. You can use #{empty param.onlySave} for the fields which you want to skip the validation and as per your requirements.

   <f:param name="onlySave" value="true"/>

A: So far the best solution i figured out is:
//p:label and p:message with property for=someId for each input above

   <f:param name="onlySave" value="true"/>

The save button just updates only all errors and labels, so I am able to see converters errors etc, but I dont lost required styles on inputs. In this example I just lost red color of input borders.
If u re using * in labels for required fields, dont update .ui-outputlabel

A: I figured out a solution :
JSF page
<h:form id="form" prependId="false">
            <c:if test="#{param['onlySave'] eq  true}">
                <c:set  value="#{false}"  target="#{myBean}" property="required"/>
            </c:if>

        </h:form>

Bean
@ManagedBean
@ViewScoped
public class MyBean implements  Serializable{

    private String data1, data2, data3;
    private boolean required;

    @PostConstruct
    public void init(){
        required = true;
    }

    public void save() {
        System.out.println(data1+", "+data2+", "+data3);
        required = false;
        //FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","Saved"));
       //  FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("onlySave", "false");// FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("onlySave"));
    }

// ... Getters & Setters
}


text:
Q: Expired FB token in Parse User table is not updated Once a user's token expires (either because of the expiration date or because the app was removed from the FB apps list) any graph request generates an error (in my case error 190) because of the invalid token.
If the user tries to log in again I get a new token but that token does not get stored in the parse User table. For the login I use:
PFFacebookUtils.logInInBackground(withReadPermissions: permissions) {(returnedUser, error) in

I'm expecting Parse SDK to update the AuthData entry for that user with the new token and expiration date but that's not happening. Any idea why is that?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to automatically back up and archive my photo library? I have a Macbook Air. I love it, but the hard drive is too small to fit my entire photo library. At this point the hard-drive is full and I need to find a way to move the files to a back-up location. I know I could just buy an external hard drive and move the files manually, but I would rather find a way where I could automate the process of backing up and moving older photos (or better yet, photos not recently viewed) to an external hard-drive and a remote backup location. I know of a few services that will automatically back up the photos (if I remember to leave the app running) but they don't remove the files, and I have no way of knowing which files have successfully been backed up and/or could be restored if I wanted to. So I don't feel like I have enough confidence in my backups to feel like I can delete the files to clear up space.
So I'm wondering if you know of a way to automate this process.

A: iCloud Photo Library would achieve a very similar end result.
In Photos, click Photos > Preferences, choose the iCloud tab and enable iCloud Photo Library.
If you turn on Optimise Storage, iCloud Photo Library will automatically manage the size of your library on your Mac. All of your original photos and videos are stored in iCloud while thumbnails are kept on your Mac. You can download the original photos and videos when you need them.
Note that your photos would no longer be stored in any backup you make, but iCloud Photo Library does keep deleted photos and videos for about a month.


text:
Q: State Diagram with two inputs For a lab exercise I have to design a 2-input sequence and I'm struggling with the state diagram, as It has 2 inputs, A,B and it says that in the start if we have same values the exit Y=1 and Y=0 when are different. When it finds 3 continuously same values of inputs the exit will reverse. So what can I do?
is this diagram state correct?

A: You will need 6 states for this, 3 to correspond to 0 output, 3 for 1.  So your state diagram and truth table are wrong.
And there is a slight advantage if you pick the 6 (of 8) states properly.
This should get you started in the right direction.


text:
Q: Should NpgSql Datetime bind parameters be switching Datetime.Kind value? I'm using Npgsql.EntityFramework (2.2.7) to interact with a new PostgreSQL (9.6.2) database installed on windows server 2012.  I am experiencing some unexpected behavior while querying the database with parameters of type DateTime. At the time I am supply EF the parameters for the query, they are bound with DateTime.Kind = UTC.  However, when I look at the parameters using an IDbCommandInterceptor, the parameter values are actually bound as DateTime.Kind = Unknown.  This is currently causing issues for me as I use the interceptor to ensure that any dates that are inserted/updated/queried against the database are of Kind = UTC to ensure consistent date storage.  This works fine with an Oracle database using the Oracle-supplied entity framework driver.  I read the documentation at http://www.npgsql.org/doc/types/datetime.html and I was led to believe that the value should be unchanged upon binding.  Is this a bug that the Datetime.Kind is being changed within the npgsql driver?  Or is this expected behavior?  If expected, why?
Thanks in advance!


text:
Q: Connection pool problem with Spring and programmatic transaction management I need your help in order to solve connection pool problem with Spring.
I'm using Spring with Java 1.4 (no annotation).
Here is the datasource and the connection pool definition:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName">
        <value>${database.jdbcName}</value>
    </property>
    <property name="url" value="jdbc:sybase:${database.url}">
    </property>
    <property name="username">
        <value>${database.username}</value>
    </property>
    <property name="password">
        <value>${database.password}</value>
    </property>
    <property name="maxActive">
         <value>${database.maxActive}</value>
    </property>
    <property name="maxIdle" >
         <value>${database.maxIdle}</value>
    </property>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource">
        <ref bean="dataSource" />
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.SybaseDialect</prop>
            <prop key="show_sql">true</prop>
            <prop key="hibernate.connection.release_mode">after_transaction</prop>
            <prop key="hibernate.dbcp.maxWait">100000</prop>
            <prop key="hibernate.connection.autocommit">false</prop>
            <prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
        </props>
    </property>
    ...

When all the connections are active, if the system need a new connection I got a message saying "opening JDBC connection" and all the process are stopped. I don't understand why all the threads are locked.
All services and DAO classes are defined as singletons in Spring application context.
Any idea?
Thanks for your help.
Béranger

A: What values are you using for maxActive and maxIdle? I can give you a more definitive answer if I know those values, but in the meantime you can also try changing the value of hibernate.dbcp.maxWait from 100000 to 1 and test your application again.
Also make sure you haven't you accidentally made some of your DAO methods synchronized.

A: This was a weird one but I finally solved my problem.
The reason of this connection locking was that I used both declarative and programmatic transaction management with Spring. I think that my programmatic transaction management was wrong.
Here is the code used to begin a transaction:
//Return Spring context
ApplicationContext context = ApplicationContextHolder.getContext();
// transactionManager
PlatformTransactionManager transactionManager = (PlatformTransactionManager) context.getBean("txManager");
//Set propagation required
DefaultTransactionDefinition td = new DefaultTransactionDefinition();
td.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
// Begin
TransactionStatus transactionStatus = transactionManager.getTransaction(td);

As you can see I set the programmatic transactions as "required". But when those transactions were started in a transactional context, Spring didn't recognized the current transaction and started a new one.  It leaded to a connection locking...
I solved this mystery by removing the programmatic transaction management.


text:
Q: Drawble , почему для xxhdpi экрана коэффициент масштабирования 2,5 а не 3? Вот для удобства: https://gyazo.com/695dea42c3667aea2cbba9ee8ced928f
        Есть эмулятор с разрешением экрана 1080x1920 ,  5,5 дюймов, а значит плотность пикселей 400. Я добавил в папку изображение шириной 1080 px и андроид при загрузке изображения в битмап уменьшил  ширину до 900 пикселей.
Вот параметры экрана который выдаются при выполнении:
   DisplayMetrics metrics = getResources().getDisplayMetrics();
   System.out.println("РаЗМЕР" + metrics);

Параметры
 DisplayMetrics{density=2.5, width=1080, height=1800, scaledDensity=2.5, xdpi=400.0, ydpi=400.0}

Почему то density 2,5 вместо 3 для xxhdpi (плотность от 400 до 560 пикселей на дюйм)
Берем 1080 делим на 3, и получаем размер Mdpi изображения 1080/3 = 360. Коэффициент масштабирования 2,5 (почему то) . Умножаем : 2,5 *360 = 900 . Становится понятно почему изображение сжалось . Хотя экран Телефона имеет разрешение 1920x1080 и диагональ 5,5 вместо коэффициента масштабирования  3 , андроид использует 2,5 . Вопрос : Почему ?
Объявил и инициализировал
Bitmap field;
field = BitmapFactory.decodeResource(getResources(),R.drawable.gamefield);
System.out.println("ширина  "+field.getWidth());

размер изображения становится меньше, чем того ,что лежит в папке drawble-xxhdpi

A: За значение density = 1 принимается размер экрана 160dpi. Ваш размер экрана - 400dpi. Соответственно получаем: 400/160 = 2.5. При этом данный параметр вычисляется из значения текущей плотности пикселей устройства и никак не связан с такими понятиями, как экран XXHDPI
Сама по себе загрузка изображения в Bitmap не должна приводить к изменению размера изображения в пикселях, поэтому стоит учесть следующее:
Папка /drawable не читается по умолчанию, как -mdpi -  ресурсы этой папки берутся "по умолчанию", когда нет более точного соответствия текущего экрана с каким либо квалификатором.
Далее, на вашем скриншоте указаны коэффициенты пропорционального увеличения размера изображения программистом, для наиболее приемлемого отображения на экранах с определенной плотностью, а не коэффициенты увеличения устройством. То есть, если изображение для экрана MDPI у вас имеет размер 100х100 пикселей, то чтобы оно так же (приблизительно) смотрелость и на экране XXHDPI, то в папку /drawable-xxhdpi нужно поместить аналогичное изображение, но размером 300х300 пикселей. Вот что значит эта таблица.
Изображения в папках ресурсов не масштабируются в назначенную квалификатором плотность. То есть, изображение из папки с квалификатором -xxhdpi не увеличивается в 3 раза, а наоборот, изображение в такой папке должно быть в три раза больше, чем в папке -mdpi изначально (при подготовке ресурсов) - эту работу делает программист, а не система.
В любом случае, какого бы размера не были ваши изображения, они не будут масштабироваться от размещения в папках квалификаторов и будут выводиться на экран "как есть". Единственная функция квалификатора - указать системе, что если плотность, к примеру, 400dpi, то картинку брать из папки с квалификатором -xxhdpi, если она есть (а не увеличивать ее в 2,5 , 3 или сколько ли бы ни было раз). Если подходящего квалификатора нет, то брать из папки /drawable. При этом, если в папки поместить одинаковые изображения (по размерам в пикселях), то на одном и том же  экране они будут выглядеть одинаково.
Проблемы не соответствия связаны с разметкой, которая масштабирует исходное изображение под размеры виджета на экране, параметров масштабирования, установленных для этого виджета и реальными размерами рабочего экрана (в котором не учитывается место, занятое навигационной панелью для телефонов без мех.кнопок, статусбаром и экшенбаром), но ни каким образом не с квалификаторами.
Проблемы с размерами - результат подгонки изображения под текущий экран, чтобы оно вошло целиком в отведенное виджету место с сохранением пропорций этого виджета (так как высота виджета меньше высоты всего экрана, а изображение имеет высоту, равную высоте экрана, то оно пропорционально масштабируется под виджет - уменьшение высоты приводит и к уменьшению ширины для сохранения пропорций). То есть вы пытаетесь поместить изображение 1080х1920 в виджет размером 1080х1800 (за вычетом статусбара, навигационной панели и экшенбара). Дальнейшие действия системы по размещению этого изображения будут зависеть от параметра scale в виджете (fit, center, crop и др.) - по умолчанию изображение будет подогнано под меньшую сторону, чтобы войти в виджет целиком и соответственно пропорциям уменьшится и большая сторона - получится итоговое изображение 1012х1800 пикселей. Используя другие параметры атрибута scale можно получить другие способы "вписать" изображение в виджет.
PS:Если вы рассчитываете каким то образом получить точное соответствие по пикселям изображения с экранами всевозможных устройств, то это безнадежная задача и у вас определенно ничего не получится, максимум для одного конкретного устройства с определенным набором параметров. На другом устройстве, с незначительными отличиями параметров экрана уже ничего соответствовать не будет.
Подробнее о работе квалификаторов смотрите этот ответ


text:
Q: Recording the ArcPy script execution method I have composed an ArcPy script which is run via a windows scheduler.The same script is loaded into a script tool so a user can run the process manually. I've used: get parameters as text, with or's and not's, to hard-wire the standard variables, if they are not speicifed.
ReportFolder = arcpy.GetParameterAsText(0)
if ReportFolder == '#' or not ReportFolder:
    ReportFolder = "C:\\Data\\GIS"

The process runs and during so writes to a text file log, for example:
txtFile.write("=    For ArcGIS 10.3.1: Date: "+str(timed)),txtFile.write ('\n')

I'd like to record what method was used to execute the script; was it via the windows scheduler, or by the script tool, or by a python client like PyScripter.
Is anyone aware of some form of os environment thingy that can be called by ArcPy?

A: I suggest use parameter passing to the script while you call this script using task scheduler and grab this parameter using sys module- as below
try:
    data = "=    For ArcGIS 10.3.1: Date: "+str(timed)+ sys.argv[1]+'\n'  #grab parameters passed
except:
    data = "=    For ArcGIS 10.3.1: Date: "+str(timed)+ "Arcgis tool used"+'\n'  # else arcgis tool used to run

And passing parameters to script in task scheduler is easy just add space and pass string ( like "test") as below-

A: Along a different line of thinking:
import os
ComputerName =os.getenv('COMPUTERNAME')
txtFile.write("=    Run By: "+str(ComputerName)),txtFile.write ('\n')


text:
Q: Ajax call to HTTPS failing I am trying to call my Spring-MVC controller which will be responsible to go ahead with login/authorization mechanism using Spring security.
here are the requirements

*

*Spring security need to have request from HTTPS else it will throw an error.

i followed the following tutorial to accomplish this /implementing_ajax_authentication_using_jquery.
here is my piece of Jquery code
jQuery("#loginForm").submit(function(e) {
        e.preventDefault();
        jQuery.ajax({
            url: "https://localhost:9002/myApp/springSecurity/login.json",
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            },
            type: "POST",
            data: jQuery("#loginForm").serialize(),
            dataType: 'application/json',

            success: function(data, status) {

                if (data.loggedIn) {
                   // location.href = getHost() + '${ctx}/users';
                    //login_pannel
                    alert("jai ho");
                } else {
                    loginFailed(data);
                }
            },
            error: loginFailed
        });

    });

In order to handle  cross domain problem i have created a Filter and placed it in my web.xml with following entries
response.setHeader("Access-Control-Allow-Origin", "http://" + req.getServerName());
response.setHeader("Access-Control-Allow-Methods", "GET,POST");
response.setHeader("Access-Control-Max-Age", "360");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
response.setHeader("Access-Control-Allow-Credentials", "true");

Spring Controller
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public SpringSecurityLoginStatus login(@RequestParam("j_username") final String username,
            @RequestParam("j_password") final String password, final HttpServletRequest request, final HttpServletResponse response)
    {

        LOG.info("Starting login process");
        return springSecurityLoginService.login(username, password, request, response);
    }

But i am undergoing a strange problem, when i am hitting the submit button, browser is sending request to the secure URL like https://localhost:9002/myApp/springSecurity/login.json but my Controller method is never getting called and in fact this is error i saw in by Mozilla error console

After looking at the console it seems like browser is calling again with GET method which seems like a redirect.
I am not sure why this is happening and why browser is doing a redirect from HTTPS to HTTP using GET request silently
Here is the output from Mozila net pannel
    Response Headersview source
Access-Control-Allow-Cred...    true
Access-Control-Allow-Head...    x-requested-with
Access-Control-Allow-Meth...    GET,POST
Access-Control-Allow-Orig...    https://localhost
Access-Control-Max-Age  360
Content-Length  0
Date    Thu, 14 Jun 2012 11:12:36 GMT
Location    http://localhost:9001/myapp/springSecurity/login.json
Server  Apache-Coyote/1.1
Set-Cookie  _system.tenantID_=""; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/
Request Headersview source
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-us,en;q=0.5
Connection  keep-alive
Cookie  JSESSIONID=26BEEB7DC056D2A5F08D107E3D4BCDDB; __atuvc=4|22; secureGUID=60be684d748027c1f567eadead08f28771ab7d25; JSESSIONID=4E2300220697C799AF4539ABCB9108DD
Host    localhost:9002
Referer http://localhost:9001/myapp/
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0

    Response Headers From Cache
Access-Control-Allow-Cred...    true
Access-Control-Allow-Head...    x-requested-with
Access-Control-Allow-Meth...    GET,POST
Access-Control-Allow-Orig...    https://localhost
Access-Control-Max-Age  360
Content-Length  0
Date    Thu, 14 Jun 2012 11:12:36 GMT
Location    http://localhost:9001/myapp/springSecurity/login.json
Server  Apache-Coyote/1.1
Set-Cookie  _system.tenantID_=""; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/

on a side note if i change the URL http://localhost:9001/myapp/springSecurity/login.json i.e to HTTP protocol, its able to call my Controller.
Respone Class
public class SpringSecurityLoginStatus
{

    private final boolean loggedIn;
    private final String username;

    public SpringSecurityLoginStatus(final boolean loggedIn, final String username)
    {
        this.loggedIn = loggedIn;
        this.username = username;
    }

    public boolean isLoggedIn()
    {
        return loggedIn;
    }

    public String getUsername()
    {
        return username;
    }

A: It looks like you haven't implemented 'GET' method for the url 'login.json'.
If you look at your controller it implements only POST request method, but your request type is GET that is why you are getting this error.
Can you share the return value of your login method?
It looks like you are returning a 302 moved temporarily status from your login method.


text:
Q: Javascript Function Inside Dynamically Added User Control Inside Update Panel Is Not Defined I've got an ASP.NET Webforms page that is largely dynamically generated based on information received from a database. The controls get injected into an UpdatePanel. For the most part everything is working, except one control contains a javascript function that is executed when the user clicks a button inside the control. The control works perfectly on a test page, but when used inside this dynamically created page, clicking the button returns a JS console error saying that the function "is not defined" even though a page source inspection through the browser shows that it is present. Trying to execute the function through the chrome developer tools console after that control is injected onto the page gives the same error. How do I make the function available to execute?
At a high level / pseudocode it looks like the below:
<Page>
...
     <DynamicWizardControl>
          <UpdatePanel>
               <!--dyanamically injected stuff-->
               <WizardDocumentSubmissionControl>
                    <DocumentSubmissionControl ID="Attachments" runat="server">
                         <asp:Textbox ID='txtFile' runat='server'></asp:Textbox>
                         <asp:Button ID='btnAdd' runat='server' Text='Add File' />
                         <script>
                              function submitFile<%=btnAdd.ClientID%>() {
                                   alert($('#<%=txtFile.ClientID%>').val());
                              }
                         </script>
                    </DocumentSubmissionControl>
               </WizardDocumentSubmissionControl>
               <!--End Dynamically Injected Stuff-->
          </UpdatePanel>
     </DynamicWizardControl>
</Page>

Code Behind for the WizardDocumentSubmissionControl
Page_Load
Attachments.JSSubmitButton.OnClientClick = Attachments.SubmitFileJSFunctionName

Code Behind for the DocumentSubmissionControl
Public ReadOnly Property SubmitFileJSFunctionName As String
    Get
        Return "submitFile" & btnAdd.ClientID
    End Get
End Property
Public ReadOnly Property JSSubmitButton As Button
    Get
        Return btnAddJS
    End Get
End Property

A: So it seems like the dynamically injected control doesn't register the javascript to the DOM. I got it to work by using the ScriptManager.RegisterClientScriptBlock to register the entire javascript function which is something I was hoping to avoid because I feel that the JS should live inside the HTML portion of the control, not the code behind. If anyone knows of any better method, please let me know.


text:
Q: Protecting Scripting Language Source Code I'd like to protect the PHP and JavaScript program source code from the prying eyes of my client. How can I do that?

A: your javascript source is fair game I'm afraid.  You can minify it, you can obscure it and compress it but you can't hide it.
if you are storing PHP files on your clients server, then this issue will be difficult to overcome also.
Apparently there are some PHP encrypters available but they have an adverse affect on performance.
So yeah, not much you can do really.  Especially if your client is technically savvy.

A: If someone has access to your source code it will always be susceptible. The best you can do is obfuscate it ala Google-JS style but it can always be reverse-engineered.
And what makes your application so special anyway? Unless it's some sort of program for something like the government I don't think you should really give a care.

A: Use a javascript obfuscator.
Jasob :: JavaScript Obfuscator - CSS Obfuscator
Although it won't be 100% irreversible. Just makes it hard to read and understand.
For PHP
PHP Obfuscator
and
Code Eclipse

A: Given you are using a scripting language that is interpreted at runtime, your options are limited:
1) Run the most sensitive parts of your application on your own server and have the client access them over web services.
2) Code obfuscation (this is reversible with enough effort).


text:
Q: Help with a regex to parse through and grab contents of  tag in html I have a site I am trying to grab data from, and the content is laid out like this:

TestData TestData TestData

TestData1 TestData1 TestData1

I am using Java to grab the webpage's content, and am trying to parse through it like this:
        Pattern p = Pattern.compile(".*?p1' class=''>(.*?)<.*");
        Matcher m = p.matcher(data);

        //Print out regex groups to console
        System.out.println(m.group(1)) ;

But then an exception is thrown saying there is no match found...
Is my regex right? What else could possibly be going on? I am getting the html ok, but apparently there is no match for my regex...
Thanks

A: If the text elements contain multiple text lines, then it wouldn't find a match, because the dot (.) doesn't match \n (by default).
Give this a try:
 Pattern p = Pattern.compile(".*?p1' class=''>(.*?)<.*", Pattern.DOTALL);


text:
Q: Unable to automatically deploy a dotnet app to Elastic Beanstalk I'm trying to deploy a test application to EB. I'm running into an issue. I followed this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/dotnet-linux-core-tutorial.html
When I upload the test application, it fails to start. /var/log/eb-engine.log says

2022/02/07 21:59:18.585543 [ERROR] An error occurred during execution of command [app-deploy] - [CheckProcfileForDotNetCoreApplication]. Stop running the command. Error: err
or stat /var/app/staging/dotnet-core-tutorial: no such file or directory with file /var/app/staging/dotnet-core-tutorial

So I changed the parent directory in my source bundle so that it exported into /var/app/staging/dotnet-core-tutorial instead of /var/app/staging. Now I get this error

2022/02/07 22:29:51.468918 [ERROR] An error occurred during execution of command [app-deploy] - [CheckProcfileForDotNetCoreApplication]. Stop running the command. Error: the
re is no .runtimeconfig.json file for your single application. Please provide a valid application

I confirmed that the source bundle does have a .runtimeconfig.json file.

A: The .runtimeconfig.json file is generated when you run the dotnet publish -o site command, so check if this command is running properly for you.
If you take a look on the tutorial, section "To create a source bundle" you have this file, so check the steps that you already did.
Also if you want to force this file to be generated you can add set
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> directly, but this is normally needed when you are not creating executable files like class libraries.


text:
Q: How to create a column in a data frame that bins n rows of the data frame consecutively I have a data frame
    structure(list(id = c(31068L, 4741L, 31068L, 48783L, 48783L,
4741L, 40866L, 602L, 43498L, 602L, 47365L, 27643L, 30657L, 47365L,
2456L, 30657L, 48783L, 40866L, 31068L, 31068L), chrom = structure(c(10L,
2L, 10L, 18L, 18L, 2L, 1L, 12L, 15L, 12L, 3L, 14L, 13L, 3L, 5L,
13L, 18L, 1L, 10L, 10L), .Label = c("chr1", "chr10", "chr11",
"chr12", "chr13", "chr14", "chr15", "chr16", "chr17", "chr18",
"chr19", "chr2", "chr3", "chr4", "chr5", "chr6", "chr7", "chr8",
"chr9", "chrM", "chrUn", "chrX", "chrY"), class = "factor"),
    strand = structure(c(2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L,
    1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L), .Label = c("-",
    "+"), class = "factor"), position = c(32233920L, 63320175L,
    32233915L, 105252695L, 105252690L, 63320180L, 160222550L,
    60750690L, 111386910L, 60750685L, 89019895L, 155820080L,
    146439265L, 89019890L, 56738465L, 146439260L, 105252700L,
    160222545L, 32233910L, 32233925L), state = c(1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L), probability = c(0.0609068958401659, 0.0652616906258002,
    0.0692068771991058, 0.0692812165331229, 0.0701354955671266,
    0.0703768347393804, 0.0711103024384338, 0.0741845396230543,
    0.0743938664894217, 0.0749688062517259, 0.079612884618025,
    0.0813520378059492, 0.0826542716746912, 0.0846949902404464,
    0.0861396527789957, 0.0864410597153605, 0.0871058913414357,
    0.087430325878555, 0.0878512688974869, 0.0880022007028806
    ), differential = c(-0.23435362433765, -0.23435362433765,
    -0.171785943061141, 0.196483908128415, 0.251738193935959,
    -0.23435362433765, -0.23435362433765, -0.278594311118605,
    0.242648431724363, -0.278594311118605, -0.278594311118605,
    0.209140348612477, -0.28152682524624, -0.234047089198976,
    0.290374904597332, -0.242344380735883, 0.196483908128415,
    -0.23435362433765, -0.171785943061141, -0.155502764975432
    ), tag1 = c(0L, 0L, 0L, 15L, 15L, 0L, 0L, 5L, 30L, 5L, 5L,
    10L, 2L, 3L, 15L, 7L, 15L, 0L, 0L, 0L), mut1 = c(0L, 0L,
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L), tag2 = c(15L, 15L, 11L, 5L, 2L, 15L, 15L, 25L,
    15L, 25L, 25L, 0L, 21L, 19L, 0L, 25L, 5L, 15L, 11L, 10L),
    mut2 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), group = c(1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)), .Names = c("id",
"chrom", "strand", "position", "state", "probability", "differential",
"tag1", "mut1", "tag2", "mut2", "group"), class = c("data.table",
"data.frame"), row.names = c(NA, -20L), .internal.selfref = <pointer: 0x102819778>)

and I would like to create a new column df$bin such that the bin column creates bins of length n of consecutive values.
For example, if n = 2, I would want there to be 2 bins where the bin column looks like bin = c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2)
such that the values in for df$bin would be 1:n and each value would be repeated nrow(df)/n times.

A: You can use the base R function cut for this:
df$bin = cut(1:nrow(df), breaks = 2, labels = FALSE)


text:
Q: JaCoCo with multi-module Maven project - Only record coverage by module owned tests We have a large Maven project with about 50 modules. Today we have a good setup where we get a combined JaCoCo coverage for the whole project. We also use the final binary generated by JaCoCo for custom coverage logic.
We would like to implement a more strict coverage policy where only tests in the same module contribute to the overall coverage. We want every module to be responsible for its own tests and coverage.
For example. Module A depends on module B. A has code that makes use of code in B. When tests in A is run, we do not want to have coverage from any class in B recorded.
Is this setup possible? Trying around, I find that JaCoCo has many options for filtering when generating the final report, but I'd like to do this in the first step, when the coverage is collected.
Eventually, I'd like to end up with a JaCoCo exec file in each module's target directory that only has classes recorded from its own module. It would be perfectly fine if we had to do some configuration on a module-by-module basis like having an explicit package expression for inclusion.

A:
Trying around, I find that JaCoCo has many options for filtering when generating the final report, but I'd like to do this in the first step, when the coverage is collected.

There is also options for filtering during collection - see includes and excludes options of JaCoCo Java Agent and corresponding options of  prepare-agent in jacoco-maven-plugin.
Build of JaCoCo itself uses them exactly for this.


text:
Q: Adding dynamic script (code, not url) from NewRelic library does not work I have to integrate NewRelic with script tag they have provided to me.
The fact is if I include it in the head, it works. But if I add it dinamically, creating a script element, append it to the head, etc, it does not work.
How do I identify if it works or not? Because that script triggers a fetch that gets another javascript in a request.
I'm trying to understand why. I found another way to implement it but Im very curious about it. No errors in console. I guess it is a minified version, and also probably compiled version (Not Es6), but it should work.


text:
Q: Can WCF Data Service cascade update an object down to it's children? example:
Parent
class Product
{
    int id {get; set;}
    string title {get; set;}
    Location loc {get; set;}
}

Child
class Location
{
    int id {get; set;}
    int CityID {get; set;}
}

Can I update Product and Location, send Product to the WCF Data Service method "Update"?
The Product gets updated, but not the Child! And yes the EntityData model on the other end of the WCF Service is set up with all relations Managed.

A: Deep update is not supported in the OData protocol. Deep insert is supported, although not by WCF Data Services. You can batch the changes and send one payload by calling something like context.SaveChanges(SaveChangesOptions.Batch);, but be aware that not all services support batch and may return a 405 Method Not Allowed.


text:
Q: How to cause validation when clicking on a ToolStripButton Menu from a MDI in Windows Form Application? I have a ContextMenuStrip with a ToolStripButtonMenu "Print".
A MDI child form is open containing a DataGridView. I am doing a validation to an editable column "Copies" in that grid. I don't want the user to input letters for example. The validation is working fine when leaving the cell but if I am clicking on a control such as the "Print" button, the validation is not caused.
The following screen shot shows how I can click on the "Print" button while the Copies cell contains letters:

// The code for the cell validation
private void QuantitiesDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        if (e.ColumnIndex == QuantitiesDataGridView.Columns[COL_COPIES].Index)
        {
            QuantitiesDataGridView.Rows[e.RowIndex].ErrorText = "";
            int enteredValue;

            if (!int.TryParse(e.FormattedValue.ToString(), out enteredValue) || enteredValue < 1)
            {
                e.Cancel = true;
                QuantitiesDataGridView.Rows[e.RowIndex].ErrorText = "Invalid number of copies";
            }
        }
    }

I was looking for a property of the ToolStripButtonMenu such as CauseValidation but there is not such one.
Is there a way to trigger the validation when clicking on one of the ToolStripButtonMenu so the Print button will not be triggered until the Copies value is valid?

A: In your ToolStripButton's Click method, try calling the active form's ValidateChildren function:
private void toolStripButton1_Click(object sender, EventArgs e) {
  if (this.ActiveMdiChild.ValidateChildren()) {
    // do your processing ...
  }
}


text:
Q: I'm not getting reputation from all votes
Possible Duplicates:
Missing credits for answer
What is the daily reputation cap and how can I hit it?
How does "Reputation" work?

I am seeing something a little odd in my Stack Overflow reputation, specifically on question If Java's garbage collector moves objects, what is Object.hashCode and System.identityHashCode?. I have 7 up-votes and an accepted answer, but my reputation graph for today only shows 20 points for up-votes and 15 for the accepted answer.
What's up? Is there a better way to report this?

A: You have already exceeded your reputation limit for today (200 reputation from question and answer votes) after the first two upvotes. Any remaining votes today don't give you any reputation.
However, you can still earn reputation above the limit for accepted answers and bounties.


text:
Q: Split a string, sort it, then concatenate the resulting splits in SPARQL I am trying to split a string based on a specific character, and then order the resulting strings depending on some specific order and then concatenate them into a new string.
Example: consider numeric order and - as a separator
1-5-2-3 should become 1-2-3-5.
Is there any way to achieve that?
My first try is splitting using regular expressions and then compare the results each resulting split with its next, however, this does not work as there is no way to store the intermediate resulting string.
SELECT ?url ?url1

WHERE {

  BIND ("1-2-3" as ?urls)
  VALUES ?n {0 1 2  } # Split at most 10 URLs mangled together
  VALUES ?m {0 1 2  }

  BIND (concat("^((.+?-)?){", str(?n) ,"} *") AS ?newvar)
  BIND (replace(?urls, ?newvar, "") AS ?remaining)
  BIND (replace(?remaining, "-.+", "") AS ?url)

  BIND (concat("^((.+?-)?){", str(?n + 1) ,"} *") AS ?newvar1)
  BIND (replace(?urls, ?newvar1, "") AS ?remaining1)
  BIND (replace(?remaining1, "-.+", "") AS ?url1)

}


text:
Q: Evaluate expression(in postfix notation) using concrete stack in C If the user enter 235+*, the result will be 16.
#include <stdio.h>
#include <stdlib.h>

#define MAX 100

struct Stacks
{
    int top;
    unsigned cap;
    int* array;
};

struct Stacks* createStacks(unsigned cap)
{
    struct Stacks* stack = malloc(sizeof(struct Stacks));
    stack->cap = cap;
    stack->top = -1;
    stack->array = malloc(stack->cap * sizeof(int));
    return stack;
}

int isEmpty(struct Stacks* stack)
{
    return stack->top == -1;
}

int isFull(struct Stacks* stack)
{
    return stack->top == stack->cap - 1;
}

void push(struct Stacks* stack, int item)
{
    if (isFull(stack))
        return;
    stack->array[++stack->top] = item;
    printf("%d has been pushed to stack\n", item);
}

int pop(struct Stacks* stack)
{
    if (isEmpty(stack))
        return 0;
    return stack->array[stack->top--];
}

int showTop(struct Stacks* stack)
{
    if (isEmpty(stack))
        return 0;
    return stack->array[stack->top];
}

int isOperand(char ch)
{
    if ((ch>='a'&&ch<='z') || (ch>='A'&&ch<='Z'))
        return 1;
    else
        return 0;
}

int main()
{
    struct Stacks* stack = createStacks(MAX);
    char postfix[MAX], ch;
    int i = 0, op1, op2, result, m;

    printf("Please enter a postfix expression: \n");
    fgets(postfix, MAX, stdin);
    while (postfix[i] != '\0')
    {
        ch = postfix[i];
        if (isOperand(ch) == 1)
        {
            printf("Enter the value of %c:", ch);
            scanf("%d", &m);
            push(stack, m);
        }
        else
        {
            op2 = pop(stack);
            op1 = pop(stack);
            switch (ch)
            {
                case '+': result = op1 + op2;
                          push(stack, result);
                          break;
                case '-': result = op1 - op2;
                          push(stack, result);
                          break;
                case '*': result = op1 * op2;
                          push(stack, result);
                          break;
                case '/': result = op1 / op2;
                          push(stack, result);
                          break;
            }
        }
        i++;
   }
    printf("\nThe result is %d", showTop(stack));
    return EXIT_SUCCESS;
}

And below is the output:
Please enter a postfix expression:
abc+*
Enter the value of a:2
2 has been pushed to stack
Enter the value of b:3
3 has been pushed to stack
Enter the value of c:5
5 has been pushed to stack
8 has been pushed to stack
16 has been pushed to stack

The result is 0

Can someone help me out why result not correct, thx.

A: When you call fgets, there will be a newline included in your result (if space is available).  This results in six characters being in postfix, not five.  When that last newline character is processed, you pop two values from the stack (the second one with the stack empty) and don't push any new values.  When you print the result at the end you have an empty stack.
You add some validation to your switch (ch) statement to report unexpected characters, and add some code to ignore spaces (space, tab, newline) in the expression you are parsing.


text:
Q: Find the domain of $\arcsin\left(\frac{3-x}{\sqrt{9-x^2}}\right)$
Find the domain of
  $$\arcsin\left(\dfrac{3-x}{\sqrt{9-x^2}}\right)$$

This question is given in my book. The answer is as follows:

For the function to be defined, $-1\le3-x\le1$ and $9-x^2>0$. Solve these inequalities and take their common region.
  $$2\le x\le4\tag1$$
  $$-3 < x < 3\tag2$$

The answer is $2\le x<3$. My question is why have they not taken $-1\le\dfrac{3-x}{\sqrt{9-x^2}}\le 1$, in which case the answer would have been different. Please help.

A: You are right. For instance, $x=1$ is clearly in the domain of the function, but it isn't in the interval given in your book.
The correct domain should be :

$$x \in [0,3)$$

(For its proof, see Mr.Lab Bhattacharjee's answer)

A: For $x\ne3,\dfrac{3-x}{\sqrt{9-x^2}}=\sqrt{\dfrac{3-x}{3+x}}$
Now we need $$-1\le\sqrt{\dfrac{3-x}{3+x}}\le1\iff0\le\dfrac{3-x}{3+x}\le1$$
If $\dfrac{3-x}{3+x}=0\implies x=3\ \ \ \ (1)$
$\dfrac{3-x}{3+x}>0\iff(3-x)(3+x)>0\iff(x-3)(x+3)<0\iff-3<x<3\ \ \ \ (2)$
$\dfrac{3-x}{3+x}\le1\iff0\ge\dfrac{3-x}{3+x}-1=\dfrac{3-x-(3+x)}{3+x}=-\dfrac{2x}{3+x}$
By $(2),x+3>0,$ so we need $-2x\le0\iff x\ge0\ \ \ \ (3)$
By $(1),(2),(3):0\le x<3$


text:
Q: How to add files in solution explorer of visual studio? How to get the path of solution explorer of visual studio 2010 programmatically(Without Hard Coding)  using c# during addin development?So that we can add files under active project folder residing within solution explorer?
For example
During addin development,if we are creating a file,Visual studio saves the files in this *C:\Users\user_name\Documents\Visual Studio 2010\Projects\project_name*programatically using AppDomain.CurrentDomain.BaseDirectory;.But I want to save the file, one level ahead.i.e in
*C:\Users\user_name\Documents\Visual Studio 2010\Projects\project_name\project_name*.So I want to know how to do this programmatically(using visual studio api's) in c# ?

A: This should do
public String SolutionPath()
{
    return Path.GetDirectoryName(_applicationObject.Solution.FullName);
}

Gotten from: Visual studio addin - finding current solution folder path


text:
Q: 'void android.widget.LinearLayout.setVisibility(int)' on a null object reference when i want to display a LinearLayout I have a problem with a button that modifies the visibility of a LinearLayout
I always get the error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setVisibility(int)' on a null object reference
I have this function that creates a variable of the LinearLayout that I want to display

Exclusive_Login.java

public void showbutton(){
        LinearLayout btn_publicar = (LinearLayout) findViewById(R.id.btn_publicar);
        btn_publicar.setVisibility(View.VISIBLE);
    }

And it runs on this line

Exclusive_Login.java

ini_ses.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String obtusuario = usuario.getText().toString();
                String obtcontra = contrasena.getText().toString();
                if (obtusuario.equals("ADMIN") && obtcontra.equals("admin")){
                    showbutton();
                    Toast.makeText(getBaseContext(),"Datos Correctos",Toast.LENGTH_LONG).show();
                    //Intent accion = new Intent(getBaseContext(), BarraNavegacionDesplegable.class);
                    //startActivity(accion);

                }else{
                    Toast.makeText(getBaseContext(),"Introduzca correctamente los datos",Toast.LENGTH_LONG).show();
                }

            }
        });

This is Fragment_Home.xml where I reference the LinearLayout

Fragment_Home.xml

<LinearLayout
    android:id="@+id/btn_publicar"
    android:visibility="invisible"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:layout_margin="5dp"
    android:orientation="horizontal"
    android:gravity="center"
    android:background="@drawable/public_contenedor1">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginRight="20dp"
        app:srcCompat="@drawable/lapiz1" />

    <Button
        android:id="@+id/publicnotice1"
        android:layout_width="280dp"
        android:layout_height="45dp"
        android:background="@drawable/style_bottom"
        android:text="Crear publicaciones"
        android:textAllCaps="false"
        android:textColor="@color/black"
        android:textSize="15sp"
        android:textStyle="bold" />

</LinearLayout>

A: Try with declare the layout gobally
LinearLayout  btn_publicar;

 btn_publicar = (LinearLayout) findViewById(R.id.btn_publicar);

put it on onViewCreated.
And in the function
public void showbutton(){
        btn_publicar.setVisibility(View.VISIBLE);
    }


text:
Q: VB.net - Read .msg file from the shared folder and extract the attachments inside it I'm completely new to VB and I'm trying to extract the attachment which is saved available inside the .msg file using the below code.
Could someone help me if this is the right approach to do this ?
I'm facing below compiler errors. Could someone help me how to resolve this issue ?

*

*Outlook.Attachment is not defined.

*End Sub' must be preceded by a matching 'Sub'

*Reference to a non-shared member requires an object reference.

*Statement cannot appear within a method body. End of method assumed

*Method arguments must be enclosed in parentheses.

*Type 'Outlook.MailItem' is not defined.

Sub SaveOlAttachments()
    Dim msg As Outlook.MailItem
    Dim att As Outlook.Attachment
    Dim strFilePath As String
    Dim strAttPath As String
    Dim strFile As String

    strFilePath = "C:\Users\...\Desktop\Test\"
    strAttPath = "C:\Users\...\extracted attachment\"
    strFile = Dir(strFilePath & "<Doc Name>.msg")

    Do While Len(strFile) > 0
        msg = Application.CreateItemFromTemplate(strFilePath & strFile)
        If msg.Attachments.Count > 0 Then
            For Each att In msg.Attachments
                att.SaveAsFile strAttPath & att.FileName
            Next
        End If
        strFile = Dir
    Loop
End Sub

A: First of all, check out the file path where you try to find the template:
 msg = Application.CreateItemFromTemplate(strFilePath & strFile)

The strFilePath string may include the file name already:
strFile = Dir(strFilePath & "<Doc Name>.msg")

Second, make sure attachments are saved using unique file names:
att.SaveAsFile strAttPath & att.FileName

The FileName string can be the same in different emails. I'd recommend adding IDs or the current time and etc. to the file name to uniquely name attached files on the disk.

A: Here is the code we use to grab a daily report attachment.  I left a few commented statements in case you might need them (we didn't).
Sub Extract_Outlook_Email_Attachments()
    On Error GoTo ErrHandler
    Dim OutlookApp As Outlook.Application
    Dim OutlookNamespace As Namespace
    Dim folder As MAPIFolder
    Dim OutlookMail As Variant
    Dim i As Integer
    Dim olNS As Outlook.Namespace
    Dim objOwner As Outlook.Recipient

    Set OutlookApp = New Outlook.Application
    Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")

    Dim saveFolder As String
    saveFolder = strAttPath  ' SAVE THE ATTACHMENT TO

    'this bit is added to get a shared email
    Set objOwner = OutlookNamespace.CreateRecipient("SHARED FOLDER NAME")
    objOwner.Resolve

    If objOwner.Resolved Then
        Debug.Print "Outlook GB Fulfillment is good."
        Set folder = OutlookNamespace.GetSharedDefaultFolder(objOwner, olFolderInbox) 'can use olFolderInbox or olFolderSentMail
    End If

'Write mail to spreadsheet - create named range, from and to dates on the spreadsheet
i = 1
For Each OutlookMail In folder.Items
    '  Debug.Print "SenderEmailAddress: " & OutlookMail.SenderEmailAddress

        'If OutlookMail.SenderEmailAddress = "no-reply@OurCompany.com" Then
    If OutlookMail.subject = "Daily Report" Then
        ' If OutlookMail.SenderName = "no-reply@OurCompany.com" And OutlookMail.Subject = "Daily New Subscriber Plan Election Fulfillment" And OutlookMail.Attachments(1) = "NewSubscriberPlanElectionFulfillment_Subscription.xls" Then

        Debug.Print "Received: " & OutlookMail.ReceivedTime
        Debug.Print "Attach: " & OutlookMail.Attachments(1)
        dateformat = Format(OutlookMail.ReceivedTime, "m-d-yy")
            Debug.Print dateformat

        FName = dateformat & " " & OutlookMail.Attachments(1).fileName
            Debug.Print "FName: " & FName

        Dim strFileExists As String

        strFileExists = Dir(saveFolder & FName)

        If strFileExists = "" Then
'        MsgBox "The selected file doesn't exist"
            Else
'        MsgBox "The selected file exists"
                Exit Sub
        End If
        OutlookMail.Attachments(1).SaveAsFile saveFolder & FName

        Set outAttachment = Nothing

    End If
    Next OutlookMail

    Set folder = Nothing
    Set OutlookNamespace = Nothing
    Set OutlookApp = Nothing

ErrHandler:
    Debug.Print Err.Description
End Sub

A: Instead of using CreateItemFromTemplate, you can use Namespace.OpenSharedItem to open an MSG file.
You also need to add Outlook to your VB.Net project references.


text: Q: How to read a json object in d3 How to read a JSON object in D3 javascript library. One could read a json from file with d3.json method. Is there a way to read json object as a variable rather than reading it from file in D3 ?


text:
Q: python, dynamically implement a class onthefly this is related to python, dynamically implement a class onthefly.
when i restarted my pc, couldnt get back to add comments to the post - below is an example to explain what meant by save the class_with_the_methods_used
class bank(object):
   def __init__(self, bal=0):
       self.bal = bal
   def deposit(self, amount):
       self.bal+=amount
       print self.bal

def debit(self, amt):
   self.bal-=amt
   print self.bal

bank.debit = debit

myacct = bank()
myacct.deposit(1000) # prints 1000
myacct.debit(99) # print 901

dir(myacct) # print [ ....'bal', 'debit', 'deposit']

then i used pickle and saved the object myacct
after saving, restarted my python and tried the commands below
>>> import pickle
>>> obj = pickle.load(open('bank.pkl'))
>>> dir(obj) # prints [....'bal', 'deposit']

note that 'debit' is not among the attributes . So my problem is how to make methods like 'debit' persistent?

A: Check out the new module (http://docs.python.org/library/new.html)
It has a lot of tools for doing things dynamically. The problem you are having is debit is not a instance method, it is just a normal function. Methods defined in classes are different than functions defined outside.

A: This is due to the way pickle dumps custom classes.
>>> class Bank(object):
...     pass
...
>>> def debit(self, amt):
...     print amt
...
>>> Bank.debit = debit
>>>
>>> acct = Bank()
>>> acct.debit
<bound method Bank.debit of <__main__.Bank object at 0x023B57D0>>
>>> import pickle

Look at the following:
>>> print pickle.dumps(acct)
ccopy_reg
_reconstructor
p0
(c__main__
Bank
p1
c__builtin__
object
p2
Ntp3
Rp4
.

You'll see that in fact the entire instance isn't pickled; instead, pickle simply records that it is an instance of Bank and recreates it by re-instantiating Bank. You will have to define a custom pickle protocol if you want to do this properly, which is complicated.


text:
Q: Hibernate sess.flush() hangs I have a method loading up a persistent object and then have it updated. When I use flush(), the process hangs with no errors. Any idea?
Code:
    public Task changeStatus(Long taskNo, String status) {
    Session sess = HibernateUtil
            .getSessionFactory()
            .openSession();
    Task task = (Task) sess.load(Task.class, taskNo);

    task.setStatus(status);

    sess.flush();
    return task;
}

The log shows this:

INFO: 09:33:05,329 DEBUG Printer:83 - listing entities:
INFO: 09:33:05,329 DEBUG Printer:90 - models.Task{userByAssignedToCheck=null, client=models.Client#1, status=Withdrawn, datasets=, urgent=false, taskLogs=, userByCheckedBy=null, dateReceived=29 August 2013, dateCompleted=null, fee=null, onTime=false, userByOriginatorId=models.User#1, taskCat=null, userByAssignedToWork=null, source=null, originatorOld=null, description=null, userByCompletedBy=null, method=null, taskNo=11492, dueDate=null, requestVia=null, comments=}
INFO: 09:33:05,329 DEBUG AbstractBatcher:366 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
INFO: 09:33:05,329 DEBUG SQL:401 - /* update models.Task */ update DBAKZHU0.INFO_TASK set CLIENTNO=?, ASSIGNEDTOCHECK=?, TASKTYPENO=?, COMPLETEDBY=?, CHECKEDBY=?, ORIGINATORID=?, SOURCENO=?, ASSIGNEDTOWORK=?, METHOD=?, REQUESTVIA=?, DATERECEIVED=?, DATECOMPLETED=?, DUEDATE=?, STATUS=?, ORIGINATOROLD=?, ONTIME=?, URGENT=?, FEE=?, DESCRIPTION=? where TASKNO=?
INFO: Hibernate: /* update models.Task */ update DBAKZHU0.INFO_TASK set CLIENTNO=?, ASSIGNEDTOCHECK=?, TASKTYPENO=?, COMPLETEDBY=?, CHECKEDBY=?, ORIGINATORID=?, SOURCENO=?, ASSIGNEDTOWORK=?, METHOD=?, REQUESTVIA=?, DATERECEIVED=?, DATECOMPLETED=?, DUEDATE=?, STATUS=?, ORIGINATOROLD=?, ONTIME=?, URGENT=?, FEE=?, DESCRIPTION=? where TASKNO=?


text:
Q: Activate Windows File Explroer I thought this was easy but it seems not. I just want to activate File Explorer this way:
WinActivate ahk_exe Explorer.EXE
But it won't work. It seems that all others work just fine:
WinActivate ahk_exe chrome.exe ; works
WinActivate ahk_exe notepad++.exe ; works
WinActivate ahk_exe OUTLOOK.EXE ; works

I also tried
WinActivate "ahk_class CabinetWClass"

A: The second approach works, but you shouldn't use quotes. Try this:
WinActivate ahk_class CabinetWClass

You can also make it an expression and then you must use quotes, like this:
WinActivate % "ahk_class CabinetWClass"


text:
Q: Invalid Cast Exception was unhandled String to Integer I am about to finish my college project, so I am just really eager to finish this! after apparently finishing all of the hard bit and running the program, errors began popping up. This is the one I can't fix so far. Below see a link to the error log
http://pastebin.com/8FMjUFF5
Also, bellow you can see my code for that bit I am trying to do:
Public Sub Pizza()
    If Pizza_BaseTextBox.Text = 1 Then
        PizzaBase = 2.99
    ElseIf Pizza_BaseTextBox.Text = 2 Then
        PizzaBase = 4.99
    ElseIf Pizza_BaseTextBox.Text = 3 Then
        PizzaBase = 6.99
    ElseIf Pizza_BaseTextBox.Text = 4 Then
        PizzaBase = 8.99
    Else
        MsgBox("Please enter the correct number corresponding the pizza size you desire! See instructions")

    End If

    If CInt(Topping1TextBox.Text) > 0 And CInt(Topping1TextBox.Text) < 12 Then 'Error here
        Topping1 = 0.5
    Else
        Topping1 = 0
    End If
    If CInt(Topping2TextBox.Text) > 0 And CInt(Topping2TextBox.Text) < 12 Then
        Topping2 = 0.5
    Else
        Topping2 = 0
    End If
    If CInt(Topping3TextBox.Text) > 0 And CInt(Topping3TextBox.Text) < 12 Then
        Topping3 = 0.5
    Else
        Topping3 = 0
    End If
    If CInt(Topping4TextBox.Text) > 0 And CInt(Topping4TextBox.Text) < 12 Then
        Topping4 = 0.5
    Else
        Topping4 = 0
    End If
    If CInt(Topping5TextBox.Text) > 0 And CInt(Topping5TextBox.Text) < 12 Then
        Topping5 = 0.5
    Else
        Topping5 = 0
    End If

    PizzaTotal = PizzaBase + Topping1 + Topping2 + Topping3 + Topping4 + Topping5
End Sub

I would really appreciate it if I could receive some help about this.
Thanks a lot for the help and support, all comments are welcome.
Regards,
Jose rodriguez

A:  CInt(Topping1TextBox.Text) > 0

If the TextBox is empty CInt will throw an exception.  Since it is user input, there is always the very real possibility that it is blank or contains "ziggy" instead of numerals.
Since it is user input, we can test and convert it at once:
Dim tmp As Integer
If Integer.TryParse(Topping1TextBox.Text, tmp) = False Then
   ' display error message that the value is invalid
Else
    If tmp > 0 And tmp < 12 Then
        Topping1 = 0.5
    Else
        Topping1 = 0
    End If
End If

' repeat pattern for the others

Integer.TryParse will return a Boolean indicating whether the string/text was able to be parsed into the variable passed.  If True, then the variable will hold the value.  All the data types have this function (Decimal.TryParse etc) and there are other similar functions such as Integer.Parse and Convert.ToInt32 for different situations.
The current program logic also does not account for a "-1" in the textbox.  Usually, for something like this, a NumericUpDown is a better choice as it will force the input to be in a given range and numeric.

A: You can check each textbox to see if its contents are numeric.  If they are not numeric, then you ignore them or assign a default value.
For example:
Ignoring non-numeric:
If IsNumeric(Topping1TextBox.Text) Then
    If CInt(Topping1TextBox.Text) > 0 And CInt(Topping1TextBox.Text) < 12 Then
        Topping1 = 0.5
    Else
        Topping1 = 0
    End If
End If

Default value for non-numeric:
If IsNumeric(Topping1TextBox.Text) AndAlso CInt(Topping1TextBox.Text) > 0 AndAlso CInt(Topping1TextBox.Text) < 12 Then
    Topping1 = 0.5
Else
    Topping1 = 0
End If


text:
Q: VSTS Maven build - no JUnit tests run [Update: Problem cause found! read below]
Problem: VSTS Maven build does not seem to run JUnit, does not show any JUnit results, does not seem to produce any JUnit testreports.
In VSTS, we have a Java project with a Contact and TestContact class with 1 testcase;
source\module\src\main\java\nl\customer\model\situation\Contact.java
source\module\src\test\java\nl\customer\model\ContactTest.java
source\module\pom.xml

Running Maven from Eclipse works fine. Console shows Maven using Surefire reports, running/passing the 1 unit test.
Running the project with Maven on a Windows PC also works:
mvn test

Logging:
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Domain Model
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ module ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 30 resources
[INFO] skip non existing resourceDirectory C:\project\source\projectdomain\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ module ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ module ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\project\source\module\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ module ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.20.1:test (default-test) @ module ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running nl.customer.module.ContactTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 s - in nl.customer.module.ContactTest
[INFO]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.109 s
[INFO] Finished at: 2018-01-09T14:05:03+01:00
[INFO] Final Memory: 10M/196M
[INFO] ------------------------------------------------------------------------

In VSTS, using the Maven build step (goal: install) succeeds, but the log does not show anything about JUnit, even with system.debug = true.
Consequently, trying the "Publish test results" always fails (both when using a seperate build task or the Publish TFS option in the maven build task).

A: It seems I have found the cause of the problem: in VSTS, the Maven build task has the option
Set MAVEN_OPTS to

In our build definition, this was set to
-Xmx1024m -X

The first parameter is correct, it sets the maximum memory.
The second parameter is incorrect. If you want Maven to give debug output, you should put the "-X" parameter under Goal(s).
There is no real warning about the second parameter in the logging.


text:
Q: HTML / PHP / SQL How to display a button under certain circumstances? So I have a script using HTML, PHP, and mysql, and I want to display a button under certain circumstances.
Here is my script:
<?php
include_once('dbconnect.php');
    $q = $_POST['q'];
    $q = $_GET['query'];
    $query = mysqli_query($conn,"SELECT * FROM `Persons` WHERE `id` LIKE '%$q%'");
    $count = mysqli_num_rows($query);
    if($count != "1"){
        $output = '
No result found!
';
    }else{
        while($row = mysqli_fetch_array($query)){
        $s = $row['name'];
                $output .= '
Found: '.$s.'

';
            }
        }
?>
<!DOCTYPE html>

        <title>Search</title>

        <form method="POST" action="index.html">
            <input type="submit" name="return" value="Return">
        </form>
        <?php echo $output; ?>

Specifically, I want to display the return button only when the output is  "No results found", when the amount of rows in the SQL database matching the given query is not 1. How could I go about accomplishing this? I'm relatively new to PHP and mySQLi, but from my research I couldn't figure out how to do such a task, any ideas?

A: <?php
if ($count==0) {
 echo '<input type="submit" name="return" value="Return">';
}
?>

A: If you want a much cleaner html code, do this:
<form method="POST" action="index.html">
    <?php if ($count!= "1") : ?>
    <input type="submit" name="return" value="Return">
    <?php else : ?>

    <?php endif; ?>
</form>

You can read more about escaping from HTML here.

A: <?php
    include_once('dbconnect.php');
    $q = $_POST['q'];
    $q = $_GET['query'];
    $query = mysqli_query($conn,"SELECT * FROM `Persons` WHERE `id` LIKE '%$q%'");
    $results = mysqli_fetch_array($query);
?>
<!DOCTYPE html>

        <title>Search</title>

        <form method="POST" action="index.html">
            <input type="submit" name="return" value="Return">
        </form>
        <?php if(0 < count($results)) ?>
        <?php foreach($results AS $row) : ?>

<?= $row['name'] ?>

        <?php endforeach; ?>
        <?php else : ?>

 No results found!

        <?php endif; ?>


text:
Q: 12V relay with capacitor resistor - need some guidance I am considering using the following example
https://www.the12volt.com/relays/relaydiagram43.html
to use a 12v relay to generate a pulsed ground. However I have zero experience with capacitors, resistors etc (although i bought a bunch of resistors awhile back in case i might need them).
Anyway I am hoping someone can point me to what capacitor to use (electrolytic/ceramic etc) and how to properly wire this. Also can either the cap or resistor be wired backwards?
Would love to know more about all the numbers on capacitors to determine more but not sure where to find the info (yes ive been googling)
Thanks in advance for any insights.

So here is a picture of how i connected the cap and resistor - i tied them together
ran positive of capacitor to pin 85 on relay
ran negative of capacitor to pin 87 of relay
relay pin 86 is 12v power
relay pin 30 is supposed to be where pulsed ground for 1/2 second is when 12v is removed from pin 86
doesn't seem to work as i connected relay pin 30 to the negative side of a buzzer (while its positive connection was connected to a different 12v location)

A: That's an interesting example relay circuit, what do you plan to use it for? This context is probably needed to answer the part of your question about proper wiring.
There are lots of good intros available for Capacitors (e.g., https://learn.sparkfun.com/tutorials/capacitors/all). The link includes a section about identification.
Kyle B's advice in the comments is important. Some capacitors are reversible and some are not. Smoke and explosive hot goo the likely result of getting that wrong https://hackaday.com/2011/05/18/blowing-up-capacitors/
Resistors on the other hand can be reversed. Again plenty of tutorials e.g., https://learn.sparkfun.com/tutorials/resistors/all
Edit: Updated with information based on the comments. The relay circuit referenced in the question was:

The symbol used for the capacitor represents a fixed polarised capacitor of 1K (i.e., 1000) micro-farads. Where a farad is the SI unit for capacitance, and the symbol mu is the SI symbol for micro (the greek letter mu looks like a u with a long tail). The asymmetrical symbol reminds us to plug the negative side of the capacitor (curved side of the symbol) to the negative or ground side of the circuit, and the positive side of the capacitor (flat side of the symbol) to the positive side of the circuit. Polarized capacitors (e.g., electrolytic) usually have clear marking showing which side is which.
Capacitors are selected to exceed the maximum voltage of the circuit they'll be installed in. The rated voltage is also often marked on the capacitor.
So you could select something like a 16V 1KuF electrolytic capacitor. In the picture below you'll see that the negative side is marked with the vertical white chevron stripe down the can, with a minus symbol on it, pointing at the negative leg.


text:
Q: Last grid_forget does not update parent The LabelFrame f is updated after the first grid_forget, but not after the second. Why?
import tkinter as tk

root=tk.Tk()
f = tk.LabelFrame(root, text='The frame')
l1 = tk.Label(f, text='Label1')
l1.grid()
l2 = tk.Label(f, text='Label2')
l2.grid()

f.after(3000, l1.grid_forget)
f.after(6000, l2.grid_forget)
f.pack(fill=tk.BOTH, expand=True)
root.mainloop()

A: Once the last child of the frame is removed, grid no longer "owns" the window, so it doesn't know that it needs to resize the frame.
The simplest solution is to place a tiny 1x1 pixel frame in there which will keep grid as the manager of the widgets within the frame.


text:
Q: How do I search GitHub issues "created in the last seven days"? We'd like to list all GitHub issues created in the last seven (or, n) days. This is a relative time window.
We don't want to use a specific date, because we'd like to create a link that is always correct (so we can link to the report of recent issues).
Thanks!

A: According to https://help.github.com/articles/searching-issues/#search-based-on-when-an-issue-or-pull-request-was-created-or-last-updated
created:2016-12-01..2016-12-08
Will output issue created during these 7 days.

A: You could create a bookmarklet, like I have, to for example, show your merged PRs last 7 days within a repo. Here's my bookmarklet:
javascript:document.location.href%3D%60https://github.com/calcom/cal.com/pulls%3Fq%3Dis%253Apr%2Bauthor%253Aleog%2Bis%253Aclosed%2Bmerged%253A%253E%24%7Bnew Date((new Date).setDate((new Date).getDate()-7)).toISOString().split("T")%5B0%5D%7D%60%3B


text:
Q: Custom Formatter for two slick grids on same page I am rendering two slick grids in a single page and I have written a custom formatter for displaying date picker on page load instead of doing it in editable mode(default functionality).
I am distinguishing the two grids with a grid column name.
function DateFormatter (row, cell, value, columnDef, dataContext) {

      var template = null;
      var rowString = row.toString();
      var cellString = cell.toString();

      if(dataContext.seasonName!= null){

          var hiddenIdentitySeason = "#dpSeason"+rowString+cellString;

          var dateIdentitySeason = "#seasonDateInput"+rowString+cellString;
      $(hiddenIdentitySeason).datepicker({
             buttonImage: "../images/calendar.gif",buttonImageOnly: true,changeMonth: true,changeYear: true,showOn: "both", onSelect: function(dateText, inst) {
             $(dateIdentitySeason).val(dateText);
       }
       });
      template = '<input type="text" id = "seasonDateInput'+rowString+cellString+'" style="width:75px;" value='+value+'></input><input type="hidden" id="dpSeason'+rowString+cellString+'"  ></input>';
      }else if(dataContext.foodName!= null){
          var hiddenIdentity = "#dpFood"+rowString+cellString;
          var dateIdentity = "#foodDateInput"+rowString+cellString;
          $(hiddenIdentity).datepicker({
                 buttonImage: "../images/calendar.gif",buttonImageOnly: true,changeMonth: true,changeYear: true,showOn: "both", onSelect: function(dateText, inst) {
                 $(dateIdentity).val(dateText);
           }
           });
          template = '<input type="text" id = "foodDateInput'+rowString+cellString+'" style="width:75px;" value='+value+'></input><input type="hidden" id="dpFood'+rowString+cellString+'"  ></input>';
      }

      return template;

  }

But date picker icon is not getting displayed which means datepicker() is not called.
If I write this formatter for only one grid,it works fine as expected.
Code thats works fine for one grid:
function DateFormatter (row, cell, value, columnDef, dataContext) {

      var rowString = row.toString();
      var cellString = cell.toString();
      var hiddenIdentitySeason = "#dpSeason"+rowString+cellString;
     var dateIdentitySeason = "#seasonDateInput"+rowString+cellString;
      $(hiddenIdentitySeason).datepicker({
             buttonImage: "../images/calendar.gif",buttonImageOnly: true,changeMonth: true,changeYear: true,showOn: "both", onSelect: function(dateText, inst) {
             $(dateIdentitySeason).val(dateText);
       }
       });
     return '<input type="text" id = "seasonDateInput'+rowString+cellString+'" style="width:75px;" value='+value+'></input><input type="hidden" id="dpSeason'+rowString+cellString+'"  ></input>';

  }

Kindly advice.

A: Based on the commentary, the season grid actually loads the datepicker when the food grid is initializing. If you create only the season grid you should not get the datepicker. This is due to the fact that the template being returned from the formatter is what the datepicker requires in order to properly "bind" itself and is not available within DOM when looked up.
One possible solution is to set a small timeout to allow the function to return the template for SlickGrid to insert into the DOM, thereby allowing jQuery to properly look up the elements. See the following example:

<link rel="stylesheet" type="text/css" href="http://mleibman.github.io/SlickGrid/slick.grid.css">
<link rel="stylesheet" type="text/css" href="http://mleibman.github.io/SlickGrid/examples/examples.css">

 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">

<button id='debugB'>Debug</button>


text:
Q: Why was p[:] designed to work differently in these two situations? p = [1,2,3]
print(p) # [1, 2, 3]

q=p[:]  # supposed to do a shallow copy
q[0]=11
print(q) #[11, 2, 3]
print(p) #[1, 2, 3]
# above confirms that q is not p, and is a distinct copy

del p[:] # why is this not creating a copy and deleting that copy ?
print(p) # []

Above confirms p[:] doesnt work the same way in these 2 situations. Isn't it ?
Considering that in the following code, I expect to be working directly with p and not a copy of p,
p[0] = 111
p[1:3] = [222, 333]
print(p) # [111, 222, 333]

I feel
del p[:]

is consistent with p[:], all of them referencing the original list
but
q=p[:]

is confusing (to novices like me) as p[:] in this case results in a new list !
My novice expectation would be that
q=p[:]

should be the same as
q=p

Why did the creators allow this special behavior to result in a copy instead ?

A: As others have stated; p[:] deletes all items in p; BUT will not affect q. To go into further detail the list docs refer to just this:

All slice operations return a new list containing the requested
  elements. This means that the following slice returns a new (shallow)
  copy of the list:
>>> squares = [1, 4, 9, 16, 25]
...
>>> squares[:]
[1, 4, 9, 16, 25]

So q=p[:] creates a (shallow) copy of p as a separate list but upon further inspection it does point to a completely separate location in memory.
>>> p = [1,2,3]
>>> q=p[:]
>>> id(q)
139646232329032
>>> id(p)
139646232627080

This is explained better in the copy module:

A shallow copy constructs a new compound object and then (to the
  extent possible) inserts references into it to the objects found in
  the original.

Although the del statement is performed recursively on lists/slices:

Deletion of a target list recursively deletes each target, from left to right.

So if we use del p[:] we are deleting the contents of p by iterating over each element, whereas q is not altered as stated earlier, it references a separate list although having the same items:
>>> del p[:]
>>> p
[]
>>> q
[1, 2, 3]

In fact this is also referenced in the list docs as well in the list.clear method:

list.copy()
Return a shallow copy of the list. Equivalent to a[:].
list.clear()
Remove all items from the list. Equivalent to del a[:].

A: Basically the slice-syntax can be used in 3 different contexts:

*

*Accessing, i.e. x = foo[:]

*Setting, i.e. foo[:] = x

*Deleting, i.e. del foo[:]
And in these contexts the values put in the square brackets just select the items. This is designed that the "slice" is used consistently in each of these cases:

*

*So x = foo[:] gets all elements in foo and assigns them to x. This is basically a shallow copy.

*But foo[:] = x will replace all elements in foo with the elements in x.

*And when deleting del foo[:] will delete all elements in foo.
However this behavior is customizable as explained by 3.3.7. Emulating container types:

object.__getitem__(self, key)
Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised.
Note
for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence.
object.__setitem__(self, key, value)
Called to implement assignment to self[key]. Same note as for __getitem__(). This should only be implemented for mappings if the objects support changes to the values for keys, or if new keys can be added, or for sequences if elements can be replaced. The same exceptions should be raised for improper key values as for the __getitem__() method.
object.__delitem__(self, key)
Called to implement deletion of self[key]. Same note as for __getitem__(). This should only be implemented for mappings if the objects support removal of keys, or for sequences if elements can be removed from the sequence. The same exceptions should be raised for improper key values as for the __getitem__() method.

(Emphasis mine)
So in theory any container type could implement this however it wants. However many container types follow the list-implementation.

A: del and assignments are designed consistently, they're just not designed the way you expected them to be. del never deletes objects, it deletes names/references (object deletion only ever happens indirectly, it's the refcount/garbage collector that deletes the objects); similarly the assignment operator never copies objects, it's always creating/updating names/references.
The del and assignment operator takes a reference specification (similar to the concept of an lvalue in C, though the details differs). This reference specification is either a variable name (plain identifier), a __setitem__ key (object in square bracket), or __setattr__ name (identifier after dot). This lvalue is not evaluated like an expression, as doing that will make it impossible to assign or delete anything.
Consider the symmetry between:
p[:] = [1, 2, 3]

and
del p[:]

In both cases, p[:] works identically because they are both evaluated as an lvalue. On the other hand, in the following code, p[:] is an expression that is fully evaluated into an object:
q = p[:]

A: del on iterator is just a call to __delitem__ with index as argument. Just like parenthesis call [n] is a call to __getitem__ method on iterator instance with index n.
So when you call p[:] you are creating a sequence of items, and when you call del p[:] you map that del/__delitem__ to every item in that sequence.

A: I'm not sure if you want this sort of answer. In words, for p[:], it means to "iterate through all elements of p". If you use it in
q=p[:]

Then it can be read as "iterate with all elements of p and set it to q". On the other hand, using
q=p

Just means, "assign the address of p to q" or "make q a pointer to p" which is confusing if you came from other languages that handles pointers individually.
Therefore, using it in del, like
del p[:]

Just means "delete all elements of p".
Hope this helps.

A: Historical reasons, mainly.
In early versions of Python, iterators and generators weren't really a thing. Most ways of working with sequences just returned lists: range(), for example, returned a fully-constructed list containing the numbers.
So it made sense for slices, when used on the right-hand side of an expression, to return a list. a[i:j:s] returned a new list containing selected elements from a. And so a[:] on the right-hand side of an assignment would return a new list containing all the elements of a, that is, a shallow copy: this was perfectly consistent at the time.
On the other hand, brackets on the left side of an expression always modified the original list: that was the precedent set by a[i] = d, and that precedent was followed by del a[i], and then by del a[i:j].
Time passed, and copying values and instantiating new lists all over the place was seen as unnecessary and expensive. Nowadays, range() returns a generator that produces each number only as it's requested, and iterating over a slice could potentially work the same way—but the idiom of copy = original[:] is too well-entrenched as a historical artifact.
In Numpy, by the way, this isn't the case: ref = original[:] will make a reference rather than a shallow copy, which is consistent with how del and assignment to arrays work.
>>> a = np.array([1,2,3,4])
>>> b = a[:]
>>> a[1] = 7
>>> b
array([1, 7, 3, 4])

Python 4, if it ever happens, may follow suit. It is, as you've observed, much more consistent with other behavior.


text:
Q: Generate heatmap with color as amount of instances between two intercepts I have a lot of data that is barely interpretable by bare sight as an xy-scatter plot. For mit it is more intereseting where clusters where built this is why I have chosen the idea of an heatmap:
heatmap, yedges, xedges = np.histogram2d(y, x, bins=(10,10))
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

generates the following plot

which is quite alright. However I'm not sure what this color even indicates but it's not the amount of datapoints between a certain range (e.g. 4>x>5 & 11>y>12).
The question
I know I could write a program that merges appropriate datapoints, count the instances for a cell and draw the desired heatmap by my own, but isn't there already an implementation of such a neat tool in data science?

A: you could use matplotlib hexbin for a straightforward approach, or check the kde plots in seaborn. I am not sure I follow your comment about the counts. Do you think they are misplaced? Due to matrix orientation differences with other languages, there is often confusion about origin of axis or the need to transpose the matrix. Other than that, the 2D bin at ~(8, 12) should have about 14 elements, as given by the color bar.

A: I decided to type it on my own, here is for all who look for a rudimentary solution (thanks to). As desired with the X- values in the center of a block:
import numpy as np
import matplotlib.pyplot as plt

def makeOwnHeatMap(x,y,bins):
    #shift +/- for the axes labels and
    xMin = float(int(min(x)))-0.5
    xMax = float(int(max(x)))+0.5
    yMin = float(int(min(y)))-0.5
    yMax = float(int(max(y)))+0.5
    yStep = float(yMax-yMin)/bins[0]
    xStep = float(xMax-xMin)/bins[1]

    downscaledGraph = np.zeros((bins[0],bins[1]))

    #make heatmap
    for i in range(0,len(y)):
        curY = y[i] #current y-value from data
        curX = x[i] #current x-value from data

        yetY = 0 #current y compare value within a stepsize
        yetX = 0 #current x compare value within a stepsize
        cntY = 0 #counter y for matrix coordinates
        cntX = 0 #counter x for matrix coodrinates
        while (yetY < curY-yMin):
            yetY += yStep
            cntY += 1

        while (yetX < curX-xMin):
            yetX += xStep
            cntX += 1

        #ends up with incrementing 1 x too much
        cntY -= 1
        cntX -= 1

        downscaledGraph[cntY,cntX] += 1

    #make axes labels
    xbar = []
    ybar = []
    thisY = yMin
    while thisY <= yMax:
        ybar.append(thisY)
        thisY += yStep

    thisX = xMin
    while thisX <= xMax:
        xbar.append(thisX)
        thisX += xStep

    #draw heatmap
    xbar, ybar = np.meshgrid(xbar, ybar)
    intensity = np.array(downscaledGraph)
    plt.pcolormesh(xbar, ybar, intensity)
    plt.show()

    for i in range(0,bins[0]):
        for j in range(0, bins[1]):
            print downscaledGraph[i,j],"\t",
        print "|"
    print "_______"

here the result.

and
0.0     0.0     0.0     0.0     0.0     0.0     0.0     0.0     |
0.0     0.0     1.0     0.0     0.0     0.0     0.0     0.0     |
1.0     0.0     12.0    0.0     0.0     0.0     0.0     0.0     |
18.0    0.0     7.0     0.0     0.0     16.0    0.0     0.0     |
8.0     0.0     7.0     0.0     0.0     10.0    0.0     1.0     |
15.0    0.0     6.0     0.0     0.0     12.0    0.0     7.0     |
0.0     0.0     3.0     0.0     0.0     3.0     0.0     6.0     |
0.0     0.0     4.0     0.0     0.0     1.0     0.0     0.0     |
0.0     0.0     0.0     0.0     0.0     0.0     0.0     0.0     |
0.0     0.0     2.0     0.0     0.0     0.0     0.0     0.0     |

Note: I can't guarantee if it's priting right results. Use the lineprint to verify its correctnes


text:
Q: ActionBarSherlock (library) on Android Studio I had the problem like wired00 on Problems importing project into Android Studio regarding ActionBarSherlock
I do exactly the solution (Edit2) but when I run I get
Gradle: package com.actionbarsherlock.app does not exist
Strange thing is that on code I don't get any error, just on compiling.
Update 1:
build.gradle:
buildscript {
    repositories {
        maven { url 'http://repo1.maven.org/maven2' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.4'
    }
}
apply plugin: 'android'

dependencies {
    compile files('libs/android-support-v4.jar')
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }
}

MainActivity:
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockActivity;

public class MainActivity extends SherlockActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

Module Settings:

Structure:

Error:

A: I think you need to add the following dependency in you gradle file:
compile project(':StoKit:actionbarsherlock')
(within the dependency section)
EDIT 25/05/2013
Ok, so this is my project structure which is currently compiling fine in android studio and via gradle command line:

EDIT 31/05/2013
Ok, so my build.gradle file within DecisionBuddy-DecisionBuddy module is:
buildscript {
    repositories {
        maven { url 'http://repo1.maven.org/maven2' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.4'
    }
}
apply plugin: 'android'

repositories{
    mavenCentral()
}

dependencies {
    compile project(':libraries:actionbarsherlock')
    compile files('libs/GoogleAdMobAdsSdk-6.3.1.jar')
    compile files('libs/libGoogleAnalyticsV2.jar')
    compile files('libs/mobileservices-0.2.0.jar')
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }
}

And the one in the actionbarsherlock module is:
buildscript {
    repositories {
        maven { url 'http://repo1.maven.org/maven2' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.4'
    }
}
apply plugin: 'android-library'

dependencies {
    compile files('../../DecisionBuddy/libs/android-support-v4.jar')
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            res.srcDirs = ['res']
        }
    }
}

Does this help?
Also make sure you updated to the latest version of the tools - I was having some issues until I did that.

A: I had the same problem and solve it by adding
compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'

to the dependencies of the build.gradle of the slidingMunu library project.
here is my build.gradle
apply plugin: 'android-library'

dependencies {
    compile 'com.android.support:support-v4:18.0.+'
    compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
}

android {
    compileSdkVersion 16
    buildToolsVersion '20.0.0'

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 21
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            res.srcDirs = ['res']
      }
      }
}


text:
Q: AttributeError: Can't pickle local object in Multiprocessing I am very new to python and I encounter this error.
CODE 1 :
import multiprocessing as mp
import os

def calc(num1, num2):
    global addi
    def addi(num1, num2):
        print(num1+num2)
    m = mp.Process(target = addi, args = (num1, num2))
    m.start()

    print("here is main", os.getpid())
    m.join()

if __name__ == "__main__":
    # creating processes
   calc(5, 6)

ERROR 1 :    ForkingPickler(file, protocol).dump(obj)
AttributeError: Can't pickle local object 'calc.<locals>.addi'

After reading around a little I understand that pickle cannot be used for local methods and so I also tried the below solution which gave another error.
CODE 2 :
import multiprocessing as mp
import os

def calc(num1, num2):
    **global addi**
    def addi(num1, num2):
        print(num1+num2)
    m = mp.Process(target = addi, args = (num1, num2))
    m.start()

    print("here is main", os.getpid())
    m.join()

if __name__ == "__main__":
    # creating processes
   calc(5, 6)
ERROR 2 :
 self = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'addi' on <module '__mp_main__' from '/Users

Could someone please help me out with this? I am clueless on what to do next!
The python version I am using is python3.8.9
Thank you so much!

A: Basically, the reason you are getting this error is because multiprocessing uses pickle, which can only serialize top-module level functions in general. Function addi is not a top-module level function. In fact, the line global addi is not doing anything because addi has never been declared in the outer module. So you have three ways to fix this.
Method 1
You can define addi in the global scope before executing calc function:
import multiprocessing as mp
import os

def addi(num1, num2):
    print(num1 + num2)

def calc(num1, num2):

    m = mp.Process(target=addi, args=(num1, num2))
    m.start()

    print("here is main", os.getpid())
    m.join()

if __name__ == "__main__":
    # creating processes
    calc(5, 6)

Output
here is main 9924
11

Method 2
You can switch to multiprocess, which uses dill instead of pickle, and can serialize such functions.
import multiprocess as mp  # Note that we are importing "multiprocess", no "ing"!
import os

def calc(num1, num2):

    def addi(num1, num2):
        print(num1 + num2)

    m = mp.Process(target=addi, args=(num1, num2))
    m.start()

    print("here is main", os.getpid())
    m.join()

if __name__ == "__main__":
    # creating processes
    calc(5, 6)

Output
here is main 67632
11

Method 2b
While it's a useful library, there are a few valid reasons why you may not want to use multiprocess. A big one is the fact that the standard library's multiprocessing and this fork are not compatible with each other (especially if you use anything from within the subpackage multiprocessing.managers). This means that if you are using this fork in your own project, but also use third-party libraries which themselves use the standard library's multiprocesing instead, you may see unexpected behaviour.
Anyway, in cases where you want to stick with the standard library's multiprocessing and not use the fork, you can use dill yourself to serialize python closures like the function addi by subclassing the Process class and adding some of our own logic. An example is given below:
import dill
from multiprocessing import Process  # Use the standard library only
import os

class DillProcess(Process):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._target = dill.dumps(self._target)  # Save the target function as bytes, using dill

    def run(self):
        if self._target:
            self._target = dill.loads(self._target)    # Unpickle the target function before executing
            self._target(*self._args, **self._kwargs)  # Execute the target function

def calc(num1, num2):

    def addi(num1, num2):
        print(num1 + num2)

    m = DillProcess(target=addi, args=(num1, num2))  # Note how we use DillProcess, and not multiprocessing.Process
    m.start()

    print("here is main", os.getpid())
    m.join()

if __name__ == "__main__":
    # creating processes
    calc(5, 6)

Output
here is main 23360
11

Method 3
This method is for those who cannot use any third-party libraries in their code. I will recommend making sure that the above methods did not work before resorting to this one because it's a little hacky and you do need to restructure some of your code.
Anyways, this method works by referencing your local functions in the top-module scope, so that they become accessible by pickle. To do this dynamically, we create a placeholder class and add all the local functions as its class attributes. We would also need to make sure that the functions' __qualname__ attribute is altered to point to their new location, and that this all is done every run outside the if __name__ ... block (otherwise newly started processes won't see the attributes). Consider a slightly modified version of your code here:
import multiprocessing as mp
import os

def calc(num1, num2):

    def addi(num1, num2):
        print(num1 + num2)

    # Another local function you might have
    def addi2():
        print('hahahaha')

    m = mp.Process(target=addi, args=(num1, num2))
    m.start()

    print("here is main", os.getpid())
    m.join()

if __name__ == "__main__":
    # creating processes
    calc(5, 6)

Below is a how you can make it work by using the above detailed method:
import multiprocessing as mp
import os

# This is our placeholder class, all local functions will be added as it's attributes
class _LocalFunctions:
    @classmethod
    def add_functions(cls, *args):
        for function in args:
            setattr(cls, function.__name__, function)
            function.__qualname__ = cls.__qualname__ + '.' + function.__name__

def calc(num1, num2, _init=False):
    # The _init parameter is to initialize all local functions outside __main__ block without actually running the
    # whole function. Basically, you shift all local function definitions to the top and add them to our
    # _LocalFunctions class. Now, if the _init parameter is True, then this means that the function call was just to
    # initialize the local functions and you SHOULD NOT do anything else. This means that after they are initialized,
    # you simply return (check below)

    def addi(num1, num2):
        print(num1 + num2)

    # Another local function you might have
    def addi2():
        print('hahahaha')

    # Add all functions to _LocalFunctions class, separating each with a comma:
    _LocalFunctions.add_functions(addi, addi2)

    # IMPORTANT: return and don't actually execute the logic of the function if _init is True!
    if _init is True:
        return

    # Beyond here is where you put the function's actual logic including any assertions, etc.
    m = mp.Process(target=addi, args=(num1, num2))
    m.start()

    print("here is main", os.getpid())
    m.join()

# All factory functions must be initialized BEFORE the "if __name__ ..." clause. If they require any parameters,
# substitute with bogus ones and make sure to put the _init parameter value as True!
calc(0, 0, _init=True)

if __name__ == '__main__':
    a = calc(5, 6)

So there are a few things you would need to change in your code, namely that all local functions inside are defined at the top and all factory functions need to be initialized (for which they need to accept the _init parameter) outside the if __name__ ... clause. But this is probably the best you can do if you can't use dill.

A: set_start_method('fork') in main


text:
Q: How to change position of list using the onkey function in python I want to change the shape of turtle with a list that has been made shapes = ["square", "triangle", "circle"] by using the onkey function. What I mean is whenever I press a button, for example h, how would I make it so that it goes through each of the shapes whenever I press h. I will be using the turtle.shape () function to achieve this.
What I have done so far is created a list of shapes but I have no idea on how to achieve the next thing that I want to achieve.
  def turtle1 ():
   shapes = ["square", "triangle", "circle", "pentagon", "star", "octagon"]
   shapeiter = itertools.cycle(shapes)
   next(shapeiter)
   1
   shape(next(shapeiter))
   next(shapeiter)
   2
   shape(next(shapeiter))
   next(shapeiter)
   3
   shape(next(shapeiter))
   next(shapeiter)
   4
   shape(next(shapeiter))
   next(shapeiter)
   5
   shape(next(shapeiter))
   next(shapeiter)
   6
   shape(next(shapeiter))

 onkey(turtle1, "h")

A: itertools.cycle() will let you cycle through a sequence indefinitely.
>>> t = itertools.cycle((1, 2, 3))
>>> next(t)
1
>>> next(t)
2
>>> next(t)
3
>>> next(t)
1
>>> next(t)
2

A: This question didn't seem to have proper closure so I'm going to attempt such.
Below is a rewrite using @IgnacioVazquez-Abrams' itertools.cycle()-based solution.  @Hayden's original code listed shapes that weren't necessarily valid, which might have caused his code to quit prematurely.  I've used turtle.getshapes() to obtain the valid shapes and I've also changed the window title to provide the shape name:
import turtle
import itertools

def reshape():
    turtle.shape(next(shape_iterator))

    turtle.title(turtle.shape())

screen = turtle.Screen()

shape_iterator = itertools.cycle(screen.getshapes())

screen.onkey(reshape, "h")

screen.listen()

reshape()

screen.mainloop()

Click on the window to make it active and then type 'h' to cycle through all the built-in turtle shapes.