text:
Q: ReactJs adding multiple reducers with context I have implemented single reducer but I want to add multiple reducers here ? I searched to get solution but i am still stuck here
 1 - loginReducer.js
    export const loginReducer = (state, action) => {
        switch (action.type) {
          case 'LOGIN':
            return [
              ...state,
              {
                loggedIn: true,
              }
            ];
          case 'LOGOUT':
            loggedIn: false,

            return state ;
          default:
            return state;
        }
      };

2 - provider.js
import { loginReducer } from "./reducers/loginReducer";

const GlobalContext = React.createContext();
const GlobalProvider = props => {
  const [login, dispatch] = useReducer(loginReducer, []);
  return(
    <GlobalContext.Provider value={{login, dispatch}}>
      {props.children}
    </GlobalContext.Provider>
  )
}

export default GlobalProvider;

How can I add another reducer same like loginReducer ?
and What is the syntax to add here GlobalContext.Provider value={{login, dispatch}}

A: You can use Array.prototype.reduce:

const reducerA = (state, action) => state + action;
const reducerB = (state, action) => state * action;
const rootReducer = (state, action) =>
  [reducerA, reducerB].reduce(
    (state, reducer) => reducer(state, action),
    state
  );
console.log('root reducer:',rootReducer(1, 2));


text:
Q: Flask SQLAlchemy Set expire_on_commit=False In Flask-SQLAlchemy, at:
https://pythonhosted.org/Flask-SQLAlchemy/queries.html
you access to your session via db.session.
How do you make the session accessed via db.session have
expire_on_commit=False
I tried db.session.expire_on_commit = False but this does not appera to take affect.

A: You can use the session_options dictionary when making the database object.
db = SQLAlchemy(app, session_options={"expire_on_commit": False})

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to start selenium standalone server ith IE11 webdriver? I'm trying this command in order to start selenium standalone server with internet explorer 11:
java -jar selenium-server-standalone-3.141.59.jar -Dwebdriver.ie.driver=C:\Users\MyUser\Downloads\IEDriverServer_x64_3.14.0\IEDriverServer.exe -Dwebdriver.ie="C:\Program Files\internet explorer\iexplore.exe"

where MyUser is my current username.
But I'm getting exception.
Using selenium standalone server version 2.53.1 works fine with the same arguments but it's recommanded to use the same version for IE webdriver and selenium.
Here's the exception I have:
Exception in thread "main" com.beust.jcommander.ParameterException: Was passed main parameter '-Dwebdriver.ie.driver=C:\Users\Xavier\Downloads\IEDriverServer_x64_3.14.0\IEDriverServer.exe' but no main parameter was defined in your arg class
    at com.beust.jcommander.JCommander.initMainParameterValue(JCommander.java:936)
    at com.beust.jcommander.JCommander.parseValues(JCommander.java:752)
[...]

Does anyone know how to run it ?

A: Fixed this by moving -jar .... at the end of the command:
java -Dwebdriver.ie.driver=C:\Users\MyUser\Downloads\IEDriverServer_x64_3.14.0\IEDriverServer.exe -Dwebdriver.ie="C:\Program Files\internet explorer\iexplore.exe" -jar selenium-server-standalone-3.141.59.jar


text:
Q: Is there a function that makes an image not clickable so that the default chrome widget doesn't appear and allow them to download the image?
Is there a function that makes an image not clickable so that the default chrome widget doesn't appear and allow them to download the image??

A: You could just add it onto a canvas which makes the image unclickable:
HTML
<canvas id="myCanvas">
<img id="image"src='https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/220px-SNice.svg.png'>

Javascript
window.onload = function() {
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  var img = document.getElementById("image");
  ctx.drawImage(img, 10, 10);
};

A: CSS

body {
-webkit-user-select: none;  /* Chrome all / Safari all */
-moz-user-select: none;     /* Firefox all */
-ms-user-select: none;      /* IE 10+ */
-o-user-select: none;
user-select: none;
}

JS

<script>
document.addEventListener('contextmenu', event => event.preventDefault());
</script>

HTML

<body oncontextmenu="return false;">


text:
Q: What's the best way to link to an external style sheet in SharePoint I have some user controls that I'm loading in SharePoint and I would prefer to have all those styles contained in an external style sheet.  What's the best way to link to an external stylesheet in CSS?
Thanks.

A: Can you not add a <link rel...> to the head?  If not, can you this.page.header.controls.add?

A: This code will ensure that you only add 1 stylesheet reference to a page regardless of how many web parts you have on it - same code snippet can be used for javascript.
protected override void OnPreRender(EventArgs e)
   {
      const string stylesheet = "YourStylesheet.css";
      if (!Page.IsClientScriptBlockRegistered(stylesheet))
         {
         Page.RegisterClientScriptBlock(stylesheet,
            string.Format(@"<link href=""{0}/{1}"" rel=""stylesheet""/>",
                         this.ClassResourcePath, stylesheet));
         }
       base.OnPreRender(e);
   }

A: Thanks,
I was looking at that way too complicated like.  Your answer solved my problem and will actually work a lot better than the method that I was going to approach it from.

A: If you're using MOSS, you can remove this configuration from your code entirely by using SharePoint's built in alternate style sheet property.

*

*Drop down the Site Actions menu, and select Site Settings->Modify All Site Settings.

*On the resulting page, click on the Master page link in the Look and Feel column.

*On the Site Master Page Settings page, scroll to the bottom to the Alternate CSS URL section. Select the Specify a CSS file... radio button and enter the URL of your style sheet. I put mine in the Home site's Style Library, but you can pretty much put it where you want.

*If you like, you can set it for all the subsites to by selecting the Reset all subsites to inherit this alternate CSS URL checkbox.

*Click the OK button.

Sadly,this configuration isn't available for WSS sites. But the object model does have it. So you can apply it with code in both WSS and MOSS, either in a web part or via something like PowerShell.
In code, once you have a reference to the the SPWeb object, say in a cleverly named variable called theWeb, you can just assign the URL of stylesheet with the following code:
    theWeb.AlternateCssUrl = "http://server/site/library/stylesheet.css";
    theWeb.Update();


text:
Q: How to send large files to and from dotnet core without using system memory I am trying to upload large files to an API from a dotnet core front end.
I have tried to use the code from Microsoft here but they are using angular and I want to do this from within a .net core HttpClient.
I have got it working but the upload uses up the memory of the system and doesn't release it. I can expect files multiple GB in size
My code looks like the following.
I have an http client that looks something like this
public async Task<UploadModel> UploadFileAsync(Stream fileStream, string param1, string param2)
{
    var uri = new Uri("upload", UriKind.Relative);

    try
    {
        var ch = GetClaimsMessageProcessor();

        var fileStreamContent = new StreamContent(fileStream);

        using (var mfdContent = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString()))
        {
            mfdContent.Add(fileStreamContent);
            var response = await _restClient.PostAsync(uri, mfdContent, callbacks: new Action<HttpRequestMessage>[] { ch.AddClaims,
               (x) => {
                   x.Headers.Add("param1",param1);
                   x.Headers.Add("param2",param1);
                } });

            var content = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                // log and throw exception etc
            }

            return JsonConvert.DeserializeObject<UploadModel>(content);
        }
    }
    catch (Exception e)
    {
        // log etc
    }
}

And my API looks something like this:
[HttpPost("upload")]
[Filters.DisableFormValueModelBinding]
public async Task<IActionResult> Upload()
{
    if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
    {
        return BadRequest($"Expected a multipart request, but got {Request.ContentType}");
    }

    // Get Header Parameters
    string param1, param2;

    try
    {
        param1 = Request.Headers["param1"][0];
        param2 = Request.Headers["param2"][0];
    }
    catch (Exception e)
    {
        // log and throw exception
    }

    var filePath = GetFilePath();

    if (!Directory.Exists(filePath))
    {
        Directory.CreateDirectory(filePath);
    }

    var targetFilePath = Path.Combine(filePath , GetFileName());

    var boundary = MultipartRequestHelper.GetBoundary(
        MediaTypeHeaderValue.Parse(Request.ContentType),
        _defaultFormOptions.MultipartBoundaryLengthLimit);
    var reader = new MultipartReader(boundary, HttpContext.Request.Body);

    var section = await reader.ReadNextSectionAsync();
    while (section != null)
    {
        using (var targetStream = System.IO.File.Create(targetFilePath))
        {
            await section.Body.CopyToAsync(targetStream);
        }
        section = await reader.ReadNextSectionAsync();
    }

    // Validate

    // Do stuff with uploaded file
    var model = new UploadedModel
    {
        //some properties
    };

    return Ok(model);
}

I have noticed that there is only one section read. I would assume there should be multiple?


text:
Q: How can I dynamically populate an address in another textbox when user enter zip code? i am trying to dynamically populate an address from a getAdd($Url) function to textbox(addressD) when user keying postal code in another textbox(postalCode). but no value is populated to the addressD textbox at all. can anyone tell me what's wrong?
<?php
  function getAdd($Url){

      if (!function_exists('curl_init')){
          die('cURL is not installed. Install and try again.');
      }

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, 'http://gothere.sg/a/search?q='.$Url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      $output = curl_exec($ch);
      curl_close($ch);

        $trimData = strstr($output, 'locf');
        $extractData = substr($trimData, 13);
        $findPos = strpos($extractData, '<');
        $extractData2 = substr($extractData, 0, $findPos);

        echo "<script type="text/javascript">";
        echo "document.getElementByID('addressD').value = $extractData2";
        echo "</script>";
  }
?>

<html>
<body>
    <form id="contact-form" method="post">
       Postal Code*:
       <input type="text" name="postalCode" value="" onkeypress="getAdd(this.value)" />

       Address*:
       <input type="text" name="addressD" id="addressD" value="" />
    </form>
</body>
</html>

A: When you press the button, the browser tries to execute a javascript function called getAdd(). However, you've created a php function called getAdd() - that won't work. You cannot call a server-side function from the browser without using ajax calls. The php function is never sent to the user's browser, it's parsed by the server and then the html beneath it is sent out.


text:
Q: How do I choose a random element from a random array? I'm a Ruby beginner who's trying to add multiple categories to my hangman game.
I know how to choose a random element from an array. For example:
animals = ['dog', 'cat', 'mouse']
random = animals[rand(animals.length)]
puts random

However, I want to choose an entire array randomly, and then a single random element from that random array. For example:
animals = ['dog', 'cat', 'mouse']
planets = [['jupiter'], ['mars']]
fruits = [['apple'], ['orange'], ['mango']]

categories =[[animals], [planets], [fruits]]

#the code I tried was:
random_array = categories[rand(categories.length)]
random_element = random_array[rand(random_array.length)]
puts random_element

But this puts an entire array, instead of one element. Please help!
Thanks

A: animals = ['dog', 'cat', 'mouse']
planets = [['jupiter'], ['mars']]
fruits = [['apple'], ['orange'], ['mango']]

categories = [animals, planets, fruits]
puts categories.sample.sample #=> jupiter

As Sawa remarks, this would return either a string or one of the sub-arrays. *categories.sample.sample (a splat) always retuns a string.

A: your code is correct, but array initialization is not. Here's what you have to do:
animals = ['dog', 'cat', 'mouse']
planets = ['jupiter', 'mars']
fruits = ['apple', 'orange', 'mango']

