text:
Q: NullPointerException en EntityManager.createQuery Tengo el siguiente método con el que busco una persona por su nombre y apellidos contcatenandolos (ya que están en 2 tablas), el problema es que desde que le puse el concat cuando llega al método createQuery este devuelve un NullPointerException
public List<Person> searchPersons(String busqueda) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery criteriaQuery = builder.createQuery();
    Root entidad = criteriaQuery.from(Person.class);
    Predicate p1 = builder.and(builder.isNull(entidad.get("deleteDate")));

    Predicate p2 = builder.and(builder.or(builder
            .like(builder.concat(builder.concat(entidad.get("name"), " "), entidad.get("lastName")), busqueda),
                builder.like(entidad.get("alias"), busqueda)));
    criteriaQuery.select(entidad).where(p1, p2);

    Query query = entityManager.createQuery(criteriaQuery);
    return query.getResultList();
}

Y la excepción

java.lang.NullPointerException    at
  org.hibernate.ejb.QueryImpl.extractParameterInfo(QueryImpl.java:114)
    at org.hibernate.ejb.QueryImpl.(QueryImpl.java:97)    at
  org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:467)
    at
  org.hibernate.ejb.criteria.CriteriaQueryCompiler.compile(CriteriaQueryCompiler.java:221)
    at
  org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:587)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)     at
  org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241)
    at com.sun.proxy.$Proxy43.createQuery(Unknown Source)   at
  es.duonet.person.PersonRepository.searchPersons(PersonRepository.java:40)
    at
  es.duonet.person.PersonService.searchPersons(PersonService.java:182)
    at
  es.duonet.person.PersonController.search(PersonController.java:361)
    at
  es.duonet.person.PersonController$$FastClassByCGLIB$$9b31899b.invoke()
    at
  org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at
  org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
    at
  org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at
  org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    at
  org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    at
  org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    at
  org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at
  org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
    at
  es.duonet.person.PersonController$$EnhancerByCGLIB$$1cdcba2.search()
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)     at
  org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
    at
  org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at
  org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at
  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
    at
  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
    at
  org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at
  org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at
  org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at
  org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    at
  org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)     at
  org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)     at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at
  org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at
  org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:108)
    at
  org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at
  org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at
  org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at
  org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at
  org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at
  org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at
  org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at
  org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at
  org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at
  org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at
  org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at
  org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at
  org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at
  org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at
  org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at
  org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
    at
  org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at
  org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at
  org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at
  org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at
  org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at
  org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
    at
  org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:279)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at
  org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)


text:
Q: Patch function won't add to specific person columns (but others are fine) I've customized a SharePoint Online list form in PowerApps to pull together data from multiple other lists and put it all in the new item. When the "Submit" button is clicked, it submits the form and immediately patches the columns that require data from those other lists. The patch function works great for most fields, and throws no errors, but two columns (both people pickers) don't seem to receive the patched objects. Meanwhile, three other people picker columns are patched with no trouble at all. I don't know what the difference is between the two groups.
Here's a simplified example.
Lists:

*

*Locations

*Regions

*Requests (this list)

Fields from the "Requests" list:

*

*Location (text)

*Manager (person)

*RegionalManager (person)

*Region (text)

*Request (text)

The 'Location' field is a drop-down that filters options from the "Locations" list on another site, and also contains the "Manager" and "Region" for the location. When a location is selected, the "Regions" list is queried based on the "Region" field and returns the "Regional Manager". Let's code.
"NewRequest" form:
// Location.OnChange:
Set(
    _location,
    LookUp(
        Locations,
        Title = Location.Selected.Title,
        ThisRecord
    )
);
Set(
    _region,
    LookUp(
        Regions,
        Title = Location.Selected.Region,
        ThisRecord
    )
);

// Submit.OnSelect:
SubmitForm(NewRequest);
Patch(
    Requests,
    LookUp(
        Requests,
        ID = NewRequest.LastSubmit.ID
    ),
    {
        Location:_location.Title,
        Manager:_location.Manager,
        Region:_location.Region,
        RegionalManager:_region.RegionalManager
    }
);

When submitted, we end up with a list item that looks like this:
Location: Atlanta
Manager: Tony Danza
Region: Southeast
Regional Manager: (blank)
Request: Hold me closer

To make sure the Region record is being correctly pulled, I added a label:
// Label.Text:
"Region: " & _location.Region &
Char(13) &
"Regional Manager: " & _region.RegionalManager.DisplayName

The label displays any part of the _region object that I want, and it changes whenever I change the "Location" selected. But it simply won't patch. Any ideas?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get user profile on battle.net oauth I'm tring to login with Blizzard ID in my site.
I think my code is work. User profile request failed.
I don't understand Blizzard's user profile Data structure.
Can you help me to get user's Id, Email and Battle Tag?
Here's my code
<?php
class Hybrid_Providers_Kakao extends Hybrid_Provider_Model_OAuth2
{
/**
* initialization
*/
function initialize()
{
    parent::initialize();

    // Provider API end-points
    $this->api->api_base_url  = "https://kr.api.battle.net/";
    $this->api->authorize_url = "https://kr.battle.net/oauth/authorize";
    $this->api->token_url     = "https://kr.battle.net/oauth/token";

    // redirect uri mismatches when authenticating with Battle.
    if (isset($this->config['redirect_uri']) && !empty($this->config['redirect_uri'])) {
        $this->api->redirect_uri = $this->config['redirect_uri'];
    }
}

/**
* finish login step
*/
function loginFinish()
{
    $error = (array_key_exists('error', $_REQUEST)) ? $_REQUEST['error'] : "";
    // check for errors
    if ( $error ){
        throw new Exception( "Authentication failed! {$this->providerId} returned an error: $error", 5 );
    }
    // try to authenicate user
    $code = (array_key_exists('code', $_REQUEST)) ? $_REQUEST['code'] : "";
    try{
        $this->authenticate( $code );
    }
    catch( Exception $e ){
        throw new Exception( "User profile request failed! {$this->providerId} returned an error: $e", 6 );
    }
    // check if authenticated
    if ( ! $this->api->access_token ){
        throw new Exception( "Authentication failed! {$this->providerId} returned an invalid access token.", 5 );
    }
    // store tokens
    $this->token("access_token",  $this->api->access_token);
    $this->token("refresh_token", $this->api->refresh_token);
    $this->token("expires_in",    $this->api->access_token_expires_in);
    $this->token("expires_at",    $this->api->access_token_expires_at);
    // set user connected locally
    $this->setUserConnected();
}

/**
* load the user profile
*/
function getUserProfile()
{

    $this->api->decode_json = false;
    $this->api->curl_header = array( 'Authorization: Bearer ' . $this->api->access_token );

    $data = $this->api->api("account/profile", "POST");

    if ( ! isset( $data->id ) ) {
        throw new Exception("User profile request failed! {$this->providerId} returned an invalid response.", 6);
    }
    # store the user profile.
    $this->user->profile->identifier  = @ $data->id;
    $this->user->profile->displayName = @ $data->battletag;
    return $this->user->profile;
}

private function authenticate($code)
{
    $params = array(
        "response_type" => $code,
        "grant_type"    => "authorization_code",
        "client_id" => $this->api->client_id,
        "redirect_uri" => $this->api->redirect_uri,
        "state" => $token,
        "scope" => "sc2.profile",
    );

    if( $this->api->client_secret && ($this->api->client_secret !== $this->api->client_id) ){
        $params['client_secret'] = $this->api->client_secret;
    }

    $response = $this->request($this->api->token_url, $params, $this->api->curl_authenticate_method);
    $response = $this->parseRequestResult($response);
    if ( ! $response || ! isset($response->access_token) ) {
        throw new Exception("The Authorization Service has return: " . $response->error);
    }
    if ( isset($response->access_token) )  $this->api->access_token            = $response->access_token;
    if ( isset($response->refresh_token) ) $this->api->refresh_token           = $response->refresh_token;
    if ( isset($response->expires_in) )    $this->api->access_token_expires_in = $response->expires_in;

    // calculate when the access token expire
    if ( isset($response->expires_in) ) {
        $this->api->access_token_expires_at = time() + $response->expires_in;
    }

    return $response;
}

private function request($url, $params=false, $type="GET")
{
    if(Class_exists('Hybrid_Logger')){
        Hybrid_Logger::info("Enter OAuth2Client::request( $url )");
        Hybrid_Logger::debug("OAuth2Client::request(). dump request params: ", serialize( $params ));
    }
    $this->http_info = array();
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL           , $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT       , $this->api->curl_time_out);
    curl_setopt($ch, CURLOPT_USERAGENT     , $this->api->curl_useragent);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->api->curl_connect_time_out);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->api->curl_ssl_verifypeer);
    curl_setopt($ch, CURLOPT_HTTPHEADER    , $this->api->curl_header);

    if ( $this->api->curl_proxy ) {
        curl_setopt( $ch, CURLOPT_PROXY, $this->curl_proxy);
    }
    if ( $type == "POST" ) {
        curl_setopt($ch, CURLOPT_POST, 1);
        if ($params) curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($params) );
    }

    $response = curl_exec($ch);
    if(Class_exists('Hybrid_Logger')){
        Hybrid_Logger::debug( "OAuth2Client::request(). dump request info: ", serialize(curl_getinfo($ch)) );
        Hybrid_Logger::debug( "OAuth2Client::request(). dump request result: ", serialize($response ));
    }
    $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $this->http_info = array_merge($this->http_info, curl_getinfo($ch));
    curl_close ($ch);

    return $response;
}

private function parseRequestResult($result)
{
    if ( json_decode($result) ) return json_decode($result);
    parse_str( $result, $ouput );
    $result = new StdClass();
    foreach( $ouput as $k => $v )
        $result->$k = $v;

    return $result;
}
}

I think this code can't read user id
    $this->user->profile->identifier  = @ $data->id;
    $this->user->profile->displayName = @ $data->battletag;

on this part.
It's not pure HybridAuth.


