text:
Q: What should I study after finishing 'Causal Inference in Statistics: A Primer'? I have almost finished studying 'Causal Inference in Statistics: A Primer', but I still feel that I need to learn more.
I considered 'Causality' (Pearl, 2009), but there seem to be several good learning resources about DAG (ex. Review Paper & etc).
What should I study after finishing 'Causal Inference in Statistics: A Primer'?


text:
Q: Where to put functions that help me execute controller tasks? I'm currently working on an ASP.net MVC web site project.
I've put all database related stuff in my model, such as queries and update/delete/save functions.
I also created a couple of controllers that execute the logic. I added a Helpers namespace and inside that namespace there are a few classes that contain logic for pagination, internationalization etc.
I was wondering what is the best practice for placing functions and classes that do some general stuff, like generating an invoice?

A: As I expressed in a comment above, I'm too very much interested in this question.
First, it seems wrong to create additional directories (for the other classes and utilities) directly in your ASP.NET MVC project. Also, I don't feel that it should be in model. To me, model is more or less data classes which in some way represents the database (or the data we are trying to model). On top of that, often the business functionality (or the "real" pieces of code in your application) deals with several model classes at a time, and so there may not be a natural place for it in some model class.
So I think I am leaning towards the following schema:

*

*Make controller actions very small; just few lines of code each.

*Keep model simple and mostly functionless, and put it into a separate project.

*Put all your code that does all the "real" work (the "business layer") into a separate project.

This way you will get a complete freedom in choosing your own namespaces, you will be able to create any number of utility classes, functions, and generally able to structure your code as you like without being restricted by ASP.NET MVC.
This is just an idea. At the moment I'm working on my first larger ASP.NET MVC application. So I'm actually going to learn whether and how this works in practice.

A: I have Model classes that have Crud and Poco like you have.
Apart from that I have Viewmodels that are used for the typed Views.
My Viewmodels are pretty big and used in a couple of views (around 10-15 viewmodels for the whole appplication). In my application these ViewModels ended up as being the perfect place for the code that seamed to big and repetetive for the controller actions.
For example I have some logic that is pretty near to UI when I add a Product to the Cart. I now have a method  in the ViewModel: AddToCart(IProductService productService, ICartService cartService).

A: You might consider creating some services that you inject into your controllers.
It's almost too wide a question.

A: This kind of business logic should be somewhere in your Model.
However, I find that when there is just something that doesn't really "fit" anywhere - and you might be tempted to create a Utilities class - this is usually a good place to utilize Extension methods.
Perhaps you can add extension methods on your dataset to help you with pagination?

A: I you really need the best practice, consider looking at Domain Driven Design. It doesn't suit all projects and does require good OOP skills, but I think it is without doubts a "best practice"... as long as you can afford it ;-)
Notice that you do already violate DDD since you use Active Record pattern (put persistence logic into entities). So, I do not say that you have to follow DDD. But it will be useful to grok anyway.

A: I think the best solution to this question about practice is:
Put the logic in the Model if it's going to be used across controllers.
If it's controller specific, just drop it in your controller.
When I say the Model, this could be a separate project that conatins your Entity Data Model, or it could be a View Model, or it could be just the Models folder of your MVC project.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change dropdown caret on click of other LI item I'm creating a website and having trouble with some carets on my dropdown.
I have a sidebar like so:
Home
Menu item >
Menu item 2 >
Menu item 3 >

When I click on a menu item the little caret icon goes from > to v and expands the dropdown content like so:
Home
Menu item v
  Sub-menu item
  Sub-menu item 2
Menu item 2 >
Menu item 3 >

If I click on Menu item v - the caret goes from v to > again which is correct.
However, if I click on Menu Item 2 > for example, menu item 2 opens, but the caret on menu item stays as v like so:
Home
Menu item v
Menu item 2 v
  Sub-menu item
  Sub-menu item 2
Menu item 3 >

How do I get it so when Menu item 2 has been clicked, menu item v will change back to menu item >
I have this as my JS
$('.dropdown').click(function(){
    $(this).find('.nav-arrow').toggleClass('fa-angle-left fa-angle-down');
});

$('.dropdown').click(function(){
    $('.collapse').collapse('hide');
})

My drop down looks like this:

*Home

Menu item

Sub menu item

Sub-menu item 2

Menu item 2

Sub menu item

Sub-menu item 2

Menu item 3

Sub menu item

Sub-menu item 2

A: What you need to do is first convert all of the
 elements to a left-facing caret, and then only change the target element back. Unfortunately, as there's no (simple) way to know which carets are open and which are closed, it's best to change them explicitly:
$('.dropdown').click(function(){
  $('.nav-arrow').removeClass('fa-angle-down');
  $('.nav-arrow').removeClass('fa-angle-left');
  $(this).find('.nav-arrow').removeClass('fa-angle-left');
  $(this).find('.nav-arrow').addClass('fa-angle-down');
});

Hope this helps!

A: I think this will handle the case where you have toggled a menu open and close and if you have toggled the menu by selecting another entry in the menu.
jQuery(".dropdown").click(function(event){
  // Evaluate the target of the click event was already opened.
  if(jQuery(event.target).hasClass("fa-angle-down")){
    // Change the caret to looks like they are closed.
    jQuery(event.target).removeClass("fa-angle-down").addClass("fa-angle-left");

  // Evaluate the target of click event was not opened.
  }else{
    // Remove any opened menu items carets.
    jQuery(".dropdown.fa-angle-down").removeClass("fa-angle-down").addClass("fa-angle-left");
    // Add the appropriate caret to the newly opened menu item.
    jQuery(event.target).removeClass("fa-angle-left").addClass("fa-angle-down");
  }
});

Let me know if you have any questions or if I can improve on this to make it better for you.


text:
Q: Do mysql querys in python with zip file Im trying to do some querys on my data base, but the file is to large and is spending to much time, exists some way to upload one zip file with those querys to my table?
ps: the file have between 350Mb to 500Mb

A: Store the zip file somewhere else on your server and simply store the name or the file location string in your dB.
Mysql really isn't intended to store large files or better yet zip folders.
Then when you go to retrieve it just unload the file location into an <a> tag it will link to it.


text:
Q: Rails: Paperclip-delay detect when job finished hi i'm kinda noob in this ..
i'm using paperclip-delay to throw the image processing in the background on resque and i'm trying to trigger action after the job finished..
i tried  forking the gem and add the action myself in it but that looks like an ugly approach ..like it appear in this question's answer
Knowing when resque worker had completed job
also thought of ripping some code from the gem and use it directly in my model
is there any other ideas
========Edited
i used
 if @video.save
  Delayed::Worker.new.work_off
  @video.reload
  put 'aheee'
  respond_to do |format|
    format.html {redirect_to videos_path, notice: 'Video uploaded and will be converted shortly '}
  end

like referenced in the gem README and it give me

uninitialized constant ImagesController::Delayed

i have no idea

A: the paperclip-delay gem supports this already by adding a processing column to your database.  it will be set when the processing is finished.  The info is in the README


text:
Q: Create a div for every row in a table I have 1 table in my html. Now I want to create for every row a new div. In this div is a
 which is in the first column of the first row. And the same for the second column in the first row. How can I do this?

A: If your goal was to dynamically create it with an array of information heres my simplest approach:
Quick JSFiddle Example
Lets say you start with an empty table and an array with row arrays and string elements inside:

    1
    2
    3

let myInfo = [
  ['A', 'B', 'C'],
  ['X', 'Y', 'Z'],
];

We select the table first:
let table = document.querySelector('#target');
let tbody = table.querySelector('tbody');

Then we loop for each row in our myInfo array, create a div and append it to tbody
myInfo.forEach((row) => {
  let div = document.createElement('div');
  tbody.appendChild(div);
});

Now for each row we create our p element as a cell. we set the innerHTML with the passed cell argument (the strings inside each row array) and append it to the row div we created in the outer scope.
myInfo.forEach((row) => {
  let div = document.createElement('div');
  tbody.appendChild(div);

  row.forEach((cell) => {
    let p = document.createElement('p');
    p.innerHTML = cell;
    div.appendChild(p);
  });
});

last but not least we make the divs and paragraphs display semantically correct with css
tbody > div {
  display: table-row;
}
tbody > div > p {
  display: table-cell;
}


text:
Q: cant see what i did wrong (simple animation)

body {
  background: hsl(210, 100%, 95%);
}
#Title {
  font-family: Lobster, monospace;
  font-size: 45px;
  text-align: center;
  color: white;
}
 h1:hover {
   color: black;
   transform: scale(1.2)
}
.circles {
  height: 80px;
  width: 80px;
  border-radius:50%;
  border:solid;
  position:fixed;
  animation-name: 123;
  animation-iteration-count: infinite;
  animation-duration: 10s;
}

#circle1 {

  animation-timing-function: linear;
  background: linear-gradient(45deg, #ccffff, #ffcccc);
  left:50%;
}
#circle2 {

  animation-timing-function: linear;
  background: repeating-linear-gradient(90deg, #A52A2A 2px, #cccccc 5px, orange 10px);
  left:25%;
}

@keyframes 123 {
  50% {
  bottom: 10%;
 }
}
<!DOCTYPE html>

    <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">

    <title>Animation-1</title>

Placeholder

Gone over it 3 times already, can't see where im messing up

A: try to use string instead of number in keyframes naming
here is your animation example. https://codepen.io/baomastr/pen/KKgNGbg

.circles {
  height: 80px;
  width: 80px;
  border-radius: 50%;
  border: solid;
  position: absolute;
  animation-name: test;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
  animation-duration: 5s;
}

#circle1 {
  background: linear-gradient(45deg, #ccffff, #ffcccc);
  left: 50%;
}

#circle2 {
  background: repeating-linear-gradient(
    90deg,
    #a52a2a 2px,
    #cccccc 5px,
    orange 10px
  );
  left: 25%;
}

@keyframes test {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(20px);
  }
  100% {
    transform: translateY(0);
  }
}

A: 1st is keyframe with number is not accepted. 2nd In you keyframe you need to specify 0% and 100% as well. To be for example like:
@keyframes slidein {
   0%   { bottom: 60%; }
   50%  { bottom: 10%; }
   100% { bottom: 0%; }
}

DEMO:

body {
  background: hsl(210, 100%, 95%);
}
#Title {
  font-family: Lobster, monospace;
  font-size: 45px;
  text-align: center;
  color: white;
}
 h1:hover {
   color: black;
   transform: scale(1.2)
}
.circles {
  height: 80px;
  width: 80px;
  border-radius:50%;
  border:solid;
  position:fixed;
  animation-name: slidein;
  animation-iteration-count: infinite;
  animation-duration: 10s;
}

#circle1 {

  animation-timing-function: linear;
  background: linear-gradient(45deg, #ccffff, #ffcccc);
  left:50%;
}
#circle2 {

  animation-timing-function: linear;
  background: repeating-linear-gradient(90deg, #A52A2A 2px, #cccccc 5px, orange 10px);
  left:25%;
}

@keyframes slidein {
  0%   { bottom: 60%; }
  50%  { bottom: 10%; }
  100% { bottom: 0%; }
}
<!DOCTYPE html>

    <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">

    <title>Animation-1</title>

Placeholder