categories = [animals, planets, fruits]

In your code, animals is array, planets and fruits are arrays of arrays, and categories is array of three arrays, inside of each one is one of you variables

A: What you have should work, it's your categories array that's not working.
It supposed to be:
categories =[animals, planets, fruits]

and not a mix of arrays within an array.

A: Why not flatten them all or is that an overkill
a = (animals.flatten + fruits.flatten + planets.flatten)
r = a[rand(a.flatten.size)]
=> "dog"

You might also use the more efficient << to concatenate arrays.

A: Using the Array#sample method.

A: This should be the shortest and cleanest way to do it.
animals = ['dog', 'cat', 'mouse']
planets = [['jupiter'], ['mars']]
fruits = [['apple'], ['orange'], ['mango']]

[animals, planets, fruits].flatten.sample

#flatten returns a new array with all elements but in just one dimension.
#sample returns one random element from you array


text:
Q: new keyword with POJO returns null reference to nested objects I have a POJO with lombok @Data annotation like this
@Data
public class RmsSearchRequestDto {
     private AuditCredentialsDto auditCredentialsDto;
     private RmsSearchCriteriaDto rmsSearchCriteriaDto;
}

the inner class are POJOs with @Data annotation again.
Now when I create a new instance of RmsSearchRequestDto as:
RmsSearchRequestDto rmsSearch=new RmsSearchRequestDto();

it sets auditCredetialsDto and rmsSearchCriteriaDto to null and results in NullPointerException when I try to access
rmsSearch.getRmsSearchCriteriaDto().getSearchType();

cause rmsSearch.getRmsSearchCriteriaDto() returns null instead of returning an instance of RmsSearchCriteriaDto (desired result)
This behavior is very strange to me and cannot find anything on google. I'm using Spring boot 2.5.6. This is a 20 year old legacy project and I did not have this issue until lately when I tried switch from CustomValidators to Spring Bean Validation. Thanks.

A: Lombok site is down today but according to what I've heard from others. This is the default behavior of @data annotation as seen in the comments above as well. I changed this class from having only string fields to having nested classes which caused this confusion on my part. Refactoring my test cases to initialize inner class instances explicitly now. Thanks everyone.


text:
Q: What is the $\epsilon^{00}$-topology? "If $F$ is a locally convex space, then the topology on $F^*$ (the topological dual of F) will be the strong topology, and the topology on $F^{**}$ will be the $\epsilon^{00}$-topology." This is the first time I've seen this notation. It is described as the uniform convergence topology on the polars of p-unit balls, but I would like to know what is the exact thing this $\epsilon^{00}$-topology is referring to, it is also mentioned in some other papers without any further explanation - is it always the same thing explained here?
The paper I'm reading right now was published in 1974, "Linear Operators and Vector Measures" by Brooks and Lewis.

A:
Before  stating  the  main  theorems  we  recall  some  facts  about  representing  measures  and  other topics.  $Y'$  is  the continuous dual  of $Y$,  $Y''$  the continuous  bi-dual.  Let  $σ(Y'', Y')$  denote  the $Y'$  topology  of $Y''$ and  let $\{q'\}$ be a family  of  seminorms generating this topology.  Since representing measures  can be  taken  as  being  defined  on $B(H)$ (see  [10]), $H$  a compact Hausdorff   space,  and  are  $L_c''(X,  Y)$-valued,  $xμ(\cdot)$  being  countably  additive  in  the $(Y''Y')$  topology  for  each  $x \in X$,  we  may  define  our  integral with  convergence in  $\{q'\}$   rather than $\{q''\}$,  where  $\{q''\}$   denotes the  family of  continous  seminorms  generating  the  topology  on  $Y''$  sometimes  called the  "$\epsilon^{00}$  topology"  [20,  p.  71],  which  is  the  usual  norm  topology  of   $Y''$ when  $Y$  is  a  normed  space.

https://msp.org/pjm/1984/111-1/pjm-v111-n1-p17-s.pdf


text:
Q: AddDefaultTokenProviders мешает создать миграцию При попытке создать миграцию появляется ошибка -
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType:

Microsoft.AspNetCore.Identity.DataProtectorTokenProvider`1[server.Domain.Models.UserModel] Lifetime: Transient ImplementationType:

Microsoft.AspNetCore.Identity.DataProtectorTokenProvider`1[server.Domain.Models.UserModel]': Unable to resolve service for type

'Microsoft.AspNetCore.DataProtection.IDataProtectionProvider' while attempting to activate 'Microsoft.AspNetCore.Identity.DataProtectorTokenProvider`1[server.Domain.Models.UserModel]'.)
Unable to create an object of type 'AppDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Мой Program -
builder.Services.AddDbContext<AppDbContext>(ServiceLifetime.Transient);

builder.Services.AddIdentityCore<UserModel>()
    .AddUserManager<UserManager<UserModel>>()
    .AddEntityFrameworkStores<AppDbContext>()
    .AddDefaultTokenProviders(); // без этого метода работает

DbContext класс -
public class AppDbContext : IdentityDbContext<UserModel>
    {
        public AppDbContext(
            DbContextOptions<AppDbContext> options
            )
                : base(options)
        { }
    }


text:
Q: If we know Spec($M_1$) and Spec($M_2$), what could we say about Spec($M_1 \cup M_2$)? Let two domains $M_1$ and $M_2$ (Dirichlet conditions). If we know the spectrum of the Laplacian on $M_1$ and $M_2$, what could we say about Spect($M_1 \cup M_2$)?
Is there a theorem that might give us some information about it?

A: Let $\{\lambda_k\}$ be the eigenvalues of $M_1\cup M_2$; similarly, let $\{\lambda_k^{(j)}\}$ be the eigenvalues of $M_j$, $j=1,2$; in both cases arrange them in non-decreasing order. The domain monotonicity of Dirichlet eigenvalues implies that $$\lambda_k\ge \max(\lambda_k^{(1)}, \lambda_k^{(2)})\tag1$$ for every $k$. Equality holds in $(1)$ when $M_1=M_2$.
There is no upper bound for $\lambda_k$ in terms of $\lambda_k^{(j)}$. Indeed, let $M_1$ and $M_2$ be very thin spiral-like domains such that their union is a disk of radius $1$. Then the eigenvalues $\lambda_1^{(j)}$ can be made arbitrarily large while $\lambda_1$ remains the same.


text:
Q: Zend Framework - POP3 - retrieving message source Is it possible to retrieve the complete message source (similar tu Unix Mbox format) using Zend_Mail_Storage_Pop3 from the Zend Framework?
I'm using the following code to retrieve messages:
  $mail = new Zend_Mail_Storage_Pop3(array('host'     => 'localhost',
                                           'user'     => 'test',
                                           'password' => 'test'));
  echo $mail->countMessages() . " messages found\n";
  foreach ($mail as $message) {
      echo "Mail from '{$message->from}': {$message->subject}\n";
  }

It looks like the $mail object contains the message already split up into fields (ie. headers, contents, etc.). Is there any way to retrieve the original message source? I would like to be able to store it so if I need to parse the message again using a different tool, I will have the necessary information.

A: For now I'm trying to use the following code:
<?php
foreach ($mail as $messageNumber => $message) {
    echo $mail->getRawHeader($messageNumber);
    echo $mail->getRawContent($messageNumber);
}
?>


text:
Q: Sync Staging and Production Database How to sync staging and production database?
I have staging database and i want to sync it with production database. Production database contains new customers and sales order. I dont want to replace customers and sales orders tables. What is the correct way to import staging database into production database without replacing orders and new customers.
** I know there are lot of magento stores and every one is dealing with same kind of situation.Please share correct way of doing this. Thanks

A: It is possible to do this through the magerun2 command db:dump which makes it possible to strip tables from your database dump.
Below a small description about the Strip option (Use the --help flag for more information)
Strip option
  If you like to skip data of some tables you can use the --strip option.
  The strip option creates only the structure of the defined tables and
  forces `mysqldump` to skip the data.

  Separate each table to strip by a space.
  You can use wildcards like * and ? in the table names to strip multiple
  tables. In addition you can specify pre-defined table groups, that start
  with an

  Example: "dataflow_batch_export unimportant_module_* @log

     $ n98-magerun.phar db:dump --strip="@stripped"

Available Table Groups
  @admin         Admin tables.
  @log           Log tables.
  @sessions      Database session tables.
  @stripped      Standard definition for a stripped dump (logs, sessions).
  @sales         Sales data (orders, invoices, creditmemos etc).
  @quotes        Cart (quote) data.
  @customers     Customer data - Should not be used without @sales.
  @trade         Current trade data (customers and orders). You usally do not
                 want those in developer systems..
  @development   Removes logs and trade data so developers do not have to work
                 with real customer data.
  @ee_changelog  Changelog tables of new indexer since EE 1.13.
  @search        Search related tables.
  @idx           Tables with _idx suffix.


text:
Q: Remove knockout js bindings on cloned element I am using the knockout js template binding functionality to render a collection of items to an element:

When clicked, the child items are cloned and placed into another element:
$(".childSelector").on("click", ".childItem", function () {
    var clone = $(this).clone()[0];
    ko.cleanNode(clone);
    $(".targetNode").append(clone);
});

The problem is that when the source data changes and the template is re-bound to the new data, the following error is thrown:

Uncaught Error: Unable to parse bindings. Message: ReferenceError:
  Text is not defined; Bindings value: attr: { title: Text }

I had found another post that suggested using ko.cleanNode(element) to remove knockout's bindings, however this has not resolved the issue in my case.
Is there a way to remove knockout's bindings on a cloned element to prevent this error when re-binding?  If not I'll just "manually" clone the element by extracting the required data from the clicked element.
Here is a simple example of what I'm doing

A: You can remove all knockout bindings from an element by traversing the DOM and removing the data-bind attributes and knockout comments.
Use removeDataBindings(clone); but first clean the node with ko.cleanNode(clone) to clear any event handlers.
var commentNodesHaveTextProperty = document.createComment("test").text === "";
var startCommentRegex = commentNodesHaveTextProperty ? /^$/ : /^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/;
var endCommentRegex =   commentNodesHaveTextProperty ? /^$/ : /^\s*\/ko\s*$/;

function isStartComment(node) {
    return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
}

function isEndComment(node) {
    return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
}

function traverseNode(node, func) {
    func(node);
    node = node.firstChild;
    while (node) {
        traverseNode(node, func);
        node = node.nextSibling;
    }
}

function removeDataBindings(element) {
    var koComments = [];

    traverseNode(element, function (node) {
        if (isStartComment(node) || isEndComment(node)) {
            koComments.push(node);
            return;
        }
        //remove the 'data-bind' attributes
        if (node.nodeType === 1) { //ELEMENT_NODE
            node.removeAttribute('data-bind');
        }
    });

    //remove Knockout binding comments
    for (i = 0; i < koComments.length; i++) {
        node = koComments[i];
        if (node.parentNode) {
            node.parentNode.removeChild(node);
        }
    }
}