text:
Q: Ajax data embedding page instead of returning proper results I have a simple search area that that uses JavaScript to display relevant search results while the user is typing. The following is the code for it:

    <input type="text" id="user_search" class="form-control search_box" placeholder="Search for people">

        Enter your query

The following is the JS in lib.js:
$("input#user_search").keyup(function() {
    var elt = $("input#user_search").val();
    $curr = $(this);
    $.ajax({
        url : "u.search.php",
        type: "GET",
        data : {val: elt},
        success:function(data, textStatus, jqXHR)
        {
            if (data.length) {
                $("div#search_results").html(data);
            }
            else $("div#search_results").html('Enter your query');
        },
        error: function(jqXHR, textStatus, errorThrown){}
    });
});

Lastly, the following is the code for u.search.php:
<?php
$search = strtolower(htmlspecialchars($_GET['val']));

if (strlen($search) < 1);else {
    // Run query on the DB
    ...
    print "
";
    // populate results
    while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
    {
        // variable declarations
        print "";
        print     "";
        print     "$name";
        print "";
    }
    print "
";
}
?>

The problem here is that if I type anything in the textbox, the index.php page (page where the search box resides), the html of div#search_results becomes index.php. If I do console.log(data) in the ajax success function, the console shows the code of the index.php page (not the actual source code, but the one that you can see in the browser's page source).
div#search_results basically has index.php embedded inside it. I tried making changes to the PHP backend code, but no changes reflected in the results. What's wrong here?

A: You are using the Querystring to get the search variable. But you are not sending anything.  So change your search.php to use POST or change the ajax method to send the query string...
$.ajax({
        url : "u.search.php?val=" + encodeURIComponent(elt),
        type: "GET",
        success:function(data, textStatus, jqXHR)
        {
            if (data.length) {
                $("div#search_results").html(data);
            }
            else $("div#search_results").html('Enter your query');
        },
        error: function(jqXHR, textStatus, errorThrown){}
    });


text:
Q: How to execute local javascript file using selenium webdriver in C# I am developing an application where i want to execute a java script file using selenium web driver in C#. I am keeping the file as a part of application so whenever application launch, i want that js file executed.I already tried placing that js file on server but I don't want that. I want that js as a part of application.

A: Use the JavascriptExecutor:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("[INSER JS HERE]");


text:
Q: Ruby on Rails: alternative to nested partials (which are too slow) I need my Rails application to generate huge table (about 5-7 columns, and about 2000-3000 rows), it is for internal company usage so we don't care about traffic and so on.
The structure of objects being displayed should be quite flexible: when some column gets added/changed/removed, it is changed in just one place (apart from modifying db schema), and all the views (index, show, edit form) get updated automatically.
I had totally no experience in Rails before. I took partials as a way to reuse code (which is good thing), and so, I've seen nothing bad in using nested sub-sub-sub-partials. Say, I have several models, index view of each of them renders generic partial gen_index, and for each cell of the table there is special partial gen_field_view.
The same partial gen_field_view is rendered from the show views, so, I'd really like to have it as a partial.
If I have even just 600 rows and 5 columns, this partial gets rendered 3000 times. This was a huge surprise for me that it is so hard for Rails: it currently takes about 7 seconds to generate the page. If I remove gen_field_view partial and include it directly into gen_index partial, it takes about 3 seconds: more than twice faster (which is quite slow anyway, but this is different story).
It seems, we should avoid nested partials for such cases, but then, what else should we use to reuse views code?
We probably can return html code from some method in the model, but it actually kills the idea of Rails, and, after all, it's not convenient.

A: What about using a caching strategy ? You can use rail's fragment cashing feature:
<% Product.all.each do |p| %>
  <% cache(p) do %>
    <%= render partial: 'some_partial', locals: {product: p} %>
  <% end %>
<% end %>

A: Some of the things you can try are

*

*Caching the main partial result which will then be reused while the record isn't updated

*Render records as json on the page and render a template of the table row and then use javascript to render the actual table
<div id="data" data-records="<%= @products.to_json %>">

*Use pagination with a gem like will_paginate and then reduce the amount of records showing on the page at the same time

*Use a presentation object that renders the html as string
class ModelPresentation
  def initialize(model)
    @model = model
  end

  def render
    [title, rate].join
  end

  def title
    "
@model.title
"
  end

  def rates
    "Rate #{@model.score}"
  end
end


text:
Q: Inner folders are shown side by side in Visual Studio
So my folders suddenly started to look like this in VS code. How do I make it look like as normal again?

A: They appear like that when the folder only have one sub-folder. Once you add more folders, it will start appearing as usual.

A: Disable "Compact folders" in settings


text:
Q: Generic Pattern for querying Master-Detail-Records into nested Maps I'm currently looking for an elegant solution to query all related child-records of all master-objects in a specific trigger and returning them in a nested map that has the master's object id as first-level key and a map of the related records (to this specific master-record) as first-level value.
I'm implementing this to cache variables for my MasterObjectTriggerHandler in the Lightweight Apex Trigger Framework by Chris Aldrige, in case there might be a better solution than what I currently think of.
I've only gotten so far:
private static Map<Id, Map<Id, DetailObject__c>> getDetailsForMaster(Map<Id, MasterObject__c> ms) {

    Map<Id, DetailObject__c> ds = new Map<Id, DetailObject__c>();
    Map<Id, Map<Id, DetailObject__c>> tempReturn = new Map<Id, Map<Id, ProdEvent__c>>();
    ds.putAll([SELECT Id, id__c, master__c FROM DetailObject__c WHERE master__c IN:ms.keySet()]);

    // now some magic happens

    return tempReturn;

}

A: You can iterate the child to get your map and then return the map. here is simple code sample for you.
Map<Id, Map<Id, DetailObject__c>> tempReturn = new Map<Id, Map<Id, ProdEvent__c>>();
    for(DetailObject__c  do :[SELECT Id, id__c, master__c FROM DetailObject__c WHERE master__c IN:ms.keySet()]){
       if(!tempReturn.containsKey(do.master__c))
                tempReturn.put(do.master__c, new Map<Id, DetailObject__c>());
    tempReturn.get(do.master__c).put(do.Id, do);
}
return tempReturn;


text:
Q: How to detect duplicated monitors as separate screens Using the answer in this question I can get the "screen" count. However, this doesn't seem to work with monitors that are set to "duplicate" (one monitor is reported instead of 2). My application prompts a user to switch from VGA to HDMI (this is on a device with both output ports), and then puts a "can you see this?" prompt on screen to verify that both video ports are working.
I am trying to detect that the switch has happened before showing the prompt, but due to the above mentioned problem the code does not see the monitor count decrement, then increment (that is how I am detecting the switch).
How can I detect the video device switch if everything is set to duplicate? The existing code works if the monitors are set to "extend". There is an internal video device that is always present as well (not trying to test this one).

A: See This question and use the provided (and fixed in the answer) wrapper for QueryDisplayConfig.
change the signature of the import to have out DisplayConfigTopologyId topology as the last parameter.
Use the QueryDisplayFlags.DatabaseCurrent for the display flags, otherwise you'll get status 87 (invalid parameter)
After calling QueryDisplayFlags the topology will be Clone, Extend etc.
call the method...
var status = CCDWrapper.QueryDisplayConfig(
    CCDWrapper.QueryDisplayFlags.DatabaseCurrent,
    ref numPathArrayElements, pathInfoArray, ref numModeInfoArrayElements,
    modeInfoArray, out currentTopologyId);

In my tests numPathArrayElements always came back as the number of monitors currently In Use. If I changed it to "Show Only Screen 1", It said 1 screen, topology internal. "Show Only Screen 2" came back with 1 screen external. "Cloned" showed 2 screens.

A: James Barrass' answer didn't work for me.  I ended up going with the answer here: link
Here's the code:
public static int GetScreenCount()
{
    ManagementObjectSearcher searcher =
        new ManagementObjectSearcher("root\\CIMV2",
        "SELECT * FROM Win32_PnPEntity where service =\"monitor\"");

    return searcher.Get().Count;
}


text:
Q: Records with empty fields not showing in MS access query I have multiple Inner joined tables that i can summon with  a query however there is a certain field that sometimes can be Null, when i use query to summon records it will only show records that already have that certain field populated.
So how to show the records that have other conditions full filled whether it have empty fields or dont have any ??
I have the table Employee with one to one relation with company car licence plate Number. some employees might not have assigned car. The CARS has a separate table so the following example for two record scenarios :
SocialNo | FirstName | LastName | LicencePlate | Other
14256335 | John      | Wick     | 213546       | bla bla
12348596 | Sara      | Milles   |              | bla bla
18596563 | Leo       | Cranes   | 185647       | bla bla

In my case the licence in my country is just numbers and of course i cant have duplicates of the same car for different employees. But employees with no cars will be left blank. If i were to make a query to show all records only John and Leo will appear and if i add like 0 Licence for every employee with no car will create duplicates which will violate the 1-to-1 relation.
And so for any query i will make as long as i inner joining between the two tables.
SELECT SocialNo ,FirstName, LastName, Car.LicenceID From Employees
Inner Join Car On Employees.Licence=Car.LicenceID
Where ( Car.LicenceID=[Forms]![EmployeesQuery]![LicenceCombo]
    Or [Forms]![EmployeesQuery]![LicenceCombo] Is Null)

Solution is to make LEFT Join instead of inner join.


text:
Q: Is it possible to call a Codeigniter class function from an executable PHP file? Is it possible to call a Codeigniter class function from an executable PHP file?
I have a controller class and I want to call a function of that class from an executable PHP file.
Why? Because my application works with cronjobs. When I create a cronjob from the GUI, a new php file is created and set with the configuration to call the controller function.
How can I do it?
Edit:
I've tried this example, but It doesn't work. The cronjobs created are (combinations to test):
* * * * * /usr/bin/php /home/myweb/public_html/CI/application/controllers/tools message
* * * * * /usr/bin/php http://www.myweb.com/CI/site/index.php/tools/message
* * * * * /usr/bin/php index.php tools message
* * * * * php index.php tools message