text:
Q: Notation: What's meant by $C^{\infty}_{0}(\mathbb{R}^{+})$? In Chapter 0 of Iwaniec's Spectral Methods of Automorphic Forms Iwaneic uses the notation $C^{\infty}_{0}(\mathbb{R}^{+})$ without definition.
I assume that it's the set of infinitely differentiable functions from $\mathbb{R} \to \mathbb{R}$ with range a subset of the positive reals and which tend toward zero "sufficiently quickly," but I don't know whether my guess is right or what the precise definition of "sufficiently quickly" is in this context.
What does the subscript of $0$ refer to?

A: From an MO question in which that notation is defined (second paragraph):
$C_b(\mathbb{R})$ (resp. $C_0(\mathbb{R})$) are the continuous functions from $R$ to $R$ that are bounded (resp. vanish at infinity).

A: This is one of the unfortunate cases where the notation can mean two different things. It can either be the compactly supported smooth functions on the positive reals, or it can be the smooth functions which tend to $0$ when $x \to 0$ or $x \to \infty$. I personally prefer to use a $c$ subscript for the former and reserve the $0$ subscript for the latter.
Without further context, it really isn't possible to answer your query.


text:
Q: Delete Postman Cookies Is there any way to expire authtoken in postman saved after login call?
I have tried to code get response object
{
tests["Login successfull"] = responseCode.code === 200;
var token = postman.getResponseCookie("authtoken");
console.log(token)
}

this is  object am getting
{
name: "authtoken"
expires: null
maxAge: 0
domain: "cdn.contentstack.io"
path: "/"
secure: true
httpOnly: true
hostOnly: true
value: "rxE1TWD13Ji1dRCQK"
}

A: The Postman collection can automatically detect an expired access_token value and request a new one by using the refresh_token. By default this feature is enabled but it can be turned off by setting the enable_auto_refresh_access_token Postman environment variable to false
Reference LINK


text:
Q: How to mask environment variables created in Github when running a workflow? I created a Github workflow that runs a python script with a cron schedule. On every run of the workflow an access_token is generated, which is required during the next run.
To save the token the python script writes the token to the GITHUB_ENV file. In the next step, I use the hmanzur/actions-set-secret@v2.0.0 action to save the token to a Github secret. All works fine.
My only problem is, that the token gets displayed in the logs of the second step as an environment variable.
Here is a minimal version of the workflow file:
name: Tests
on:
  schedule:
    - cron: "0 1 * * *"
jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python: ['3.9']
    steps:
      - uses: actions/checkout@v1
      - uses: actions/setup-python@v1
        with:
          python-version: ${{ matrix.python }}
      - name: Install dependencies
        run: pip install -r requirements.txt
      - name: Run tests
        working-directory: ./src
        run: python -m unittest
        env:
          ACCESS_TOKEN: ${{secrets.ACCESS_TOKEN}}
      - uses: hmanzur/actions-set-secret@v2.0.0
        with:
          name: 'ACCESS_TOKEN'
          value: ${{env.ACCESS_TOKEN}}
          repository: Me/MyRepository
          token: ${{ secrets.REPO_ACCESS_TOKEN }}

I tried applying ::add-mask::. Adding echo "ACCESS_TOKEN=::add-mask::$ACCESS_TOKEN" >> $GITHUB_ENV only added ::add-mask:: to the string.
Is there a way of masking all environment variables in the GITHUB_ENV file I can apply in the first step? Can I apply the masking to the variable while writing to the GITHUB_ENV file in python? Or is there a way to disable the display of the environment variables during the workflow?

A: Your usage of "::add-mask::" is wrong (not your fault, I hate GHA doc).
What you need to do is:
echo "::add-mask::$ACCESS_TOKEN"
echo "ACCESS_TOKEN=$ACCESS_TOKEN" >> $GITHUB_ENV

A: My solution, if someone is having the same problem.
There seems to be no direct solution. As a workaround I use the cryptocode library to encode and decode the access token in the python script. Only the encrypted token is send to the workflow environment and saved in the repos secret.
Here a minimal working example:
workflow.yml:
name: Test
on:
  push:
    branches:
      - main
jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python: ['3.9']
    steps:
      - uses: actions/checkout@v1
      - uses: actions/setup-python@v1
        with:
          python-version: ${{ matrix.python }}
      - name: Install dependencies
        run: pip install -r requirements.txt
      - name: Run tests
        working-directory: ./
        run: python encrypt-secret.py
        env:
          ENCRYPTED_ACCESS_TOKEN: ${{secrets.ENCRYPTED_ACCESS_TOKEN}}
          INITIAL_ACCESS_TOKEN: ${{secrets.INITIAL_ACCESS_TOKEN}}
          PASS_KEY: ${{secrets.REPO_ACCESS_TOKEN}}
      - uses: hmanzur/actions-set-secret@v2.0.0
        with:
          name: 'ENCRYPTED_ACCESS_TOKEN'
          value: ${{env.ENCRYPTED_NEW_ACCESS_TOKEN}}
          repository: Der-Henning/test-workflows
          token: ${{ secrets.REPO_ACCESS_TOKEN }}

encrypt-secret.py:
from os import environ
from random import random
import cryptocode

def main():
  ## Get Github environment file
  ## Only run this part when GITHUB_ENV is set -> workflow detection
  env_file = environ.get('GITHUB_ENV', None)
  if env_file:

    ## PASS_KEY to encrypt the secret
    passkey = environ.get("PASS_KEY", None)

    access_token = environ.get("INITIAL_ACCESS_TOKEN")

    ## get the encrypted token and decrypt with passkey
    encrypted_old_access_token = environ.get("ENCRYPTED_ACCESS_TOKEN", None)
    if encrypted_old_access_token and passkey:
      old_access_token = cryptocode.decrypt(encrypted_old_access_token, passkey)
      if old_access_token:
        print("Access Token from secret: {}".format(old_access_token))
        print("Correct Token: {}".format(old_access_token.startswith('ThisIsASecret')))
        access_token = old_access_token
    else:
      print("No encrypted Access Token provided!")

    ######
    #
    # Do stuff here
    # Use old_access_token to access an API ...
    #
    #####

    ## Encrypt new access token from API for next run
    ## Save encrypted token to GITHUB_ENV
    new_access_token = "ThisIsASecret{}".format(random())
    print("New Token: {}".format(new_access_token))
    if passkey:
      encrypted_new_access_token = cryptocode.encrypt(new_access_token, passkey)
      with open(env_file, "a") as file:
        file.write("ENCRYPTED_NEW_ACCESS_TOKEN={}\n".format(encrypted_new_access_token))

if __name__ == "__main__":
  main()


text:
Q: Project aggregation in sbt I am just starting to learn sbt to build scala projects.
Here is my build.sbt file
lazy val commonSettings = Seq(
  organization := "com.example",
  version := "0.1.0",
  scalaVersion := "2.11.7"
)

lazy val task = taskKey[Unit]("An example task")

lazy val root = project.in(file(".")).
  aggregate(core).
  settings(commonSettings: _*).
  settings(
    task := { println("Hello!") },
    name := "hello",
    version := "1.0"
  )

  lazy val core = project.in( file("SbtScalaProjectFoo") )

My project structure is as follows
  SbtScalaProject
  |--SbtScalaProjectFoo
     |--build.sbt
  |--build.sbt

When I try to run "sbt" inside SbtScalaProject I get the following
No project 'core' in 'file:/Users/asattar/Dev/work/SbtScalaProject/'

What am I missing?

A: Having multiple build.sbt's has proven to make problems for me, too.
I would recommend aggregating all project data into one build.sbt. If you want to modularize the build, consider moving parts into .scala-Files in (the root project's) project/ directory.


text:
Q: Tomcat shared loader not taken into account To precise the context, I am using Eclipse with its workspace metadata for my Tomcat 7's configuration.
I have this line in my catalina.properties :
shared.loader=${catalina.home}/shared/conf

Which, should load all the files contained in ${catalina.home}/shared/conf before all the files contained in my web application (WEB-INF/classes).
But this is not what I observe, the files contained in my application always override those in my shared loader (ie. log4j.xml, etc.).
Any idea ?

A: First of all, Tomcat 4.1 hasn't been supported for over 4 years.
Second, you haven't read the page correctly. Look at the end of the "Class Loader Definitions" section where the search order is explicitly described.
If you want to change the delegation order then look at the delegate attribute of the Loader element. This is supported in all Tomcat versions from 4.1.x to 8.0.x.


text:
Q: Optimization of Eloquent queries in Laravel 4 I've just recently started using Laravel and I've got a problem, that my page is really slow.
The issue is that my queries are not ideal:
`

  @foreach ($product as $single)
    <?php
      $tagy = $single->tags()->get();
      echo "
tagID)->first();
        echo " item".$premenna->id;
      }
      echo "'>";
    ?>

        id }}"><img class="image" src="<?=Croppa::url($single->destinationPath.'/'.$single->coverphoto, 250)?>" />

            id }}">
{{ $single->name }}

{{ $single->city }}

{{ $single->date }}

            gpsn}},{{$single->gpse}}&ll={{$single->gpsn}},{{$single->gpse}}=17" target="_blank">

              <?php
                  foreach($tagy as $tag) {
                    $variable= Tags::where('id','=',$tag->tagID)->orderBy('name')->first();
                    echo "id."'>".$variable->name." ";
                  }
              ?>

  @endforeach

`

This is my Controller function:
protected function index()
{
    $product = Product::where('active','=',1)->orderBy('date')->get();
    $tagy = Tags::orderBy('name')->get();

    return View::make('uvod',['product' => $product, 'tags' => $tagy]);
}

I've made one-to-many relationship between Product Class and ProductTag Class - that's the fucntion tags();
Could you please somehow help me optimizing the code (queries)? I would like to use @foreach function only once if possible - when i deleted the foreach functions inside the main one the page speed significantly improved.
Thank you very much for any kind of help :)


text:
Q: Meteor: Unique MongoDB URL for different users I'm very keen to utilize Meteor as the framework for my next project. However, there is a requirement to keep customer data separated into different MongoDB instances for users from different customers.
I have read on this thread that it could be as simple as using this:
var d = new MongoInternals.RemoteCollectionDriver("<mongo url>");
C = new Mongo.Collection("<collection name>", { _driver: d });

However, I was dished this error on my server/server.js. I'm using meteor 0.9.2.2
with meteor-platform 1.1.0.
Exception from sub Ep9DL57K7F2H2hTBz Error: A method named '/documents/insert' is already defined
    at packages/ddp/livedata_server.js:1439
    at Function._.each._.forEach (packages/underscore/underscore.js:113)
    at _.extend.methods (packages/ddp/livedata_server.js:1437)
    at Mongo.Collection._defineMutationMethods (packages/mongo/collection.js:888)
    at new Mongo.Collection (packages/mongo/collection.js:208)
    at Function.Documents.getCollectionByMongoUrl (app/server/models/documents.js:9:30)
    at null._handler (app/server/server.js:12:20)
    at maybeAuditArgumentChecks (packages/ddp/livedata_server.js:1594)
    at _.extend._runHandler (packages/ddp/livedata_server.js:943)
    at packages/ddp/livedata_server.js:737