A: Oliver, using jQuery to clone elements bound to knockout like this is not a good idea. You should be using data-binding for the targetNode. If you haven't yet done so, its a good idea to go through the Knockout Tutorials to get a good understanding of the basic uses.
If you are trying to keep a list of items, with a clone button, here is a dead simple fiddle using nothing but Knockout to do so. If you are trying to do something else, let me know; your question isn't entirely clear on your goal.
HTML:

    <button data-bind="click: $parent.clone">Clone</button>

JS:
var ViewModel = function(data) {
    var self  = this;
    self.items = ko.observableArray(data);
    self.clone = function(item) {
        //The ko.toJS here is a handy copy tool for viewModels
        //It isn't necessary for simple arrays like this one
        //But I included it because for an array of objects, you will want to use it
        self.items.push(ko.toJS(item));
    };
};


text:
Q: Hibernate Criteria limit select So, I have a rather complex query I am trying to make using the Hibernate Criteria API. I have the following entity classes:

Code
  Gift
  GiftVendor
  GiftVendorStatus

with the following relationships:

Code 1<>1 Gift
  Gift 1<>* GiftVendor
  GiftVendor 1<>1 GiftVendorStatus

I need to build a Criteria query that returns a List of Code objects, but that restricts it to only Codes that have a Gift that have at least one GiftVendor with a GiftVendorStatus of Online. Here is the code I am using to build the criteria:
Criteria base = CodeDao.getBaseCriteria();
base.createAlias("gift","gift");
base.createAlias("gift.giftVendor","giftVendor");
base.createAlias("giftVendor.giftVendorStatus","giftVendorStatus");
base.add(Restrictions.like("giftVendorStatus.description", "Online%"));
return base.list();

This gives me a List of Code objects, restricted as I would expect. However, it also does additional queries to build out all of the unused relationships of the Gift object, even though I have all of the mappings set up with a fetch mode of Lazy. This results in 4 additional, separate queries for each of my 10000+ results.
I have code to do the query using HQL that works as expected:
String hql = "select c FROM Code c inner join c.gift g inner join g.giftVendors gv inner join gv.giftVendorStatus gvs" +
    " WHERE gvs.description like :desc";
HashMap<String,Object> params = new HashMap<String, Object>();
params.put("desc", "Online%");
return performQuery(hql, params);

That code gives me a List of Code objects, as expected, without doing all of the extra queries to populate the Gift object. How do I tell Hibernate not to do those extra queries with the Criteria API?
UPDATE: The problem here is not the retrieval of the Gift table, but rather unrelated one-to-one relationships from the Gift table. For example, Gift has a one-to-one relationship to GiftCommentAggregateCache. This table is in no way related to this particular query, so I would expect lazy initialization rules to apply, and the query to GiftCommentAggregateCache to not occur unless a read is attempted. However, with the Criteria query written out as above, it makes that separate query to populate the model object for GiftCommentAggregateCache.
If I use:
base.setFetchMode("gift.giftCommentAggregateCache", FetchMode.JOIN);

then I do not have any problems. However, that means that in order for this to work as I would expect, I need to add that line for every single unused one-to-one relationship that Gift has. Any ideas as to why the Lazy rules specified in the mappings are not coming into play here?
There are a few different things I have tried:
base.setFetchMode("gift", FetchMode.LAZY); // Still does additional queries

and
base.setFetchMode("gift", FetchMode.SELECT); // Still does additional queries

and
base.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); // Still does additional queries

and
base.setResultTransformer(Criteria.ROOT_ENTITY); // Still does additional queries

and
base.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP); // Still does additional queries

and
base.setProjection(Projections.property("gift")); // Does not do additional queries, but incorrectly returns a List of Gift objects, instead of a List of Code objects

A: From the Hibernate documentation:

Join fetching: Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.

In other words, try using base.setFetchMode("gift", FetchMode.JOIN)
I hope that helps.
Cheers


text:
Q: MongoDB aggregation too slow after migration from 2.4 to 2.6.11 In 2.4 version the aggregation works in about 1 minute and after migration to 2.6.11, the aggregation process ends in about 3 hours. I've recreated all indices but still remains slow. There are 6549937 objects in this collection.
The aggregation script:
db.runCommand({
aggregate: "Profile",
pipeline:
[
    { $match : { "count" : { "$gt" : 0} } },
    { $group :
        { "_id" : "$type", "sum" : { "$sum" : "$count"},
        "count" : { "$sum" : 1}, "min" : { "$min" : "$count"} ,
        "max" : { "$max" : "$count"}
        }
    },
    { $project:
        { _id: 1,
          count: 1,
          sum: 1,
          min: 1,
          max: 1
        }
    }
]});

Explain:
{
"stages" : [
    {
        "$cursor" : {
            "query" : {
                "count" : {
                    "$gt" : 0
                }
            },
            "fields" : {
                "count" : 1,
                "type" : 1,
                "_id" : 0
            },
            "plan" : {
                "cursor" : "BtreeCursor count_1",
                "isMultiKey" : false,
                "scanAndOrder" : false,
                "indexBounds" : {
                    "count" : [
                        [
                            0,
                            Infinity
                        ]
                    ]
                },
                "allPlans" : [
                    {
                        "cursor" : "BtreeCursor count_1",
                        "isMultiKey" : false,
                        "scanAndOrder" : false,
                        "indexBounds" : {
                            "count" : [
                                [
                                    0,
                                    Infinity
                                ]
                            ]
                        }
                    }
                ]
            }
        }
    },
    {
        "$group" : {
            "_id" : "$type",
            "sum" : {
                "$sum" : "$count"
            },
            "count" : {
                "$sum" : {
                    "$const" : 1
                }
            },
            "min" : {
                "$min" : "$count"
            },
            "max" : {
                "$max" : "$count"
            }
        }
    },
    {
        "$project" : {
            "_id" : true,
            "count" : true,
            "sum" : true,
            "min" : true,
            "max" : true
        }
    }
],
"ok" : 1 }

Explain query in 2.4 version:
{
"cursor" : "BtreeCursor count_1",
"isMultiKey" : false,
"n" : 5710623,
"nscannedObjects" : 5710623,
"nscanned" : 5710623,
"nscannedObjectsAllPlans" : 5710623,
"nscannedAllPlans" : 5710623,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 36445,
"nChunkSkips" : 0,
"millis" : 3556300,
"indexBounds" : {
    "count" : [
        [
            0,
            1.797693134862316e+308
        ]
    ]
},
"allPlans" : [
    {
        "cursor" : "BtreeCursor count_1",
        "n" : 5710623,
        "nscannedObjects" : 5710623,
        "nscanned" : 5710623,
        "indexBounds" : {
            "count" : [
                [
                    0,
                    1.797693134862316e+308
                ]
            ]
        }
    }
],
"oldPlan" : {
    "cursor" : "BtreeCursor count_1",
    "indexBounds" : {
        "count" : [
            [
                0,
                1.797693134862316e+308
            ]
        ]
    }
}}

Explain query in 2.6.11 version
{
"cursor" : "BtreeCursor count_1",
"isMultiKey" : false,
"n" : 5710623,
"nscannedObjects" : 5710623,
"nscanned" : 5710623,
"nscannedObjectsAllPlans" : 5710623,
"nscannedAllPlans" : 5710623,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 2585642,
"nChunkSkips" : 0,
"millis" : 17121523,
"indexBounds" : {
    "count" : [
        [
            0,
            Infinity
        ]
    ]
},
"allPlans" : [
    {
        "cursor" : "BtreeCursor count_1",
        "isMultiKey" : false,
        "n" : 5710623,
        "nscannedObjects" : 5710623,
        "nscanned" : 5710623,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nChunkSkips" : 0,
        "indexBounds" : {
            "count" : [
                [
                    0,
                    Infinity
                ]
            ]
        }
    }
],
"filterSet" : false,
"stats" : {
    "type" : "FETCH",
    "works" : 8293430,
    "yields" : 2585642,
    "unyields" : 2585642,
    "invalidates" : 2583,
    "advanced" : 5710623,
    "needTime" : 0,
    "needFetch" : 2580241,
    "isEOF" : 1,
    "alreadyHasObj" : 0,
    "forcedFetches" : 0,
    "matchTested" : 0,
    "children" : [
        {
            "type" : "IXSCAN",
            "works" : 5710623,
            "yields" : 2585642,
            "unyields" : 2585642,
            "invalidates" : 2583,
            "advanced" : 5710623,
            "needTime" : 0,
            "needFetch" : 0,
            "isEOF" : 1,
            "keyPattern" : "{ count: 1 }",
            "isMultiKey" : 0,
            "boundsVerbose" : "field #0['count']: (0.0, inf.0]",
            "yieldMovedCursor" : 0,
            "dupsTested" : 0,
            "dupsDropped" : 0,
            "seenInvalidated" : 0,
            "matchTested" : 0,
            "keysExamined" : 5710623,
            "children" : []
        }
    ]
}}


text:
Q: CRM 2013: Confirmation box on business process flow using Javascript I think its a little problem for you gurus, I want to add a confirmation box on stage completion of Business process flow. So I want to seek your kind help in this regard.

A: I'm not (yet) familiar with business process flows, but I understand they're basically real-time workflows attached to the form: I'd attempt "cheating" the system like this:

*

*Add two new fields to the form, make them hidden and readonly

*Attach to one of the new field's onchange the code to request confirmation

*Split the flow in two parts, before and after the confirmation

*The first half is what you invoke in place of what you have now

*Attach to the other field the second half of the flow

*The onchange will request confirmation

*on confirm, change the second field's value (so the second half of the flow runs)

Logic similar to when you needed to perform real-time processsing through plugins (change hidden field - save - preupdate plugin)


text:
Q: Delay validation until user tabs out of all inputs in an input group My form has a group of three checkboxes. The user must select at least one of the three options:
<form id="myform" class="validated-form" novalidate="novalidate">
  <div id="fname" class="btn-group btn-group-toggle" data-toggle="buttons">
    <label>
      a
      <input type="checkbox" value="a" name="fname"/>
    </label>
    <label>
      b
      <input type="checkbox" value="b" name="fname"/>
    </label>
    <label>
      c
      <input type="checkbox" value="c" name="fname"/>
    </label>
  </div>
</form>

I am using the following onfocusout callback to validate the checkbox group:
onfocusout: function(element) {

  if($(element).prop('type') == 'checkbox') {
        this.element(element);
      }

  }

See JSFiddle.

The problem: When the user tabs through the options, I would like the validator to wait until they have tabbed out of the group completely (i.e. when all three of the checkboxes have lost focus) before validating it.

My first attempt was to modify the if-statement in the callback above to include a condition that selects all elements within the group that have focus and then checks that the length of the resulting object array is 0, like so:
onfocusout: function(element) {

   if($(element).prop('type') == 'checkbox' && $(element).closest('.btn-group').find('label:focus').length == 0) {
        this.element(element);
      }
  }

But since there is a lag between the time that one element loses focus and another one receives it, the above doesn't work. I think this is due to the callback firing as soon as the input being validated loses focus and before the new element gains focus. At this time, no elements are in focus, so the if-statement condition always evaluates to true. For the same reason, I am unable to detect which element the focus has shifted to (so I can't check if the newly focused element is part of the checkbox group).
So my next attempt was to use setTimeout:
onfocusout: function(element) {

  setTimeout(function() {
    if($(element).prop('type') == 'checkbox' && $(element).closest('.btn-group').find('label:focus').length == 0) {
        this.element(element);
      }
  }, 1);
  }