But they don't work
Edit:
After the Ben's answer, I've tried (I have a site folder):
* * * * * /usr/bin/php /home/myweb/public_html/CI/index.php tools message
* * * * * /usr/bin/php /home/myweb/public_html/CI/site/index.php tools message

I obtain the next log errors:
ERROR - 2013-01-30 05:52:01 --> Severity: Notice  --> Undefined index:  REMOTE_ADDR /home/myweb/public_html/CI/system/core/Input.php 351
ERROR - 2013-01-30 05:52:01 --> Severity: Warning  --> Cannot modify header information - headers already sent by (output started at /home/myweb/public_html/CI/system/core/Exceptions.php:185) /home/myweb/public_html/CI/system/libraries/Session.php 675
ERROR - 2013-01-30 05:52:01 --> Severity: Warning  --> Cannot modify header information - headers already sent by (output started at /home/myweb/public_html/CI/system/core/Exceptions.php:185) /home/myweb/public_html/CI/system/helpers/url_helper.php 542

[Solved]
I've solved it with curl:
* * * * * /usr/bin/curl http://www.myweb.com/CI/site/index.php/tools/message

A: Yes it is possible. Straight from the CI documentation...
http://ellislab.com/codeigniter/user-guide/general/cli.html
Edit from your question update...
A couple of issues with your cron...
Cron 1) You are using absolute path to the controller file, should be the absolute path to the index.php
Cron 2) If you want to use the http address, then you should be using curl -L --silent "www.example.com"
Cron 3) Not an absolute document path
Cron 4) should use the absolute path for both php and the index.php

A: Yes you can. just make sure all the correct files are included in the context that you want.
Create a "new" CodeIgniter Object from your classes, and then use the functions.


text:
Q: Gmail API - has something changed permissions wise for government accounts? We've had tens of thousands of users using our app that integrates with the Gmail API for 7 years or so, however in the past week or so we've suddenly seen widespread failures (401 responses), but only for government customers based in the US.
I've managed to obtain a trace from one of our customers of the HTTP traffic between our app and the Gmail server:
Request
I have abbreviated the access token here for brevity / security, but I have confirmed the actual value in the header matches the access token received from Google. I have also abbreviated the multipart MIME message and changed the customer's email address.
POST https://www.googleapis.com/upload/gmail/v1/users/me/drafts?uploadType=multipart HTTP/1.1
Content-Type: multipart/related; boundary="f31e2e89cedf4242be6fcbe5e793173e"
User-Agent: Affixa Enterprise 1.2021.3.15
Authorization: Bearer ya29.A0ARrdaM8v6BZrUpbTJb...N2wbiX8Ej9vY
Host: www.googleapis.com
Content-Length: 8249
Expect: 100-continue

--f31e2e89cedf4242be6fcbe5e793173e
Content-Type: application/json; charset=UTF-8

{}
--f31e2e89cedf4242be6fcbe5e793173e
Content-Type: message/rfc822

MIME-Version: 1.0
X-Mailer: Affixa Enterprise 1.2021.3.15
From: foo@bar.gov
Subject: LogCrossSearchResult_22A0XSR5009663_2022-03-23-15-13.csv
Date: Thu, 31 Mar 2022 10:39:19 -0500
Message-ID: <1.6139e48b20e838d93825@msg.affixa.com>
Content-Type: multipart/mixed;
    boundary="----=_NextPart_001_2C7F_AA3B1314.8E6FEB65"

------=_NextPart_001_2C7F_AA3B1314.8E6FEB65
Content-Type: multipart/alternative;
    boundary="----=_NextPart_000_1462_A4B24415.C610B984"

------=_NextPart_000_1462_A4B24415.C610B984
Content-Type: text/plain;
    charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

Response
HTTP/1.1 401 Unauthorized
X-GUploader-UploadID: ADPycdsnG_KOSQm3Cok7zCHHavR5wr0elW-o3cMbzRCP2OGTULeAdvCIbIQ7xFF6MCf7EAsBrjzNI-TBVa_5spdFcnLGQyFNPQ
WWW-Authenticate: Bearer realm="https://accounts.google.com/"
Vary: Origin
Vary: X-Origin
Vary: Referer
Content-Type: application/json; charset=UTF-8
Content-Length: 507
Date: Thu, 31 Mar 2022 15:39:19 GMT
Server: UploadServer
Alt-Svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"

{
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "errors": [
      {
        "message": "Invalid Credentials",
        "domain": "global",
        "reason": "authError",
        "location": "Authorization",
        "locationType": "header"
      }
    ],
    "status": "UNAUTHENTICATED"
  }
}

Nothing has changed in the software or with our application's registration in the Google Developer Console.
FWIW, our application hasn't been reviewed by Google, however neither does it need to be as business-facing application that's installed from the Workspace Marketplace. The application can only be used by an entire Workspace organisation and installed by an Admin; it can't be installed on a per-user basis.
The customer has confirmed that all the required scopes are still granted:

Has something changed that I'm not aware of?

A: I've now figured out the problem - and it's nothing to do with what the 401 error message suggests.
Our application is written in C# and is attempting to use TLS 1.0 by default. When we force it to use TLS 1.2, it works absolutely fine.
So the real problem is the cryptography ciphers used in the HTTPS connection and is nothing to do with the Authorization header, etc.
I'm guessing non-governmental accounts are still OK with TLS 1.0 for the moment?


text:
Q: Change default XcomArg key in custom operators I have a bunch of custom operators and I wanted to try to make use of XcomArg and using .output in my tasks.
For example, below I commented out the xcom_push to return the list:
def execute(self, context):
    # context["ti"].xcom_push(key="extract_list", value=extract_list)
    return extract_list

The issue is that my key has historically been "extract_list" and I have some references to that key elsewhere. And I pass other xcoms (such as maximum ID/timestamp) and those xcoms are labeled as return_value.
Can I change the key of an xcom that I push?
This snippet works, but the key is return_value:
    extract = FileToAzureBlobOperator(
        task_id="extract-test",
        remote_directories=["/input/test"],
        subfolders=["test", "raw"],
        params={
            "start": "{{ data_interval_start }}",
            "end": "{{ data_interval_end }}",
        },
    )

    transform = PrepareParquetOperator(
        task_id="transform-test",
        input_files=extract.output,
        output_folder="test/staging",
        custom_transform_script="scripts.common.test",
        partition_columns=["date_id"],
    )

I have tried adding test = XComArg(operator=extract, key="test_key") and then have the input_files=test in my transform task as well, but no luck. I think I need to overwrite the default key inside of my FileToAzureBlobOperator.

A: I believe you should be able to return the value as dictionary to get what you want:
return {"extract_list": extract_list}

A: Here is an example which worked using XComArg. It required changing my DAG file a bit.
    extract = FileToAzureBlobOperator(
        task_id="extract-test",
        remote_directories=["/input/test"],
        subfolders=["test", "raw"],
        params={
            "start": "{{ data_interval_start }}",
            "end": "{{ data_interval_end }}",
        },
    )

    extracted_files = XComArg(extract, "extract_list")

    transform = PrepareParquetOperator(
        task_id="transform",
        input_files=extracted_files,
    )

    transformed_files = XComArg(transform, "filter_list")

    finalize = DatasetToDatasetOperator(
        task_id="finalize",
        input_files=transformed_files,

    )

    extracted_files >> transformed_files >> finalize

Eventually my plan is to remove xcom.push() from my operators and just return the values directly so I can make use of .output without requiring the XComArg line. I just need to clean up references to the custom key names in other areas.


text:
Q: Android Studio 2.0 Gradle Bug I wasn't sure what to name the question so bear with me.
I work on two machines, my PC and my Mac. Currently I have upgraded to Android Studio 2.0 on my PC to get all the new features and it is a mess. I need help.
So what is happening is that when I try to run the app the gradle build fails. It fails with this message :
Executing tasks: [:app:clean, :app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources, :app:assembleDebug]

Configuration on demand is an incubating feature.
Incremental java compilation is an incubating feature.
:app:clean
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAnimatedVectorDrawable2320Library
:app:prepareComAndroidSupportAppcompatV72320Library
:app:prepareComAndroidSupportDesign2320Library
:app:prepareComAndroidSupportRecyclerviewV72320Library
:app:prepareComAndroidSupportSupportV42320Library
:app:prepareComAndroidSupportSupportVectorDrawable2320Library
:app:prepareDebugDependencies
:app:compileDebugAidl
:app:compileDebugRenderscript
:app:generateDebugBuildConfig
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources
:app:mergeDebugResources
:app:processDebugManifest
:app:processDebugResources
:app:generateDebugSources
:app:mockableAndroidJar UP-TO-DATE
:app:preDebugUnitTestBuild UP-TO-DATE
:app:prepareDebugUnitTestDependencies
:app:preDebugAndroidTestBuild UP-TO-DATE
:app:prepareDebugAndroidTestDependencies
:app:compileDebugAndroidTestAidl
:app:processDebugAndroidTestManifest
:app:compileDebugAndroidTestRenderscript
:app:generateDebugAndroidTestBuildConfig
:app:generateDebugAndroidTestAssets UP-TO-DATE
:app:mergeDebugAndroidTestAssets
:app:generateDebugAndroidTestResValues UP-TO-DATE
:app:generateDebugAndroidTestResources
:app:mergeDebugAndroidTestResources
:app:processDebugAndroidTestResources
:app:generateDebugAndroidTestSources
:app:compileDebugJavaWithJavac
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources
:app:buildInfoDebugLoader
:app:transformClassesWithExtractJarsForDebug
:app:transformClassesWithInstantRunVerifierForDebug
:app:transformClassesWithJavaResourcesVerifierForDebug
:app:mergeDebugJniLibFolders
:app:transformNative_libsWithMergeJniLibsForDebug
:app:processDebugJavaRes UP-TO-DATE
:app:transformResourcesWithMergeJavaResForDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.

> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/BCKEY.SF
File1: C:\Users\Andy\.gradle\caches\modules-2\files-2.1\org.bouncycastle\bcpkix-jdk15on\1.51\6c8c1f61bf27a09f9b1a8abc201523669bba9597\bcpkix-jdk15on-1.51.jar
File2: C:\Users\Andy\.gradle\caches\modules-2\files-2.1\org.bouncycastle\bcprov-jdk15on\1.51\9ab8afcc2842d5ef06eb775a0a2b12783b99aa80\bcprov-jdk15on-1.51.jar