Can anyone be so kind as to enlighten me whether or not I have made a mistake somewhere?
Thanks.
Br,
Ethan
Edit: This is my server.js
Meteor.publish('userDocuments', function () {
    // Get company data store's mongo URL here. Simulate by matching domain of user's email.
    var user = Meteor.users.findOne({ _id: this.userId });
    if (!user || !user.emails) return;

    var email = user.emails[0].address;
    var mongoUrl = (email.indexOf('@gmail.com') >= 0) ?
        'mongodb://localhost:3001/company-a-db' :
        'mongodb://localhost:3001/company-b-db';

    // Return documents
    return Documents.getCollectionByMongoUrl(mongoUrl).find();
});

and this is the server side model.js
Documents = function () { };
var documentCollections = { };
Documents.getCollectionByMongoUrl = function (url) {
    if (!(url in documentCollections)) {
        var driver = new MongoInternals.RemoteCollectionDriver(url);
        documentCollections[url] = new Meteor.Collection("documents", { _driver: driver });
    }

    return documentCollections[url];
};

Observation: The first attempt to new a Meteor.Collection works fine. I can continue to use that collection multiple times. But when I log out and login as another user from another company (in this example by using an email that is not from @gmail.com), the error above is thrown.

A: Downloaded meteor's source codes and peeked into mongo package. There is a way to hack around having to declare different collection names on the mongodb server based on Hubert's suggestion.
In the server side model.js, I've made these adaptation:
Documents.getCollectionByMongoUrl = function (userId, url) {
    if (!(userId in documentCollections)) {
        var driver = new MongoInternals.RemoteCollectionDriver(url);
        documentCollections[userId] = new Meteor.Collection("documents" + userId, { _driver: driver });
        documentCollections[userId]._connection = driver.open("documents", documentCollections[userId]._connection);
    }

    return documentCollections[userId];
};

Super hack job here. Be careful when using this!!!!

A: I believe Meteor distinguish its collections internally by the name you pass to them as the first argument, so when you create the "documents" collection the second time, it tries to override the structure. Hence the error when trying to create the /documents/insert method the second time.
To work around this, you could apply a suffix to your collection name. So instead of:
new Meteor.Collection('documents', { _driver: driver });

you should try:
new Meteor.Collection('documents_' + userId, { _driver: driver })


text:
Q: Delete a range of commits I have a commit history over of 40 commits.
Some of this commits are not necessary and are only there for no reason.
I would like to remove a range of unnecessary commits and at first I tried this one:
git rebase --onto <branch name>~<first commit number to remove> <branch name>~<first commit to be kept> <branch name>

Unfortunately this won't work. What I really want is to delete the very last commit in the log (the first one committed) until another one like the 10th from the last so in general to delete the last 10 commits.
I am not looking to rollback to that version, as these commits are not something useful and will lead to empty source folder.

A: You can use git rebase -i --root to rebase everything starting with the initial commit.
Let's say you had 11 commits that looked something like this:
* cf0bc41 - (HEAD, master) Faun: Eleven (2 seconds ago)
* b32d8cc - Faun: Ten (2 seconds ago)
* f789e49 - Faun: Nine (2 seconds ago)
* 780435e - Faun: Eight (2 seconds ago)
* 3c6b084 - Faun: Seven (2 seconds ago)
* fecce89 - Faun: Six (2 seconds ago)
* 0433dbe - Faun: Five (2 seconds ago)
* 8002cb7 - Faun: Four (2 seconds ago)
* 3439445 - Faun: Three (2 seconds ago)
* 38181f1 - Faun: Two (2 seconds ago)
* 9373809 - Faun: One (2 seconds ago)

If you want to remove the first 10 commits, just run git rebase -i --root, which will open something like the following in your editor:
pick 9373809 One
pick 38181f1 Two
pick 3439445 Three
pick 8002cb7 Four
pick 0433dbe Five
pick fecce89 Six
pick 3c6b084 Seven
pick 780435e Eight
pick f789e49 Nine
pick b32d8cc Ten
pick cf0bc41 Eleven

# Rebase cf0bc41 onto 0bd34c4

You can simply delete the lines of the commits that you want to delete. However, that will probably result in a conflict, as later commits most likely modified files you introduced with one of your earlier commits.
Also be aware that running this command will rewrite the SHAs for all commits, which might also cause you problems.
It's probably better to squash or fixup those initial commits. Leave the first one alone and change the word pick to squash or fixup. See the comments at the bottom of the interactive rebase for more information.
For example if you edit the interactive rebase look like this:
pick 9373809 One
fixup 38181f1 Two
fixup 3439445 Three
fixup 8002cb7 Four
fixup 0433dbe Five
fixup fecce89 Six
fixup 3c6b084 Seven
fixup 780435e Eight
fixup f789e49 Nine
fixup b32d8cc Ten
pick cf0bc41 Eleven

You'll end up with this git history:
* f8980bc - (HEAD, master) Faun: Eleven (0 seconds ago)
* 3d300e9 - Faun: One (0 seconds ago)

A: What you can do is to squash the first 10 commits into one commit. Here is an example that squashes five initial commits into one while preserving the rest of your history.

Warning: rewriting history will change SHA1s. It is not possible to prevent this. Don't rewrite the SHAs of public commits unless you've talked to your team first.

Original Log
> git log --online --decorate

f85179d (HEAD, master) ten
7de4071 nine
5c7a482 eight
9585035 seven
b41bffc six
d102f05 five
5a28cb9 four
6fc27c9 three
524b0c7 two
bb7e6ae one

Rebase everthing, which opens Notepad (or whatever commit editor you use.) Choose the commits that you want to squash together by the s option.
> git rebase -i --root

# this is notepad

pick bb7e6ae one
s 524b0c7 two
s 6fc27c9 three
s 5a28cb9 four
s d102f05 five
pick b41bffc six
pick 9585035 seven
pick 5c7a482 eight
pick 7de4071 nine
pick f85179d ten

After you save, this is the result of your log. Note that you have changed all the SHA1s.
> git log --oneline --decorate

6c63e02 (HEAD, master) ten
276cc7c nine
5248b0b eight
251f87a seven
a70d035 six
3529f1a Squash the five initial commits into one.


text:
Q: Array - Last index In an array, the index of the first element is zero. So an array declared as:
int a[5];

should have a[4] as the last element. However, when I execute the following code:
int n;
cin>>n;
int a[n];
for(int i = 0; i++<n; cin>>a[i]);
for(int i = 0; i++<n; cout<<i<<" "<<a[i]<<endl);

And give the input as:
5 1 2 3 4 5

The output is:
1 1
2 2
3 3
4 4
5 5

That implies that a[5] = 5. I was wondering as to how that is possible. Shouldn't it display some garbage value instead?

A: change i++ < n to i < n and cin>>a[i] to cin>>a[i++]

A: Logical. You are doing it wrong. Consider corner where n = 5:
Your i is 4. You do check if i++ < 5 is true and after check, i increases.
I is now 5 and this is out of bounds.
Your loop actually runs from 1 to 5 instead of 0 to 4.
Rewrite codes to:
for (int i = 0; i < n; cin >> a[i], i++);
for (int i = 0; i < n; cout << i << " " << a[i] << endl, i++);

A:
Shouldn't it display some garbage value instead?

Teaching that an unitialized variable has a garbage value or that accessing an array will yield garbage values is really a disservice.
Accessing an uninitialized variable or an array out of bounds in C++ is Undefined Behavior. This means that the program can behave in any way. It can crash, it can appear to function, it can any behavior, it can appear to have garbage values in unitialized variables.

A: Alternatively you could  just replace
int i=0 by int i=-1   and,
i++ by ++i
Now the loop will run and enter the values from a[0] to a[4] as expected.
The code could be rewritten as:
for(int i=-1;++i<n;cin>>a[i]);
for(int i=-1;++i<n;cout<<i<<" "<<a[i]<<endl);


text:
Q: CakePHP - why aren't errors being reported? I've stopped receiving error messages in my CakePHP app. Normally error messages are suppressed if you have debug set to 0; if it is 1 or 2 then you get the error message, (plus stack trace, etc.) But I don't get anything if there is an error, regardless of my debug setting. So if I introduce an error (syntax, logic, whatever) all I get is a blank page, with no indication of line number or anything. The error seems to be getting swallowed somewhere, but I can't find where. ini_get('error_reporting') returns E_ALL.
This did work, so I have almost certainly broken it myself. I just need some indication of where to start looking to try and fix it. Thanks!

A: you could start looking in yout initiasation methods to check if the debug setting has been changed somewhere to 0.
some places to start looking could be: AppController::beforeFilter() and the current controller's beforeFilter().
You could also have a look at the other hooks, just to make sure...
You can also try to issue a Configure::write('debug', 2); right before creating an erroneuous statement.

A: Check that there isn't a custom error handler which is hiding all the errors from you. The function which would define one is called set_error_handler.

A: Check if you're importing any 3rd party libraries which may set the error reporting to a different level.


text:
Q: searching for a character or string in a file (java) I was trying to read a file.dat that contains many commands which are the character at the front of each line. But somehow the code that I wrote seems to skip or not recognize some of the character at the front of some line.
This is the file(original):
p 10 1 100
p 23 1 50
p 12 2 275
d 1
s 1
p 14 2 1050
d 3
x 4
p 37 2 25
p 41 1 500
d 2
s 2
q

This is the result:
 got p!
 x, y, z of p command are: 10, 1, 100
 got p!
 x, y, z of p command are: 23, 1, 50
 got p!
 x, y, z of p command are: 12, 2, 275
 command not found
 got p!
 x, y, z of p command are: 14, 2, 1050
 command not found
 got p!
 x, y, z of p command are: 37, 2, 25
 got p!
 x, y, z of p command are: 41, 1, 500
 got s
 x of s command is: 2
 java.util.NoSuchElementException
 Process finished with exit code 0

However, the results that came out would bring another error when I tried to edit the file a bit(just swap 2 lines)
Here is the edited file:
d 3
p 10 1 100
p 23 1 50
p 12 2 275
s 1
d 1
p 14 2 1050
x 4
p 37 2 25
p 41 1 500
d 2
s 2
q

The result of the edited file:
command not found
command not found
command not found
got s
x of s command is: 1
command not found
command not found
got p!
x, y, z of p command are: 37, 2, 25
got p!
x, y, z of p command are: 41, 1, 500
got s
x of s command is: 2
java.util.NoSuchElementException
Process finished with exit code 0

And this is the code that I wrote:
import java.io.File;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class test3 {
    public static void main(String[] args) throws Exception {
        File file = new File("file.dat");
        try {
            Scanner input = new Scanner(file);
            while (input.hasNext()) {
                if ("p".equals(input.next())) {
                    System.out.println("got p!");
                    String x = input.next();
                    String y = input.next();
                    String z = input.next();

                //I put this print and variables x,y,z here for debug but also to implemented it later on
                    System.out.println("x, y, z of p command are: " + x + ", " + y + ", " + z);

                } else if ("d".equals(input.next())) {
                    System.out.println("got d!");
                    String x = input.next();
                    System.out.println("x of d command: " + x);

                } else if ("s".equals(input.next())) { //This is the show status operation from 's' command
                    System.out.println("got s");
                    String x = input.next();
                    System.out.println("x of s command is: " + x);
                } else if ("q".equals(input.next())) {
                    System.out.println("got q");
                } else {
                    System.out.println("command not found");
                }
            }
        } catch (NoSuchElementException e) {
            System.out.print(e);
        }
    }
}

I am thankful for any solutions that will come from you all