This seems to switch off validation completely - tabbing from one checkbox to another doesn't trigger validation but neither does tabbing out of the checkbox group completely. Have I used it incorrectly? (In the Fiddle, it seems to have no effect.)
Is there a better solution to this problem or am I trying to solve the wrong problem?
Note: I can't use the onclick callback because it isn't compatible with the widget I'm using in my actual form. I prefer the feel of onfocusout over onclick anyway since it's more consistent with the Validate plugin's default behaviour.

A: I used event.relatedTarget to identify which element received focus and modified the if-statement to trigger validation only if the name of the relatedTarget doesn't match that of the checkbox that lost focus:
onfocusout: function(element, event) {

    if($(element).prop('type') == 'checkbox' && $(event.relatedTarget).attr('name') != $(element).attr('name')) {
          $(element).valid();
        }

  }

See JSFiddle.
Not sure if there are any caveats to this approach and would like to leave the post open in case someone has a better solution.


text:
Q: Good approach to switch database for Test mode / Sand box mode : Rails 6 I am working on an app where I now need to add test mode or sandbox mode features like Stripe provides in the dashboard. In this feature, when the user turned the test mode on, the user can test the functionality and can create dummy data in the same login session/token.
I have tried to use the Rails 6 feature to use multiple databases but have a few questions:

*

*is it good to switch the connection in production for test mode even we will not have many test requests?

*will it be good to have a separate instance for test mode with the test subdomain? in this case how we should manage the login sessions? should we copy data to the test the database? will it be good and common practice?

I only can manage to implement this if I have user data in the test database so that when I switch database connection system will not send an unauthenticated response.
Note:

*

*for login and user update, it will use the primary database all time and for other actions, it will use the test_mode database. I am doing this by skip_around_action in a specific controller.

*We are doing this so that when the user turned off test mode, it will update the primary database and the next request will use the primary database as per around_action logic

Here is my current code in application_controller.rb:
    around_action :setup_db_connection
    def setup_db_connection
      database_key = (user.test_mode?) ? :test_mode : :primary
      ActiveRecord::Base.connected_to(database: database_key) do
        yield
      end
    end

test_mode database key has test database configuration in database.yml and similarly for primary database key. Both are completely two different databases.
Can anyone please tell me if I am going in to correct direction? Any help or thought will be appriciated. Thank you in advance!!!!

A: You should just create an additional environment as this is the exact problem that they are designed to solve.
Rails just ships preconfigured with development, test and production as thats the bare minimum you can get by with. You can actually have an unlimeted number of environments.
So lets say you want to create an enviroment named staging which closely matches your production environment. You can start by copying the productions settings:
cp app/environments/production.rb app/environments/staging.rb

And then just setup an additional hash in your database.yml and credentials files.
staging:
  <<: *default
  database: my_app_staging

You can then set the environment by using the RAILS_ENV env var or the command line arguments when starting the Rails server. Your staging environment can be run for example in a separate Heroku application made available on a subdomain. If you're using Heroku or some other SAAS platform a hobby tier will often be sufficient for staging.
When it comes to data you can either work on a set of dummy data generated by wiping and seeding or regularily wipe the staging database with a backup from your production database.
I would not consider using a "test mode switch" a good idea as it makes far to easy to inadvertantly mess things up. Using a separate environment lets you use a completely different set of credentials as well so you won't accentially do something like create a real credit card charge or destroy data on third party services. Sandboxes should be isolated.


text:
Q: Keyboard navigation in jQuery : two presses instead of one I have a keyboard navigation on my page who permit to navigate between the ".layout" classes. The problem is that after the first start of the page it's necessary to press twice the "down" arrow key to trigger the movement of the page. What's wrong ?
Press : "up" and "down" on your keyboard to see : http://jsfiddle.net/Xroad/LPvS9/4/
PS: I have to keep "#page" instead of "html,body" otherwise the code comes into conflict with other functions.
$(function(){
    var  positions = []
    $('.layout').each(function(){
       positions.push(parseInt($(this).offset().top));
    })
    console.log(positions)
    var count=-1
    var x=positions.length-1
    $(window).keydown(function (event) {
        switch (event.keyCode) {
        case 38:
            if(count>=x*(-1)&&count!==0){
                count--
                console.log(count)
                $('#page').stop().animate({scrollTop:positions[count]},700);
                }else{event.preventDefault()}

            break;

        case 40:
            if(count<=x){
                count++
                console.log(count)
                $('#page').stop().animate({scrollTop:positions[count]},700);
                }else{event.preventDefault()}

            break;
        }
     });
});

A: you initialize
var count=-1

rather do
var count=0


text:
Q: Prove that $∀a, b, c ∈ \mathbb Z$ with $b \neq 0$, if $b|c$, then $\gcd(a, b) = \gcd(a + c, b)$.
Prove that $∀a, b, c ∈ \mathbb Z$ with $b \neq 0$, if $b|c$, then $\gcd(a, b) = \gcd(a + c, b)$.

I've proved it in the following way:
$\gcd(c,b) = b.$
Let $\gcd(a,b) = x$, $x|a$ and $x|b$
Since $b$ is the $\gcd$ of $c$,
if $x|b$ then $x|c$
Thus, $\gcd(a+c, b) = x = \gcd(a, b)$.
Was wondering if this is a solid proof. If not, is there anyway I can improve on this? Thanks for helping out

A: Let $d=\gcd(a,b)$. Then since $b | c$, we have $d|c$ which implies $d| a+c$. Thus, $k=\gcd(a+c,b)\ge d$.
Now, $k | b$ and $k|a+c$. But $k|b \Rightarrow k|c \Rightarrow k|a$ (Because $k$ also divides $a+c$). Thus, we have $k$ divides both $a$ and $b \Rightarrow k\le d$
In conclusion, $k\le d $ and $k \ge d$ implies $k=d$, which was what was to be proved!

A: The conclusion $\gcd(a+c, b) = x = \gcd(a, b)$ is not that clear from your previous parts.
One way to show the claim $\gcd(a, b) = \gcd(a + c, b)$ is to split the task into two parts:
$\qquad\qquad\gcd(a, b)|\gcd(a + c, b)\qquad$ and $\qquad\gcd(a+c, b)|\gcd(a, b)$
from which equality follows.

We obtain
  \begin{align*}
\begin{array}{rlr}
\gcd(a,b)|b&\qquad\qquad(\text{by definition of }\gcd)&\qquad (1)\\
b|c&\qquad\qquad(\text{by assumption})\\
\Longrightarrow \gcd(a,b)|c&\qquad\qquad(\text{by  transitivity of }|)&\qquad(2)\\
\\
\gcd(a,b)|a&\qquad\qquad(\text{by definition of }\gcd)&\qquad(3)\\
\\
\Longrightarrow  \gcd(a,b)|(a+c)&\qquad\qquad(\text{by(2) and (3)})&\qquad(4)\\
\\
\color{blue}{\Longrightarrow  \gcd(a,b)|\gcd(a+c,b)}&\qquad\qquad(\text{by(1) and (4)})&\qquad\color{blue}{(\text{I})}\\
\end{array}
\end{align*}

We further obtain
\begin{align*}
\begin{array}{rlr}
\gcd(a+c,b)|b&\qquad\qquad(\text{by definition of }\gcd)&\qquad(5)\\
b|c&\qquad\qquad(\text{by assumption})\\
\Longrightarrow \gcd(a+c,b)|c&\qquad\qquad(\text{by  transitivity of }|)&\qquad(6)\\
\\
\gcd(a+c,b)|(a+c)&\qquad\qquad(\text{by definition of }\gcd)&\qquad(7)\\
\\
\Longrightarrow  \gcd(a+c,b)|a&\qquad\qquad(\text{by(6) and (7)})&\qquad(8)\\
\\
\color{blue}{\Longrightarrow  \gcd(a+c,b)|\gcd(a,b)}&\qquad\qquad(\text{by(5) and (8)})&\qquad\color{blue}{(\text{II})}\\
\end{array}
\end{align*}

We conclude from (I) and (II)
  \begin{align*}
\color{blue}{\gcd(a,b)=\gcd(a+c,b)}
\end{align*}


text:
Q: Disable highlight on q-item (Quasar Framework) When the current url is equal to :to="something" property, the q-item is highlighted in blue.

But I want q-item to keep black without highlighted in blue even though the current url is equal to the :to="something" property.

This is my q-item code (I use Quasar v2.0.4):
<q-item
  :to="{ name: 'home' }"
>
  <q-item-section avatar>
    <q-icon name="home" size="md" />
  </q-item-section>
  <q-item-section>
    Home
  </q-item-section>
</q-item>

Is it possible to disable highlight on q-item?

A: You can use active-class="remove-active":
<q-item
  active-class="remove-active" // Here
  :to="{ name: 'home' }"
>
  <q-item-section avatar>
    <q-icon name="home" size="md" />
  </q-item-section>
  <q-item-section>
    Home
  </q-item-section>
</q-item>

A: You can use active-class="q-item-no-link-highlighting" to make q-item inactive keeping black:
<q-item
  active-class="q-item-no-link-highlighting" // Here
  :to="{ name: 'home' }"
>
  <q-item-section avatar>
    <q-icon name="home" size="md" />
  </q-item-section>
  <q-item-section>
    Home
  </q-item-section>
</q-item>


text:
Q: How can I find the the greatest common divisor with Euclid's algorithm? How can I create a function ggt[p,q],and find the greatest common divisor with Euclid's algorithm?p,q are integer.