*

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

BUILD FAILED
Total time: 15.114 secs
Here is a list of my dependencies
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.google.code.gson:gson:2.5'
compile 'com.hierynomus:sshj:0.15.0'
compile 'joda-time:joda-time:2.9.1'
compile 'de.greenrobot:eventbus:2.4.0'
compile 'com.android.support:support-v4:23.2.0'
compile 'com.android.support:design:23.2.0'
}

Now the odd thing is that if I run the exact same source code on my mac its fine. So what is going on? Is this a bug with v2.0, it seems unlikely though.
If you need any more info let me know!
Thanks
Andy

A: Hey so with some help I figued out that com.hierynomous:sshj was also wanting Bouncy Castle and therefor conflicting with the caked in Android one.
Hope this helps someone in the future.


text:
Q: How to disable font smoothing on Firefox 18 for Linux? On my Ubuntu 12.10 machine, I've updated Firefox to version 18 some minutes ago. After that, fonts on sites are too smooth and now it's difficult to read for me.
I found some advices about my problem like that question How do I disable font smoothing/hinting/anti-aliasing on Firefox 4? and read official forums but on my machine there are none of the following items in about:config:

*

*gfx.direct2d.disabled

*gfx.content.azure.enabled
And the addon Anti-Aliasing Tuner is not available for me either.
How should I fix this problem?

A: *

*Create a boolean setting gfx.direct2d.disabled in about:config

*Set its value to  True
The above worked for me.

A: Creating ~/.fonts.conf:
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
 <match target="font" >
  <edit mode="assign" name="autohint" >
   <bool>false</bool>
  </edit>
 </match>
 <match target="font" >
  <edit mode="assign" name="rgba" >
   <const>none</const>
  </edit>
 </match>
 <match target="font" >
  <edit mode="assign" name="hinting" >
   <bool>true</bool>
  </edit>
 </match>
 <match target="font" >
  <edit mode="assign" name="hintstyle" >
   <const>hintslight</const>
  </edit>
 </match>
 <match target="font" >
  <edit mode="assign" name="antialias" >
   <bool>false</bool>
  </edit>
 </match>
</fontconfig>

worked for me

A: Tweak the following preferences on the about:config page
layers.acceleration.force-enabled > true
layers.acceleration.disabled > false
gfx.xrender.enabled > false (this one "may", not sure yet, decrease performance a little but it will give you crisp & clean font rendering)


text:
Q: Issues retrieving special characters from OPENJSON SQL Server I'm parsing data from a JSON File and am having issues when I finally load into my table, the data where there's special characters such as ñ shows as ñ instead.
The code is in NVARCHAR and I'm not sure why it's not pulling correctly
INSERT INTO @recordsInfo
    (
        messageId,
        messageType,
        messageVariation,
        windowEnvelope,
        recipientFirstName,
        recipientLastName,
        recipientAddressLine1,
        recipientAddressLine2,
        recipientCity,
        recipientState,
        recipientZip,
        recipientZipSuffix
    )
    SELECT messageId,
           messageType,
           messageVariation,
           windowEnvelope,
           recipientFirstName,
           recipientLastName,
           recipientAddressLine1,
           recipientAddressLine2,
           recipientCity,
           recipientState,
           recipientZip,
           recipientZipSuffix
    FROM
        OPENJSON(@ValueR)
        WITH
        (
            messageId NVARCHAR(100),
            messageType NVARCHAR(100) '$.messageDetails.messageType',
            messageVariation NVARCHAR(100) '$.messageDetails.messageVariation',
            windowEnvelope NVARCHAR(100) '$.messageDetails.windowEnvelope',
            recipientFirstName NVARCHAR(100) '$."shippingDetails"."recipientFirstName"',
            recipientLastName NVARCHAR(100) '$."shippingDetails"."recipientLastName"',
            recipientAddressLine1 NVARCHAR(1000) '$.shippingDetails.recipientAddressLine1',
            recipientAddressLine2 NVARCHAR(100) '$.shippingDetails.recipientAddressLine2',
            recipientCity NVARCHAR(100) '$.shippingDetails.recipientCity',
            recipientState NVARCHAR(100) '$.shippingDetails.recipientState',
            recipientZip NVARCHAR(100) '$.shippingDetails.recipientZip',
            recipientZipSuffix NVARCHAR(100) '$.shippingDetails.recipientZipSuffix'
        );

DECLARE @recordsInfo TABLE
(
    RecID INT IDENTITY(1, 1),
    messageId NVARCHAR(100),
    messageType NVARCHAR(100),
    messageVariation NVARCHAR(100),
    windowEnvelope NVARCHAR(100),
    recipientFirstName NVARCHAR(100),
    recipientLastName NVARCHAR(100),
    recipientAddressLine1 NVARCHAR(1000),
    recipientAddressLine2 NVARCHAR(100),
    recipientCity NVARCHAR(100),
    recipientState NVARCHAR(100),
    recipientZip NVARCHAR(100),
    recipientZipSuffix NVARCHAR(100)
);

RecipientFirstName is the primary one I'm looking at

A: JSON is usually UTF-8. Only in version 2019 does SQL Server understand UTF-8, so until then, you have to do it manually.
Convert text value in SQL Server from UTF8 to ISO 8859-1


text:
Q: Previously working Google Sheets App Script is now throwing the "Failed to establish a database connection" error for MySQL DB I've been using Google Sheets App Script successfully the past 4 months that is connected to a MySQL 5.7 DB hosted remotely on a VPS (this script connected to my DB successfully earlier today as well). All of a sudden this afternoon my requests are returning "Failed to establish a database connection. Check connection string, username and password." The database connection still works just fine remotely on my computer using MySQL Workbench.
Additional details:

*

*The credentials didn't change (I confirmed with a new connection test)

*I have Chrome V8 Runtime disabled since that does not work well at all

*I double checked the Google Server IPs to whitelist and noticed 1 server that's either new or I missed the first time, either way all provided IPs are currently whitelisted

*I'm connecting using this syntax: var conn = Jdbc.getConnection(url, user, pwd);

I saw some previous comments from a month ago that some people were able to add these parameters successfully: var conn = Jdbc.getConnection(url+'?verifyServerCertificate=false&useSSL=true&requireSSL=true', user, pwd);
However I just get this: Error Invalid argument: _serverSslCertificate
Any further steps or tips to get this connected successfully again is appreciated, thanks!

A: Austin, you just made my day... Same thing, my MySQL connections stopped working all of a sudden yesterday. Spent hours trying to fix it. The '?useSSL=false' worked like charm.
Thank you, thank you, thank you

A: Apparently it's just working again.... must have been a service blip. What's strange is it started working again after I decided to just try var conn = Jdbc.getConnection(url+'?useSSL=false', user, pwd); since I saw some other comments mention that. Seems like an awful solution, but it started working again after I did that, but has continued to work even after I reverted back to just var conn = Jdbc.getConnection(url, user, pwd);
Follow-up questions, are there any good alternatives to Google Sheets with App Script like usage? I'm getting really tired of Google's awful support - would rather pay for a product than to hear "you get what you pay for" with awful support.
EDIT: After this started working again yesterday by itself, the issue came back. I have now confirmed today that switching to var conn = Jdbc.getConnection(url+'?useSSL=false', user, pwd); has solved my connection issue, but that is not an ideal fix by any means at all. Google must be messing with some network settings on the Apps Script side and it's causing issues.

A: I found a solution.
Seems a change on Google now requires you to explicitly set SSL to false. (previously if you let it omitted it would default to off)
?useSSL=false
So you need to update your connection string to something like this simple example.
function myFunction() {

var conn = Jdbc.getConnection("jdbc:mysql://35.214.129.151:3306/dbiyrogncria1r?useSSL=false", "uyxfedtljijfy8", "rnqgnyrs2dthb");

Logger.log(conn);
conn.close();
}


text:
Q: Is it Possible to Color a Column/Row of Cells based on another Column/Row of Cells? There are two columns; the first contains four colored cells, while the second contains numbers. Is there any way to color the second column so that it matches the colors of the first column in the same order.
Eg. A1=Green, A2=Red, A3=Grey, A4=Black (COLORED).
    B1=4, B2=3, B3=2, B4=1 (BLANK).
=  A1=Green, A2=Red, A3=Grey, A4=Black (COLORED).
 =  B1=4 (Green), B2=3 (Red), B3=2 (Grey), B4=1 (Black) (COLORED).
Manually coloring the column will not work here because I want a cell in the second column to be able to match the cell next to it if its color changes. So for instance if a cell in column A changes from "black" to "red", I want the corresponding cell in column B to change from "black" to "red" automatically.
Eg. A1=Green, A2=Red, A3=Grey, A4=Red (COLORED).
    B1=4 (Green), B2=3 (Red), B3=2 (Grey), B4=1 (Black) (COLORED).
Here A4 is now "red", while B4 is still "black". I want it so that if A4 changes color, B4 will change color to match A4.
I tried experimenting with conditional formatting, but that doesn't seem to be working out so far, would there be a formula for something like this, or am I SOL?

A: This is possible using Conditional Formatting.
You would have to select both columns and then choose to use a formula for the conditional formatting.
There you would input
=$A1="Red"

and set the formatting to red.
The $ fixes the formula to the first column. If you omit it, only column A would be colored in.
That way you would have to write the cell background color in column A, and if you set the font color to the same value you won't see it...
Another option would be to use a VBA macro, that runs on every SheetChange Event that will copy the background color from column A to column B
Edit:
As @lowak pointed out, you will have to create one rule for each color.


text:
Q: Simple read-only access for git repository over http: Will it just work? I use gitolite to manage git repositories, that are available over the internet using SSH and private keys.
I want to provide read-only access to some of those repositories from my LAN. I know that there are some pitfalls when using git over http, and I want to avoid the complex git-over-http setup just for read-only access.
As the repositories are bare ones, and I only want to read: Will it work flawlessly, if I just setup any regular web server to server the git repositories over http? Are there any drawbacks?