A: You are skipping pieces of the file by calling input.next(). Store the result of input.next() in a variable and then use that variable in your if elses. Once you know which command you are dealing with you can call input.next() for however many inputs you are expecting for the given command.
This solution still has a problem if the file is not formatted correctly. If the command does not have the expected number of characters after it you will parse the file incorrectly. You should store the lines in a variable at the beginning of your conditionals using .nextLine() and parse the line variable from there to get your commands and avoid this issue.
Here I fixed the code for the first command:
import java.io.File;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class test3 {
    public static void main(String[] args) throws Exception {
        File file = new File("file.dat");
        try {
            Scanner input = new Scanner(file);
            while (input.hasNextLine()) {
                string currentLine = input.nextLine();
                string[] currentLineArray = currentLine.split(" ");
                if ("p".equals(currentLineArray[0])) {
                    System.out.println("got p!");
                    if(currentLineArray.length == 4){
                        String x = currentLineArray[1];
                        String y = currentLineArray[2];
                        String z = currentLineArray[3];
                        System.out.println("x, y, z of p command are: " + x + ", " + y + ", " + z);
                    } else {
                        System.out.println("Incorrect number of arugments for command p!")
                    }
                }
            }
        }
    }
}

A: The problem here is that you test on input.next() which iterates over your file input, I suggest you put the result of input.next() in a variable and test on its content.


text:
Q: Create HBASE transformations on the HUB How can i develop generic programs which will do the following.
a.       Reading Data from HBASE
b.      Loading Data to HBASE
c.       Using HBASE Table as a Lookup in MapReduce
I need to create transformations which are generic enough and they should be easily integratable in the data pipeline.

A: HBase stores data as byte arrays, so you can put any data in you want.  You can serialize everything to XML or JSON and treat HBase as pure blob storage.  This is actually pretty efficient, as long as you only want to query by key, or scan through a table based on keys.
One thing you lose by doing this is the ability to filter on the server side based on a row value.  For example, if you wanted all of your rows in a table of HTTP transactions from the past month (where the key is based on a timestamp), but you only want to look at rows that had an error condition (a 500 response), if you stored the response code as a column you could create a filter that only returns items with the 500 response code.  While you still have to scan through the relevant portion of your table, only the data that matches the error code will be sent over the network to your hbase client.
One way around this is to do a hybrid approach where you store your data as a serialized object (JSON / XML / whatever), and also store additional columns for things you might want to filter on.


text:
Q: Using TensorFlow-metal plugin, training stops after some time without any errors? I've followed the steps provided by Apple, which utilizes conda, to install TensorFlow to get the best out of the M1 Pro MacBook Pro. As the title is self-descriptive, the training stops after some time without any errors. Please see the Keras training log below. This has happened many times. What could be the reason behind this situation? Have you experienced the same on your end? If so, how can I overcome this situation?
...
Epoch 38/50
625/625 [==============================] - 18s 29ms/step - loss: 1.6704 - acc: 0.4178 - val_loss: 1.8169 - val_acc: 0.4044
Epoch 39/50
625/625 [==============================] - 18s 29ms/step - loss: 1.6788 - acc: 0.4157 - val_loss: 1.6830 - val_acc: 0.4029
Epoch 40/50
625/625 [==============================] - 18s 28ms/step - loss: 1.6921 - acc: 0.4089 - val_loss: 1.7088 - val_acc: 0.4049
Epoch 41/50
625/625 [==============================] - 18s 28ms/step - loss: 1.6705 - acc: 0.4170 - val_loss: 1.6650 - val_acc: 0.4182
Epoch 42/50
625/625 [==============================] - 18s 29ms/step - loss: 1.6659 - acc: 0.4177 - val_loss: 1.9102 - val_acc: 0.3443
Epoch 43/50
625/625 [==============================] - 18s 29ms/step - loss: 1.6760 - acc: 0.4166 - val_loss: 1.6647 - val_acc: 0.4222
Epoch 44/50
532/625 [========================>.....] - ETA: 2s - loss: 1.6639 - acc: 0.4217


text:
Q: Enterprise library logging + dynamic connection string I am using the enterprise library logging and exception handling.

Currently I am adding the connection string in the configuration file, and this means that it is static.

My problem is that the user may connect to a different database each time depending on his user name. Is there any way to change the connection string at run time?

A: I created a CustomTraceListener

A: You can set the Connection string at run time by using ConfiguratiomManager class from System.Configuration namaspace as below;
ConfigurationManager.ConnectionStrings[0].ConnectionString = "Your new Connection string";


text:
Q: Crowdsourcing points by on-click to web map with moderation? I want to build a really lightweight web map interface where a user can click anywhere on a map, create a point, type in a comment -- ideally all via Facebook, but I don't want to get ahead of myself -- and have that comment pop up next to the point on mouse-over. Eventually, a large "crowdsourced" smattering of points with comments will be formed ... kind of like this New York Times map.
I have access to everything I need to build something with the ArcGIS API for JavaScript, and some basic knowledge of JavaScript / that API, but am stymied by the need for the following features, in order of importance (1 & 2 are about equal):

*

*A moderator of some sort (me) can go in & remove any inappropriate points/comments.

*User X cannot edit any other users' points.

*User X who makes a point on the map can go back and edit any of their own points.

It seems the ArcGIS API can help you make a web map that allows a point-editing free-for-all, but nothing like the above features, as far as I know. And I don't know much about the server/database side of web technologies. What kind of technology would even be necessary to:

*

*Recognize User X as User X & not User Y?

*Recognize points a, b, and c as belonging to user X?

*Letting user X edit those points and no other points?

I imagine there would need to be some kind of account creation / logging-in situation, tied to map editing capability? Where would one even begin crafting something like that?
For functionality, Crowdmap (like this example here) does exactly what I'm looking for in terms of the key requirements 1 & 2, but I want something a lot more simple ... just one click on the map, type in a box to put your comment, and you're done, no clicking through to "report submission" forms with tons of fields and sending it off somewhere to get processed.
For aesthetics & some functionality, I really like the look & simplicity of this cool map, which also fulfills 1 & 2, but I have no idea how user-submitted polygons are being read and presumably appended to a geo-enabled table/database, and in fact that very part seems crucially incomplete, because the things you draw on the map don't seem to actually get saved.
Would love to get pointed in the right direction, as I would be thrilled to know how to do this! Or even what I need to learn more broadly.

A: As I understand it, Esri's IdentityManager is designed for managing ArcGIS.com users:

This class provides the framework to  implement a solution for managing user credentials for (1) ArcGIS Server resources secured using token-based authentication and (2) Secured ArcGIS.com resources (i.e. web maps).

Your users would need to register for an Esri global account - this is fine for staff members within your organisation, but not so good if you want to allow random users to sign in via Facebook, Google, or your own login system.
You may need to write a "wrapper" which handles the user management aspects of your application.
As a suggestion, you could create an editable feature layer. To incorporate your user management, you'd need functionality which allows edits via the Editor dijit when the user is properly authorised (that's the bit you'd have to write, or perhaps find a plugin which does this).
For example, you could wrap your entire application in a WordPress page, and use something like this user access manager to control who can do what. Or write something in Rails as in this example. (These are both untested - I just mean to find something which already handles common user actions like Register, Sign In, Forgot Password, etc so you don't have to write it yourself.)
In terms of the approval queue, you could write functionality which flagged new edits for you to handle - again there's nothing out-of-the-box for this, to my knowledge.

A: I recently accomplished almost exactly what you describe using ArcGIS (JavaScript API), ArcGIS Server 10.2 (this controls the administration and edit tracking), and PostGRESQL. I originally used this (outdated) Flex API example as a template. In this example, the user logs in and creates some features with related attribute information. These features are then stored in the database along with information related to the specific user.
Do you have an ArcGIS Server license? This is a key component as it hosts your feature services and acts as the bridge between your database and the front-end web mapping interface.
GeoServer is a free alternative to ArcGIS Server, but the learning curve is a bit steeper.

A: Well, I'm going to "answer" my own question -- while the below isn't an ideal solution, it is pretty darn close and meets all 3 of the requirements I outlined in the question. Note that the limitations were: No immediately available access to our own map server (as it turned out), I don't have the know-how to write my own user registration system in only a couple of days, and no readily available database back end to store the data or user account info anyway.
First, I set up a Google spreadsheet and created a form in HTML that would submit its values into this spreadsheet. That would be kind of like my "database", that I'd have full moderator access to. Upon submission, Google has built-in functionality to let you go back and edit your own submission, as long as you don't leave the site. You can't mess with anyone else's submissions.
Then, I used the Google Maps JavaScript API to embed a map above the form. When the user clicks the map (within a restricted area delineated by a polygon I threw in there), it automatically writes the coordinates of their click to two fields in the form (and puts a marker there, to let them know that's where they clicked).
When they submit, it's written to the spreadsheet, which I can then pull down and map however I want. So, collecting the crowdsourced points is decoupled from actually mapping them, but that could probably be easily remedied as well.
I wanted something that could potentially take advantage of my own database and ArcGIS Server, so Stephen's answer above did a great job of pointing the way for what I should learn next, but I think this was a great solution given the time and tech constraints. Hope someone finds it helpful.

A: ArcGIS Online for Organization allows to Track edits and restrict edits to feature owners which state:

You can have ArcGIS Online keep track of who created the features in
  the published feature layer and restrict access accordingly. To track
  the edits, follow the steps to edit web layer details and check Keep
  track of who created and last updated features.
In some scenarios, you may want to allow someone to delete or modify
  the features they created but not delete or modify others' features.
  This might be the case with volunteered geographic information (VGI)
  apps in which you want to limit the control each contributor has over
  the data. To restrict feature modification to just the person who
  created the feature, check Editors can only update and delete the
  features they add.
Edits are not tracked if you choose to make the service public.

As the administrator of your organization, you still maintain full editing control over the feature layer.  The only downside is that, per the term of service, you will need an AGOL named user login credential for each contributor.


text:
Q: Problems with deserializing xml to object structure c# I have the following xml:
<Root>
<ProcessingUnit>Lifestyle</ProcessingUnit>
<ProcessingData>
    <ProcessType>Product</ProcessType>
    <ProcessAction>Create</ProcessAction>
    <Id>7</Id>
</ProcessingData>
</Root>

And i have the following object structure
[XmlRoot("Root")]
public class XmlRoot
{
    ProcessingUnit ProcessingUnit { get; set; }
    [XmlElement("ProcessingData")]
    ProcessingData ProcessingData { get; set; }
}

public class ProcessingData
{
    public ProcessType ProcessType { get; set; }
    public ProcessAction ProcessAction { get; set; }
    public int Id { get; set; }
}

When i deserialize i do the following:
XmlSerializer _serializer = new XmlSerializer(typeof(XmlRoot));
using (var reader = new StringReader(stringtest))
{
     var tradeData = (XmlRoot)_serializer.Deserialize(reader);
}

Deserializing to enums works fine, the processingUnit is deserialized correctly but the property ProcessingData is null.
I have tried decorating with a lot of different xml attributes but i cant see why i get the null value.
EDIT:
The stringtest variable has the value:
var stringtest =
            "<Root><ProcessingUnit>Lifestyle</ProcessingUnit><ProcessingData><ProcessType>Product</ProcessType><ProcessAction>Create</ProcessAction><Id>7</Id></ProcessingData></Root>";

The enums looks like this:
public enum ProcessType
{
    [XmlEnum(Name = "Product")]
    Product,

    [XmlEnum(Name = "Category")]
    Category,
}

public enum ProcessAction
{
    [XmlEnum(Name = "Create")]
    Create,

    [XmlEnum(Name = "Delete")]
    Delete,

    [XmlEnum(Name = "Update")]
    Update,
}

public enum ProcessingUnit
{
    [XmlEnum(Name = "LifeStyle")]
    LifeStyle
}

A: Properties have to be public
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string stringtest = "<Root>" +
                "<ProcessingUnit>Lifestyle</ProcessingUnit>" +
                "<ProcessingData>" +
                    "<ProcessType>Product</ProcessType>" +
                    "<ProcessAction>Create</ProcessAction>" +
                    "<Id>7</Id>" +
                "</ProcessingData>" +
                "</Root>";

            XmlSerializer _serializer = new XmlSerializer(typeof(XmlRoot));
            using (var reader = new StringReader(stringtest))
            {
                XmlRoot tradeData = (XmlRoot)_serializer.Deserialize(reader);
            }

        }
    }
    [XmlRoot("Root")]
    public class XmlRoot
    {
        [XmlElement("ProcessingUnit")]
        public ProcessingUnit ProcessingUnit { get; set; }
        [XmlElement("ProcessingData")]
        public ProcessingData ProcessingData { get; set; }
    }
    [XmlRoot("ProcessingData")]
    public class ProcessingData
    {
        [XmlElement("ProcessType")]
        public ProcessType ProcessType { get; set; }
        [XmlElement("ProcessAction")]
        public ProcessAction ProcessAction { get; set; }
        [XmlElement("Id")]
        public int Id { get; set; }
    }
    [XmlRoot("ProcessingUnit")]
    public class ProcessingUnit
    {
        [XmlText]
        public string text { get; set; }
    }
    [XmlRoot("ProcessType")]
    public class ProcessType
    {
        [XmlText]
        public string text { get; set; }
    }
    [XmlRoot("ProcessAction")]
    public class ProcessAction
    {
        [XmlText]
        public string text { get; set; }
    }
}