A: Like this:
ggt[p_, q_] := First[NestWhile[{Last[#], Mod @@ #} &, {p, q}, Last[#] != 0 &]]


text:
Q: Is Multi-AZ RDS a solution for slow database speeds overseas? I have an app based in Australia, which runs quick enough within Australia, Asia and the US. However, in Europe/UK, it's unbearably slow.
The data being sent across is reasonably negligible, so I'm assuming it's latency communicating with the database. I've never attempted to horizontally-scale a database, so I'm not sure where to start.
Would using AWS Multi-AZ RDS work for this use case?

A: AWS Multi-AZ RDS will not work in this case as the purpose of Multi-AZ is fault tolerance/high availability rather than performance:

Amazon RDS provides high availability and failover support for DB instances using Multi-AZ deployments.

Beyond that simple answer, this is an architecture question that will be highly dependent on your application and the cost/benefit of removing this latency. From a technical perspective, to remove regional latency you should consider multi-region architectures. This may be at the database level, a cache level, or require a full active-active multi-region architecture depending on your application and cost considerations. For example:

*

*AWS Re:invent multi-region architecture

*Multi-region active-active discussion

*Cross-region read replicas


text:
Q: Solve nonlinear differential equation $y'=a(y^{a-1} + (C-y)^{a-1})$ My differential equation reads
\begin{align}
y'=a(y^{a-1} + (C-y)^{a-1})
\end{align}
where $a\in(0,1)$ is some scalar and $y(0)=1/C$ a constant.

*

*Can you guys hint me to the solution, if it exists?


text:
Q: Simplifying a simple Summation Here is a series: S = { $0,1,1,2,2,3,3 ...$}
To find out sum of $1st$ n terms, expression is:
$$
S = \sum_{k=1}^{n}\left\lfloor\frac{k}{2}\right\rfloor
$$
How do I simplify the above summation?
Also, I want to avoid fractions in the answer.

A: You do not need the first $0$ term when summing. Just consider the set $\{1,1,2,2,3,3,\dots\}$ then the sum of first $2n$ terms is
$$ S_{2n} = 2 \sum_{i=1}^n i = 2 ( 1 + 2 + \dots + n) = n(n+1) $$
This can be seen by summing $1+2+\dots+n$ with $n+(n-1)+\dots+1$ and adding terms to terms. You get $n$ times the number $n+1$.
The sum of first $2n+1$ terms is
$$S_{2n+1} = S_{2n} + n+1 = n(n+1)+n+1= (n+1)^2$$
Indeed when you compute $S_n$ you get
$$ 1,2,4,6,9,12,16,\dots$$
which alternates between perfect squares terms and $n(n+1)$ terms.

A: Deal separately with the cases $n$ even (say $n=2m$) and $n$ odd (say $n=2m+1$).
For the case $n=2m$, you want $2(1+2+3+\cdots)$, which is $m(m+1)$.
For the case $n=2m+1$, you get $m(m+1)+(m+1)$, which is $(m+1)^2$.

A: Well, that's exactly the thing we want to do, avoid fractions and remove the floor. So, what is the most natural thing to do when we want to remove the floor? Separate into cases!
$$\sum_{k=1}^{n}\left \lfloor \frac{k}{2} \right \rfloor  = \sum_{k=1}^{[n/2]} \left \lfloor \frac{2k}{2} \right \rfloor + \left \lfloor \frac{2k+1}{2} \right \rfloor = \sum_{k=1}^{[n/2]} (2k + 1/2) = t(t+1) + t/2$$ where $t = [n/2]$


text:
Q: Need design suggestion for storing data for budget keeping application I'm writing an application that I will use to keep up with my monthly budget. This will be a C# .NET 4.0 Winforms application.
Essentially my budget will be a matrix of data if you look at it visually. The columns are the "dates" at which that budget item will be spent. For example, I have 1 column for every Friday in the month. The Y axis is the name of the budget item (Car payment, house payment, eating out, etc). There are also categories, which are used to group the budget item names that are similar. For example, a category called "Housing" would have budget items called Mortgage, Rent, Electricity, Home Insurance, etc.
I need a good way to store this data from a code design perspective. Basically I've thought of two approaches:
One, I can have a "BudgetItem" class that has a "Category", "Value", and "Date". I would have a linear list of these items and each time I wanted to find a value by either date or category, I iterate this list in some form or fashion to find the value. I could probably use LINQ for this.
Second, I could use a 2D array which is indexed first by column (date) and second by row. I'd have to maintain categories and budget item names in a separate list and join the data together when I do my lookups somehow.
What is the best way to store this data in code? I'm leaning more towards the first solution but I wanted to see what you guys think. Later on when I implement my data persistence, I want to be able to persist this data to SQL server OR to an XML file (one file per monthly budget).

A: While your first attempt looks nicer, obviusly the second could be faster (depends on how you implement it). However when we are talking about desktop applications which are not performance critical, your first idea is definitely better, expecially because will help you a lot talking about maintaining your code. Also remember that the entity framework could be really nice in this situation
Finally if you know how to works with XML, I think is really better for this type of project. A database is required only when you have a fair amount of tables, as you explained you will only have 2 tables (budgetitem and category), I don't think you need a database for such a simple thing


text:
Q: How to shift the red border underneath of black box? I am trying to shift the red border underneath of the black box. How shall I shift the red border?
This is for a css project. In the past I tried to shift the div in html, but the result is unchanged.

#box{
width:150px;
padding:5px;
height:30px;
background-color:#323232;
float:right;
color:white;
text-align:center;
text-transform:uppercase;
}

#border{
border-bottom:2px solid red;
position: relative;
}

Text Goes Inside

Here how it should look like

A: Simple: instead of using float to get your box to the right, use margin-left: auto;
So you can change your CSS to:
#box {
    width:150px;
    padding:5px;
    height:30px;
    background-color:#323232;
    margin-left: auto;
    color:white;
    text-align:center;
    text-transform:uppercase;
}

#border {
    border-bottom:2px solid red;
    position: relative;
}

Here's the JSFiddle.

A: Float: right; is what is making the border go above your box. If you add clear: both; to your border it should display how you'd like.

#box{
width:150px;
padding:5px;
height:30px;
background-color:#323232;
float:right;
color:white;
text-align:center;
text-transform:uppercase;
}

#border{
border-bottom:2px solid red;
position: relative;
clear: both;
}

Text Goes Inside

A: html:

Text Goes Inside

CSS:
#box{
width:150px;
padding:5px;
height:30px;
background-color:#323232;
color:white;
text-align:center;
text-transform:uppercase;
position: relative;
}

#border{
border-bottom:2px solid red;
position: relative;
}

.outer {
  width: 100%;
}


text:
Q: How to Pass Widget and Functions of That Widget To main.dart When Completing an Animation? I'm kinda new to Flutter. In main.dart file I have a logo and when I run the application, the logo fades into the screen and go to the top of the screen. I have used two animation controllers for that.
In welcome.dart file there is a code for two buttons (login and Signup) one animation controller for fade in animation to that buttons.
I need to show that when logo completes the animations, show the buttons on the screen with fade in animation.
What I have tried is put adListener to the logo animation and when logo animation completes, start the button animations. But it's not working.
Here's my code -
main.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'welcome.dart';

void main() {
  runApp(MyApp());

  SystemChrome.setSystemUIOverlayStyle(
    SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarBrightness: Brightness.light),
  );

}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: ('SplashScreeen'),
      home: MySplashScreen(title: 'SplashScreen'),
    );
  }
}

class MySplashScreen extends StatefulWidget {
  MySplashScreen({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MySplashScreenState createState() => _MySplashScreenState();
}

class _MySplashScreenState extends State<MySplashScreen>
    with TickerProviderStateMixin {

  AnimationController fadeAnimationLogoController;
  AnimationController moveUpAnimationLogoController;
  Animation<double> fadeAnimationLogo;
  Animation<Offset> moveUpAnimationLogo;

  initState(){

super.initState();

fadeAnimationLogoController = AnimationController(duration: Duration(milliseconds: 1500),vsync: this);
moveUpAnimationLogoController = AnimationController(duration: Duration(milliseconds: 1000),vsync: this,);
fadeAnimationLogo =CurvedAnimation(parent: fadeAnimationLogoController, curve: Curves.easeIn);
moveUpAnimationLogo = Tween<Offset>(begin: Offset(0,0),end: Offset(0, -0.2),).animate(moveUpAnimationLogoController);

fadeAnimationLogoController.forward();

fadeAnimationLogoController.addListener((){

if(fadeAnimationLogo.status == AnimationStatus.completed){

  moveUpAnimationLogoController.forward();
}

});

  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: FadeTransition (
        opacity: fadeAnimationLogo,
        child: SlideTransition(
          position: moveUpAnimationLogo,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image(
              image: AssetImage('assets/images/csrhuntlogo.png'),
              height: 300,
              width: 300,
            ),
            Text(
              ('C S R  H U N T'),
              style: TextStyle(
                fontFamily: 'League Spartan',
                height: 1,
                fontSize: 34,
                color: Colors.black,
                decoration: TextDecoration.none,
              ),
            ),
            Text(
              ('FIND     PLAY     EARN'),
              style: TextStyle(
                fontFamily: 'Montserrat',
                height: 1,
                fontSize: 15,
                color: Colors.black,
                decoration: TextDecoration.none,
              ),
            ),
          ],
        ),
      ),
      ),
    );

  }

}

welcome.dart
import 'package:flutter/material.dart';

class Welcome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: ('WelcomeScreen'),
      home: WelcomeScreen(title: 'WelcomeScreen'),
    );
  }
}