A: Here are your options:

*

*As you mentioned u can use http (no setup required) for read only.

*Use git bundle (Its is used as a read only repository) http://git-scm.com/docs/git-bundle

*Set up a commit/push hook and in your hook use exit 0 to terminate the git push without anything being pushed to your repository.

*Of course there are other options (but they are not ones that worth mentioning in details: like set up groups permissions, block any user that is not u (hooks) and more.)
Hope it was helpful for you.

A: See the article Share over apache http for a complete cook-book on setting up the Apache sharing and on controlling access.
This very detailed article is much too long to reproduce here.


text:
Q: Age range on age range in WHERE to heavy - POSTGRES I have 2 columns in the database for events.

*

*agelow (int)

*agehigh (int)

How it's structured:

*

*agehigh is being used for "and under" which is represented by 0 in the column

*the high age is placed in the agelow column

*The "and over" is represented by 99 and is not a problem since it has the agehigh and the agelow in the right columns.

*all ages are represented with 99 in both columns.

I am trying to write a WHERE that can pull all event ages if no ages are passed in but also need to be able to pull events just for one age passed in or for an age range passed in. The age range is making this a big headache.
Example
If I pass in agelow 5 and agehigh 15, I would need to grab all events that are

*

*available for anyone from 5 up to 15 which includes the "5 and under", "5 and up", "15 and under" and all ages.

Here is the WHERE part:
WHERE
((events.age_low >= agelow AND events.age_high <= agehigh) OR
 (events.age_low <= agelow AND events.age_high >= agehigh) OR
 (events.age_low <= agelow /* LOW (99 for all) */ AND events.age_high >= agelow /* LOW (99 for all) */) OR
 (events.age_low <= agelow /* LOW (99 for all) */ AND events.age_high = 99 /* DEFAULT 99 */) OR
 (events.age_low >= agelow /* LOW (99 for all) */ AND events.age_high = 0 /* DEFAULT 0 */) OR
 (events.age_high >= agehigh /* HIGH (0 for all) */ AND events.age_low <= agehigh /* HIGH (0 for all) */) OR
 (events.age_low >= agehigh /* HIGH (0 for all) */ AND events.age_high = 0 /* DEFAULT 0 */) OR
 (events.age_low <= agehigh /* HIGH (0 for all) */ AND events.age_high = 99 /* DEFAULT 99 */) OR
 (events.age_low = 99 AND events.age_high = 99));

Here is a small selection of the age columns:
CREATE TABLE events(age_low,age_high)
AS VALUES
  (  99 ,  99 ),
  (   3 ,  12 ),
  (   1 ,   6 ),
  (   5 ,   0 ),
  (  99 ,  99 ),
  (  99 ,  99 ),
  (  99 ,  99 ),
  (   5 ,  11 ),
  (   5 ,   0 ),   -- this is 5 and below
  (  16 ,  99 ),   -- this is 16 and up
  (   1 ,   4 ),
  (  13 ,  18 ),
  (  99 ,  99 ),   -- this is all ages
  (   5 ,   0 ),
  (  99 ,  99 );

A: One approach to improve readability would be to use a CTE to add a couple of calculated columns..  However, this approach could also be slow, depending on the size of the table..  But it would look something like this
WITH true_ages AS (
  SELECT
    <cols>,
    CASE WHEN age_high < age_low THEN age_high -- handle case of 'x and below'
         WHEN age_low = 99 and age_high = 99 THEN 0 -- handle case of 'all ages'
         ELSE age_low END as true_low,
    CASE WHEN age_low < age_high and age_high = 99 THEN 999 -- handle case of 'x and above'
         WHEN age_low = 99 and age_high = 99 THEN 999 -- handle case of 'all ages'
         ELSE age_high END as true_high
  FROM <table>
) SELECT
  <cols>
FROM true_ages
WHERE <target_age> BETWEEN true_low and true_high;

You could potentially add some WHERE clause in the CTE to reduce the result set initially, but that might add unnecessary complexity.

A: If you have two number ranges, aStart to aEnd and bStart to bEnd, then they overlap if:

*

*aStart <= bEnd, and

*aEnd >= bStart

In reality, you just have three cases:

*

*all ages (99-99)

*"and under" (X - 0)

*regular, plus "and over" (X - Y)

For "and over", Y happens to be 99, instead of 0-18. Since the values still represent a valid range, that doesn't need to be a special case.
So, this WHERE clause should work:
WHERE
      -- standarad range, or "and over"
      (    events.agelow <= agehigh
       AND events.agehigh >= agelow
      )
   OR -- "and under"
      (    events.agehigh = 0
       AND events.agelow >= agelow
      )
   OR -- all ages
      (    events.agelow = 99
       AND events.agehigh = 99
      )

Note: only tested mentally, not via actual code.

A: One option is to wrap greatest and least to assist this. We can use this to iron out the oddities

*

*5,0 being five and under. That should really be 0,5 if there was any level of sanity.

*That 99,99 is all ages. Here if the lower bound is 99 we set that to -1 just be sure it's all ages.

Code,
CREATE FUNCTION normalize_query_range(start int, finish int)
RETURNS int4range
AS
$$
  SELECT int4range(
    CASE WHEN least(start,finish) = 99 THEN -1 ELSE least(start,finish) END
    , greatest(start,finish)
  );
$$ LANGUAGE sql
IMMUTABLE;

Now, we can easily do this using the range operators for @> contains, and && overlaps.
SELECT age_low,age_high
FROM events
WHERE normalize_query_range(age_low,age_high) && int4range(5,15);

And, even better, creating an index will speed this up.
CREATE INDEX ON events
  USING gist(normalize_query_range(age_low, age_high));


text:
Q: Fixed point problem with a monotone vector as a fixed point? Suppose $F : [0,1]^n \to [0,1]^n$ is continuously differentiable and $0 < \frac{\partial F_1}{\partial x_i} \leq \dots \leq \frac{\partial F_n}{\partial x_i} < \beta < 1$ for all $i =1,\dots,n$. Conjecture: there exists unique $x^* = F(x^*)$, and moreover, $x_1^* \leq \dots \leq x_n^*$.
Proof of the first part is quite straightforward: one can easily verify that $F$ is a contraction mapping and then apply the contraction mapping theorem. I would need some help with the second claim.