text:
Q: How can I output null-terminated strings in Awk? I'm working on a shell script that will be used by others, and may ingest suspect strings. It's based around awk, so as a basic resiliency measure, I want to have awk output null-terminated strings - the commands that will receive data from awk can thus avoid a certain amount of breakage from strings that contain spaces or not-often-found-in-English characters.
Unfortunately, from the basic awk documentation, I'm not getting how to tell awk to print a string terminated by an ASCII null instead of by a newline. How can I tell awk that I want null-terminated strings?

Versions of awk that might be used:
[user@server1]$ awk --version
awk version 20070501

[user@server2]$ awk -W version
mawk 1.3.3 Nov 1996, Copyright (C) Michael D. Brennan

[user@server3]$ awk -W version
GNU Awk 3.1.7

So pretty much the whole family of awk versions. If we have to consolidate on a version, it'll probably be GNU Awk, but answers for all versions are welcome since I might have to make it work across all of these awks. Oh, legacy scripts.

A: You can also pipe your awk's output through tr:
awk '{...code...}' infile | tr '\n' '\0' > outfile

Just tested, it works at least on Linux and FreeBSD.
If you cannot use newlines as separators (for example, if output records can contain newlines inside), just use some other character that's guaranteed not to appear inside a record, e.g. the one with code 1:
awk 'BEGIN { ORS="\001" } {...code...}' | tr '\001' '\0'

A: There are three alternatives:

*

*Setting ORS to ASCII zero:
Other solutions have awk -vORS=$'\0' but:
The $'\0' is a construct specific to some shells (bash,zsh).
So: this command awk -vORS=$'\0' will not work in most older shells.

There is the option to write it as: awk 'BEGIN { ORS = "\0" } ; { print $0 }', but that will not work with most awk versions.

*Printing (printf) with character \0: awk '{printf( "%s\0", $0)}'

*Printing directly ASCII 0: awk '{ printf( "%s%c", $0, 0 )}'
Testing all alternatives with this code:
#!/bin/bash

test1(){   # '{printf( "%s%c",$0,0)}'|
    a='awk,mawk,original-awk,busybox awk'
    IFS=',' read -ra line <<<"$a"
    for i in "${line[@]}"; do
        printf "%14.12s %40s" "$i" "$1"
        echo -ne "a\nb\nc\n" |
        $i "$1"|
        od -cAn;
    done
}

#test1 '{print}'
test1 'BEGIN { ORS = "\0" } ; { print $0 }'
test1 '{ printf "%s\0", $0}'
test1 '{ printf( "%s%c", $0, 0 )}'

We get this results:
            awk      BEGIN { ORS = "\0" } ; { print $0 }   a  \0   b  \0   c  \0
           mawk      BEGIN { ORS = "\0" } ; { print $0 }   a   b   c
   original-awk      BEGIN { ORS = "\0" } ; { print $0 }   a   b   c
    busybox awk      BEGIN { ORS = "\0" } ; { print $0 }   a   b   c
            awk                     { printf "%s\0", $0}   a  \0   b  \0   c  \0
           mawk                     { printf "%s\0", $0}   a   b   c
   original-awk                     { printf "%s\0", $0}   a   b   c
    busybox awk                     { printf "%s\0", $0}   a   b   c
            awk               { printf( "%s%c", $0, 0 )}   a  \0   b  \0   c  \0
           mawk               { printf( "%s%c", $0, 0 )}   a  \0   b  \0   c  \0
   original-awk               { printf( "%s%c", $0, 0 )}   a  \0   b  \0   c  \0
    busybox awk               { printf( "%s%c", $0, 0 )}   a   b   c

As it can be seen above, the first two solutions work only in GNU AWK.
The most portable is the third solution: '{ printf( "%s%c", $0, 0 )}'.
No solution work correctly in "busybox awk".
The versions used for this tests were:
          awk> GNU Awk 4.0.1
         mawk> mawk 1.3.3 Nov 1996, Copyright (C) Michael D. Brennan
 original-awk> awk version 20110810
      busybox> BusyBox v1.20.2 (Debian 1:1.20.0-7) multi-call binary.

A: Alright, I've got it.
awk '{printf "%s\0", $0}'

Or, using ORS,
awk -vORS=$'\0' //

A: I've solved printing ASCII 0 from awk.
I use UNIX command printf "\000"
echo | awk -v s='printf "\000"' '{system(s);}'


text:
Q: Doctrine: addSelect method creates undesired seperate object (Symfony) I want to query the entity based on a calculated property that does not exist in the database or on the entity.
If I run
    return $this->createQueryBuilder('b')
            ->select('b')
            ->addSelect(
                '... as extra_property'
            )
            ->having('extra_property = :param')
            ->setParameter('param', $param)
            ->orderBy('extra_property', 'ASC')
            ->getQuery()
            ->getResult();

This results in a collection with each entity in the following format:
"0": {}, // The 9 entity properties
"extra_property": "value"

However, I want the extra_property to be added to the other entity properties as the tenth property. How do I fix this?

A: The problem lies in the getResult() method, the default hydration method is "HYDRATE_OBJECT" which will try to hydrate the output as the defined entity, which does not know about your extra property.
public function getResult($hydrationMode = self::HYDRATE_OBJECT)
{
    return $this->execute(null, $hydrationMode);
}

Depending on what your other properties are, you could just use the "HYDRATE_SCALAR" option which will just give you a flat output of the results.
If you other properties are nested entities, you will have to manually select the fields in your select to bypass the hydration process, or find a way to add that property to your entity and tell the hydrator to get that data from a dedicated query or something.
You can find the different hydration methods as constants of the AbstractQuery class, you can read more on the Doctrine documentation
/**
 * Hydrates an object graph. This is the default behavior.
 */
public const HYDRATE_OBJECT = 1;

/**
 * Hydrates an array graph.
 */
public const HYDRATE_ARRAY = 2;

/**
 * Hydrates a flat, rectangular result set with scalar values.
 */
public const HYDRATE_SCALAR = 3;

/**
 * Hydrates a single scalar value.
 */
public const HYDRATE_SINGLE_SCALAR = 4;

/**
 * Very simple object hydrator (optimized for performance).
 */
public const HYDRATE_SIMPLEOBJECT = 5;

/**
 * Hydrates scalar column value.
 */
public const HYDRATE_SCALAR_COLUMN = 6;


text:
Q: Trying to convert a for loop to SIMD in C++ For a game i'm trying to make faster, i have a part of code that makes sure tanks evade eachother, by pushing them away from eachother with a force.
for ( unsigned int i = 0; i < (MAXP1 + MAXP2); i++ )
{
    if (game->m_Tank[i] == this) continue;
    float2 d = pos - game->m_Tank[i]->pos;
    float dlsq = (d.x * d.x + d.y * d.y);
    if (dlsq < 64) force += normalize(d) * 2.0f;

    else if (dlsq < 256) force += normalize(d) * 0.4f;

}

Now i'm trying to do 4 tanks at a time using SIMD, so i have
for (unsigned int i = 0; i < (MAXP1 + MAXP2) / 4; i++)
{
    union {
        __m128 valuesx4;
        float valuesx[4];
    };
    union {
        __m128 valuesy4;
        float valuesy[4];
    };
    __m128 dx4 = _mm_set_ps((pos - game->m_Tank[i*4]->pos).x, (pos - game->m_Tank[i*4+1]->pos).x, (pos - game->m_Tank[i*4+2]->pos).x, (pos - game->m_Tank[i*4+3]->pos).x);
    __m128 dy4 = _mm_set_ps((pos - game->m_Tank[i*4]->pos).y, (pos - game->m_Tank[i*4+1]->pos).y, (pos - game->m_Tank[i*4+2]->pos).y, (pos - game->m_Tank[i*4+3]->pos).y);
    __m128 dlsq4 = _mm_add_ps(_mm_mul_ps(dx4, dx4), _mm_mul_ps(dy4, dy4));
    __m128 sixtyfour4 = _mm_set_ps1(64.0f);
    __m128 twofiftysix4 = _mm_set_ps1(256.0f);
    __m128 mask0 = _mm_cmpeq_ps(dlsq4,_mm_set_ps1(0.f));
    __m128 adjdlsq4 = _mm_add_ps(dlsq4, _mm_and_ps(mask0, _mm_set_ps1(300.f)));
    __m128 mask1 = _mm_cmplt_ps(adjdlsq4, sixtyfour4);
    __m128 mask2 = _mm_and_ps(_mm_cmplt_ps(adjdlsq4, twofiftysix4), _mm_cmpge_ps(adjdlsq4,sixtyfour4));
    __m128 multiplier4 = _mm_add_ps(_mm_and_ps(mask1, _mm_set_ps1(2.0f)), _mm_and_ps(mask2, _mm_set_ps1(0.4f)));
    __m128 rsqrt4 = _mm_rsqrt_ps(adjdlsq4);
    __m128 values4 = _mm_mul_ps(rsqrt4, multiplier4);
    valuesx4 = _mm_mul_ps(values4, dx4);
    valuesy4 = _mm_mul_ps(values4, dy4);

    force += (valuesx[0], valuesy[0]);
    force += (valuesx[1], valuesy[1]);
    force += (valuesx[2], valuesy[2]);
    force += (valuesx[3], valuesy[3]);
}