class WelcomeScreen extends StatefulWidget {
  WelcomeScreen({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _WelcomeScreenState createState() => _WelcomeScreenState();
}

class _WelcomeScreenState extends State<WelcomeScreen>
    with SingleTickerProviderStateMixin {
  AnimationController fadeAnimationWelcomeController;
  Animation<double> fadeAnimationWelcome;

  @override
  void initState() {
    fadeAnimationWelcomeController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 2000),
    );
    fadeAnimationWelcome = CurvedAnimation(
        parent: fadeAnimationWelcomeController, curve: Curves.easeIn);
    super.initState();

    fadeAnimationWelcomeController.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: FadeTransition(
        opacity: fadeAnimationWelcome,
        child: Stack(
          children: <Widget>[
            Positioned(
              top: 590,
              left: 20,
              child: SizedBox(
                width: 350.0,
                height: 50.0,
                child: RaisedButton(
                  color: new Color.fromRGBO(255, 213, 0, 1.0),
                  textColor: Colors.black,
                  onPressed: () {},
                  child: Text(
                    'log in',
                    style: TextStyle(
                      height: 1,
                      fontSize: 25,
                      fontFamily: 'League Spartan',
                    ),
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(18.0),
                    side: BorderSide(color: Colors.transparent),
                  ),
                ),
              ),
            ),
            Positioned(
              bottom: 50,
              left: 20,
              child: SizedBox(
                width: 350.0,
                height: 50.0,
                child: RaisedButton(
                  color: new Color.fromRGBO(255, 213, 0, 1.0),
                  textColor: Colors.black,
                  onPressed: () {},
                  child: Text(
                    'Sign up',
                    style: TextStyle(
                      height: 1,
                      fontSize: 25,
                      fontFamily: 'League Spartan',
                    ),
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(18.0),
                    side: BorderSide(color: Colors.transparent),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

A: You can copy paste run full code below
For demo purpose, I slow down animation duration to 5 seconds
You can set a bool showWelcome to control when to show SingUp button
When Move Up Logo animation complete show SignUp button with setState
code snippet
moveUpAnimationLogoController.addListener(() {
      if (moveUpAnimationLogo.status == AnimationStatus.completed) {
        //moveUpAnimationLogoController.forward();
        setState(() {
          showWelcome = true;
        });
      }
    });

showWelcome
              ? Expanded(
                  child: WelcomeScreen(
                    title: "test",
                  ),
                )
              : Container(),

working demo

full code
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());

  SystemChrome.setSystemUIOverlayStyle(
    SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarBrightness: Brightness.light),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: ('SplashScreeen'),
      home: MySplashScreen(title: 'SplashScreen'),
    );
  }
}

class MySplashScreen extends StatefulWidget {
  MySplashScreen({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MySplashScreenState createState() => _MySplashScreenState();
}

class _MySplashScreenState extends State<MySplashScreen>
    with TickerProviderStateMixin {
  AnimationController fadeAnimationLogoController;
  AnimationController moveUpAnimationLogoController;
  Animation<double> fadeAnimationLogo;
  Animation<Offset> moveUpAnimationLogo;
  bool showWelcome = false;

  initState() {
    super.initState();

    fadeAnimationLogoController =
        AnimationController(duration: Duration(seconds: 5), vsync: this);
    moveUpAnimationLogoController = AnimationController(
      duration: Duration(seconds: 5),
      vsync: this,
    );
    fadeAnimationLogo = CurvedAnimation(
        parent: fadeAnimationLogoController, curve: Curves.easeIn);
    moveUpAnimationLogo = Tween<Offset>(
      begin: Offset(0, 0),
      end: Offset(0, -0.2),
    ).animate(moveUpAnimationLogoController);

    fadeAnimationLogoController.forward();

    fadeAnimationLogoController.addListener(() {
      if (fadeAnimationLogo.status == AnimationStatus.completed) {
        moveUpAnimationLogoController.forward();
      }
    });

    moveUpAnimationLogoController.addListener(() {
      if (moveUpAnimationLogo.status == AnimationStatus.completed) {
        //moveUpAnimationLogoController.forward();
        setState(() {
          showWelcome = true;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          Container(
            color: Colors.white,
            child: FadeTransition(
              opacity: fadeAnimationLogo,
              child: SlideTransition(
                position: moveUpAnimationLogo,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Image(
                      image: AssetImage('assets/images/csrhuntlogo.png'),
                      height: 300,
                      width: 300,
                    ),
                    Text(
                      ('C S R  H U N T'),
                      style: TextStyle(
                        fontFamily: 'League Spartan',
                        height: 1,
                        fontSize: 34,
                        color: Colors.black,
                        decoration: TextDecoration.none,
                      ),
                    ),
                    Text(
                      ('FIND     PLAY     EARN'),
                      style: TextStyle(
                        fontFamily: 'Montserrat',
                        height: 1,
                        fontSize: 15,
                        color: Colors.black,
                        decoration: TextDecoration.none,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          showWelcome
              ? Expanded(
                  child: WelcomeScreen(
                    title: "test",
                  ),
                )
              : Container(),
        ],
      ),
    );
  }
}

class WelcomeScreen extends StatefulWidget {
  WelcomeScreen({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _WelcomeScreenState createState() => _WelcomeScreenState();
}

class _WelcomeScreenState extends State<WelcomeScreen>
    with SingleTickerProviderStateMixin {
  AnimationController fadeAnimationWelcomeController;
  Animation<double> fadeAnimationWelcome;

  @override
  void initState() {
    fadeAnimationWelcomeController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 2000),
    );
    fadeAnimationWelcome = CurvedAnimation(
        parent: fadeAnimationWelcomeController, curve: Curves.easeIn);
    super.initState();

    fadeAnimationWelcomeController.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: FadeTransition(
        opacity: fadeAnimationWelcome,
        child: Stack(
          children: <Widget>[
            Positioned(
              top: 590,
              left: 20,
              child: SizedBox(
                width: 350.0,
                height: 50.0,
                child: RaisedButton(
                  color: new Color.fromRGBO(255, 213, 0, 1.0),
                  textColor: Colors.black,
                  onPressed: () {},
                  child: Text(
                    'log in',
                    style: TextStyle(
                      height: 1,
                      fontSize: 25,
                      fontFamily: 'League Spartan',
                    ),
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(18.0),
                    side: BorderSide(color: Colors.transparent),
                  ),
                ),
              ),
            ),
            Positioned(
              bottom: 50,
              left: 20,
              child: SizedBox(
                width: 350.0,
                height: 50.0,
                child: RaisedButton(
                  color: new Color.fromRGBO(255, 213, 0, 1.0),
                  textColor: Colors.black,
                  onPressed: () {},
                  child: Text(
                    'Sign up',
                    style: TextStyle(
                      height: 1,
                      fontSize: 25,
                      fontFamily: 'League Spartan',
                    ),
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(18.0),
                    side: BorderSide(color: Colors.transparent),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}


text:
Q: Algorithm: array of arrays in Cocoa Touch (perhaps using NSCountedSet) This one is a bit tedious in as far as explaining, so here goes. I'm essentially populating a tableView on the iPhone with multiple sections, and potentially multiple rows per section. To my understanding, it's best to have an array of arrays so that you can simply determine how many sections one has by sending a message to the top level array of count, then for rows per section, doing the same for the inner array(s).  My data is in the form of a dictionary. One of the key/value pairs in the dictionary determines where it will be displayed on the tableView.  An example is the following:
{
  name: "bob",
  location: 3
}
{
  name: "jane",
  location: 50
}
{
  name: "chris",
  location: 3
}

In this case I'd have an array with two subarrays. The first subarray would have two dictionaries containing bob and chris since they're both part of location 3. The second subarray would contain jane, since she is in location 50. What's my best bet in Cocoa populate this data structure? A hash table in C would probably do the trick, but I'd rather use the classes available in Cocoa.
Thanks and please let me know if I need to further clarify.

A: The following code works: (edit: added my initialization code)
NSArray * arrayOfRecords = [NSArray arrayWithObjects:

    [NSDictionary dictionaryWithObjectsAndKeys:
     @"bob", @"name",
      [NSNumber numberWithInt:3], @"location",  nil],

    [NSDictionary dictionaryWithObjectsAndKeys:
     @"jane", @"name",
      [NSNumber numberWithInt:50], @"location",  nil],

    [NSDictionary dictionaryWithObjectsAndKeys:
     @"chris", @"name",
      [NSNumber numberWithInt:3], @"location",  nil],

    nil];

NSMutableDictionary * sections = [NSMutableDictionary dictionary];

for (NSDictionary * record in arrayOfRecords)
{
    id key = [record valueForKey:@"location"];
    NSMutableArray * rows = [sections objectForKey:key];

    if (rows == nil)
    {
        [sections setObject:[NSMutableArray arrayWithObject:record] forKey:key];
    }
    else
    {
        [rows addObject:record];
    }
}

NSArray * sortedKeys = [[sections allKeys] sortedArrayUsingSelector:@selector(compare:)];
NSArray * sortedSections = [sections objectsForKeys:sortedKeys notFoundMarker:@""];

NSLog(@"%@", sortedSections);

A: And NSDictionary is a hash table.

A: In Cocoa, it's best to use model objects rather than primitive collections, especially when using Bindings. The dictionaries should certainly be model object, and you may want to turn your inner arrays into model objects as well. (The outer array should stay an array.)
Cocoa Touch doesn't have Bindings, but I find (in Cocoa, as I don't program my iPhone) that model objects make things easier to think about and work with. I recommend you make model objects anyway.
("Model" refers to Cocoa's "Model-View-Controller" pattern, in which Cocoa provides view and controller objects and you provide the model.)


text:
Q: How to create WPF UserControl in MVVM I have one doubt in MVVM, What is the procedure to create UserControl Example EmunRadioButton.
Public class EmunRadioButton: RadioButton.
{
//code
}

My Question is: where to create this EmunRadioButton class that is ( View , ViewModel or Model);
Please give the hint

A: I dont think this is UserControl. More like CustomControl.
In UserControl, its basicaly multiple controls put together. In CustomControl, you either create or modify completly new control.
In both cases, it would be little wrong to try to put MVVM into this. Especialy because you need to use Dependency properties to expose state of your new control. This way you can use MVVM when you put your control in another View.

A: Since this class is derived from a View related class, and doesn't touch your model directly I personally would put the file (XAML or code file) in my View folder.


text:
Q: MediaPlayer Windows Server 2012 I made my own media player using System.Windows.Media.MediaPlayer and it's working perfectly on Windows 7/Windows 8/Windows 8.1, but when I am using my media player on Windows Server 2012 I receive the error "Error: System.Windows.Media.MediaPlayer.ExceptionEventArgs". What can I do to fix that ?
The server on which I want to run the media player it's not mine and I don't have unattended access to it so I created a virtual machine with Windows Server 2012 on it, but I received the same error. Also I have to mention that the application is using .NET Framework 4.5 which I can see that it's already installed on Windows Server 2012.
Please help me with these guys !

A: Add this feature; User Interface and Infrastructure > Desktop Experience.
After that try that.


text:
Q: how to override existing jar implementation of hive with custom jar I have to provide my own implementation of some existing hive functionality with my custom jars. I try --auxpath with setting

set mapreduce.job.classpath.user.precedence=true;

but it didn't work. Can anybody help me what is wrong with this method as hive pics it's own jars to execute instead of my jars.

A: try exporting HIVE_AUX_JARS_PATH variable as
export HIVE_AUX_JAR_PATH=$HIVE_AUX_JAR_PATH:/path/to/your/jar

or add you jar path in varaible  HIVE_AUX_JARS_PATH in hive-env.sh file
And add following property in hive-site.xml
<property>
  <name>hive.aux.jars.path</name>
  <value>file:///path/to/JAR</value>
</property>

A: /usr/bin/hive -hiveconf hive.aux.jars.path=file:///PATH/TO/JAR


text:
Q: Combine multiple SQL select statements into columns I'm having a hard time wrapping my mind around this, any assistance is most appreciated.
I have two select statements with joins to 1 or more tables.
SELECT repinfo.repName, SUM(callstatssummary.CallsIn)
FROM repinfo
LEFT JOIN callstatssummary
ON repinfo.isaacID = callstatssummary.IsaacID AND callstatssummary.ShiftDate >= '2013-02-10' AND callstatssummary.ShiftDate <= '2013-02-16'
GROUP BY repinfo.repName;

The output of the first statement is a list of everyone in the repinfo table, with the sum of the total calls they took during the week. I used a left join to include people who didn't take calls in the result.
SELECT repinfo.repName, SUM(`1036`.afterRgu) - SUM(`1036`.priorRgu)
FROM repinfo
JOIN reporders
ON repinfo.repID = reporders.oRep
JOIN `1036`
ON reporders.workOrder = `1036`.workOrder AND `1036`.entryDate >= '2013-02-10' AND `1036`.entryDate <= '2013-02-16' AND `1036`.afterRgu >= `1036`.priorRgu
GROUP BY repinfo.repName;

The second statement outputs the number of products that each person sold during the week. The repinfo table has the information about the representative, which joins with the reporders table to match the work order. The 1036 table has detailed information about the orders.
I am looking to output something like this - essentially combine the output of the two select statements:
|  repName  |  SUM(callstatssummary.CallsIn) |  SUM(`1036`.afterRgu) - SUM(`1036`.priorRgu)  |
______________________________________________________________________________________________
| Bruce W   | 41                             | 13                                            |
| Cathy M   | 84                             | 17                                            |
| Jonah S   | NULL                           | 29                                            |

Any suggestions?

A: One way to combine those statements is to make each of them a derived-table / inline-view and join on repName.
Please note: Obviously you would want to join on a rep ID number (or whatever you call the primary key of the repinfo table) if two reps can have the same name.
select
  r.repName, c.sumCallsIn, o.sumProdSold
from
  repinfo r
  left join (
    SELECT repinfo.repName,
           SUM(callstatssummary.CallsIn) sumCallsIn
    FROM   repinfo
           LEFT JOIN callstatssummary
           ON repinfo.isaacID = callstatssummary.IsaacID
           AND callstatssummary.ShiftDate >= '2013-02-10'
           AND callstatssummary.ShiftDate <= '2013-02-16'
    GROUP BY repinfo.repName
  ) c
  on c.repName = r.repName
  left join (
    SELECT repinfo.repName,
           SUM(`1036`.afterRgu) - SUM(`1036`.priorRgu) sumProdSold
    FROM   repinfo
           JOIN reporders
           ON repinfo.repID = reporders.oRep
           JOIN `1036`
           ON reporders.workOrder = `1036`.workOrder
           AND `1036`.entryDate >= '2013-02-10'
           AND `1036`.entryDate <= '2013-02-16'
           AND `1036`.afterRgu >= `1036`.priorRgu
    GROUP BY repinfo.repName
  ) o
  on r.repName = o.repName
order by r.repName;


text:
Q: How to return more than one token on Bison parser? My grammar is something like this
decl:

   attributes;  {/*create an object here with the attributes $$?*/ }

attributes:

  |

  att1 attributes {$$ = $1;}

  |

  att2 attributes {$$ = $1;}

  |

  attn attributes {$$ = $1;};

I want to get all the attributes entered by the user, some of them are optional and the order doesn't matter, types are different

A: You need to return a structure in your $$ variable; assign to its members as you need to. Here's an example from some code I have handy:
struct value_list {
    char *value;
    struct value_list *next;
};

# ...

valuelist:  TOK_VALUE
    {
        struct value_list *new = calloc(1, sizeof(struct value_list));
        if (!new)
            yyerror(_("Memory allocation error."));
        PDEBUG("Matched: value (%s)\n", $1);

        new->value = $1;
        new->next = NULL;
        $$ = new;
    }

valuelist:  valuelist TOK_VALUE
    {
        struct value_list *new = calloc(1, sizeof(struct value_list));
        if (!new)
            yyerror(_("Memory allocation error."));
        PDEBUG("Matched: value (%s)\n", $1);

        new->value = $2;
        new->next = $1;
        $$ = new;
    }

Another example from the same parser, which puts more effort into customizing a struct based on an entry than the above simpler rules; the downside is that this is getting quite complex, but the upside is that this is a better demonstration of attributes of a single object:
/* from a header file */
struct codomain {
    char *namespace;
    char *name;             /* codomain name */
    char *attachment;
    struct alt_name *altnames;
    void *xmatch;
    size_t xmatch_size;
    int xmatch_len;
    /* ... and it goes on like this ... */
}

# from the grammar:

profile_base: TOK_ID opt_id flags TOK_OPEN rules TOK_CLOSE
    {
        struct codomain *cod = $5;

        if (!cod) {
            yyerror(_("Memory allocation error."));
        }

        cod->name = $1;
        cod->attachment = $2;
        if ($2 && $2[0] != '/')
            /* we don't support variables as part of the profile
             * name or attachment atm
             */
            yyerror(_("Profile attachment must begin with a '/'."));
        cod->flags = $3;
        if (force_complain)
            cod->flags.complain = 1;

        post_process_nt_entries(cod);
        PDEBUG("%s: flags='%s%s'\n",
               $3,
               cod->flags.complain ? "complain, " : "",
               cod->flags.audit ? "audit" : "");

        $$ = cod;

    };

A: struct objectStruct{
  char* name;
  int value;
  objectStruct next;
  //...
}

now the grammar
decl:
  attributes {
    objectStruct* myObject = $1;
    while(myObject!=NULL){
       if(myObject->name!=NULL){
          //do something with name
          myObject=myObject->next;
       }
       else if(myObject->value!=NULL){
          //do something with value
          myObject=myObject->next;
       }
       //...
     }
  };

attributes:
 {$$=NULL;}
|
 NAME attributes {
   objectStruct* myObject = new objectStruct();
   myObject->name = $1;
   myObject->value = NULL;
   myObject->next = $2;
   $$=myObject;
}
|
 VALUE attributes {
   objectStruct* myObject = new objectStruct();
   myObject->value = $1;
   myObject->name= NULL;
   myObject->next = $2;
   $$=myObject;
}
//...
;


text:
Q: Which constructor will trigger the move semantics? I'm currently learning c++ and is wondering about the which one is the right way to use std::move
//Code might be incorrect since I havent tested it out
Xyt::ByteArray* Xyt::ResourceManager::LoadFileToByteArray(std::string Path)
{
try {
    std::ifstream FileStream(Path, std::ios::in);
    std::ifstream::pos_type Pos = FileStream.tellg();

    FileStream.seekg(0, std::ios::beg);

    std::vector<char> Buff(Pos);
    FileStream.read(Buff.data(), Pos);

    FileStream.close();

    //I want to trigger the move constructor here
    return new Xyt::ByteArray(std::move(Buff));
}
catch (std::exception e) {
    std::cout << "ERROR::FILE::FILE_NOT_SUCCESFULLY_READ" << Path << std::endl;
    return nullptr;
    }
}

What I'm confused about is which one will trigger the move constructor for std::vector ?
Is it this one (compile error when caller doesnt use std::move)
Xyt::ByteArray::ByteArray(std::vector<char>&& Buffer)
{
    this->Buffer = Buffer;
}

this one (accepts both std::move(Buff) and Buff) ?
Xyt::ByteArray::ByteArray(std::vector<char> Buffer)
{
    this->Buffer = Buffer;
}

or this one ?
Xyt::ByteArray::ByteArray(std::vector<char> Buffer)
{
    this->Buffer = std::move(Buffer);
}

My understanding from reading around the internet, that the 1st constructor is the correct way to utilize the move semantics. But if I use the 1st constructor does that mean I need to make another constructor if I want to actually do a copy on the std::vector Buff ?
Any help would be appreciated!

A: The only one that works is the third. But that's because you used std::move inside the constructor. And it provokes two moves: one to fill in the parameter, and one from the parameter into the value.
The correct way to do this is:
Xyt::ByteArray::ByteArray(std::vector<char>&& Buf)
  : Buffer(std::move(Buf))
{}

This only invokes the move operation once.
You have to explicitly move from named rvalue references if you want to invoke a move operation.

But if I use the 1st constructor does that mean I need to make another constructor if I want to actually do a copy on the std::vector Buff ?

You don't strictly have to. You could require users to do the copying themselves when they call the function:
Xyt::ByteArray(std::vector<char>(Buff))

But yes, if you want users to provide an lvalue directly, and you want to copy from the lvalue, then you need to provide a constructor that takes a (const) lvalue reference and performs a copy.


text:
Q: Adding kriging results back to a GWR model in R? How can I add the kriging results of a downscaling process back to a GWR model? Basically, I have 2 raster, 1 at 400m (let's call it x1) resolution and 1 at 100m resolution. I upscaled the latter to 400m, I performed GWR, I extracted the residuals and then I performed kriging on these residuals in order to downscale them. Now, I want to add them (the downscaled residuals which are in raster format at 100m) back to GWR model so I can produce the x1 at 100m. I am following the paper "Downscaling MODIS images with area-to-point regression kriging, Wang et al., 2015". According to the authors, "After both regression and ATPK are completed , their outputs (i.e., Zv1 Zv2) are combined to produce the final downscaled result, as indicated in Eq. 1" (see image attached), where the second part of the equation is the predictions of the regression and ATPK. Can someone help me on how I can do this in R? Here is the code and the data:
#GWR part
library(spgwr)
library(sf)
library(raster)

block.data = read.csv(file = "path/block.data.csv")

#create separate df for the x & y coords
x = as.data.frame(block.data$x)
y = as.data.frame(block.data$y)

#convert the data to spatialPointsdf and then to spatialPixelsdf
coordinates(block.data) = c("x", "y")
gridded(block.data) <- TRUE

# specify a model equation
eq1 <- ntl ~ pan

# find optimal ADAPTIVE kernel bandwidth using cross validation
abw <- gwr.sel(eq1, data = block.data, adapt = T, gweight = gwr.Gauss);

# fit a gwr based on adaptive bandwidth
ab_gwr <- gwr(eq1,
              data = block.data,
              adapt = abw,
              gweight = gwr.Gauss,
              hatmatrix = T,
              se.fit = T);
#print the results of the model
ab_gwr

sp <- ab_gwr$SDF
sf <- st_as_sf(sp)

map.resids <- as.data.frame(sf$gwr.e)
map.resids <- SpatialPointsDataFrame(data=map.resids, coords=cbind(x,y))
gridded(map.resids) <- TRUE
r <- raster(map.resids)
writeRaster(r, filename = "path/rsds.tif", format = "GTiff")
#end of GWR

#Kriging part
library(atakrig)

rsds = raster("path/rsds.tif")
pan = raster("path/pan.tif")

rsds.d <- discretizeRaster(rsds, 100); beep(7)
grid.pred <- discretizeRaster(pan, 100, type = "all"); beep(7)
pan.d = discretizeRaster(pan, 100); beep(7)

## area-to-area Kriging
aod.list <-list(rsds = rsds.d, pan = pan.d)
sv.ck <-deconvPointVgmForCoKriging(aod.list,
                                   model = "Sph",
                                   rd = 0.7,
                                   maxIter = 20); beep(7)

# prediction
pred.ataok <- ataKriging(rsds.d,
                         grid.pred,
                         sv.ck$rsds,
                         showProgress = TRUE); beep(7)

# convert result to raster
pred.ataok.r <-rasterFromXYZ(pred.ataok[,-1]);
plot(pred.ataok.r)
writeRaster(pred.ataok.r$pred, 'path/pred.ataok.r.tif', overwrite=TRUE)

A: I think I managed to solve it. If not, I will update this answer. So, after performing kriging on residuals, I returned to the GWR code and I extracted the prediction column as raster (let's call this pred_gwr), from the data.frame called sf (please see the code above). Then, I upscaled the downscaled residuals (let's call them res_krig) to match the pixel size of the pred_gwr and finally, I added the 2 rasters and I resampled the result to 100m. Here is the code:
map.pred <- as.data.frame(sf$pred)
map.pred <- SpatialPointsDataFrame(data=map.pred, coords=cbind(x,y))
gridded(map.pred) <- TRUE
r <- raster(map.pred)
writeRaster(r, filename = "path/gwr_pred.tif", format = "GTiff")

res_krig = raster("path/res_krig.tif")
gwr_pred = raster("path/ntl_nov.tif")

res_krig = resample(res_krig, gwr_pred, method = 'bilinear')

ntl_downscaled = res_krig + gwr_pred
ntl_downscaled  <- aggregate(ntl_downscaled, fact = 4)
writeRaster(ntl_downscaled, filename = "path/ntl_downscaled.tif", format = "GTiff")


text:
Q: Why does not CSS appy to the HTML in Visual Studio? I am working on a very simple ASP.NET project in Visual Studio 2013. I added an HTML, a CSS and JS file(each empty). I created the links in between the pages, and I put them into the same folder.
<head>
<title>Analog Clock</title>
<script type="text/javascript" src="script.js"></script>
<link type="text/css" rel="stylesheet" href="style.css">
</head>

I figured out, that I didn't mispelt anything, but my CSS doesn't apply on the HTML Ids.
My HTML body:
<svg width="140" height="140">
<circle id="clock-face" cx="70" cy="70" r="65" />
<line id="h-hand" x1="70" y1="70" x2="70" y2="38" />
<line id="m-hand" x1="70" y1="70" x2="70" y2="20" />
<line id="s-hand" x1="70" y1="70" x2="70" y2="12" />
<line id="s-tail" x1="70" y1="70" x2="70" y2="56" />
<text x="62" y="18">12</text>
<text x="126" y="76">3</text>
<text x="66" y="130">6</text>
<text x="7" y="76">9</text>
</svg>

And my CSS (stlye.css):
 #clock-face{
      stroke:black;
      stroke-width:2px;
      fill:white;
 }

I looked up stackoverflow and I found this link:
CSS not being applied in Visual Studio 2012 designer?
It says to change the link to this.(Obviously I put my folders name instead of content)
<link href="/content/default.css" rel="stylesheet" type="text/css" />
<% if (false) {%>
    <link href="../../content/default.css" rel="stylesheet" type="text/css" />
<% } %>

So did I, but I got the same result. Apologies for the dumb question, but I don't know what I am doing wrong.


text:
Q: How to add 2 series in Bar chart using crystal report visual studio 2013 I am using crystal report with Visual Studio 2013 and have to design report with bar chart.
I have consolidated verification report and have to show bar chart with 2 series.
I have data like this.
public class VerifiedCountData
{
    public List<VerifiedCountData>  GetDataList()
    {
       this.VerifiedCountList  = new List<VerfiedCountList>();

       this.VerifiedCountList.Add(new VerifiedCountData(new DateTime(2015,08,02),1,1));
       this.VerifiedCountList.Add(new VerifiedCountData(new DateTime(2015,08,03),5,0));
       this.VerifiedCountList.Add(new VerifiedCountData(new DateTime(2015,08,04),2,4));
       this.VerifiedCountList.Add(new VerifiedCountData(new DateTime(2015,08,05),6,2));

       return this.VerifiedCountList;
    }
    public VerifiedCountData(DateTime date, int yesCount, int noCount)
    {
        this.Date = date;
        this.YesCount = yesCount;
        this.NoCount = noCount;
    }

    public DateTime Date {get;set;}
    public int YesCount {get;set;}
    public int NoCount {get;set;}
    public List<VerifiedCountData> VerifiedCountList {get;set;}

}

here is snap what I have to design in cystal report.
Please check this Image
https://www.dropbox.com/s/t9qjzcjxb80dugi/sample.png?dl=0
In Design of crystal report right click on report and then goto insert option and select chart.
In chart Expert Data tab layout is advance inside of data a drowp down is comming for 'On Change Of' I have added two fields one for YesCount and second NoCount and in Show value(s) I added Date field.
here is image is explain what i did
https://www.dropbox.com/s/siy99mb3092m396/sample1.png?dl=0
but when i run result is coming like this
dropbox.com/s/dbb6aac3pxqeh3w/sample.3png.png?dl=0
Thanks

A: Finally I have done this by changing the  values in 'Chart Expert > Data(tab)'
Instead of this :

To


text:
Q: How to mock Func? I have a service method as below. I am trying to mock in test method
public class A
{
    private readonly IHandler createDeviceContentStatus;
    private readonly IHandler updateDeviceContentStatus;
    public A(Func<Type, IHandler> handlerFactory)
    {
        this.createDeviceContentStatus = handlerFactory(typeof(CreateDCS));
        this.updateDeviceContentStatus =
            handlerFactory(typeof(UpdateDeviceContentStatus));
    }
}

How can I create Mock for class A constructor in test method?
Any leads are appreciated

A: I recommend to add an overloaded constructor:
public class A
{
    private readonly IHandler createDeviceContentStatus;
    private readonly IHandler updateDeviceContentStatus;
    public A(Func<Type, IHandler> handlerFactory)
      : this(handlerFactory(typeof(CreateDCS)), handlerFactory(typeof(UpdateDeviceContentStatus)))
    {
    }
    public A(IHandler createDeviceContentStatus, IHandler updateDeviceContentStatus)
    {
        this.createDeviceContentStatus = createDeviceContentStatus;
        this.updateDeviceContentStatus = updateDeviceContentStatus;
    }
}

Then mocking will be quite easy:
Mock<IHandler> createDeviceMock = new Mock<IHandler>();
Mock<IHandler> updateDeviceMock = new Mock<IHandler>();
// setup the mocks
A a = new A(createDeviceMock.Object, updateDeviceMock.Object);

If you don't want to create this constructor, create a lambda that returns your mocks:
Mock<IHandler> createDeviceMock = new Mock<IHandler>();
Mock<IHandler> updateDeviceMock = new Mock<IHandler>();
// setup the mocks
Func<Type,IHandler> factory = (t) =>
{
if(t == typeof(CreateDCS)) return createDeviceMock.Object;
if(t == typeof(UpdateDeviceContentStatus)) return updateDeviceMock.Object;
throw new ArgumentException();
};
A a = new A(factory);


text:
Q: EF Core-generated Collection navigation property throws InvalidOperationException: Nullable object must return a value on ASP.NET Core login I have scaffolded the DB context from a SqlServer DB into a new ApplicationDbContext class using the EF Core 6 CLI. When I start trying to login using the new db context and AspNetUser (inherits from IdentityUser) with no new properties, only foreign relationships, I get an InvalidOperationException: Nullable object must have a value. when it comes to a many-to-many relationship configuration in my OnModelCreating method, modelBuilder.Entity<AspNetUser>(entity => ...).
Here is where my stack trace sends me (objects and properties are renamed to represent my understanding of the related tables and the joint table/entity between them):
Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.Property(Type propertyType, string propertyName, MemberInfo memberInfo, Nullable<ConfigurationSource> typeConfigurationSource, Nullable<ConfigurationSource> configurationSource)
Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.GetActualProperties(IReadOnlyList<Property> properties, Nullable<ConfigurationSource> configurationSource)
Microsoft.EntityFrameworkCore.Metadata.Internal.InternalIndexBuilder.Attach(InternalEntityTypeBuilder entityTypeBuilder)
Microsoft.EntityFrameworkCore.Metadata.Internal.PropertiesSnapshot.Attach(InternalEntityTypeBuilder entityTypeBuilder)
Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.Property(Type propertyType, string propertyName, MemberInfo memberInfo, Nullable<ConfigurationSource> typeConfigurationSource, Nullable<ConfigurationSource> configurationSource)
Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.IndexerProperty(Type propertyType, string propertyName, Nullable<ConfigurationSource> configurationSource)
Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder.IndexerProperty<TProperty>(string propertyName)
DataView.Data.ApplicationDbContext+<>c.<OnModelCreating>b__43_35(EntityTypeBuilder<Dictionary<string, object>> j) in ApplicationDbContext.cs

entity.HasMany(leftEntity => leftEntity.CollectionR)
.WithMany(rightEntity => rightEntity.CollectionL).
UsingEntity<Dictionary<string, object>>("JoinEntityName",
leftEntityTypeBuilder => leftEntityTypeBuilder.HasOne<PropertyR>().WithMany().HasForeignKey("PropertyR").OnDelete(DeleteBehavior.ClientSetNull).HasConstraintName("FK_JOIN_TABLE_NAME_RIGHT_TABLE_NAME"),
rightEntityTypeBuilder => rightEntityTypeBuilder.HasOne<PropertyL>().WithMany().HasForeignKey("PropertyL").OnDelete(DeleteBehavior.ClientSetNull).HasConstraintName("FK_JOIN_TABLE_NAME_LEFT_TABLE_NAME"),
joinEntityTypeBuilder =>
{
  j.HasKey("PropertyL", "PropertyR");
  j.ToTable("JOIN_TABLE_NAME");
  j.HasIndex(new[] { "PropertyL" }, "IX_JOIN_TABLE_NAME");
  j.IndexerProperty<string>("PropertyL").HasMaxLength(450).IsUnicode(false);
  j.IndexerProperty<string>("PropertyR").HasMaxLength(50).IsUnicode(false).HasColumnName("PROPERTY_R").HasDefaultValueSql("('')");
})

I've read all I can from
https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/complex-data-model?view=aspnetcore-6.0&tabs=visual-studio
and
https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key
and several other MS docs articles, StackOverflow threads, and GitHub issues.
This bit seemed especially interesting from the first link:

EF Core doesn't require a foreign key property for a data model when the model has a navigation property for a related entity. EF Core automatically creates FKs in the database wherever they're needed. EF Core creates shadow properties for automatically created FKs. However, explicitly including the FK in the data model can make updates simpler and more efficient. For example, consider a model where the FK property DepartmentID is not included. When a course entity is fetched to edit:

*

*The Department property is null if it's not explicitly loaded.
To update the course entity, the Department entity must first be fetched.

But it seems like the whole Fluent API UsingEntity method should be taking care of that. Identity was working great until adding foreign keys. Not sure what about the entity generation introduces the exception on login.
Thanks!


text:
Q: Auto-Hide ViewBag Message in C# after 15 seconds I am displaying a message via ViewBag in C# and it works fine. Now what I want is to auto Hide the ViewBag message after 15 seconds. How should I do that?
Following is my code where I am using ViewBag:
public ActionResult ForgetPassword(String EmailId, string message)
    {
        ViewBag.Message = message;
        ForgetPassword objForgetPassword = new ForgetPassword { EmailId = EmailId };
        return View();
    }

//Other Model where I am passing the Message
 if (objResult.Status)
            {
                return RedirectToAction("Login", new { message = "Password changed Successfully. Please Login with the New Password."});
            }

CSHTML code for the same:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

@ViewBag.Message

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.OTP, htmlAttributes: new { @class = "control-label" })

            @Html.EditorFor(model => model.OTP, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.OTP, "", new { @class = "text-danger" })

A: You can use the javascript setTimeout function to run the code to hide the message using the query fadeOut function:
$(document).ready(function(){
    setTimeout(function(){
        $("#msg").fadeOut();
    }, 15000);
});

and in view:

@ViewBag.Message

here's fiddle: https://dotnetfiddle.net/3Sw1O9

A: You can use Javascript setTimeout() function to do so.
Give your label an particular Id like 'lblMsg'
setTimeout(function(){ document.getElementById('lblMsg').style.display = "none"; }, 15000);

Or Simply you want to remove the element after 15 seconds.
Using JQuery you can use remove() function.
setTimeout(function(){ $('#lblMsg').remove(); }, 15000);

A: You can use JS to hide element which contains ViewBag data like this:
setTimeout(function() { $("h4").hide(); }, 15000);

$("h4").delay(15000).fadeOut();

Or using CSS selector display: none:
setTimeout(function() { $("h4").css('display','none'); }, 15000);

Make sure the h4 is the only one element which contains the message, otherwise use
 with id attribute.

A: Give an id to the container of the message. Then add document.ready method that hide the container after 15 sec. Use settimeout function as below:
setTimeout(function() {
        $("#successMessage").hide('bind', {}, 500)
    }, 5000);


text:
Q: Blackberry How to access Contacts from Contact List of Phone I am developing one application in that i have contact details ,when i click the contact number it will ask some option like call.How to access contact list in blackberry so that  it should show contact list of phone.
Just similar to the image shown:

A: BlackBerryContactList list = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY);
PIMItem contact = list.choose();

This lets you navigate, edit, and choose a contact. After that you can use the chosen contact's information to call, or sms, etc.
If the native selector isn't what you want, iterate over the entries in list and build your own.