A: Here is the question by @TomH (exact quote from the above):
Suppose $F : [0,1]^n \to [0,1]^n$ is continuously differentiable and $0 < \frac{\partial F_1}{\partial x_i} \leq \dots \leq \frac{\partial F_n}{\partial x_i} < \beta < 1$ for all $i =1,\dots,n$. Conjecture: there exists unique $x^* = F(x^*)$, and moreover, $x_1^* \leq \dots \leq x_n^*$.`
Proof of the first part is quite straightforward: one can easily verify that $F$ is a contraction mapping and then apply the contraction mapping theorem. I would need some help with the second claim.

Let me provide a counter-example $\ F : [0;1]^2\rightarrow [0;1]^2\ $ in dim 2 (it can be written in $n$ variables too):
Let an auxiliary function $\ g:[0;1]^2\rightarrow \mathbb R\ $ be given as follows:
$$g(x\ y)\,\ :=\,\ \frac14\cdot(x-\frac12)\ +\ \frac12\cdot(y-\frac14)$$
Then $\ -\frac14\le g(x\ y) \le \frac12\ $ for every $\ (x\ y)\in [0;1]^2;\ $ and $\ g(\frac12\ \frac14)\ =\ 0.\ $ Consider $\ F:[0;1]^2\rightarrow [0;1]^2\ $ defined by:
$$F(x\ y)\ :=\ \left(\frac12 + g\left(x\ y\right),\ \frac14 + g\left(x\ y\right)\right)$$
Indeed, the values of the first coordinate of $F$ belong to the interval $\ \left[\frac14;1\right],\ $ and of the second coordinate to $\ \left[0;\frac34\right].\ $ Thus the range of $F$ is in $\ [0;1]^2\ $. Also, the partial derivatives, with respect to $x$, of the two coordinate functions are the same; and the same is true about $y$. Of course both derivatives (constants) belong to a proper closed subinterval of $\ [0;1].\ $ Finally
$$F(\frac12\ \frac14)\ =\ (\frac12\ \frac14)$$
where $\ \frac12 > \frac14.\ $ That's it.

A: So I see that you are assuming that the $n^2$ first order partial derivatives are all strictly between $0$ and $1$. The fixed point can be found by repeatedly applying $F$ starting (almost?) anywhere. It would be sufficient then that the property $x_1 \le x_2 \le \cdots \le x_n$ is preserved by application of $F$. On way to have that happen is to have conditions such as $\frac{\partial F_i}{x_j} \le \frac{\partial F_{i+1}}{x_{j}}$ although that is more than is needed. Indeed, if any subset of the set of points with ordered coordinates( such as the line $x_1=x_2=x_3=\cdots=x_n$ or the curve ($t^n,t^{n-1},\cdots,t^1)$) is mapped to itself, that suffices. So all the $F_i$ equal would be enough.
In a way that is trivial since the minimal condition is that there is a $1$ point set mapped into itself and that point is ordered. So what is your function or at least what flavor of properties are you considering?


text:
Q: Можно ли настроить откат AUTO_INCREMENT полей при отмене транзакции? Заметил в mysql, при откате транзакции ROLLBACK, операций INSERT INTO AUTO_INCREMENT не откатывается. Тип таблицы innoBD.
Проблема в том что нужно что бы были одинаковые id, так как в дальнейшем идет выборка связкой таблиц по id.
Можно ил как то настроить откат AUTO_INCREMENT или надо добавлять новый столбец в контролировать целостность id?

A: Значения автоинкрементных полей, (а также самостоятельные sequence generators там где они реальзованы) существуют вне транзакций. В этом есть своя мудрость. Иначе было бы сложно избежать повторов в конкурирующих транзакциях.
Как справедливо заметил Mike,  вам нужен только один автоинкремент. Сначала вставили в таблицу с автоинкрементом, затем ссылаетесь на значение из last_insert_id() во всех остальных местах.

A: Документация (http://dev.mysql.com/doc/refman/5.7/en/innodb-auto-increment-handling.html) говорит следующее:

"Lost" auto-increment values and sequence gaps
In all lock modes (0, 1, and 2), if a transaction that generated auto-increment values rolls back, those auto-increment values are "lost". Once a value is generated for an auto-increment column, it cannot be rolled back, whether or not the "INSERT-like" statement is completed, and whether or not the containing transaction is rolled back. Such lost values are not reused. Thus, there may be gaps in the values stored in an AUTO_INCREMENT column of a table.

Так что увы...

A: Вы оставляете AI в одной таблице (назовем её "Главной" с точки зрения бизнес-логики), а для второй таблицы лучше использовать вставку с использованием foreign key. Это решит непосредственно задачу связки таблиц для выборки.
В любом случае нельзя использовать два AI в разных таблицах для задач связанности данных - это архитектурно неверный путь.


text:
Q: Problem starting phpMyAdmin in XAMPP I have a problem starting phpMyAdmin in XAMPP. Do I need to make any changes in the config files or should I change some port numbers?

(Click image to enlarge)

A: Actually i had previously installed mysql-workbench and had completely forgotten about it, hence the mysql server and phpmyadmin was not starting. So, Please be sure to uninstall any other server or ide before installing xampp, also remember to remove the configuration files of the previous server or ide. This worked for me, hopes work for others too.


text:
Q: Why DNS server changes when enabling another interface on machine My system has 6 interfaces, a loopback, a Xen Bridge, and then 4 ethernet interfaces eth0-3. In this system, my DNS server assigned by DHCP on xenbr0 is 192.168.1.1.
Initially eth1 is disabled and DNS assigned (checked via /etc/resolv.conf) is 192.168.1.1. When I enable eth1, internet on this system stops working, I checked with /etc/resolv.conf and now DNS is 127.0.0.1 (why?). Anyway DNS resolution doesn't work now.
Question is How can I make internet work while keeping all interfaces active? Why DNS server changes, and how to stop that?
About Environment: This is a Ubuntu 12.04 VM running in Xen in VirtualBox. eth1 is connected to a VBox host-only network 192.168.56.0/24. eth2 and eth3 are connected to VBox internal networks, there is no config on these two interfaces. xenbr0 is xen bridge and eth0 is added as its one port. In Vbox eth0 is sharing IP with host machine via NAT (currently getting 10.0.2.15). IP of host machine is 192.168.1.x and router IP is 192.168.1.1 which is default gateway for host and DNS too. This is hown DNS is propagated upto guest machine via xenbr0.

A: Sounds like your system uses the same init script on all(?) interfaces, thus the most-recent DHCPconfigured connection will overwrite /etc/resolv.conf with whatever that DHCP defined


text:
Q: Hibernate changes database change from oracle to mysql I am using Spring and Hibernate in my project. My database has changed from Oracle 10g to MySQL.
Can you please tell me what changes do I need to make in my Hibernate configuration?
Also are there any changes required in my Java code.

A: If you are using the hibernate.cfg.xml for your project to define the database property, then you need to change it to the below values for MySQL :-
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/{db.name}</property>
        <property name="hibernate.connection.username">{db.name}</property>
        <property name="hibernate.connection.password">{db.password}</property>

    </session-factory>
</hibernate-configuration>

Also you need to include the mysql-connector jar in your pom.xml for example
  <!--Mysql-Connector-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.36</version>
        </dependency>

if you are not using the hibernate.cfg.xml and instead using some sessionFactory bean in your Spring ApplicationContext.xml. Then you need to change it to below :-
<bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="annotatedClasses">

        </property>
        <property name="hibernateProperties">
            <props>
                <!-- As of now not using hibernate.cfg.xml -->
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.validator.apply_to_ddl">false</prop>
                <prop key="hibernate.validator.autoregister_listeners">false</prop>
                <prop key="show_sql">true</prop>
                <prop key="format_sql">true</prop>
            </props>
        </property>
    </bean>

<bean id="dataSource"
    class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
      <property name="driverClassName" value="${jdbc.driverClassName}" />
      <property name="url" value="${jdbc.url}" />
      <property name="username" value="${jdbc.user}" />
      <property name="password" value="${jdbc.pass}" />
   </bean>

Please follow http://www.baeldung.com/hibernate-4-spring for complete example on how to setup hibernate with spring.


text:
Q: How implement RxJs using jQuery ajax? This is my implementation:
Rx.Observable.fromPromise( $.ajax({
        url     : url + postal_value +  '&types=(regions)&location=51.509865,-0.118092&key=' + key,
        type    : "GET",
        datatype: "json"
    }));

but the ajax call proceeds even without subscribe.
Is that right?

A: The ajax call is a promise which will start executing as soon as you call it. You need to defer execution by wrapping it in Rx.Observable.defer(() => Rx.Observable.fromPromise($.ajax(/*...*/))) so it only gets wired when actually subscribing to it


text:
Q: all he did was "ask" or "asking"? "asking" - In this case this kind of language element is called gerund, right?
In high school my teacher firmly told us two verbs can never be together (25 years later I can still remember her angry face).
But I do see a lot of sentences like this, in some literature:

All he did was ask a question.

I am pretty sure my English teacher wouldn't be happy with this and would put a big "X" next to it. She told us you either convert the latter verb to an infinitive or a gerund, so it is either:

All he did was asking a question.

or:

All he did was to ask a question.

So is the first writing grammatically right? And if it is, is there any difference in meaning of the three sentences?

A: Yes!  And an English teacher wouldn't put a big "X" next to it. He will instead be happy that you know better than others. Because it's acceptable in English to use  "bare infinitive " after "do/does/ did "   in this sort of sentences. So you can write -
1) All he did was ask a question.
or
All he did was to ask a question.
or
All he did was asking a question.
But The last one, I think, is best.


text:
Q: WorkBookPath property is not available in UiPath Studio I am working on one project in UiPath Studio. I am not able to find WorkbookPath option in Read Range activity. Is there any other option, from where I can browse my XLSX file in Read Range activity. Please check attached screenshot.

A: The Read Range activity must be within the Excel Application Scope (see the red message on the right upper side).
So simply delete both activities above the scope and use the existing Read Range on the bottom of your image.
Before that, select the Excel Application Scope and set the parameter Workbook path to your Excel file.
Now the Read Range works properly.
And if you need 2 different Excel files, just create another scope for that one.


text:
Q: Convert unix timestamp with a timezone to javascript date I have a legacy web app that stores dates as a UNIX timestamp (seconds since the epoch 1970). Usually a timestamp like this represents UTC, however these timestamps are UTC-8. It doesn't look like it ever accounts for Daylight Savings Time (DST). I could convert it on the server to UTC and send to the client, but I would like to know if there is a javascript only solution.
Example Input:
1399335987

Example Output:
"2014-05-05T16:26:27-07:00" // Pacific Daylight Time (PDT)

The client should display the date/time according to their local machine. I looked into using momentjs but I could not find how to construct a date from a number without the number being UTC already. Is this possible?

A: Yes, it's possible given the unix timestamps are in UTC, with Moment Timezone (http://momentjs.com/timezone/)
moment
  .unix(1399335987)
  .tz('MST')
  .format('YYYY-MM-DDTHH:mm:ssZ');

And you get
  "2014-05-05T17:26:27-07:00"

Note here I'm using MST, and you should be able to use whatever timezone you want, via Timezone Data Builder (http://momentjs.com/timezone/data/)
Actually, by default, moment parses and displays in local time.
This means, only if you're in a different timezone (offset really) and still want to get the local time in MST, it's necessary to set the timezone as MST.
Otherwise, moment.unix(1399335987).format('YYYY-MM-DDTHH:mm:ssZ') is good to go.


text:
Q: div and ion-list removed the col-6 effect on the grid Below code is working fine.
.html
<ion-content class="content">
 <ion-grid no-padding>
   <ion-row class="row3">
   <ion-col col-6 *ngFor="let d of data">
     <presentation [data]="d"></presentation>
   </ion-col>
  </ion-row>
 </ion-grid>
</ion-content>

.scss
.content {
        ion-grid {
            height: 40%;
        }
        .row1 {
            flex: 1;
            padding: 5px 0 0 0;
            .searchbar {
                padding: 0 5px 5px 5px;
            }
        }
        .row2 {
            flex: 1;
        }
        .row3 {
            .col * {
                padding: 0 10px 10px 5px;
            }
            flex: 2;
        }
        img {
            width: 100%;
            height: 100%;
        }
        [col-1] {
            img {
                width: 100%;
                height: 30%;
            }
        }
    }

Renderd on Browser

UI 1:

I have changed it like this.Only HTML code.I have just introduced this 2 lines.
  <div [ngSwitch]="pet">
            <ion-list *ngSwitchCase="'kittens'">

.html
<ion-content class="content">
  <ion-grid no-padding>
 <ion-row class="row3">
      <div [ngSwitch]="pet">
        <ion-list *ngSwitchCase="'kittens'">
          <ion-col col-6 *ngFor="let d of data">
            <presentation [data]="d"></presentation>
          </ion-col>
        </ion-list>
      </div>
    </ion-row>
  </ion-grid>
</ion-content>

Now rendered on Browser

UI 2:

You can see that, now there is no col-6 effect.Can you help me to reinstate it back? In other words same as on the first use case.
When I replaced it with div it shows as below.It brakes col-6 now.But I need 2 columns.Any trick?
 <ion-row class="row3">
      <div [ngSwitch]="pet">
        <div *ngSwitchCase="'kittens'">
          <div col-6 *ngFor="let d of data">
            <presentation [data]="d"></presentation>
          </div>
        </div>
      </div>
    </ion-row>

UI 3:

A: As I see it, I think there is a problem with the HTML element nesting (between ion-row and ion-col). Because of that, the styles are not applying correctly for the ion-col.
Try changing your HTML as follows:
<ion-row class="row3">
    <ion-col col-6 *ngFor="let d of data">
        <div [ngSwitch]="pet">
            <div *ngSwitchCase="'kittens'">
                <presentation [data]="d"></presentation>
            </div>
            <!-- other ngSwitchCases -->
        </div>
    </ion-col>
</ion-row>

Cheers!


text:
Q: setuptools: force version of another package (if present) while not forcing installation of this package (when not present) During development of Pylint, we encountered interesting problem related to non-dependency that may break pylint package.
Case is following:

*

*python-future had a conflicting alias to configparser package. Quoting official docs:

This release removes the configparser package as an alias for ConfigParser on Py2 to improve compatibility with Lukasz Langa's backported configparser package. Previously python-future and the configparser backport clashed, causing various compatibility issues. (Issues #118, #181)

*python-future itself is not a dependency of Pylint

What would be a standard way to enforce if python-future is present, force it to 0.16 or later limitation? I want to avoid defining dependency as future>=0.16 - by doing this I'd force users to install package that they don't need and won't use in a general case.

A: kw = {}
try:
    import future
except ImportError:
    pass
else:
    kw['install_requires'] = ['future>=0.16']

setup(
    …
    **kw
)

A: One workaround for this issue is to define this requirement only for the all target, so only if someone adds pylint[all]>=1.2.3 as a requirement they will have futures installed/upgraded.
At this moment I don't know another way to "ignore or upgrade" a dependency.
Also, I would avoid adding Python code to setup.py in order to make it "smart",... is a well known distribution anti-pattern ;)

A: There is no supported way to tell pip or setuptools that a package needs to satisfy a constraint only if installed. There might be some hacks but I imagine they'll all be fragile and likely breaking in the future versions of pip/setuptools.
Honestly, the only good way is to document it for users that future < 16.0 would break pylint, in the appropriate location in the documentation.

Making your setup.py script contain conditional dependencies is something that has been strongly discouraged for some time now. Once a wheel is built, the package is installed with the same dependency information as the wheel holds - setup.py is not run on the end-user's system, only on the packager's system, which means any setup.py hack (like @phd's) would not be useful (since pylint distributes wheels).


text:
Q: Maintain a transitive mapping in Java Scenario
class A{
  String aId;
;}

class B{
  String bId;
;}

class C{
  String bId;
;}

class D{
    B b;
    C c;
;}

I hava a List<A>. I traverse this list using a for loop, perform some DB operations and create a List<B>. I need a mapping from A to B, so I create a Map<A,B> also.
From this List<B>, I make a bulk API call and fetch a List<D>. I require a mapping from B to C also, so I traverse over this List<D> and create a Map<B,C> .
My main requirement is a mapping from A to C. I can't remove the bulk API call but want to remove the extra overhead of maintaining two maps. Is there some way of maintaining a transitive mapping, a mapping of A to  C directly in JAVA?

A: You can generate it as follows:
for loop
import java.util.HashMap;
import java.util.Map;

public class Main
{

    public static void main(String[] args)
    {
        Map<String,String> m1= new HashMap<>();
        Map<String,String> m2 = new HashMap<>();
        m1.put("aaa", "bbb");
        m2.put("bbb", "ccc");
        Map<String,String> combined = new HashMap<>();
        for(String key : m1.keySet())
        {
            // TODO: add error handling or make sure get never returns null
            combined.put(key, m2.get(m1.get(key)));
        }
        System.out.println(combined.get("aaa"));
    }
}

streams
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;;

public class Main
{

    public static void main(String[] args)
    {
        Map<String,String> m1= new HashMap<>();
        Map<String,String> m2 = new HashMap<>();
        m1.put("aaa", "bbb");
        m2.put("bbb", "ccc");
        Map<String,String> combined = m1.keySet().stream().collect(Collectors.toMap( Function.identity(), x->m2.get(m1.get(x))));
        System.out.println(combined);
    }

}

Edit: As requested, added a version using streams, even though I prefer the first version.


text:
Q: BottomNavigationView switching between fragments quickly just crashes the app I have a BottomNavigationView in my MainActivity and 3 fragments to switch in between.
All these 3 fragments have almost the same content with some minor naming changes which will display a recyclerView with data from FirebaseDatabase
FruitsFragment.kt:
class FruitsFragment :Fragment() {
    private val adapter = GroupAdapter<GroupieViewHolder>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_fruits,container,false)

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val ref = FirebaseDatabase.getInstance().getReference("/Fruits/")
        ref.addListenerForSingleValueEvent(object: ValueEventListener {
            override fun onDataChange(p0: DataSnapshot) {

                if (isAdded && activity !=null ){
                    p0.children.forEach {
                        val data = it.getValue(UpdateRow::class.java) ?: return
                        val vegetableName = it.key
                        val price = data.p
                        val priceFormatted = PriceQuantityFormat.priceFormat(price)
                        val quantity = data.q
                        val downloadURL = data.downloadURL
                        adapter.add(VegetableRow(requireContext(),ftFragment,vegetableName!!,price,priceFormatted,quantity,downloadURL))
                    }
                }
                else {
                    Toast.makeText(requireContext(),"Error: too fast",Toast.LENGTH_SHORT).show()
                }

            }

            override fun onCancelled(p0: DatabaseError) {

            }
        })
        fruitsRV.adapter = adapter
    }

}

Here is my fragment, all the loading of data goes into my adapter(using Groupie) which is just simple loading of textViews
Now switching fast before content load between these fragments crashes my app.
I tried checking isAdded() as suggested by another post on this forum but didnt work at all.
Also tried searching everywhere couldn't find an answer.
Thanks in advance.
Edit: error log
Process: com.example.myapplication, PID: 5021
    java.lang.IllegalStateException: Fragment VegetablesFragment{6f7374 (10863cd2-1ac1-4318-8959-cd11218fee65)} not attached to a context.
        at androidx.fragment.app.Fragment.requireContext(Fragment.java:774)
        at com.example.myapplication.VegetablesFragment$onActivityCreated$1.onDataChange(VegetablesFragment.kt:49)
        at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@16.0.4:183)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.4:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)


text:
Q: Return back to location on page after Post request using PHP LARAVEL I am trying to build a one page web page using PHP laravel and all its features.
I use javascript to scroll through the pages when pressing specific links.
At the bottom of the page I have a form that runs some php code (sends an email,...)
After this POST request I redirect back to my webpage.
The problem is that when I redirect back I see the top of the page and the contact form and error or success codes are at the bottom of my page near the FORM.
This is why I am looking for a way to automatically scroll/move to the contact form after the post request just like i do when pressing the link button.
HTML:
        @if (count($errors) > 0)

                <button type="button" class="close" data-dismiss="alert">×</button>

                @foreach ($errors->all() as $error)

{{ $error }}

                @endforeach

        @endif
        @if ($message = Session::get('success'))

                <button type="button" class="close" data-dismiss="alert">×</button>
                {{ $message }}

        @endif
        <form method="post" action="sendemail">
            {{ csrf_field() }}

                Name
                <input type="text" class="form-control" name="name" id="exampleFormControlInput1">

                Email
                <input type="email" class="form-control" name="email" id="exampleFormControlInput1">

                Message
                <textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="8"></textarea>

                <input type="submit" name="send" class="btn btn-secondary" value="Send" />

        </form>

PHP Route:
Route::post('/sendemail', 'App\Http\Controllers\SendEmailController@send');

PHP Controller:
function send(Request $request)
{
    $this->validate($request, [
    'name'     =>  'required',
    'email'  =>  'required|email',
    'message' =>  'required'
    ]);

        $data = array(
            'name'      =>  $request->name,
            'email'     =>  $request->email,
            'message'   =>  $request->message
        );
    Mail::to($request->email)->send(new SendMailValidation($data));
    return back()->with('success', 'Thank you!');
}

Javascript (atm only used for client side browsing when pressing a link item):
let  contactLinkItem = document.querySelector("#contactLinkItem");

contactLink.addEventListener("click", navigateContact, false);

function navigateContact() {
  contactLinkItem.scrollIntoView({ behavior: "smooth" });
}

A: You can check if errors bag has any messages then call javascript function that you already created above to trigger scrolling behavior
@if($errors->any())

@endif

// Your old code
let  contactLinkItem = document.querySelector("#contactLinkItem");

contactLink.addEventListener("click", navigateContact, false);

function navigateContact() {
  contactLinkItem.scrollIntoView({ behavior: "smooth" });
}

Recommendation:
Use Ajax calls with API to submit your forms (Or Livewire), and you have the ability to show validation errors without scrolling or even leaving the page. This is the best for your users experience.


text:
Q: MySQL JSON UPDATE ON DUPLICATE KEY column merge removing empty array wrapper I am having weird issue with updating JSON column in MySQL. I am developing a plugin on WordPress platform. Here is the scenario.
In the cart table I have a column customers the default value is NULL for the column.
On duplicate I am updating row with the update values for few columns including the customers column.
SQL Query
INSERT INTO {$this->pg_table} ({$imploded_column})
VALUES({$imploded_format}) ON DUPLICATE KEY
UPDATE qty = qty + '%d', customers = JSON_MERGE(customers, '%s'), added_at = now()

Customer data
$this->customers = json_encode($customers);

The above code will insert json as {"Jatin Soni": "rdyad@email.com"}. However, if the $customers is empty, it will insert [] empty array.
Now ON DUPLICATE KEY
    UPDATE using JSON_MERGE it will wrap as [{"Jatin Soni": "rdyad@email.com"}] as the $customers was empty.
So I can not be sure if the customer column value is {"Jatin Soni": "rdyad@email.com"} or [{"Jatin Soni": "rdyad@email.com"}] which is depend on user when they set the field value.
Additionally, I have tried setting null value if $customers is empty.
$this->customers     = empty($customers) ? NULL : json_encode($customers);

WordPress prepare method doesn't allow to insert NULL so the column
  will set to empty instead.

So the column will be empty if no data. In that case it is giving error when someone Updates. As I believe this is because in JSON_MERGE(customers, '%s') the customers is empty while it needs a JSON.

Question:
How can I keep the json string structure consistent in all
  above cases?

A: I found a workaround but I am still looking for the proper solution rather than this one.
Here I have added empty json string if $customers is empty.
$this->customers = empty($customers) ? '{}' : json_encode($customers);


text:
Q: BrowserSync Not Reloading Changes I started BrowserSync with this command:
browser-sync start --proxy localhost:8001 --files "app/css/*.css"

I have the code snippet in index.html and when I open the page in my browser, I see the message:
Connected to BrowserSync

But when I make changes to the CSS, the BrowserSync does not reload the page with the changes.  I have to manually reload to see the change.

A: *

*It is --files="app/css/*.css" and not --files "app/css/*.css"

*Browsersync reads index.html by default, hence you get the message 'Connected to browsersync'
And here's the solution to your answer..
In every forum I have checked, everyone is following the same nomenclature of "css/*.css". Without realizing what the initial css stands for. Its the name of the folder or directory not something for vague..
Hence, make sure that inside those quotes you have pointed to the right directory. For example, if the styles.css file is just outside (i.e. in the root directory) alongside index.html, then just write --files="styles.css". It shall work like charm.
And if you want Browsersync to watch multiple css files then put --files="*.css". If you want to sync different types of files, then use --files="*.html,*.js".
If these css files are in some directory say 'xfolder' then --files="xfolder/*.css"


text:
Q: What does locking a password using `passwd -l` mean? It is possible to lock a password using
$ passwd -l john

But what does that actually mean to lock a password?

A: Why don't you just read the man page for passwd?

-l, --lock
             Lock the password of the named account. This option disables a password by changing it to a value which matches no possible
             encrypted value (it adds a ´!´ at the beginning of the password).
Note that this does not disable the account. The user may still be able to login using another authentication token (e.g. an
             SSH key). To disable the account, administrators should use usermod --expiredate 1 (this set the account's expire date to Jan
             2, 1970).
             Users with a locked password are not allowed to change their password.


text:
Q: Hive aggregation function that produces a map I have the following hive table
ID, class,value
1, A, 0.3
1, B, 0.4
1, C, 0.5
2, B, 0.1
2, C, 0.2
I want to get
ID, class:value
1, [A:0.3, B:0.4, C:0.5]
2, [B:0.1, C:0.2]

I know that there is a collect_set() UDAF that produces a list of class or list of value, is there anyway to get a list of key:value pairs?
NOTE:
I guess I can use two collect_set() one for class column and one for value column but I am not sure if the lists will be in the same order.

A: I've used the UnionUDAF from the Brickhouse library to do something similar. You create a map from each pair, and then union them all together during the aggregation.
Add JAR brickhouse.jar;
create temporary function BH_union as 'brickhouse.udf.collect.UnionUDAF';

SELECT S.ID, BH_union(S.v_map)
FROM (SELECT ID, map(class, value) as v_map from mytable) S
GROUP by S.ID

A: You can use custom Map/Reduce scripts and collect_list() (from Hive 0.13.0) to achieve the same.
Let me know if you need more help in this.


text:
Q: UWP equivalent to XamlWriter for serializing XAML I'm writing an application in which the user is able to place elements onto a canvas and customize them to create a picture. I've been able to save the picture as bitmap but need to be able to serialize and save the canvas's XAML code itself so that I can deserialize and reconstruct the image and let the user edit it again.
XamlWriter is unfortunately not available in UWP but is there any equivalent to serialize XAML? Or would I have to go through the ordeal of inspecting each element in the canvas and saving its position and properties?

A: There are couple of serializers in UWP: XmlSerializer, DataContractSerializer, JsonSerializer.
Here is nice article about it:
Choosing the right serialization engine for your Windows Store app
and here is one else:
Saving and Loading App Data (Windows Store C# UWP / 8.1)


text:
Q: External data from file throws error while using where clause I am trying to read a text file with 2,000 values, but my where clause throws error.
    SELECT mac.mac_id,mac.mac,mac.mac_type,record.soc_id
    from mso_charter.mac
    where record.soc_id in ('C:\Users\xyz\worldbox2_Prod_09-17-2017.txt')
    join mso_charter.record on mac.record_id = record.header_id;

    ERROR:  syntax error at or near "join"
    LINE 4: join mso_charter.record on mac.record_id = record.header_id;
            ^
    ********** Error **********

    ERROR: syntax error at or near "join"
    SQL state: 42601
    Character: 155

A: This:
SELECT mac.mac_id,mac.mac,mac.mac_type,record.soc_id
from mso_charter.mac
join mso_charter.record on mac.record_id = record.header_id
where record.soc_id in ('C:\Users\xyz\worldbox2_Prod_09-17-2017.txt');

and unless you have multiple soc_Id's
where record.soc_id = ('C:\Users\xyz\worldbox2_Prod_09-17-2017.txt');
Not this:
SELECT mac.mac_id,mac.mac,mac.mac_type,record.soc_id
from mso_charter.mac
where record.soc_id in ('C:\Users\xyz\worldbox2_Prod_09-17-2017.txt')
join mso_charter.record on mac.record_id = record.header_id

Compilers are pretty picky about the order

*

*SELECT

*FROM

*JOIN

*WHERE

*GROUP BY

*HAVING

*ORDER BY

Though order of execution is

*

*FROM

*JOIN

*WHERE

*GROUP BY

*SELECT

*HAVING

*ORDER BY


text:
Q: How to get parameter hints in VSCode for pyd files in general and confluent_kafka specifically? I am new to kafka, and trying work some basic examples via VScode. The problem is I can't seem to make parameter hints work at all for all the artefacts imported via confluent_kafka. The module itself is a wrapper, and I was wondering if there was a way to get parameter hinting the same way other python classes and modules work?

A: It's impossible. Because what you want was stored in the file of cimpl.cp39-win_amd64.pyd.
The Language Server can not provide Intellisense from the file with pyd filename extension.
You can have a look at the cimply with PyCharm, as it can decompilation it.

A: Currently, it is not supported by VScode. One way to get the tooltips is to create a .pyi file for your package which defines the interface the functions. If you ship this with the package (or have this file in your VSCode working directory) it will be able to give parameter hints and such!
You can create one using mypy's stubgen, but it does not automatically include the docstrings. You can write one yourself however. Have a look here: Python: Generate function stubs from C module


text:
Q: Why did the WMAP mission last so much longer than Planck? NASA endorsed 9 years of data taken with the Wilkinson Microwave Anisotropy Probe (WMAP). The High Frequency Instrument aboard the Planck satellite ran out of coolant at the start of 2012, after about two and a half years of operation. Even if the Low Frequency instrument runs for another two years, its operating life will be much shorter than WMAP's.
Why is there such a big difference between the operational life-spans of the two missions, given that they have basically the same objective: to measure the cosmic microwave background?

A: Dan Neely gave an excellent answer.  I wanted to add that WMAP was initially planned as a one-year mission, and soon extended to two years---in which it reached its designed sensitivity goals.
After that point, it continued due to its success and the reasons listed by Dan.

A: From Wikipedia:

Passive thermal radiators cool the WMAP to ca. 90 degrees K; they are
  connected to the low-noise amplifiers. The telescope consumes 419 W of
  power. The available telescope heaters are emergency-survival heaters,
  and there is a transmitter heater, used to warm them when off. The
  WMAP spacecraft's temperature is monitored with platinum resistance
  thermometers.

Because no coolant was used, there was no hard deadline on its operational lifetime.  Its design lifetime was for two years of data collection.  However the cost of continuing to collect data from an operational satellite is low so there was no pressing need to turn it off; and until Planck had returned its first dataset, adding more WMAP data was the only option available for scientists studying the CMB that wanted more data.  However, diminishing returns come into play; each additional scan of data from the same instruments gives a smaller return.  Planck's more sensitive instruments rapidly surpassed the quality of its data; at which point there was no reason to keep running it.
Cryogenic cooling reduces thermal noise.  Using it was one way the Planck team could increase the sensitivity of their instruments.  Planck completed five complete scans of the sky before exhausting the coolant for the HFI.  The LFI is expected to have another 6-9 months of operation before its coolant is exhausted.
Finally the amount of coolant used isn't a finely tunable parameter.  Rockets come in a relatively small number of discrete sizes; you can't just spend a few tens of thousands of dollars to add a few extra kg of payload.  The next larger rocket size can easily cost millions of dollars more.  As a result, most missions are designed around the payload capacity of the rocket they're budgeted for and have a fixed mass as a result.  An extra kg of coolant means removing a kg somewhere else.


text:
Q: In Firestore, how can I prevent "Please ensure that the Firestore types you are using are from the same NPM package" errors I have several NPM codebases that use Firestore. One is client-side, one is server-side, and I am trying to refactor some code to a common dependency codebase. The server codebase uses firebase-admin as its dependency, but if I try to set objects with sentinel types (e.g. firebase.firestore.Timestamp), I incur this error:
Please ensure that the Firestore types you are using are from the same NPM package

I can avoid mixing firestore implementations by injecting the instance into my library codebase, e.g.:
import * as admin from "firebase-admin";
const libraryCode = new MyFirestoreLibrary(admin.firestore())

But, are there ways to access these sentinel types in library code?
An example of what I'm hoping to make work is here: https://github.com/okhobb/firestore-dependency-tester

A: I agree this is extremely silly from the firebase team. I'm in your exact sitiuation, and have shared code where I define types and objects between both client and server - sounds reasonable right?
Here's my workaround:

import * as firebase from 'firebase-admin';
import Timestamp = firebase.firestore.Timestamp;

export const now = () => {
  const newTimestamp = Timestamp.fromMillis(Date.now()) as any;
  const ret =  JSON.parse(JSON.stringify(newTimestamp));

  for (const prop of Object.getOwnPropertyNames(Timestamp.prototype).filter(prop => prop !== "constructor"))
    ret[prop] = newTimestamp[prop]

  return ret as Timestamp;
}

This just creates a new object and copies the properties so that the toDate, toMillis etc functions are all still there, it's just not a direct instance of timestamp, so any instanceof checks will return false.
After doing that awful hack, it seems like the check they have in place to make sure "you are importing from the same npm package" no longer works.