I adjust the dlsq to account for the case where the checked Tank is the current Tank. For some reason however, in contrast to the normal way where the tanks gather around the target and stay roughly in a filled circle around the target, in the SIMD version, the tanks start following a sloped line and intersecting with eachother. They all move on a line with direction (1,-1) from the target. Does anyone see where it goes wrong?


text:
Q: How to disable copy and paste activity in ionic3 form fields Is it possible to remove copy and paste in ionic3 form fields?
I tried using the below CSS code but not working,(i.e the options are displaying, long press on input field )
 ion-input {
    -webkit-touch-callout: none;    /* prevent callout to copy image, etc when tap to hold */
    -webkit-text-size-adjust: none; /* prevent webkit from resizing text to fit */
    -webkit-user-select: none;      /* prevent copy paste, to allow, change 'none' to 'text' */
    -ms-touch-callout: none;
    -ms-user-select: none;
    -ms-text-size-adjust: none;
    -moz-touch-callout: none;
    -moz-user-select: none;
    -moz-text-size-adjust: none;
  }


text:
Q: How to refer to next and previous array value? I'm trying to make a simple blog. On the bottom of the page content i placed pagination which displays links to next and previous blog entry, with the blog title in the link that I'm getting from the database table called "pages", column "menu_name".
I did this by first making a query and creating an array through a function in the class called "Blog" and then setting some variables:
$sql = "SELECT * FROM pages ";
$sql .= "ORDER BY id DESC ";
$pages = Blog::find_by_sql($sql);
$blog_page = reset($pages);
$page_id = Blog::find_by_id(isset($_GET['page']) ? $_GET['page'] : $blog_page->id);

Then I made the code for the previous blog link as follows:
public function pagination_previous(){
    global $address; //$address = "list_blogs.php?page=";
    global $page_id;
    global $pagination; //a class for storing functions that handle pagination
    global $pages;
    if($pagination->has_next_page()){
        echo "\n        next_page();
        echo " title=\"Newer Blog\">« ";
        foreach($pages as $page => $value){
            if($page_id->id + 1 == $value->id){
                echo $value->menu_name;
            }
        };
        echo " ";
    }else{
        echo "";
    }
}

This is the function has_next_page()
public function has_previous_page(){
    return $this->previous_page() >= 1 ? true : false;
}

and this is previous_page():
public function previous_page(){
    global $blog;
    return $this->current_page - 1;
}

This worked great until I decided to make admin area from where I can delete blog entries.
The problem starts when I delete a blog entry with id let's say 6. Since there is no more item with id=6 in the database table "pages", the links to next or previous page on the pages that came before and after the missing page are empty but still point to the page=6 since has_previous_page() subtracts 1 from $current_page.
I half-way figured out a way out of this mess by setting the pagination_next() function like this:
public function pagination_next(){
    global $address;
    global $pagination;
    global $page_id;
    global $pages;
    if($pagination->has_previous_page()){
        foreach($pages as $page => $value){
            if($page_id->id - 1 == $value->id){

                echo "\n        id;
                echo " title=\"Older Blog\">";
                echo $value->menu_name;
                break;
            }

        }
        echo " » ";
    }else{
        echo "";
    }
}

This however still does not work because of the if condition inside the foreach loop.
I need to set this condition in both pagination_previous() and pagination_next() to reference the next and previous array item based on its array index ($page), not on the id ($value->id) but I can't figure this out for the life of me. This is how the array $pages looks like:
Array
(
[0] => Blog Object
    (
        [id] => 8
        [subject_id] => 2
        [menu_name] => Aliquam sed interdum
        [position] => 4
        [visible] => 1
        [created] =>
        [content] =>
    Aliquam sed interdum tortor. Vivamus et blandit velit...

[1] => Blog Object
    (
        [id] => 7
        [subject_id] => 2
        [menu_name] => Vestibulum ante ipsum
        [position] => 3
        [visible] => 1
        [created] =>
        [content] =>
    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices...

[2] => Blog Object
    (
        [id] => 5
        [subject_id] => 2
        [menu_name] => Praesent massa mi
        [position] => 2
        [visible] => 1
        [created] =>
        [content] =>
    Praesent massa mi, pretium et leo vitae, aliquam...

[3] => Blog Object
    (
        [id] => 4
        [subject_id] => 2
        [menu_name] => Nam interdum tincidunt
        [position] => 1
        [visible] => 1
        [created] =>
        [content] =>
    Nam interdum tincidunt purus quis lacinia. Aliquam erat volutpat.
)

)
Can someone help me out with this?
Thank you all for your answers, but unfortunately none of them helped me solve my problem.
After exhausting all options, I definitely concluded that the only way to solve this without messing up the entire code is to figure out how to refer to the next or previous existing $value->id in the if condition without adding or subtracting 1 to get to the next page, because that causes empty links to appear when id is missing from the database.
If anyone can solve this puzzle, I will be eternally grateful to that person.

A: You could turn your previous_page function to something along these lines :
public function previous_page( )
{
    global $blog;

    $prev = -1; // Initialize

    $arrayKeys = array_keys( $blog );

    rsort( $arrayKeys );    //  Sort keys array in reverse order

    while( list( $key ,$cursor ) = each( $arrayKeys ) )
    {
        if( $cursor == $this->current_page )
        {
            if( list( $key ,$prev ) = each( $arrayKeys ) ) return $prev;
            break;
        }
    }
    return $prev;
}

The below might give more understanding :
//  Test data

$array = array( 0 => 'Obj 0' ,1 => 'Obj 1' ,2 => 'Obj 2' ,3 => 'Obj 3' ,4 => 'Obj 4' , );

$current = 3;   //  Try with any valid key of the array

//  Get the keys into an array

$arrayKeys = array_keys( $array );

//  Search for next

$next = -1; // Initialize

sort( $arrayKeys ); //  Sort the keys array

while( list( $key ,$cursor ) = each( $arrayKeys ) )
{
    if( $cursor == $current )
    {
        if( list( $key ,$cursor ) = each( $arrayKeys ) )
        {
            $next = $cursor;
        }
        break;
    }
}
//  Search for previous

$prev = -1; // Initialize

rsort( $arrayKeys );    //  Sort keys array in reverse order

while( list( $key ,$cursor ) = each( $arrayKeys ) )
{
    if( $cursor == $current )
    {
        if( list( $key ,$cursor ) = each( $arrayKeys ) )
        {
            $prev = $cursor;
        }
        break;
    }
}

if( $prev <> -1 )   echo '
Prev : ' ,$array[$prev];
if( $next <> -1 )   echo '
Next : ' ,$array[$next];

A: I recommend using sql to get the previous and next blog entries
previous post
select * from pages where id = ( select max(id) from pages where id < <current_post_id> )

next post
select * from pages where id = ( select min(id) from pages where id > <current_post_id> )

A: Full-featured option might be to have a persistent sequence index field on your blog objects. Pagination can check for prev/next sequence indexes. You can either write your function to blindly assume they are truly sequential ( and make sure you re-index them when deleting posts ) for easy +1/-1 implementation or write a function that finds the next highest/lowest ( probably from the db ). This would allow you to move them around arbitrarily as well as ensure existence. Decouple order from arbitrary object id.

A: Before foreach loop of your array update your array index using array_values function it will reindex your array so now your logic will remain same and function properly.


text:
Q: Quantum Mechanics mistake in partial trace I have a given a density matrix by $\rho:=\frac{1}{2} |\psi_1 \rangle \langle \psi_1|+\frac{1}{8} |\psi_2 \rangle \langle \psi_2|+\frac{3}{8} |\psi_3 \rangle \langle \psi_3|.$
Where $|\psi_1\rangle := \frac{1}{\sqrt{2}}(|0. \rangle -i |1. \rangle )$
$|\psi_2\rangle := \frac{1}{\sqrt{3}}(|0. \rangle - |2. \rangle - |3.\rangle  )$
$|\psi_3\rangle := \frac{1}{\sqrt{2}}(i|0. \rangle + |3. \rangle )$
where we have that $|0.\rangle := |0\rangle \otimes |0\rangle$
$|1.\rangle := |0\rangle \otimes |1\rangle$
$|2.\rangle := |1\rangle \otimes |0\rangle$
$|3.\rangle := |1\rangle \otimes |1\rangle$
Now I wanted to write down $\rho_A$, which means that I have to trace out the basis B.
I got: $\rho_A=\frac{1}{2}\left(\frac{1}{2}|0\rangle \langle 0|+ \frac{1}{2}|0\rangle \langle 0|\right)+\frac{1}{8}\left(\frac{1}{3}|0\rangle \langle 0|+ \frac{1}{3}|1\rangle \langle 1|-\frac{1}{3}|0\rangle \langle 1|- \frac{1}{3}|1\rangle +\langle 0|\right)+\frac{3}{8}\left(\frac{1}{2}|0\rangle \langle 0|+ \frac{1}{2}|1\rangle \langle 1|\right)$
The problem is: The trace of $tr(\rho_A)=\frac{1}{2}(\frac{1}{2}+\frac{1}{2})+\frac{1}{8}(\frac{1}{3}+\frac{1}{3})+\frac{3}{8}(\frac{1}{2}+\frac{1}{2}) \neq 1$ and therefore this cannot be a density matrix. What have I done wrong?-I have written this in this extended form so that it is easier for you to see what I have down. Does anybody here know how to do this correctly?

A: As I had written in the comments, it is the second term that you have gotten incorrect.
Focusing exclusively on this term (leaving aside the $1/8$ factor), we have
$$
|\psi_2\rangle \langle \psi_2| = \frac{1}{3}(|00\rangle \langle 00|+ |10\rangle \langle 10|+ |11\rangle \langle 11| - |00\rangle \langle 10|-|10\rangle \langle 00| + \ ...),
$$
where I have put the ... to indicate that those terms do not contribute to the reduced density matrix of A.
Now taking partial trace, we get the correct answer:
$$
\rho_{A,2} = \frac{1}{3}(|0\rangle \langle 0|+ 2|1\rangle \langle 1|-|0\rangle \langle 1|-|1\rangle \langle 0|)
$$
You may have missed the contribution from $ |10\rangle \langle 10| $, I guess. Adding 1/8 of this to the other two (correctly obtained) density matrices will give us a reduced density matrix of trace $1$.
A mistake people generally tend to make (but you have not) is in the last two terms, assuming that they do not contribute. This is erroneous, since even though they are not diagonal matrix elements of the full density matrix $\rho_{\mathsf{AB}}$, they still appear when you take a partial trace since they are outer products of the same 2 elements of B.


text:
Q: Is this possible to change TextView Drawable left image on hover effect Before posting it here I was googled a lot but nothing is found.
My problem is I have a textview in one of my activity xml file with drawable left icon on it,See below -
    <TextView
        android:id="@+id/edit_profile_tv"
        style="@style/style_large_text.black"
        android:drawableLeft="@drawable/ic_edit"
        android:drawableRight="@drawable/ic_next"
        android:text="@string/profile_setting" />

Now I want to change drawable left and drawable right icon of textview when textview is clicked.
I used selector for applying hover effect on any view, but not getting any way to change drawable left and right icon on hover effect.
Any help much appreciated. Thanks in advance.


text:
Q: forarray and a \gdef list parameter \documentclass{article}
\usepackage{forarray}
\begin{document}
  \newcommand{\mytext}[1]{\gdef\themytext{#1}}
  \newcommand{\mytest}[1]{\ForEach{,}{\typeout{\thislevelitem}}{#1}}

  % this one works, it prints
  % x
  % y
  % z
  \mytest{x,y,z}

  % this one doesn't work, it prints
  % x,y,z
  \mytext{x,y,z}
  \mytest{\themytext}

\end{document}

This is a simplified example of an issue I'm facing writing a LaTeX class file. I can't get \ForEach to work when the list parameter comes via a global macro definition.
How can I modify the definition of \mytex so that the example works?
Thanks

A: This works for me:
\documentclass{article}
\usepackage{forarray}
\begin{document}
  \newcommand{\mytext}[1]{\gdef\themytext{#1}}
  \newcommand{\mytest}[1]{\ForEachX{,}{\typeout{\thislevelitem}}{#1}}

  % this one works, it prints
  % x
  % y
  % z
  \mytest{x,y,z}

  % this one works, it prints
  % x
  % y
  % z
  \mytext{x,y,z}
  \mytest{\themytext}

\end{document}

Notice the use of \ForEachX, which expands the third argument, instead of \ForEach.

A: If you are willing to modify how you call \mytest, then
\expandafter\mytest\expandafter{\themytext}

gives
x
y
z
or you could define \mytest differently
\makeatletter
  \newcommand{\mytest}[1]{\edef\mylist{#1}%
    \expandafter\@mytest\expandafter{\mylist}}%
  \newcommand{\@mytest}[1]{\ForEach{,}{\typeout{\thislevelitem}}{#1}}
\makeatother


text:
Q: Pin annotation displaying the current location I use the MKPinAnnotationView for pin annotation.Can i possibly display the curent address of the location as the pin annotation if i move the pin randomly on the map?

A: Checkout the MKReverseGeocoder class.
http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKReverseGeocoder_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40008323


text:
Q: Having trouble trying to pull the result of a Query from a Bean into a JSP I've figured out how to pull the username and display it in the categories.jsp but I just can't figure out how to display the result of the costQuery in the UserDAO.java to display in the categories.jsp where the empty

<%= %>

tags are.
the costQuery is querying the database as follows:

select sum(cost) from stocks where username=

The username is being passed into the query.
I've tried so many things now with no luck I'm not even sure what to do next.  My code is below.
Any help would be GREATLY appreciated.
index.jsp (my login form)
<%@page contentType="text/html" pageEncoding="UTF-8" language="java"%>
<%@page language="java"%>
<%@page import="java.util.*" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

        <meta http-equiv="Content-Type" content="text/html;charset=windows-1256">
        <title>Login Page</title>

        <form action="LoginServlet">

        Login

        Username:
        <input type="text" name="un"/>

        Password:
        <input type="password" name="pw"/>

        <input type="submit" value="Submit" name="Submit"/><input type="Reset" value="Reset" />

            <input type="checkbox" value="remeber" /> Remember Me on this Computer

New users click here to register

        </form>

categories.jsp
<%@page language="java" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@page import="HWpackage.UserBean"%>
<%@page import="HWpackage.StockBean"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

            Welcome <%UserBean currentUser = (UserBean) (session.getAttribute("currentSessionUser"));%><%= currentUser.getUsername()%>

You currently have a total of **<%=  %>** invested.

            Please select from the list of stock categories below.

            Type of stock
            Invested in category

Technology Stocks

$$$$$

Utility Stocks

$$$$$$$$

[Log Out]

UserBean.java
package HWpackage;

public class UserBean {

private String username;
private String password;
public boolean valid;

private String stockname;
private String stocksym;
private String stockcat;
private String action;
private String pricepershare;
private String quantity;
private String actnick;
private String acthold;
private String actnum;
private String actroute;
private String actbal;
private String cost;
private String totalcost;
private String costQuery;

public String getPassword() {
    return password;
    }

public void setPassword(String newPassword) {
    password = newPassword;
    }

public String getUsername() {
    return username;
    }

public void setUserName(String newUsername) {
    username = newUsername;
    }

public boolean isValid() {
    return valid;
    }

public void setValid(boolean newValid) {
    valid = newValid;
    }

public String getStockname() {
    return stockname;
    }

public void setStockname(String stockname) {
    this.stockname = stockname;
    }

public String getStocksym() {
    return stocksym;
    }

public void setStocksym(String stocksym) {
    this.stocksym = stocksym;
    }

public String getStockcat() {
    return stockcat;
    }

public void setStockcat(String stockcat) {
    this.stockcat = stockcat;
    }

public String getAction() {
    return action;
    }

public void setAction(String action) {
    this.action = action;
    }

public String getPricepershare() {
    return pricepershare;
    }

public void setPricepershare(String pricepershare) {
    this.pricepershare = pricepershare;
    }

public String getQuantity() {
    return quantity;
    }

public void setQuantity(String quantity) {
    this.quantity = quantity;
    }

public String getActnick() {
    return actnick;
    }

public void setActnick(String actnick) {
    this.actnick = actnick;
    }

public String getActhold() {
    return acthold;
    }

public void setActhold(String acthold) {
    this.acthold = acthold;
    }

public String getActnum() {
    return actnum;
    }

public void setActnum(String actnum) {
    this.actnum = actnum;
    }

public String getActroute() {
    return actroute;
    }

public void setActroute(String actroute) {
    this.actroute = actroute;
    }

public String getActbal() {
    return actbal;
    }

public void setActbal(String actbal) {
    this.actbal = actbal;
    }

public String getCost(){
    return cost;
}
public void setCost (String cost) {
    this.cost = cost;
    }

public String getTotalcost(){
    return totalcost;
}
public void setTotalcost (String totalcost) {
    this.totalcost = totalcost;
    }

public String getCostQuery(){
    return costQuery;
}
public void setCostQuery (String costQuery) {
    this.costQuery = costQuery;

}

}

UserDAO.java
package HWpackage;

import java.text.*;
import java.util.*;
import java.sql.*;

public class UserDAO {

static Connection currentCon = null;
static ResultSet rs = null;
static ResultSet rsTech = null;
static ResultSet rsUtil = null;
static ResultSet rsCost = null;

public static UserBean login(UserBean bean) {

//preparing some objects for connection
Statement stmt = null;

String username = bean.getUsername();
String password = bean.getPassword();
String stockname = bean.getStockname();
String stocksym = bean.getStocksym();
String stockcat = bean.getStockcat();
String action = bean.getAction();
String pricepershare = bean.getPricepershare();
String quantity = bean.getQuantity();
String actnick = bean.getActnick();
String acthold = bean.getActhold();
String actnum = bean.getActnum();
String actroute = bean.getActroute();
String actbal = bean.getActbal();
String cost = bean.getCost();
String totalcost = bean.getTotalcost();
String costQuery = bean.getCostQuery();

String searchQuery =
        "select * from users where username='"
            + username
            + "' AND password='"
            + password
            + "'";

// "System.out.println" prints in the console; Normally used to trace the process
System.out.println("Your user name is " + username);
System.out.println("Your password is " + password);
System.out.println("Query: "+searchQuery);

String techQuery =
        "select sum(cost) from stocks where username='"
            + username
            + "' AND stockcat='Tech'";

System.out.println("Your stock category is Tech");
System.out.println("Query: "+techQuery);

String utilQuery =
        "select sum(cost) from stocks where username='"
            + username
            + "' AND stockcat='Util'";

System.out.println("Your stock category is Utilities");
System.out.println("Query: "+utilQuery);

costQuery =
        "select sum(cost) from stocks where username='"
            + username
            + "'";

System.out.println("This is for all stocks");
System.out.println("Query: "+costQuery);

try
{
    //connect to DB
    currentCon = ConnectionManager.getConnection();
    stmt=currentCon.createStatement();
    rs = stmt.executeQuery(searchQuery);
    boolean more = rs.next();

    // if user does not exist set the isValid variable to false
    if (!more)
    {
        System.out.println("Sorry, you are not a registered user! Please sign up first");
        bean.setValid(false);
    }

    //if user exists set the isValid variable to true else if (more)
    else if (more)
    {
        System.out.println("Welcome " + username);
        bean.setValid(true);
    }
}

catch (Exception ex)
{
    System.out.println("Log In failed: An Exception has occurred! " + ex);
}

//some exception handling
finally
{
    if (rs != null) {
        try {
            rs.close();
        } catch (Exception e) {}
        rs = null;
    }

    if (stmt != null) {
        try {
            stmt.close();
        } catch (Exception e) {}
        stmt = null;
    }

    if (currentCon != null) {
        try {
            currentCon.close();
        } catch (Exception e) {
        }

        currentCon = null;
    }
}

return bean;

}

}

A: Assuming that your UserBean has the property cost (the code confirms this), then just do the following during login:
UserBean user = userDAO.find(username, password);
if (user != null) {
    request.getSession().setAttribute("user", user);
    // ...
}

This way it's available by ${user} in JSP. So instead of the old fashioned scriptlets

    Welcome <%UserBean currentUser = (UserBean) (session.getAttribute("currentSessionUser"));%><%= currentUser.getUsername()%>

You currently have a total of **<%=  %>** invested.

You can just do
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...

    Welcome <c:out value="${user.username}" />

You currently have a total of ${user.cost} invested.

See also:

*

*How to avoid Java code in JSP files?

Unrelated to the concrete question, you have a major problem in your UserDAO class. The connection and resultset should not be declared as a static variable.


text:
Q: Не получается подключить картинку в Wordpress (на Woocommerce single product page), путь прописан правильно Пишу себе плагин для расчета индивидуальных штор. Не могу понять, почему не получается подключить картинку. Путь прописан правильно. Все перепробовала.
function mabou_step_two(){
echo'
ШАГ 2
';
echo'
';

 $img_src=plugins_url( 'imgs/shtornaya_lenta_small.png',__FILE__);
 echo '

';
    echo '
';
}

Данную функцию я вызываю в функции mabou_add_my_fields - использую хук
add_filter('woocommerce_short_description','mabou_add_my_fields');

Это принтскрин моего плагина (по ничего не выравнивала):


text:
Q: multiple  value js alert and onclick block I am setting up a simpleCart(js) with some selectable options.
I need to show an alert if not all drop-downs meet some value, and also to block the "Add to cart" from adding items to the cart (if not all drop-downs have met some value)
This is as far as I manage, any help is highly appreciated .

The HTML

TEST

        <select id"sizeSelect" class="item_size">
        <option value="nul">Please choose size</option>
        <option value="small">Small</option>
        <option value="medium">Medium</option>
        <option value="large">Large</option>
        <option value="xlbrain">Super brain</option>
        </select>

        <select id="shippingSelect" onchange="simpleCart.update();">
        <option value="nul">Please choose shipping</option>
        <option value="ups">UPS Standard 25€</option>
        <option value="mail">Standard Mail 10€</option>
        </select>

        <select id"destiantionSelect" class="item_price">
        <option value="nul">Please choose destination</option>
        <option value="290.00">EU</option>
        <option value="220.00">World</option>
        </select>

Add to Cart

The shipping cost added to the grand total

The alert

A: I changed the a button to a actual button and used jquery and binded the click event to check the option boxes, and return if they matched nul, also you have some missing = on your id's.
$('.item_add').click(function () {
if($('#sizeSelect').val().match(/nul/)) return alert("Please choose a size");
if($('#shippingSelect').val().match(/nul/)) return alert("Please choose shipping type");
if($('#destinationSelect').val().match(/nul/)) return alert("Please enter a destination");
});

http://jsfiddle.net/y2Cf9/


text:
Q: ctags, vim and python code I generate ctags with the following command
ctags -R --fields=+l --languages=python --python-kinds=-iv -f ./tags apps/employees/models.py

and this is my code
from django.contrib.auth.models import AbstractUser
from django.contrib.postgres.fields import HStoreField
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

from author.decorators import with_author
from django_extensions.db.models import TimeStampedModel
from django_fsm import FSMField
from imagekit import models as imagekitmodels
from imagekit.processors import ResizeToFill
from phonenumber_field.modelfields import PhoneNumberField
from timezone_field import TimeZoneField

from libs import utils

# Solution to avoid unique_together for email
AbstractUser._meta.get_field('email')._unique = True

def upload_user_media_to(instance, filename):
    """Upload media files to this folder"""
    return '{}/{}/{}'.format(
        instance.__class__.__name__.lower(), instance.id,
        utils.get_random_filename(filename))

__all__ = [
    'Employee']

@with_author
class Employee(AbstractUser, TimeStampedModel):
    """Custom user model.

    Attributes:
        department (Department): What department the employee is in
        avatar (file): user's avatar, cropeed to fill 300x300 px
        notifications (dict): settings for notifications to user
        first_name (str): first name
        last_name (str): last name
        email (str): email (should be unique), this is our username field
        is_staff (bool): designates whether the user can log into
            this admin site
        is_active (bool): designates whether this user should be
            treated as active
        date_joined (datetime): when user joined
    """

    HIRED = 'H'
    ACTIVE = 'A'
    SICK = 'S'
    VACATION = 'V'
    PTO = 'P'
    FIRED = 'F'

    STATUSES = (
        (HIRED, 'hired'),
        (ACTIVE, 'active'),
        (SICK, 'sick'),
        (VACATION, 'vacation'),
        (PTO, 'pto'),
        (FIRED, 'fired'),
    )

    status = FSMField(
        default=HIRED,
        choices=STATUSES,
        protected=True)

    branch = models.ForeignKey(
        'company.Branch',
        null=True,
        related_name='employees',
        editable=True)

    department = models.ForeignKey(
        'company.Department',
        help_text='What department the employee is in',
        null=True,
        related_name='employees',
        editable=True)

    worktype = models.ForeignKey(
        'company.Worktype',
        null=True,
        related_name='employees',
        editable=True)

    recruiter = models.ForeignKey(
        'Employee',
        null=True,
        related_name='recruits',
        editable=True)

    # direct supervisor of the employee
    supervisor = models.ForeignKey(
        'Employee',
        null=True,
        related_name='supervisees',
        editable=True)

    # other people interested in this employee
    # activities
    followers = models.ManyToManyField(
        'self',
        related_name='following')

    username_ldap = models.CharField(
        max_length=255,
        null=True)

    is_utilized = models.BooleanField(
        default=True)

    is_contractor = models.BooleanField(
        default=False)

    is_daily_report_required = models.BooleanField(
        default=True)

    utilization = models.IntegerField(
        default=100,
        validators=[
            MinValueValidator(0),
            MaxValueValidator(100)])

    avatar = imagekitmodels.ProcessedImageField(
        upload_to=upload_user_media_to,
        processors=[ResizeToFill(300, 300)],
        format='PNG',
        options={'quality': 100},
        editable=True,
        null=True,
        blank=False)

    date_start = models.DateTimeField(
        _('date started'),
        null=True,
        default=timezone.now)

    address = models.CharField(
        max_length=255,
        blank=True)

    city = models.CharField(
        max_length=255,
        blank=True)

    state = models.CharField(
        max_length=50,
        blank=True)

    zip_code = models.CharField(
        max_length=20,
        blank=True)

    phone_number = PhoneNumberField(
        blank=True)

    cell_number = PhoneNumberField(
        blank=True)

    skype = models.CharField(
        max_length=255,
        blank=True)

    linkedin = models.CharField(
        max_length=255,
        blank=True)

    twitter = models.CharField(
        max_length=255,
        blank=True)

    instagram = models.CharField(
        max_length=255,
        blank=True)

    facebook = models.CharField(
        max_length=255,
        blank=True)

    website = models.CharField(
        max_length=255,
        blank=True)

    timezone = TimeZoneField()

    birthdate = models.DateField(
        null=True)

    is_birthdate_hidden = models.BooleanField(
        default=False)

    comment = models.TextField(
        blank=True)

    bucket_default_job = models.CharField(
        max_length=255,
        blank=True)

    notifications = HStoreField(
        null=True)

    # so authentication happens by email instead of username
    # and username becomes sort of nick
    USERNAME_FIELD = 'email'

    # Make sure to exclude email from required fields if authentication
    # is done by email
    REQUIRED_FIELDS = ['username']

    def __str__(self):
        return self.username

    class Meta:
        verbose_name = 'Employee'
        verbose_name_plural = 'Employees'

VIM shows a lot of bad tags (blank, defaults, editable etc) which is method arguments (field definition)
I'm using TagBar plugin: https://github.com/majutsushi/tagbar
Question
And it seems the problem is in ctags, how should I configure ctags so that it only outputs class attributes and not their definition params?

A: Use ctags from universal-ctags, it has resolved this issue, and many other fixes.
a tag which universal-ctags generated:
branch  tagbar_bug.py   /^    branch = models.ForeignKey($/;"   v       class:Employee


text:
Q: Babel: root programmatic options I seem to absolutely not grasp where to put root programmatic options for the babel.
If I have a monorepo and need to tell the different sub packages that they shall look upwards for my babel.config.js then I should put rootMode: "upwards" into the .babelrc of the sub packages, correct? This does not work, because of the resulting error
Error: .rootMode is only allowed in root programmatic options
Somehow I simply can't find any example of where to put/use root programmatic options... Can anyone point me to the right direction?

A: If you are using Webpack, you need to put it there.
module: {
  [..]
  rules: [
    // Transpile ES6 Javascript into ES5 with babel loader
    {
      test: /\.jsx?$/,
      exclude: [/node_modules/, /json/],
      loader: 'babel-loader',
      options: {
        rootMode: 'upward'
      },
    },
    [..]
  ],
  [..]
},

Otherwise I had the same issue than you, I can't put it in the package.json file using the key babel.

A: Any API-related options are called programmatic options. Take a look at my discussion with the primary maintainer of Babel: https://github.com/babel/babel/discussions/14405.

It's when you specify them directly to Babel (babel.transformSync(code, programmaticOptions) or to the Babel integration you are using (e.g. babel-loader, which can pass them to its internal babel.transform call). In other words, not in presets or config files. [...]
by @nicolo-ribaudo - Babel core team.

A: I got this error using my (probably non-standard) monorepo setup where I have top-level subdirectories for each of my packages. No top-level package. When I upgraded to Babel 7, my Jest tests were no longer transforming packages that were yarn linked into the package where I was running Jest.
I added a top-level babel.config.js as part of Babel's monorepo instructions. I had rootMode: "upwards" in these three places:

*

*ui-package/webpack.config.js for transforming the app.

*ui-package/babel-jest.js for the tests, where it appeared like:
module.exports = require("babel-jest").createTransformer({
  rootMode: "upward",
})

and was referenced from jest.config.js in that same dir like:
transform: {
  "^.+\\.jsx?$": "./babel-jest.js",
},

*And in /babel.config.js, the newly added top-level babel conf file.
Removing it from the last one removed the error.


text:
Q: How to use this script to email multiple people without showing all emails in the to field? I have this script below that i would like to tweak so it can do two things:

*

*Send emails to multiple addresses (right now it only works if one email address is being sent an email.

*In the "to" field it should not display all others who have received the same notification.  So each email should feel individual.

Code:
         //Query to get emails
         //$share_to comes from a drop down selection of users.
         //it could be 1 person or multiple people.
         //The way its stored in the field is this way user1,user2,user3,user4 or if one person then just user1.

         $sql = "SELECT email_address from accounts
         WHERE person_id='$share_to'";
         $result = mysql_query($sql);

         $query = mysql_query($sql) or die
         ("Error: ".mysql_error());

         if ($result == "")
         {
         echo "";
         }
         echo "";

         $rows = mysql_num_rows($result);

         if($rows == 0)
         {
         print("");

         }
         elseif($rows > 0)
         {
         while($row = mysql_fetch_array($query))

         {

         $email = htmlspecialchars($row['email_address']);

         print("");
         }

         }

         $headers = "MIME-Version: 1.0\r\n";
         $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
         $headers .= "From: $usermail\r\n";
         $headers .= "BCC: $email\r\n";
         $to = "support@domain.com"; //the mail in the "TO", visible to all.
         there has to be 1.
         $subject = "$fullname Asked you something";
         $message = "";
         $message .= "Hi!,

$fullname asked you something.

";
         $message .= "Click here to login.

";
         $message .= "Please reply to this email if you have any questions.

Thanks,

Abe
";
         $message .= "

";

         $message .= "";
         mail($to, "Subject: $subject",
         $message, "$headers" );
         echo "";

A: use any one of these, you can send email to multiple user
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";

OR
$headers .= 'Cc: birthdayarchive@example.com,birthdayarchive2@example.com ' . "\r\n";

See http://php.net/manual/en/function.mail.php for help
Use $headers .= 'BCc: birthdayarchive@example.com,birthdayarchive2@example.com ' . "\r\n"; to invisible other user from your contact

A: //Query to get emails
         //$share_to comes from a drop down selection
         of users.  it could be 1 person or multiple
         people.The way its stored in the field is
         this way user1,user2,user3,user4
         or if one person then just user1.

         $sql = "SELECT email_address from accounts
         WHERE person_id='$share_to'";
         $result = mysql_query($sql);

         $query = mysql_query($sql) or die
         ("Error: ".mysql_error());

         if ($result == "")
         {
         echo "";
         }
         echo "";

         $rows = mysql_num_rows($result);

         if($rows == 0)
         {
         print("");

         }
         elseif($rows > 0)
         {
         $email='';
         while($row = mysql_fetch_array($query))

         {

         $email. = htmlspecialchars($row['email_address']).',';

         print("");
         }

         }

         $headers = "MIME-Version: 1.0\r\n";
         $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
         $headers .= "From: $usermail\r\n";
         $headers .= "BCC: ".rtrim($email,",")."\r\n";
         $to = "support@domain.com"; //the mail in the "TO", visible to all.
         there has to be 1.
         $subject = "$fullname Asked you something";
         $message = "";
         $message .= "Hi!,

$fullname asked you something.

";
         $message .= "Click here to login.

";
         $message .= "Please reply to this email if you have any questions.

Thanks,

Abe
";
         $message .= "

";

         $message .= "";
         mail($to, "Subject: $subject",
         $message, "$headers" );
         echo "";

A: If you don't want recipients to see the full list, you can either send out multiple emails, one to each recipient - as Dagon mentions above, just move the mail code to inside the loop - or you can use the BCC field.
To send one email to multiple recipients, you need to add a comma separated list of addresses in -
$emails = array();
while($row = mysql_fetch_array($query)) {
    $emails[] = htmlspecialchars($row['email_address']);
}

and then:
$headers .= "BCC: " . implode(",", $emails) . "\r\n";
Should do it.