text:
Q: Error while upgrading from Rails 3.1 to Rails 3.2 Upgrade steps were performed as mentioned in http://guides.rubyonrails.org/3_2_release_notes.html
Right now I'm on Ruby 1.8.7 and Rails 3.1.x (using system ruby). I installed RVM with ruby 1.8.7 and added to rails 3.2 and then I get the following error:
[app]$ rails console
Faraday: you may want to install system_timer for reliable timeouts
$HOME/src/qbol/tapp/config/environment.rb:16:in `add': undefined method `>' for nil:NilClass (NoMethodError)
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/activesupport-3.2.17/lib/active_support/tagged_logging.rb:55:in `add'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/activesupport-3.2.17/lib/active_support/tagged_logging.rb:61:in `info'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/activerecord-3.2.17/lib/active_record/railtie.rb:86
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/activesupport-3.2.17/lib/active_support/lazy_load_hooks.rb:36:in `instance_eval'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/activesupport-3.2.17/lib/active_support/lazy_load_hooks.rb:36:in `execute_hook'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/activesupport-3.2.17/lib/active_support/lazy_load_hooks.rb:26:in `on_load'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/activesupport-3.2.17/lib/active_support/lazy_load_hooks.rb:25:in `each'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/activesupport-3.2.17/lib/active_support/lazy_load_hooks.rb:25:in `on_load'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/activerecord-3.2.17/lib/active_record/railtie.rb:80
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/railties-3.2.17/lib/rails/initializable.rb:30:in `instance_exec'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/railties-3.2.17/lib/rails/initializable.rb:30:in `run'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/railties-3.2.17/lib/rails/initializable.rb:55:in `run_initializers'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/railties-3.2.17/lib/rails/initializable.rb:54:in `each'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/railties-3.2.17/lib/rails/initializable.rb:54:in `run_initializers'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/railties-3.2.17/lib/rails/application.rb:136:in `initialize!'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/railties-3.2.17/lib/rails/railtie/configurable.rb:30:in `send'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/railties-3.2.17/lib/rails/railtie/configurable.rb:30:in `method_missing'
        from $HOME/src/app/config/environment.rb:48
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/activesupport-3.2.17/lib/active_support/dependencies.rb:251:in `require'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/activesupport-3.2.17/lib/active_support/dependencies.rb:251:in `require'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/activesupport-3.2.17/lib/active_support/dependencies.rb:236:in `load_dependency'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/activesupport-3.2.17/lib/active_support/dependencies.rb:251:in `require'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/railties-3.2.17/lib/rails/application.rb:103:in `require_environment!'
        from $HOME/.rvm/gems/ruby-1.8.7-p374/gems/railties-3.2.17/lib/rails/commands.rb:40
        from script/rails:6:in `require'
        from script/rails:6

This is on my development box. Any idea why this is happening?
EDIT: Below is the environment.rb. The error is happening on the last line App::Application.initialize!
# Load the rails application
require File.expand_path('../application', __FILE__)

module ActiveSupport
  class BufferedLogger

    def self.current_user
      Thread.current[:user]
    end
    def self.current_user=(user)
      Thread.current[:user] = user
    end

    def add(severity, message = nil, progname = nil, &block)
      return if @level > severity
      message = (message || (block && block.call) || progname).to_s
      level = {
        0 => "DEBUG",
        1 => "INFO ",
        2 => "WARN ",
        3 => "ERROR",
        4 => "FATAL"
      }[severity] || "UNKNOWN"

      user=BufferedLogger.current_user
      if(!user.nil?)
        idstr = "uid:#{user.id}"
        if !user.current_app_user.nil?
          idstr.concat(", acid: #{user.current_app_user.account_id}")
        end
      else
        idstr=""
      end

      message = "[%s: %s #{idstr}] %s" %
        ["#{level} pid: #{$$}", Time.now.strftime("%y-%m-%d %H:%M:%S"), message]

      message = "#{message}\n" unless message[-1] == ?\n
      buffer << message
      auto_flush
      message
    end
  end
end

# Initialize the rails application
App::Application.initialize!

A: The error is happening inside ActiveSupport::BufferedLogger#add method call and you appear to be monkey-patching this class. The internals of ActiveSupport::BufferedLogger have likely changing between the versions of Rails you're using.
Try removing all of the ActiveSupport::BufferedLogger code from your environment.rb to work past this error and get your app running. Then, if you still need the monkeypatch (don't know why), you'd have to rewrite it on top of the newer version of the class.


text:
Q: How to record when a control is triggered in Manipulate? I'm trying to figure out how to tell when controls have been triggered Manipulate (in Animate, actually, but I take it Manipulate is the heart of the matter). After no luck from Search on -- Manipulate control --
 through 407 questions, and scores re CurrentValue, I'm hoping this isn't a redundant question.
Given code such as
Manipulate[x, {x, 0, 1, Animator,
  AppearanceElements -> {"ProgressSlider", "PlayPauseButton",
    "FasterSlowerButtons", "StepLeftButton", "StepRightButton"}
  }
 ]

I'd like to know how to tell a) when, for instance, the "PlayPauseButton" has been hit, and, b) what's its current value). Same for "StepLeftButton", "StepRightButton", and both "FasterSlowerButtons".

A: There is no direct way, but you can monitor values of options which are affected by those elements. Here is a small example:
Panel@DynamicModule[{
   animationRunning = True,
   animationRate = Automatic
   },
  Grid[{
    {Animator[Dynamic[x], {0, 1},
      AnimationRunning -> Dynamic@animationRunning,
      AnimationRate -> Dynamic@animationRate], SpanFromLeft},
    {},
    {"AnimationRunning:", Dynamic@animationRunning},
    {"AnimationRate:", Dynamic@animationRate}
    }
   ]
  ]

Another option is to create many Animators with a single AppearanceElements option in each to compose one Animator where you can wrap each element with EventHandler:
Panel @ DynamicModule[
  {lastAction, x}

, animatorElement[element_String, running_: False] := EventHandler[
    Animator[Dynamic[x], {0, 1}
    , AppearanceElements -> {element}
    , AnimationRunning -> running
    ]
  , { "MouseEntered" :> (lastAction = "entered " <> element)
    , "MouseExited" :> (lastAction = "exited " <> element)
    , "MouseClicked" :> (lastAction = "clicked" <> element)
    }
  , PassEventsDown -> True
  ]

; Column[{
    animatorElement["ProgressSlider", True]
  , Row[animatorElement /@ {"PlayPauseButton", "FasterSlowerButtons",        "StepLeftButton", "StepRightButton"
    }]
  , Dynamic[{x, lastAction}]
  }]
]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Appropriate design for multiple objects that return similar data I'm working on the following scenario:

*

*A View has several tabs. Each tab is represented by a separate class
and contains a data grid.

*The tabs can each return the set of items that the user has selected.
These items are very similar, but each one has one or two additional
properties that are specific to it.

*The View Presenter has a method called SendItems which should get the
items from the current active tab and call the appropriate backend
service method (one method per different collection of items).
What is the appropriate design here? I have thought of two ways so far:

*

*Since the Items are very similar, I could theoretically group all the
properties into 1 Item class and then I can abstract the whole thing
out by having a method called GetItems() which would return the
collection. I can then use a delegate dictionary on the tab type to
call the right back-end method.

*I can have all the tabs derive from a base tab, store the list of
tabs in the Presenter and hold the Current tab. On SendItems, make
several conditions (one per type (if CurrentTab is TabA => MethodA(),
etc..)) and then downcast to retrieve the correct data. Finally, call
the appropriate back-end method.
I don't find either solution appealing (group separate properties into one class / downcasting) and was hoping there is a standard way of solving this type of problem.

A: I believe in your case, I would go mostly with option 2.

*

*Create a parent tab class and make your other tabs derive from it.

*Create a parent class for all of your items which has all of the shared properties in it. Specific item types for each tab can derive from the parent class to define their extra properties

*In the parent tab, keep a list of the selected items. The list should be a List. Child classes can get the items in this collection and rely on runtime casting to get more specific types. In your case, the cast will basically be a noop (depending on how you do it) so there aren't really any performance issues there.

*On the parent tab, make the SendItems method abstract so each child tab has to implement it themselves

This is close to your second option above, except for taking advantage of a little more polymorphism magic and avoiding your conditions in SendItems - if you have conditions like that, just offload the logic to the child classes instead.


text:
Q: Initialization of a struct defined in a templated parent class I have defined a struct within the protected section of a parent class, which I would like to use in an inherited class.
This works as expected if the parent/child classes aren't templated classes. But does not compile as-is below.
Specifically, the compiler (clang 8.0.1) reports:
inheritance_example.cpp:33:26: error: unknown type name 'Node'
        this->head = new Node(toAdd);

From what I have read, I am guessing that the template type specification isn't being assigned to Node, and is thus not being found by the inherited class, but trying the fixes I have found in that vein (i.e. add something along the lines of using Parent<T>::Node, or add a type specifier to the call to the Node constructor), have not worked for me.
Any ideas on how to fix this issue?
#include<iostream>

template <class T>
class Parent
{
protected:
   struct Node
   {
      Node(int value)
      {
         this->data = value;
         this->next = nullptr;
      };

      ~Node() {};
      Node* next;
      int data;
   };

   Node* head;

public:
   Parent() {};
   ~Parent() {};
};

template <class T>
class Child : Parent<T>
{
public:

   Child()
   {
      this->head = nullptr;
   };

   ~Child()
   {
      delete this->head;
      this->head = nullptr;
   };

   void dummyAdd(T toAdd) {
      this->head = new Node(toAdd);
   };

   void dummyPrint()
   {
      std::cout << this->head->data << std::endl;
   };
};

int main()
{
   Child<int> t;
   t.dummyAdd(5);
   t.dummyPrint();
   return 0;
}

A: In order to pack the comment into an answer!
Node is a depended name and hence you need to use keyword typename there. Meaning in the dummyAdd function, you need
void dummyAdd(T toAdd)
{
   this->head = new typename Parent<T>::Node(toAdd);
   //               ^^^^^^^^^^^^^^^^^^^^
};

That is, however, a bit verbose/ more typing. Therefore providing a type alias for Node in the Child will be a good idea.
template <class T>
class Child : Parent<T>
{
   using Node = typename Parent<T>::Node;  // template type alias

public:
   void dummyAdd(T toAdd)
   {
      this->head = new Node(toAdd);       // now you can this
   };

   // other code...
};


text:
Q: Chrome Extension running in background when the popup is not in view I wanted to create a Chrome Extension for starters. I'm a bit stuck because I do not know how to make my extension run in the background.
I have researched an answer for my issue but I haven't identified a suitable solution.
The logic of my extension is in AngularJS controller files.
I do not know how to create the background.js file to communicate with my AngularJS controller files or even if it's necessary to have one.
I would like the extension logic to run even when the popup does not appear in view (e.g. modHeaders app).
The manifest file is:
    "manifest_version": 2,
    "name": "Chrono",
    "version": "1.1",
    "description": "Reminder",
    "browser_action": {
            "default_icon": "images/timerIcon.png",
            "default_popup": "index.html",
            "default_title": "ChronoBip"
},
    "background": {
            "scripts": ["background.js"],
            "persistent": false
},
    "permissions": [
            "background",
            "tabs"   ]
    }

If you need more info, please tell me.

A: Instead of running separate .js file(background.js), try running your controller JS file as your background scripts. See if it works.
Here I placed my controller(myAppCtrl.js) file in background.
"manifest_version": 2,
    "name": "Chrono",
    "version": "1.1",
    "description": "Reminder",
    "browser_action": {
            "default_icon": "images/timerIcon.png",
            "default_popup": "index.html",
            "default_title": "ChronoBip"
},
    "background": {
            "scripts": ["app/controllers/myAppCtrl.js"],
            "persistent": false
},
    "permissions": [
            "background",
            "tabs"   ]
    }


text:
Q: Unable to see JSON conversion error in Spring MVC REST I am doing AngularJS and Spring REST application.
Here is my code.
  @RestController
  @RequestMapping("/user")
  // @Secured("ROLE_ADMIN")
  public class UserController
  {
    @RequestMapping(value = "/verifyUser", method = RequestMethod.POST)
    public Boolean verifyUser(@RequestBody User user)
    {
    }
  }

If     user object is not in correct format then browser says     400 (Bad Request)
No other error is displayed in Eclipse console. I just want to see what exact error occured in deserialization  if     user object is in incorrect format.

A: If you don't want to use the custom objectMapper or you don't want to use String as method input, you can use spring ExceptionHandler. Simply add the following method into your controller and then you can see the jackson databind errors in your console.
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="There was an error processing the request body.")
public void handleMessageNotReadableException(HttpServletRequest request, HttpMessageNotReadableException exception) {
    System.out.println("\nUnable to bind post data sent to: " + request.getRequestURI() + "\nCaught Exception:\n" + exception.getMessage());
}

spring documentation:  Expception handling in Spring MVC
If you want to ignore some useless jackson exceptions, you can use your own jackson ObjectMapper in the springframework. just see this answer.

A: Convert your method like below. Use ObjectMapper to convert the JSON to the object,so while converting it will throw exception and you will be able to identify the problem.
@RequestMapping(value = "/verifyUser", method = RequestMethod.POST)
    public Boolean verifyUser(@RequestBody String json)
    {
       try{
           ObjectMapper om = new ObjectMapper();
           User user = om.readValue(json, User.class);
          }
          catch(Exception e){
            e.printStackTrace()
          }
         // Write your logic.....
        return ....;

    }


text:
Q: Why don't these blocks of code give the same result? So I'm new to this Thread stuff and I wrote  a simple program to test avoiding Race Conditions. My first attempt was with Named Inner classes :
/* App1.java */

package ehsan;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class App1{
    private final int poolSize = 10;
    private final int numLoop = 5;
    private int lastThread = 0;

    public App1() {
        ExecutorService taskList = Executors.newFixedThreadPool(poolSize);
        for (int i = 0;i < poolSize;i++) {
            taskList.execute(new Counter());
        }
        taskList.shutdown();
    }

    private class Counter implements Runnable{

        @Override
        public void run() {
            synchronized (this) {
                int currentThread = lastThread;
                System.out.println("Current thread : "+currentThread);
                lastThread = lastThread + 1;
            }
            System.out.println("Thread was executed");
        }
    }

}

and App1Test.java :
package ehsan;

import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        new App1();
    }
}

So as a result it showed :
Current thread : 0
Thread was executed
Current thread : 1
Thread was executed
Current thread : 1
Thread was executed
Current thread : 3
Thread was executed
Current thread : 4
Thread was executed
Current thread : 5
Thread was executed
Current thread : 6
Thread was executed
Current thread : 7
Thread was executed
Current thread : 6
Current thread : 8
Thread was executed
Thread was executed

And whole things got mixed up and I'm facing Race conditions here even when I've use synchronized there.
But my second attempt worked! :
package ehsan;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class App1 implements Runnable{
    private final int poolSize = 10;
    private final int numLoop = 5;
    private int lastThread = 0;

    public App1() {
        ExecutorService taskList = Executors.newFixedThreadPool(poolSize);
        for (int i = 0;i < poolSize;i++) {
            taskList.execute(this);
        }
        taskList.shutdown();
    }

    @Override
    public void run() {
        synchronized (this) {
            int currentThread = lastThread;
            System.out.println("Current thread : "+currentThread);
            lastThread = lastThread + 1;
            System.out.println("Thread was executed");
        }
    }
}

And the result was as I expected :
Current thread : 0
Thread was executed
Current thread : 1
Thread was executed
Current thread : 2
Thread was executed
Current thread : 3
Thread was executed
Current thread : 4
Thread was executed
Current thread : 5
Thread was executed
Current thread : 6
Thread was executed
Current thread : 7
Thread was executed
Current thread : 8
Thread was executed
Current thread : 9
Thread was executed

So my question is why my first attempt didn't work and the second one worked greatly? Thanks for helping me, I'm a beginner in Multi-Threaded programming!

A: In the first program, you create a different Counter instance as the Runnable whose run() method is executed by each thread, so synchronized (this) uses a different lock for each thread, and therefore the code is not thread safe. If you use the same Counter instance instead of creating a new one for each thread, this program will also behave as you expected.
    Counter counter = new Counter();
    for (int i = 0;i < poolSize;i++) {
        taskList.execute(counter);
    }

In the second program, you use the same App1 instance as the Runnable whose run() method is executed by all the threads, so synchronized (this) uses the same locks for all the threads.

A: With a great deal of research I found few ways to solve this.
Please Note : Some of these solutions were pointed out by Eran, Thomas and etc. and I thank them for helping me   but I just wanted to collect all the possible solutions in a single answer so the future visitors of this post find the answers easily.

*

*For Named Inner Classes :
Instead of using this as the locking object for synchronization we can use the OutterClass instance :
 synchronized (App1.this) {
        int currentThread = lastThread;
        System.out.println("Current thread : "+currentThread);
        lastThread = lastThread + 1;
 }

*

*For Separated Classes :
Solution 1

Synchronizing on an object we are receiving from the Caller Class( The class containing the task list and ... ). Here is an example :
public App1 implements Runnable {

    private final Integer shared;/* Not spending time on auto-boxing */

    public App1(Integer sharedNum) {
        shared = sharedNum;
    }

    @Override
    public void run() {
        synchronization(shared){
            //code here
        }
    }
}

public App1Test {
    private final int forSharing = 14;
    public static void main(String[] args) {
        ExecutorService taskList = Executors.newFixedThreadPool(poolSize);
        taskList.execute(new App1(forSharing));
        // and lob lob
    }
}

Solution 2

Synchronization on class object :
synchronized (App1.class) { /* As the fields and methods of class App1 are the same for all objects */
    int currentThread = lastThread;
    System.out.println("Current thread : "+currentThread);
    lastThread = lastThread + 1;
}

Solution 3

Synchronizing on an static field ( Which I loved it because its really innovative ) :
/* Add this field to class definition */
private static Object sharedObject = new Object();

/* Now in `run` method  use the object like this : */
synchronized(sharedObject) {
    //TODO : write your code here :)
}

So these are the solutions to this sneaky problem which is a bit hard to debug :)
I hope this helps fellows who have faced the same problem :)
Cheers, Ehsan

A: synchronized (this) in Counter synchronizes on the instance, so if you pass a new instance to each thread (taskList.execute(new Counter());) there won't be any synchronization at all (since no 2 threads use the same instance to synchronize on). Thus either use synchronized(Counter.class) or some other shared monitor object (since Counter is an inner class of App1 you could use synchronize(App1.this)).
Your second approach works since you pass the same instance to each thread: taskList.execute(this);.


text:
Q: can not apply operator * to operand of type decimal and double Hi I need to apply a discount of 5.2% on a product.I have tryed doing something like this:
decimal BasePrice {get;set;}
decimal Discount = (BasePrice * 5.2) / 100;

But Visual Studio tells me that it :

can not apply operator '*' to operand of type decimal and double

If that is so how can I represent this discount?

A: Use
decimal Discount = (BasePrice * 5.2m) / 100;

Otherwise, 5.2 will be treated as a double.
From MSDN:

If you want a numeric real literal to be treated as decimal, use the suffix m or M


text:
Q: Draw on cmd using c++ I'm trying to draw a chess board on the cmd screen - 64 squares, and a letter in each one, that symbolize the solider that in this place.
After very long searching, I found a code that change the words color, but my question is how can I draw squares on the cmd? BLACK - WHITE and so on.
This is the code I've found :
int main()
{

    HANDLE hConsole;
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

    // Use the three primary colors for mixing any other color.
    // Use FOREGROUND_INTENSITY for brighter colors.
    SetConsoleTextAttribute
        (hConsole, FOREGROUND_RED | FOREGROUND_INTENSITY);
    cout << "Bright red text\n";

    SetConsoleTextAttribute
        (hConsole, FOREGROUND_BLUE | FOREGROUND_INTENSITY);
    cout << "Bright blue text\n";

    SetConsoleTextAttribute
        (hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
    cout << "Back to normal white text\n";

    // Wait for user pressing key before exiting
    // Gives them a chance to see the output
    cout << "\n\nPress any key to exit program.....";
    cin.get();

    return 0;
}

I'll be glad for some help.

A: since white is red+green+blue:  background white is
BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE

in code:
SetConsoleTextAttribute
    (hConsole,BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE )
cout << "black on white\n";

A: Someone did this on Codeproject (Draw rectangle on screen):
#include <iostream>
#include <Windows.h>

using std::cout;

/*
 *This method sets the cursor position.
 *Usage:
 *setxy(1,1);
 */
BOOL setxy(short x, short y)
{
    COORD c = {x,y};
    return SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c);
}

/*
 *This method draws the rectangle.
 *Usage:
 *DrawRect(1,1,10,10);
 *or
 *DrawRect(1,1,10,10,20,5);
 */
void DrawRect(int x, int y, int width, int height, int curPosX=0, int curPosY=0)
{
    setxy(x,y);cout << char(201);
    for(int i = 1; i < width; i++)cout << char(205);
    cout << char(187);
    setxy(x,height + y);cout << char(200);
    for(int i = 1; i < width; i++)cout << char(205);
    cout << char(188);
    for(int i = y + 1; i < height + y; i++)
    {
        setxy(x,i);cout << char(186);
        setxy(x + width,i);cout << char(186);
    }
    setxy(curPosX,curPosY);
}

int main()
{
    setxy(1,1);
    DrawRect(1,1,10,10,20,5);
    return 0;
}

Hope it helps

A: You have found the code, but you didn't really bother to understand it or to look at the documentation for SetConsoleTextAttribute.
If you had, you'd have discovered the documentation about character attributes and noticed things like BACKGROUND_RED, BACKGROUND_GREEN and BACKGROUND_BLUE which, predictably, can set the background color in the console.
Now, with the ability to change the color of the background, ask yourself "what happens if I set the background color to FOREGROUND_RED and then print a space on the console?"

A:     //win api  drawing
#include <windows.h>
#include <iostream>
#include <conio.h>
using namespace std;

void draw(HWND hwnd, HDC hdc);
void setConsoleSize();
void main()
{
  SetConsoleTitle(L"Simple Rectangle Drawing");
  HWND hwnd = GetConsoleWindow();
  HDC hdc = GetDC(hwnd);
  setConsoleSize(); // set console size
  Sleep(100);
  draw(hwnd, hdc); // drawing function
  int iKey = 1;
  while (iKey != 27) { // exit on ESC key
    if (_kbhit()) {
    iKey = _getch();
    switch (iKey)
      {
      case 112: case 80: case 167: case 135:
      draw(hwnd, hdc); // on   key 'p' we redraw
      break;
      }
    }
  }
  ReleaseDC(hwnd, hdc); //cleaning console descriptors
}

// here you place your Drawing
void draw(HWND hwnd, HDC hdc)
{
  Rectangle(hdc, 100, 60, 180, 160); // example
}

void setConsoleSize()
{
  const int colConsole = 80;
  const int rowConsole = 30;
  HANDLE hNdl = GetStdHandle(STD_OUTPUT_HANDLE);
  SMALL_RECT windowSize ={0,0,colConsole-1,rowConsole-1};
  SetConsoleWindowInfo(hNdl, TRUE, &windowSize);// bufferSize
  SetConsoleScreenBufferSize(hNdl, bufferSize);
}


text:
Q: C Socket Write adding extra characters I am trying to append " " to messages in a chat program.  In the below example buf is a character array holding the message.  The weird thing is when I send this down a socket with write() it sends it in 2 bursts.  The first burst is the correct message, then a second burst is 2-3 random non alphabetic ascii characters.  Any idea what is up? When I just send buf down the socket, it works correctly.
char nickmsg[550];
strcpy(nickmsg, "<");
strcat(nickmsg, username);
strcat(nickmsg, "> ");
strcat(nickmsg, buf);
write(sd, nickmsg, sizeof(nickmsg));

A: You don't want sizeof(nickmsg), you want strlen(nickmsg). Using sizeof(nickmsg), you're sending everything that's in that buffer, not just the string you built in it. If it's only the chars in the string you want to send, you need to calculate the length of what's in there. (btw, there are more efficient ways to create strings than repeated strcats)

A: write() isn't sending extra characters, you are.
write(sd, nickmsg, sizeof(nickmsg));

Will send 500 characters (the size of your array). Since you didn't initialize all array elements to 0 you're getting whatever garbage is in memory past the data you inserted into it.
You want:
write(sd, nickmsg, strlen(nickmsg) + 1);

A: You have this code:
char nickmsg[550];
strcpy(nickmsg, "<");
strcat(nickmsg, username);
strcat(nickmsg, "> ");
strcat(nickmsg, buf);
write(sd, nickmsg, sizeof(nickmsg));

This always sends 550 bytes, since sizeof(nickmsg) is 550. The end of the message will be marked by a zero-byte because nicknmsg is a C-style string.
If the receiver always grabs 550 bytes and ignores all bytes after the zero, this will work fine. You'll just be sending some junk bytes to the clients which might leak sensitive information.
The question is, what are you supposed to be sending? What is supposed to mark the end of the message?
Caution: Do not change sizeof(nickmsg) to strlen(nickmsg). That will leave the client no way at all to identify the end of the message. (Unless you are 100% positive the client does not need to identify the ends of messages.)

A: You are sending 500 bytes data, within which only first strlen(username)+3 has valid data. The rest is just the uninitialized data.

A: If you send it this way
    write(sd, nickmsg, sizeof(nickmsg));
you are sending data equivalent to size of the buffer.Though your string may be valid c string ending with null character but still the client may not be treating strings that way.(If you are writing your own client program you may cover up in the client's program).


text:
Q: Are there any browsers with a JSX compiler built in? Can we run react with jsx without installing the jsx compiler?

A: No, there are no browsers with a JSX compiler.
Source: https://discuss.codecademy.com/t/are-there-any-browsers-with-a-jsx-compiler-built-in/385750
However, you can use JSX without React: https://medium.com/better-programming/how-to-use-jsx-without-react-21d23346e5dc


text:
Q: Не получается установить связь моделей данных Проблема: выводит ошибку - Cannot read properties of undefined (reading 'hasOne'), при попытки установить связи между моделями данных
Код:

const sequelize = require("../db");
const {Basket} = require("./basket");
const {DataTypes} = require("sequelize");
const {User} = require("./user");

module.exports.User = sequelize.define('user', {
    id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
    name: {type: DataTypes.STRING},
    lastName: {type: DataTypes.STRING},
    userName: {type: DataTypes.STRING, unique: true},
    email: {type: DataTypes.STRING, unique: true},
    password: {type: DataTypes.STRING},
    phone: {type: DataTypes.STRING(11), unique: true},
    role: {type: DataTypes.STRING, defaultValue: "USER"},
})

User.hasOne(Basket)
Basket.belongsTo(User)


text:
Q: Enable copy/paste for SSRS report in preview mode How can we enable the copy/paste option for ssrs report content in preview mode? Now in my report, I don't get a copy/paste menu in mouse right click.

A: You cannot copy text from a report in preview mode; it has never been an option in any version of the tool that I have worked with. I have often wished it was. Pasting, of course, would never be an option.
Work around: export the results to Excel, or PDF, and copy from that output. Or, deploy the report to your reporting server, and work with the results there. Once the report is open in a browser using Report Manager, you can select and copy the results all you like.
Probably not the answer you were hoping for, but likely the only true answer. I would love to be wrong on this one.

A: Richards answer is the best answer and upvoted. When you can easily export report data in any format then why you want to copy and paste from the preview mode? if you still want to have a feel of preview mode, you can take screenshots and then probably apply some OCR?
Otherwise, just to add value to Richard's answer above, you can export the report (data) in the preview mode using export button displayed in the  screen below  and you can choose any format of your choice:

sounds good?


text:
Q: typescript: a component must have open() I'm making modal component which controlled by redux so I inject a modal component's ref by dispatching an SET_MODAL so modal component can be changed by using it.
dispatch(setModal(modalComponentRef));

// reducer
const reducer = (state, action) => {
    if (action.type === "SET_MODAL") {
      return {
        ...state,
        modal: action.payload.modal,
      }
    }
}

And then call modal component by dispatching an action SHOW_MODAL
const onOpen = () => { ... }
dispatch(showModal(onOpen));

const reducer = (state, action) => {
  if (action.type === "SHOW_MODAL") {
    return state.modal.open(action.payload.onOpen);
  }
}

modal component should open by calling its function open()
const Modal = (props) => {
  const [isOpen, setIsOpen] = useState(false);
  const open = (onOpen) => {
     setIsOpen(true);
     onOpen();
  }
  return {
    isOpen && (
      <div>
        // ...
      </div>
    )
  }
}

In this case I want to force react component must have open: () => void how to do it by defining type definition?
// modalComponentRef must have open()
dispatch(setModal(modalComponentRef));

A: If you want to enforce that the argument passed to setModal() must have .open() method, the constraint should be placed inside setModal's function signature.
function setModal<T extends { open(): void }>(ref: T): { type: string, action: { modal: T } }


text:
Q: How to Copy a file whose path comes from another file? Good afternoon,
I'd like to firstly apologize for my beginner ways, but I've tried to make a file which its sole purpose is to store a single line (a path) in order to save it for later use, without having to type it over and over.
The writing and reading from said file go well, except when I try to copy another file using that file's path. My intents are to save a path in that file so that the main course of the program (which is to copy files into said path). However, I am met with the File.Copy exception claiming the path has illegal characters in it. I've tried multiple solutions, including changing the path formatting itself, to no avail.
If it helps, here's the event for the button to write said file:
string filepath = @"C:\test folder\file.txt";
string pathinfile = @"C:\test folder\test subfolder"; //directories created previously

        using (StreamWriter sw = new StreamWriter(filepath))
        {
            sw.WriteLine(pathinfile);
        }

        MessageBox.Show("File Written.");

And here's the code for the event that reads the file, prints it through a Messagebox then tries to copy the file into a subfolder.
        //Read the File
        string filepath = @"C:\test folder\file.txt";
        string readpath = File.ReadAllText(filepath);
        MessageBox.Show(readpath);
        //Write to the file's indicated location
        File.Copy(filepath, Path.Combine(readpath, "copied file.txt")); //illegal characters

This however just breaks the program and throws the exception. Is it something I'm doing wrong, that I shouldn't  clearly be doing but still am? Or is there a better way to store data that's easier to make read? I appreciate any and all help provided, thank you.

A: Solved.
I've replaced ReadAllText with ReadAllLines and implemented it in an array. It works as it should now.


text:
Q: commuting the covariant derivative of a function Let $f$ be a smooth function such on a compact kahler manifold $(M, w)$, and the component of $w$ is denoted by $g_{ij}$, assume there is a constant $s$ such that $sf = -g^{ij}\sqrt{-1}\partial_{j}\bar\partial_{i}f$, we have:
$s \nabla_j f   = -\nabla_j \nabla_p \nabla_{\bar p} f$ suppresing the mertic.
Then how do you prove the following Bochner-Weitzenbock formula:
$(\int_{U}-\nabla_j \nabla_p \nabla_{\bar p} f \nabla_\bar j f)w^n = (\int_{U} -\nabla_{\bar p} \nabla_p \nabla_{ j} f \nabla_{\bar j} f + R^{q \bar j} \nabla_{q} f \nabla_{\bar j}f )w^n$
Thoughts: the left hand side is simply $\partial_j sf = \partial_j-g^{ik}\sqrt{-1}\partial_{j}\bar\partial_{k}f = - \partial_j g^{ik} \sqrt{-1}\partial_{j}\bar\partial_{k}f -\partial_j\sqrt{-1}\partial_{j}\bar\partial_{k}f g^{ik}$
How do you proceed?
Update:
My definition for the Ricci curvature is the following:
Lowering the index of the curvature tensor we have $R_{i \bar j k \bar l} = -\partial_{k} \partial_{l} g_{i \bar j} + g^{p \bar q}(\partial_k g_{i \bar q})(\partial_{\bar l} g_{p \bar j})$, then let $R_{i\bar j} = g^{k \bar l } R_{i \bar j k \bar l}$.
It is not obvious how to go from this definition.

A: Your identity is only using the Ricci identity; that is, the formula for how to commute derivatives in a Kähler manifold.  It requires neither integration nor the assumption $-\Delta f = sf$.
The derivation of your identity requires three observations.  First, since the connection is torsion-free, it holds that $\nabla_{\bar p}\nabla_q u = \nabla_q\nabla_{\bar p}u$ for all functions $u$.  Second, since $g$ is Kähler, it holds that
$$ \nabla_j\nabla_p\nabla_{\bar q}f = \nabla_p\nabla_j\nabla_{\bar q}f . $$
Third, by definition of the Ricci curvature,
$$ \nabla_p\nabla_{\bar p}\nabla_j f = \nabla_{\bar p}\nabla_p\nabla_j f - R_{j\bar p}\nabla_p f ; $$
here I use Einstein summation notation as in the problem statement.  Putting all of this together, we compute that
$$ -\nabla_j\nabla_p\nabla_{\bar p} f = -\nabla_p\nabla_j\nabla_{\bar p}f = -\nabla_p\nabla_{\bar p}\nabla_j f = -\nabla_{\bar p}\nabla_p\nabla_j f + R_{j\bar p}\nabla_p f . $$
Multiplying by $\nabla_{\bar j}f$ and integrating yields the display in question.  You can find proofs of these facts in Besse's book "Einstein manifolds", for example.


text:
Q: Select Command with Multiple LIKEs Functionality
User inputs text into textboxA.
Search the database records for First Names AND Last Names corresponding to the user's input.
The Problem:
It appears the results I am getting are only searching "First Name" field and not BOTH the First Name and Last Name Fields
Example:
*A search for "Mike" returns:*
Mike Smith
Mike Jones
A search for "Jones":
Mike Jones is not returned
CODE:
Protected Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles button1.Click

    If txtSearch.Text = "" Then

    Else

        Dim ConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("oakfratintdbConnectionString").ConnectionString
        Dim Conn As New SqlConnection(ConnString)
        Dim searchCMD As New SqlCommand("SELECT [FirstName], [LastName], [MidInitName], [NameSuffix], [NamePrefix], [DOB], [DOD], [BurialDate], [GeoDirection], [Space], [Lot], [Row], [IntermentSpec], [AddtlInfo] FROM [OFCInterments] WHERE ([FirstName] LIKE @FirstName)", Conn)
        Dim searchDT As DataTable = GetData(searchCMD)
        GridView1.DataSource = searchDT
        GridView1.DataBind()
    End If

End Sub

Code Explanation:
txtSearch is the user's search input

A: Change
SELECT [FirstName], [LastName], [MidInitName], [NameSuffix], [NamePrefix], [DOB],
[DOD], [BurialDate], [GeoDirection], [Space], [Lot], [Row], [IntermentSpec],
[AddtlInfo] FROM [OFCInterments] WHERE ([FirstName] LIKE @FirstName)

to
SELECT [FirstName], [LastName], [MidInitName], [NameSuffix], [NamePrefix], [DOB],
[DOD], [BurialDate], [GeoDirection], [Space], [Lot], [Row], [IntermentSpec],
[AddtlInfo] FROM [OFCInterments] WHERE ([FirstName] LIKE @FirstName or
LastName like @LastName)

A: Below is the SQL query with the WHERE clause adjusted to give you the flexibility to search by only first name, only last name, or both.
SELECT [FirstName], [LastName], [MidInitName], [NameSuffix], [NamePrefix], [DOB], [DOD], [BurialDate], [GeoDirection], [Space], [Lot], [Row], [IntermentSpec], [AddtlInfo] FROM [OFCInterments] WHERE
    (@FirstName IS NULL OR [FirstName] LIKE @FirstName)
    AND (@LastName IS NULL OR [LastName] LIKE @LastName)

With this query I'm making the assumption that if the user searches for FirstName: "Mike" and LastName: "Jones" that the search results should only contain "Mike Jones", not "Mike Smith", "Mike Jones", and "Paul Jones".
Note that if you use this approach, you will need to make sure not to populate your parameters with an empty string in the case where the user did not supply a value for a criteria.  Alternatively, you could check for empty strings in the query in addition to null.


text:
Q: Сортировка массива по просмотрам из файлов Имею массив - dump.txt, в котором 999 строк:
id|path_to_image.jpg, например:
1|images/some.jpg
2|images/some_other.jpg
...
999|images/some_999.jpg
Также имею папку views с 999 файлами названиями id, в которых пишется кол-во просмотров, например,
2.txt с содержимым 100
3.txt с содержимым 55
...
999.txt с содержимым 150
И вот возник вопрос: как можно отсортировать этот массив по количеству просмотров (популярности)?
Спасибо

A: Можно таким образом, но как уже советовали в комментариях - лучше перейти на какую нибудь базу данных, ибо при большом к-стве этих самых файлов php будет кушать очень много оперативки. вот сам код:
function sortImages(string $path_to_dump, string $views_dir, $separator = '|') {

  $data = file_get_contents($path_to_dump);
  $items = explode(PHP_EOL, $data);
  $images = [];
  foreach ($items as $item) {
    if(strlen($item) > 0 && false !== strpos($item, $separator)) {
      list($image_id, $image_path) = explode($separator, $item);
      $image_count_views = 0;
      $image_views_path = $views_dir . $image_id . '.txt';
      if(file_exists($image_views_path)) {
        $image_count_views = (int) file_get_contents($image_views_path);
      }
      $images[] = [
        'path' => $image_path,
        'views_count' => $image_count_views,
      ];
    }
  }

  usort($images, function ($a, $b) {
    return $a['views_count'] < $b['views_count'];
  });

  return $images;
}

print_r(
  sortImages('dump.txt', 'stats_views/')
);

На выходе получим отсортированый многомерный массив.


text:
Q: how to display my list from store at initialization with easy-peasy? I want to get a list of churches from the store at initialization but i can't. The log get my initial array and the new one but doesn't display. Log below:
log
here is my model:
const churchModel = {
  items: [],

  // ACTIONS

  setAllChurches: action((state, payload) => {
    state.items = payload;
  }),
  getInitialChurches: thunk(async (actions) => {
    const { data } = await axios.post(
      'http://localhost:3000/api/geo/closeto?latlong=2.3522219 48.856614&distance=10000'
    );
    let array = [];
    const resData = data.map(async (index) => {
      const res = await axios.get(`http://localhost:3000/api/institutions/all?idInstitution=${index.idInstitution}`);
      array.push(res.data[0]);
    });
    actions.setAllChurches(array);
  })
}

and my component:
const ChurchList = () => {
  const classes = useStyles();
  const setInitialChurches = useStoreActions(action => action.churches.getInitialChurches);
  const churches = useStoreState(state => state.churches.items);
  const [activeItem, setActiveItem] = React.useState(null);

  useEffect(() => {
   setInitialChurches()
  }, []);

  return (
   <div className={classes.root} style={{marginTop: '20px',}}>
    { churches.map( (church) => (
      <ChurchItem
        key={ church.idInstitution }
        church={ church }
        setActiveItem={setActiveItem}
        activeItem={activeItem}
      />)
    ), console.log(churches)}
   </div>
  )
};

export default ChurchList;

I tried a useEffect but nothing true. Could you help me please ?

A: *

*that is not a good location to put console.log in, either put it outside the component render, inside the map or on a useEffect.

*You can achieve it by using useEffect and passing churches on the array.

  useEffect(() => {
   // this will log everytime churches changes / initialized churches
   console.log(churches);
  }, [churches]);


text:
Q: Karma + jasmine + angular + ui router - testing for resolve with state.go with params I have state defined in my angular module "moduleB" as follows
$stateProvider
                .state('stateB', {
                    parent: 'stateA',
                    abstract: true,
                    templateUrl : baseUrl+'/templates/stateB.html'
                })
                .state('stateB.details', {
                    url: '/stateB/details/:param1/:param2',
                    resolve : {
                        value3 : ['$localStorage', '$stateParams', function($localStorage, $stateParams){
                            return $localStorage.value3[$stateParams.param1];
                        }]
                    },
                    views : {
                        'view1' : {
                            templateUrl : baseUrl+'/templates/view1.html',
                            controller: 'View1Ctrl'
                        },
                        'view2' : {
                            templateUrl : baseUrl+'/templates/view2.html',
                            controller : 'View2Ctrl'
                        }
                    }
                })

I would like to write unit test for the "resolve" and here is my jasmine unit test.
var rootScope, state, injector,  mockLocalStorage, httpBackend;
beforeEach(module('moduleB'));
 beforeEach(inject(function($rootScope, $state, $injector, $localStorage, $httpBackend) {
            rootScope = $rootScope;
            state = $state;
            injector = $injector;
            httpBackend = $httpBackend;
            mockLocalStorage = $localStorage;
        }));

it('should should resolve the data', function() {
            mockLocalStorage.value3 = {};
            mockLocalStorage.value3["1234567890"] = 'resolved-data';
            state.go('stateB.details', {
                                            "param1" : "1234567890",
                                            "param2" : true
                                      });
            rootScope.$digest();

            console.log('state', state);
            expect(state.current.name).toBe('stateB.details');
             expect(injector.invoke(state.current.resolve.value3)).toBe('resolved-data');

        });

1) console.log('state', state)  ==> prints
'state', Object{params: Object{}, current: Object{name: '', ........}
2) expect(state.current.name).toBe('stateB.details') ==> fails with error
   Expected '' to be 'stateB.details'.
3) expect for resolve ==> fails with error
   TypeError: 'undefined' is not an object (evaluating 'state.current.resolve.value3')
Can anyone help in pointing what am I missing?
UPDATE:
I modified my test to have assertions in the success block of the promise.
It passes the test even when the assertions are false.
it('should resolve the data', function() {
            mockLocalStorage.value3 = {};
            mockLocalStorage.value3["1234567890"] = 'resolved-data';
            state.go('stateB.details', {
                                            "param1" : "1234567890",
                                            "param2" : true
                                      }).then(function() {
                                                    console.log('state', state);
             expect(state.current.name).toBe('stateB.details');                                         expect(injector.invoke(state.current.resolve.value3)).toBe('resolved-data2');
                                             });;
        });

This test passes and nothing is displayed for "console.log('state', state);" .
And, my assertion for "resolved-data2" should fail as the expected value is "resolved-data".

A: Finally, I fixed the problem. Here is the solution for any one who is interested in.
1) Import modules
beforeEach(module('stateA'));
   beforeEach(module('stateB'));
   beforeEach(module('ui.router'));

2)
beforeEach(module(

function($provide) {
            $provide.value('$localStorage', mockStorage = { value3: []});
            $provide.value('$stateParams', stateParams = { param1: 1234, param2: "true"});
        }));

3) unit test:
it('should go to stateB.details state and resolve the data', function() {
            mockStorage.assetInfo[stateParams.value3] = 'resolved-data';
            var s = state.get('stateB.details');
            expect(injector.invoke(s.resolve.value3)).toEqual('resolved-data');
        });


text:
Q: VPN - force a selective range of ip to run on VPN (linux) Preface:
I know there are similar question here and there however I'm a kind of newbie on Net stuff so I need an answer on this specific scenario, hoping that can help others too as it is a common problem
Let say I cannot do anything on the local switch to change the local ip range, I don't want to use any complicate trick as use VMachine to hide the local ip range but I want to use net tools to solve the issue.
Scenario
my local net assign me an IP of this class 192.168.1.xxx (ex. 192.168.1.116)
and my VPN (VPNC) assign me IP of same class 192.168.1.xxx (ex. 192.168.1.247)
Obviously I need VPN to access local address (ex. 192.168.1.100) but when I open any address of the class 192.168.1.xx the route point to my local net and not to the VPN ones.
I'm on linux and i'd like gui solution (network manager) in case it is not possible let play with route command.
here what network manager offer me:

Here my actual route once connected to the VPN:
Here some route information (route -n)
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         0.0.0.0         0.0.0.0         U     0      0        0 ppp0
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 wlan0
xxx.YY.ZZ.106   192.168.1.1     255.255.255.255 UGH   0      0        0 wlan0
xxx.YY.ZZ.106   192.168.1.1     255.255.255.255 UGH   0      0        0 wlan0
192.168.1.0     0.0.0.0         255.255.255.0   U     9      0        0 wlan0
192.168.1.246   0.0.0.0         255.255.255.255 UH    0      0        0 ppp0

Here my ifconfig :
ppp0      Link encap:Point-to-Point Protocol
      inet addr:192.168.1.247  P-t-P:192.168.1.246  Mask:255.255.255.255
      UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1400  Metric:1
      RX packets:3415 errors:0 dropped:0 overruns:0 frame:0
      TX packets:2525 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:3
      RX bytes:3682328 (3.6 MB)  TX bytes:402315 (402.3 KB)

wlan0     Link encap:Ethernet  HWaddr 4c:eb:42:06:a3:a6
      inet addr:192.168.1.116  Bcast:192.168.1.255  Mask:255.255.255.0
      inet6 addr: fe80::4eeb:42ff:fe06:a3a6/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:72598 errors:0 dropped:0 overruns:0 frame:0
      TX packets:42300 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:76000532 (76.0 MB)  TX bytes:13919400 (13.9 MB)

The Question
So basically I would like to add a rule to force this particular address (192.168.1.100) on the VPN and not on my local net
Solution - Thanks to Paul
This command will route the 192.168.1.100 host out of the VPN:
ip route add 192.168.1.100 dev ppp0

This is for the command line, but you can add it above in the dialog box of the first image.
Address: 192.168.1.100
Netmask: 255.255.255.255
Gateway: 192.168.1.246

Se below answer for detail

A: I think you are going to have a problem in any case.  This command will route the 192.168.1.100 host out of the VPN:
ip route add 192.168.1.100 dev ppp0

This is for the command line, but you can add it above in the dialog box of the first image.
Address: 192.168.1.100
Netmask: 255.255.255.255
Gateway: 192.168.1.246  (the ubuntu vpnc client does not let you specify a device)

Your problem is that 192.168.1.100 will need to route back to you.  So it will see packets coming from 192.168.1.247 and think that this address is on its local network.  So it will then broadcast on the local network asking who has the IP address, and it will go unanswered.
So you need the same route back.  But this doesn't help you, because you are over a VPN and your IP address is changing.  This route added to 192.168.1.100 would tell it that .247 is behind the VPN gateway:
ip route add 192.168.1.247 via xxx.YY.ZZ.106 [ip address of vpn server]

This will only last as long as you remain on .247  As soon as you disconnect and reconnect, you'll have another IP address, and need to change the route.
The golden rule here is that you should avoid using the same address range for both ends of the VPN.


text:
Q: Implement search in Azure SQL I'm moving an .NET application to Azure since the amount of data stored is getting bigger and the concurrent users is increasing. To be able to search I need a robust solution to search the SQL which scales.
I need to return matching orders when searching (in one single field, google style). The data is stored in a few columns in these related tables: Orders, Customers and Addresses.
I've read that fulltext search isn't available in Azure so I've looked att Lucene but got a bit worried about storing the index in a blob. It doesn't seem right to hit the blob storage at every search.
Does anyone have any suggestions on how to accomplish this i a robust way?

A: One solution would be to build a "key" table.
Have one column that contains the search strings you are after, and a second column that is the key back to your orders table.
You would need to create appropriate triggers on the CRUD functions of you Order, Customer and Address tables.
By flattening the searchable fields from all three into one key table, you can then do indexed searches very quickly for a minimal space trade off.
One caveat, queries in SQL Azure are single threaded, so table-scans will be ugly.
example: where key like 'abc%' will use the index
example2: where key like '%abc% will do a table scan and on a large set will be slow.
I maintain an 11,000,000 row catalog table and server 3 million page views per day on sql azure in < 200ms, using these types of techniques.

A: We use Solr/Lucene for best full-text search results. Indexed data is stored into local storage (up to 2 TB).
Local storage is like c: disk drive, but you must declare it in the definition file and get reference to it by calling RoleEnvironment.GetLocalResource.
If you want to speed up startup time (initial full index) you can save/download index data to persistent blob storage.
Another option is to use Azure Drive, but keep in mind that ony one instance can write to it.

A: Azure has also rolled out a search as service api that works quite well.
I have it working against large data and it performs quite well.


text:
Q: List don't add date java I'm trying to separate my values from one list to two different lists. My code just verify if there is number with letters. I'm doing that way:
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.List;
import java.util.ArrayList;

public class Programa {

    public static void main(String[] args) {
        Funcionarios valido = new Funcionarios();
        Funcionarios invalido = new Funcionarios();
        Funcionarios aux = new Funcionarios();
        List<String> aux_lista = new ArrayList<>();

        Scanner entrada = new Scanner(System.in);
        String nome, apelido, cpf, nascimento, cep, endereco, numero, cidade, estado, cargo;
        Pattern filtro_letra = Pattern.compile("[^1234567890.-]+[ \\t\\n\\x0B\\f\\r]", Pattern.CASE_INSENSITIVE);
        Pattern filtro_numero = Pattern.compile("-?[\\\\d\\\\.]+", Pattern.CASE_INSENSITIVE);
        Pattern filtro_data = Pattern.compile("[^1234567890/]+[ \\t\\n\\x0B\\f\\r]", Pattern.CASE_INSENSITIVE);
        int[] indices_invalidos = new int[10];
        int[] indices_validos = new int[10];
        int i = 0, j = 1, k = 0, m = 0, n = 0, f = 0;
        String aux_teste;

        while (j == 1 && i <= 10) {
            m = 0;
            n = 0;
            System.out.println("Deseja Adicionar Um Funcionario?\n 1 - Sim \n 2 - Nao\n");
            j = Integer.parseInt(entrada.nextLine());
            if (j == 1) {
                System.out.println("Digite o Nome do Funcionario: ");
                nome = entrada.nextLine();
                aux.nome.add(nome);

                System.out.println("Digite o Apelido: ");
                apelido = entrada.nextLine();
                aux.apelido.add(apelido);

                System.out.println("Digite a Data de Nascimento: ");
                nascimento = entrada.nextLine();
                aux.nascimento.add(nascimento);

                System.out.println("Digite o CPF: ");
                cpf = entrada.nextLine();
                aux.cpf.add(cpf);

                while (aux.EncontrarCPF(cpf)) {
                    System.out.println("CPF ja cadastrado, insira outro CPF:");
                    cpf = entrada.nextLine();
                }
                System.out.println("Digite o CEP: ");
                cep = entrada.nextLine();
                aux.cep.add(cep);

                System.out.println("Digite o Endereco: ");
                endereco = entrada.nextLine();
                aux.endereco.add(endereco);
                System.out.println("Digite o Numero: ");
                numero = entrada.nextLine();
                aux.numero.add(numero);

                System.out.println("Digite a Cidade: ");
                cidade = entrada.nextLine();
                aux.cidade.add(cidade);
                System.out.println("Digite o Estado:");
                estado = entrada.nextLine();
                aux.estado.add(estado);
                System.out.println("Digite o Cargo: ");
                cargo = entrada.nextLine();
                aux.cargo.add(cargo);
            }
            i++;
        }
        i = 0;
        while (i < aux.nome.size()) {
            Matcher somente_letras = filtro_numero.matcher(aux.nome.get(i));
            aux_teste = aux.nome.get(i);
            if (!somente_letras.find()) {
                invalido.nome.add(aux_teste);
                System.out.println(invalido.nome);
            }
            i++;
            aux_teste = "";
        }

//}
        System.out.println("Invalidos");
        System.out.println(invalido.nome);

        System.out.println("Validos");
        System.out.println(valido.nome);
    }
}

My Class Funcionarios:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Funcionarios {

    List<String> nome = new ArrayList<>();
    List<String> apelido = new ArrayList<>();
    List<String> nascimento = new ArrayList<>();
    List<String> cpf = new ArrayList<>();
    List<String> cep = new ArrayList<>();
    List<String> endereco = new ArrayList<>();
    List<String> numero = new ArrayList<>();
    List<String> cidade = new ArrayList<>();
    List<String> estado = new ArrayList<>();
    List<String> cargo = new ArrayList<>();
    List<String> aux = new ArrayList<>();
    List<String> valido = new ArrayList<>();
    List<String> invalido = new ArrayList<>();
    String aux_cpf = "";
    String aux_campo = "";
    Scanner teste = new Scanner(System.in);
    int i = 0, m = 0;

    Funcionarios() {
    }

    //String Imprimir_Funcionarios(List nome, List apelido, List nascimento, List cpf, List cep, List endereco, List numero, List cidade, List estado, List cargo, int i){
    //  return String.format("%s;%s;%s;%s;%s;%s;%s;%s;%s;%s", nome.get(i),apelido.get(i),nascimento.get(i),cpf.get(i),cep.get(i),endereco.get(i),numero.get(i),cidade.get(i),estado.get(i),cargo.get(i));
    //}
    boolean EncontrarCPF(String CPF) {
        while (i < CPF.length()) {
            if (CPF.charAt(i) != '-' && CPF.charAt(i) != '.') {
                aux_cpf += String.valueOf(CPF.charAt(i));
            }
            i++;
        }
        i = 0;
        if (aux.contains(aux_cpf)) {
            return true;
        }

        aux.add(aux_cpf);
        aux_cpf = "";
        return false;
    }

}

And the value in aux.nome.get(1) will be copy to invalido.nome and aux.nome.get(0) will be copy to valido.nome. When my code print invalido.nome the result is a empty list showing [].
I've already verified my if conditions and its works. How can I fix it? Please! I'm just trying to separate correctly typed names.

A: I am sorry but I am certain that your Matching Pattern is not working properly.
if I replace that with something like:
if(!aux_teste.matches("[a-zA-Z]+$"))

It puts all names with a number into invalido.nome, confirming that the methods to put Strings into your lists are working properly.
Edit: this is how a "minimal" test case should IMO look like - delete all the user input stuff and work with simple data:
public static void main(String[] args) {
    Funcionarios valido = new Funcionarios();
    Funcionarios invalido = new Funcionarios();
    Funcionarios aux = new Funcionarios();

    Pattern filtro_numero = Pattern.compile("-?[\\\\d\\\\.]+", Pattern.CASE_INSENSITIVE);

    aux.nome.add("Juan");
    aux.nome.add("Ju4n");
    aux.nome.add("Simon");
    aux.nome.add("S1mon");

    String aux_teste;
    int i = 0;
    while (i < aux.nome.size()) {
        Matcher somente_letras = filtro_numero.matcher(aux.nome.get(i));
        aux_teste = aux.nome.get(i);
        //if (!somente_letras.find()) {
        if(aux_teste.matches("[a-zA-Z]+$")){
            valido.nome.add(aux_teste);
        }
        else{
            invalido.nome.add(aux_teste);
        }
        i++;
    }

    System.out.println("Invalidos");
    System.out.println(invalido.nome);

    System.out.println("Validos");
    System.out.println(valido.nome);
}

comment in and comment out the 2 different if-conditions and see that your pattern doesn't work.


text:
Q: Where to store AWS credentials in ECS service I have an ECS service, which requires AWS credentials. I use ECR to store docker images and jenkins visible only for VPN connections to build images.
I see 2 possibilities to provide AWS credentials to the service

*

*Store them as Jenkins secret and insert into the docker image during build

*Make them a part of the environment when creating ECS Task definition

What is more secure? Are there other possibilities?

A: First thing, You should not use AWS credentials while working inside AWS, you should assign the role to Task definition or services instead of passing the credentials to docker build or task definition.

With IAM roles for Amazon ECS tasks, you can specify an IAM role that
  can be used by the containers in a task. Applications must sign their
  AWS API requests with AWS credentials, and this feature provides a
  strategy for managing credentials for your applications to use,
  similar to the way that Amazon EC2 instance profiles provide
  credentials to EC2 instances

So sometimes the underlying application is not designed in a way that can use role so in this I will recommend storing ENV in the task definition but again from where to get the value of ENV?
Task definition support two methods to deal with ENV,

*

*Plain text as direct value

* Use 'valueFrom' attribute for ECS task definition

The following is a snippet of a task definition showing the format when referencing an Systems Manager Parameter Store parameter.
{
  "containerDefinitions": [{
    "secrets": [{
      "name": "environment_variable_name",
      "valueFrom": "arn:aws:ssm:region:aws_account_id:parameter/parameter_name"
    }]
  }]
}

This is the most secure and recommended method by AWS documentation so this is the better way as compared to ENV in plain text inside Task definition or ENV in Dockerfile.
You can read more here and systems-manager-parameter-store.
But to use these you will must provide permission to task definition to access systems-manager-parameter-store.


text:
Q: protobuf-net, "seems" to work without attributes...or RuntimeTypeModel In short. I haven't used the attributes nor RunTypeModel and Serialization and Deserialization just works, so I'm assuming that I have missed something that  will bite me later, when I have bragged to management and close to release
We have some core-objects that we prefer to keep clean from proto-net-attributes.
So we were looking at this solution:
protobuf-net serialization without attributes
When trying to test it out, It seems that everything works without any attributes and that my (poco, no attributes)-type already is "registered"
I have this code
 Type type = typeof(T);
 if(RuntimeTypeModel.Default[type] == null)
 {
    // add my type to
     RuntimeTypeModel.Default.Add(typeof(T)).Add(...);
 }

I haven't tested this code, since it seems already to be registered, it never enters the if-statement. The serialization goes well. I have also copy-pasted my class definition on the consumer side and it looks ok.
EDIT: The type comming in happens to be a record
Related question:
Later on we will need the protobuf-definitions, is it possible to get them through RuntimeTypeModel.Default[type].GenerateProtobufDefinitonAsString()  would be nice, for our non-.NET-consumers


text:
Q: How do i display progress bar on each item in the listview using flutter i have a json data which am displaying in the listview that contains item name, scores and target scores. i want to show a progress bar indicating scored points and the target points below is my code and images to help understand.
This is my json data

Below is My code:
`
import 'dart:convert';
import 'package:network/network.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class FavouriteTab extends StatefulWidget {
  @override
  _FavouriteTabState createState() => _FavouriteTabState();
}

class _FavouriteTabState extends State<FavouriteTab> {
  List products = List();

  Future getAllProducts() async {
    var response = await http.get(NetworkUrl.getProducts());
    if (response.statusCode == 200) {
      setState(() {
        products = json.decode(response.body);
      });
      return products;
    }
  }

  @override
  void initState() {
    super.initState();
    getAllProducts();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Target Scores"),
      ),
      body: FutureBuilder(
          future: getAllProducts(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              if (products.contains("empty")) {
                return Center(child: Text("NO DATA"));
              } else {
                return ListView.builder(
                    itemCount: products.length,
                    itemBuilder: (context, index) {
                      var notis = products;
                      var scoredAmt = notis[index]['scored_amt'];
                      var targetAmt = notis[index]['target_score'];
                      var _percentages = (scoredAmt / targetAmt);
                      return Card(
                        child: Container(
                          child: Column(
                            children: [
                              Text(notis[index]['item_name']),
                              Text(
                                notis[index]['target_score'],
                                style: TextStyle(color: Colors.indigo),
                              ),
                              SizedBox(height: 5),
                              Row(
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Text("Scored Amount :" +
                                        notis[index]['scored_amt']),
                                  ),
                                  Spacer(),
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Text("Target Amount :" +
                                        notis[index]['target_score']),
                                  ),
                                ],
                              ),
                              Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: SizedBox(
                                    width: 300,
                                    height: 30,
                                    child: LinearProgressIndicator(
                                        value: _percentages)),
                              ),
                            ],
                          ),
                        ),
                      );
                    });
              }
            } else {
              return LinearProgressIndicator(
                backgroundColor: Colors.purpleAccent,
              );
            }
          }),
    );
  }
}`

Am getting this error

i want to have data display like this according to the scores:
This is how i want to display

I don't know what am doing wrong kindly help

A: As the error you are getting denotes it seems that you are not parsing the strings as num's and are trying to divide Strings.
var _percentages = (num.tryParse(scoredAmt) / num.tryParse(targetAmt))

Or even better do that parsing in your model see here.
Also you are calling the getAllProducts in initState but are not caching the result and you call it again in the futureBuilder,
import 'dart:convert';
import 'package:Habapay/network/network.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class FavouriteTab extends StatefulWidget {
  @override
  _FavouriteTabState createState() => _FavouriteTabState();
}

class _FavouriteTabState extends State<FavouriteTab> {
  List products = List();
  Future allProducts;
  Future getAllProducts() async {
    var response = await http.get(NetworkUrl.getProducts());
    if (response.statusCode == 200) {
      setState(() {
        products = json.decode(response.body);
      });
      return products;
    }
  }

  @override
  void initState() {
    super.initState();
    allProducts=  getAllProducts();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Target Scores"),
      ),
      body: FutureBuilder(
          future: allProducts,/// Now the future gets called only once
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              if (products.contains("empty")) {
                return Center(child: Text("NO DATA"));
              } else {
                return ListView.builder(
                    itemCount: products.length,
                    itemBuilder: (context, index) {
                      var notis = products;
                      var scoredAmt = notis[index]['scored_amt'];
                      var targetAmt = notis[index]['target_score'];
                      var _percentages = (scoredAmt / targetAmt);
                      return Card(
                        child: Container(
                          child: Column(
                            children: [
                              Text(notis[index]['item_name']),
                              Text(
                                notis[index]['target_score'],
                                style: TextStyle(color: Colors.indigo),
                              ),
                              SizedBox(height: 5),
                              Row(
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Text("Scored Amount :" +
                                        notis[index]['scored_amt']),
                                  ),
                                  Spacer(),
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Text("Target Amount :" +
                                        notis[index]['target_score']),
                                  ),
                                ],
                              ),
                              Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: SizedBox(
                                    width: 300,
                                    height: 30,
                                    child: LinearProgressIndicator(
                                        value: _percentages)),
                              ),
                            ],
                          ),
                        ),
                      );
                    });
              }
            } else {
              return LinearProgressIndicator(
                backgroundColor: Colors.purpleAccent,
              );
            }
          }),
    );
  }
}`


text:
Q: Не правильно работает анимация UIView Писал змейку. Согласно документации, при длительности анимации <=0, анимации не происходит. Но она анимируется.
let dur = abroad ? -1 : speed
UIView.animate(withDuration: dur) {
        for i in 0..<(self.snakes.count - 1) {
            let snake = self.snakes[self.snakes.count - i - 2]
            let temp = oldFrame
            oldFrame = snake.frame
            snake.frame = temp
            if snake.frame.intersects(main.frame) {
                self.gameOver = true
                print("game over!!!!!")
            }
        }
        if self.abroad {
            print(dur) // -1
        }
    }

Причем когда делаю вот так
var dur:TimeInterval = 0

анимации нету, а когда вот так:
var dur:TimeInterval = 0
if !abroad {
    dur = TimeInterval(speed)
}

анимация происходит и тогда, когда abroad == false.
Не могу понять в чем дело. Заранее спасибо за помощь

A: Подтверждаю несоответствие поведению, указанному в документации к animate(withDuration:animations:) по крайней мере при проверке на iOS 13.5

duration
The total duration of the animations, measured in seconds. If you specify a negative value or 0, the changes are made without animating
them.

В следующем примере анимация происходит при значении меньше нуля, но ее нет при значении равном нулю (let duration: TimeInterval = 0)
Решение: использовать 0 для отключения анимации
class ViewController: UIViewController {

    @IBOutlet var label: UILabel!

    @IBAction func buttonTouchUpInside(_ sender: UIButton) {
        let duration: TimeInterval = -1 // assign 0 to disable animation

        UIView.animate(withDuration: duration) {
            self.label.frame = self.label.frame.offsetBy(dx: 0, dy: 300)
        }
    }

}


text:
Q: wordpress : add_action : why the second parameter is an array instead of a function name I am trying to create a wordpress plugin, I found one plugin which use oops concepts, my question is why the second parameter in the add_action function is an array instead of a function name

add_action('admin_menu', array(&$this,
  'my_menu'));

my_menu is a function in the same class, please help me
Thanks

A: @Thomas John, you are correct about second argument in add_action also in wordpress org not mentioned anything about this so now, let me know you, we can pass array as second argument array($this,'method').
Description:
when object creates of class then constructor automatically calls and your action performs.
WHY IT REQUIRES
in wordpress how to create or initialize the class in add_action method in short add_action referencing a class check below example
class Myclass{
 public function __construct() {

add_action( 'plugins_loaded', array( $this, 'load_plugin_textdomain' ) );

}
}

Referencing a class using add_action().

A: Because the second argument needs to be a callback. (and add_action internally uses call_user_func_array).
For functions we can just pass its name as a string but we can't do that with object methods, can we?
So an array is passed with 2 elements, first the object and second the method to call:-
array( $object, 'method' )
Oh and you can safely remove that useless '&', PHP4 days are gone now.


text:
Q: notepad ++ Help need to split groups of 4,6,8 digits to groups of 2 I have some data and would like to split the groups of 4,6 and 8 digits into groups of 2
3 16 53 7282 192331 68 83 9 29364255 00001
4 10 57 7188 6 3943 6574 1228 4558 79 00002
2 415266 80 142433 7887 26 445669 89 00003
1 223440 85 5 27 596270 13 3749 6375 00004
15 32 607381 17 465061 84 7 2035 5167 00005

output needed
3 16 53 72 82 19 23 31 68 83 9 29 36 42 55 00001
4 10 57 71 88 6 39 43 65 74 12 28 45 58 79 00002
2 41 52 66 80 14 24 33 78 87 26 44 56 69 89 00003
1 22 34 40 85 5 27 59 62 70 13 37 49 63 75 00004
15 32 60 73 81 17 46 50 61 84 7 20 35 51 67 00005

I'm not worried of this effect the 00001, 00002 as I can fix this after export to excel
screen shot of data:

A: *

*Ctrl+H

*Find what: \b(\d\d)(\d\d)?(\d\d)?\b

*Replace with: $1(?2 $2)(?3 $3)

*CHECK Wrap around

*CHECK Regular expression

*Replace all
Explanation:
\b              # word boundary, make sure we haven't a digit before
(\d\d)          # group 1, 2 digits
(\d\d)?         # group 2, 2 digits, optional
(\d\d)?         # group 3, 2 digits, optional
\b              # word boundary, make sure we haven't a digit after

Replacement:
$1              # content of group 1, the first 2 digits
(?2 $2)         # if group 2 exists, insert a space and content of group 2
(?3 $3)         # if group 3 exists, insert a space and content of group 3

Screenshot (before):

Screenshot (after):

A: Thanks for the reply. Its not quite what I was looking for.
I managed to do it this way
I added a 0 to all single digits
\b(\d)\b
0$1  (space at end)
then removed all spaces and then grouped into 2
(..)
\1 (space at end)
which worked apart from the ticket number was 00 00 1 instead of 00001
which I fix when I imported into excel
see image


text:
Q: Unable to access variable inside closure swift I'm trying to get my firebase database data into a variable to use it in my project
var someArray = [Array]()
let dbRef = Database.database().reference().child("SomeDatabase")

func loadSomeDatabaseData {
   dbRef.observeSingleEvent(of: .value) { (snapshot) in
       let someDict = snapshot.value as! [String:Any]
       let keysOfSomeDict = Array(someDict.keys)
       self.someArray.append(contentsOf: keysOfSomeDict)
       self.collectionView?.reloadData()
   }
}

I've tried calling loadSomeDatabaseData() in my viewDidload, followed by printing someArray, which results in an empty array. I know the keysOfSomeDict array has the correct data that I want, since i tried printing this array directly inside the closure. I would however also like to be able to print and use this data elsewhere in my app.

A: The observeSingleEvent is asynchronous. So immediately printing someArray after calling loadSomeDatabaseData will result in an empty array. It takes sometime to retrieve the data from Firebase api.
To use this data elsewhere in the app, you could set a flag indicating the data is loaded or send a notification to inform the data is available.

A: The Firebase  observeSingleEvent method is asynchronous method. it executive in background only because it take time to fetch data from Firebase.
if you print array immediately means you get only empty array.
so print array once you get the data from Firebase. for that you can use escaping closure
Function Declaration:
  func loadSomeDatabaseData(resultArray : @escaping([Array])->()) {
       dbRef.observeSingleEvent(of: .value) { (snapshot) in
           let someDict = snapshot.value as! [String:Any]
           let keysOfSomeDict = Array(someDict.keys)
           self.someArray.append(contentsOf: keysOfSomeDict)
           resultArray(self.someArray)
       }
    }

Func Call:
self.loadSomeDatabaseData{(firebaseReposne) in
   print("FirebaseData" , firebaseReposne)  // Hope here you will get your firebase data.
     self.collectionView?.reloadData()
}


text:
Q: Would like to map  to scroll previous colon commands I'm trying to map <S-j> to scroll previous colon commands. So <S-j> instead of : and <Up>.
nnoremap <S-j> :<Up>

Problem with this bind is that scrolling the 2nd last colon command is actually :<Up><Up>, but if you press <S-j> twice you get :<Up>:<Up> instead.
How do I map it properly so that it outputs :<Up> if not in command bar and just <Up>, if command bar has text already inside

A: I don't see your behavior. If I press <S-j> (which by the way is just a convoluted way to say J) twice, I get the previous command-line plus the literal letter J. Your command is defined for normal mode; due to the : in the right-hand side it will end in command-line mode. J = <S-j> is not mapped there (at least not by :nnoremap).
In order to be able to repeat J, you'd have to define an additional mapping for command-line mode:
:cnoremap <S-j> <Up>

This leaves out the :, as you're already in the command-line.
However, I would not recommend this, as it will leave you unable to directly type a capital J (you can still type it via <C-v>J, or as you like to say, <C-v><S-j>). You'd better switch to a mapping that uses a non-printable character (e.g. <C-j>).


text:
Q: Сумма двух столбцов со своим условием для каждого за один проход MySQL Есть таблица, содержащая следующие поля:
ID, FirstUserID, SecondUserID, FirstUserCount, SecondUserCount.
При этом гарантируется, что FirstUserID <= SecondUserID.
Нужно: за один проход посчитать сумму Count для пользователя, ID которого мы знаем.
Соответственно, нужно выбирать сначала FirstUserCount при условии FirstUserID <= UserID, а затем - SecondUserCount с условием FirstUserID > UserID, где UserID - переданный параметр. Суммировать можно в две различные переменные.
Могу ли я сделать это с помощью одного запроса MySQL?
Если нет, то как оптимально можно это сделать?
UPD: уникальность записи, а также то, что FirstUserID != SecondUserID - гарантируется.

A:
Нужно: за один проход посчитать сумму Count для пользователя, ID которого мы знаем.

SELECT SUM(CASE
           WHEN FirstUserID  = @ID THEN FirstUserCount
           WHEN SecondUserID = @ID THEN SecondUserCount
           END) totalSum
FROM `table`;

Запрос даст неверный результат, если существует запись, где FirstUserID = SecondUserID = @ID. Но это ведь несложно исправить...
PS. Но куда как разумнее нормализовать структуру.

A: Так не пойдёт?
SELECT
(SELECT SUM(a.FirstUserCount) FROM tbl a WHERE a.FirstUserId = :userId) +
(SELECT SUM(b.SecondUserCount) FROM tbl b WHERE b.SecondUserId = :userId) as total;

Либо:
SELECT SUM(
  IF(FirstUserID   = :userId, FirstUserCount, 0) +
  IF(SecondUserID  = :userId, SecondUserCount, 0)
) as total
FROM tbl;

Можно добавить WHERE FirstUserID = :userId OR SecondUserId = :userId для возможности дальнейшей оптимизации с помощью индексов.


text:
Q: "Error: 'IplImage' does not name a type when trying to build darknet with OpenCV and CUDA? I am trying to use Darkent with OpenCV and CUDA. I installed darknet according to these instructions:
https://pjreddie.com/darknet/install/
I installed CUDA according to these instructions:
https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html
Finally, I installed OpenCV according to these instructions:
http://www.linuxfromscratch.org/blfs/view/svn/general/opencv.html
I then added the following lines to the end of my bashrc:
export PATH=$PATH:/usr/local/cuda-11.1/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-11.1/lib64:/usr/include/opencv4
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig:/usr/include/opencv4

I was then having trouble with darknet finding the opencv library, so I added an opencv.pc file at /usr/local/lib/pkgconfig, with the following content:

prefix=/usr
exec_prefix=${prefix}
libdir=${prefix}/lib/x86_64-linux-gnu
includedir_new=${prefix}/include/opencv4

Name: OpenCV
Description: Open Source Computer Vision Library
Version: 4.5.0
Libs: -L${libdir} -lopencv_dnn -lopencv_ml -lopencv_objdetect -lopencv_shape -lopencv_stitching -lopencv_superres -lopencv_videostab -lopencv_calib3d -lopencv_features2d -lopencv_highgui -lopencv_videoio -lopencv_imgcodecs -lopencv_video -lopencv_photo -lopencv_imgproc -lopencv_flann -lopencv_core
Libs.private: -ldl -lm -lpthread -lrt
Cflags: -I${includedir_new}

Next, I modified the Makefile in the darknet directory such that GPU=1, and OPENCV=1. I ran make, but am encountering the error:
./src/image_opencv.cpp:12:1: error: 'IplImage' does not name a type
   12 | IplImage *image_to_ipl(image im)
      | ^~~~~~~~
compilation terminated due to -Wfatal-errors.

Any help would be greatly appreciated. I am running ubuntu 20.04, kernel 5.4.0-53-generic.

A: For OpenCV4 users who are attempting to use OpenCV in darknet,
Reprinted from (https://forums.developer.nvidia.com/t/darknet-compile-error-with-cudnn-8/141115/13): save the following in a file (patch.diff).
diff --git a/src/image_opencv.cpp b/src/image_opencv.cpp
index 7511280..c11805a 100644
--- a/src/image_opencv.cpp
+++ b/src/image_opencv.cpp
@@ -9,30 +9,34 @@ using namespace cv;

 extern "C" {

-IplImage *image_to_ipl(image im)
+Mat image_to_mat(image im)
 {
+    assert(im.c == 3 || im.c == 1);
     int x,y,c;
-    IplImage *disp = cvCreateImage(cvSize(im.w,im.h), IPL_DEPTH_8U, im.c);
-    int step = disp->widthStep;
+    image copy = copy_image(im);
+    constrain_image(copy);
+    if(im.c == 3) rgbgr_image(copy);
+    Mat m(im.h, im.w, CV_MAKETYPE(CV_8U, im.c));
     for(y = 0; y < im.h; ++y){
         for(x = 0; x < im.w; ++x){
             for(c= 0; c < im.c; ++c){
-                float val = im.data[c*im.h*im.w + y*im.w + x];
-                disp->imageData[y*step + x*im.c + c] = (unsigned char)(val*255);
+                float val = copy.data[c*im.h*im.w + y*im.w + x];
+                m.data[y*im.w*im.c + x*im.c + c] = (unsigned char)(val*255);
             }
         }
     }
-    return disp;
+    free_image(copy);
+    return m;
 }

-image ipl_to_image(IplImage* src)
+image mat_to_image(Mat m)
 {
-    int h = src->height;
-    int w = src->width;
-    int c = src->nChannels;
+    int h = m.rows;
+    int w = m.cols;
+    int c = m.channels();
     image im = make_image(w, h, c);
-    unsigned char *data = (unsigned char *)src->imageData;
-    int step = src->widthStep;
+    unsigned char *data = (unsigned char*)m.data;
+    int step = m.step;
     int i, j, k;

     for(i = 0; i < h; ++i){
@@ -42,26 +46,6 @@ image ipl_to_image(IplImage* src)
             }
         }
     }
-    return im;
-}
-
-Mat image_to_mat(image im)
-{
-    image copy = copy_image(im);
-    constrain_image(copy);
-    if(im.c == 3) rgbgr_image(copy);
-
-    IplImage *ipl = image_to_ipl(copy);
-    Mat m = cvarrToMat(ipl, true);
-    cvReleaseImage(&ipl);
-    free_image(copy);
-    return m;
-}
-
-image mat_to_image(Mat m)
-{
-    IplImage ipl = m;
-    image im = ipl_to_image(&ipl);
     rgbgr_image(im);
     return im;
 }
@@ -72,9 +56,9 @@ void *open_video_stream(const char *f, int c, int w, int h, int fps)
     if(f) cap = new VideoCapture(f);
     else cap = new VideoCapture(c);
     if(!cap->isOpened()) return 0;
-    if(w) cap->set(CV_CAP_PROP_FRAME_WIDTH, w);
-    if(h) cap->set(CV_CAP_PROP_FRAME_HEIGHT, w);
-    if(fps) cap->set(CV_CAP_PROP_FPS, w);
+    if(w) cap->set(CAP_PROP_FRAME_WIDTH, w);
+    if(h) cap->set(CAP_PROP_FRAME_HEIGHT, w);
+    if(fps) cap->set(CAP_PROP_FPS, w);
     return (void *) cap;
 }

@@ -123,7 +107,7 @@ void make_window(char *name, int w, int h, int fullscreen)
 {
     namedWindow(name, WINDOW_NORMAL);
     if (fullscreen) {
-        setWindowProperty(name, CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
+        setWindowProperty(name, WND_PROP_FULLSCREEN, WINDOW_FULLSCREEN);
     } else {
         resizeWindow(name, w, h);
         if(strcmp(name, "Demo") == 0) moveWindow(name, 0, 0);

Run git apply patch.diff.

A: It seems there are some missing header lines in file /src/image_opencv.cpp, add these lines at the beginning than make it again.
#include "opencv2/core/core_c.h"
#include "opencv2/videoio/legacy/constants_c.h"
#include "opencv2/highgui/highgui_c.h"

Additionally, you have to change the line IplImage ipl = m to IplImage ipl = cvIplImage(m); in the same file.


text:
Q: how an index value can be used to retrieve the respective name(string) By using the listdlg its possible to select the file from list, but it returns the respective index as a output but not the name(string of selected entity)of the selection. how can one get the name of the selected file in output??'
for example
[Selection, ok] = listdlg(Name,Value,...);

% selection is nothing but a index of selected entities.

A: The dialog box is filled with a cell array provided as the value of the ListString parameter. The result of the call to listdlg is the index into this cellarray.
Consider the following code:
filelist=dir("/home");
S={filelist.name};
[Selection,ok]=listdlg('ListString',S,'SelectionMode','single');
if (ok) filename=cell2mat(S(Selection)) endif

If the selection of the item user1 was made it should output
filename = user1

Update
When SelectionMode is multiple, you could use celldisp(S(Selection)). To extract individual items use S{Selection(i)} where i ranges from 1 to length(Selection).
filelist=dir("/home");
S={filelist.name};
[Selection,ok]=listdlg('ListString',S,'SelectionMode','multiple');
if (ok)
  for i=1:length(Selection)
    disp(S{Selection(i)})
  end
endif


text:
Q: scatter plot in jfreechart from database How can i draw scatter plot of datas in mysql database table using jfreechart in java. I have used swing library.
Any link would be helpful. I searched google but couldnot find a understanding solution.
If you have got code just provide me.
Actually i did do barchart and plot it using jfreechart.
The code i used for my barchart is here. Here display3 function displays the barchart.
How can i modify it  to display scatter plot?
public void display3() throws SQLException, ClassNotFoundException{

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    String JDBC_DRIVER="com.mysql.jdbc.Driver";
    String DB_URL="jdbc:mysql://localhost/data2";
    Connection conn;
    Statement stmt;
    String USER = "root";
    String PASS = "";
    try{
        Class.forName(JDBC_DRIVER);
        conn=DriverManager.getConnection(DB_URL,USER,PASS);
        System.out.println("Creating statement...");
        stmt = conn.createStatement();

        String sql;
        sql="SELECT * FROM `production` WHERE crop_id = 1 AND location_id = 1";
        ResultSet rs=stmt.executeQuery(sql);

        while (rs.next()){
            //String student = rs.getString("studentname");
            String yeartext = rs.getString("year_of_production");
            //double value = Double.parseDouble(text);
            String productiontext = rs.getString("production_amount");
            double production = Double.parseDouble(productiontext);
            Integer year = Integer.parseInt(yeartext);

            dataset.setValue(production, "production", year);

        }

        JFreeChart chart = ChartFactory.createBarChart("Bar Graph",// Chart Title
                "Year", //horizontal axis label
                "Paddy Production", // vertical axis label
                dataset, //data
                PlotOrientation.VERTICAL, //orientation of chart
                true, //include legend
                false, // tool tips
                true);//urls
        CategoryPlot p = chart.getCategoryPlot();
        ChartPanel chartPanel = new ChartPanel(chart, false);
        jPanel9.setLayout(new BorderLayout());
        jPanel9.add(chartPanel, BorderLayout.EAST);
        jPanel9.add(chartPanel);
        SwingUtilities.updateComponentTreeUI(this);
        p.setRangeGridlinePaint(blue);

        System.out.println("Database created successfully...");

    } catch(SQLException se) {
        //Handle errors for JDBC
        System.out.println("Connect failed ! ");
        se.printStackTrace();
    }

}

  I finally solved my problem:

The refine code is below and it works:
public void display3() throws SQLException, ClassNotFoundException{

        //DefaultCategoryDataset dataset = new DefaultCategoryDataset();
         XYSeriesCollection dataset = new XYSeriesCollection();
         XYSeries series = new XYSeries("production");
        String JDBC_DRIVER="com.mysql.jdbc.Driver";
    String DB_URL="jdbc:mysql://localhost/data2";
    Connection conn;
    Statement stmt;
    String USER = "root";
    String PASS = "";
        try{
            Class.forName(JDBC_DRIVER);
            conn=DriverManager.getConnection(DB_URL,USER,PASS);
            System.out.println("Creating statement...");
            stmt = conn.createStatement();
                        String sql;
                        sql="SELECT * FROM `production` WHERE crop_id = 1 AND location_id = 1";
                        ResultSet rs=stmt.executeQuery(sql);

                        while (rs.next()){
                            //String student = rs.getString("studentname");
                            String yeartext = rs.getString("year_of_production");
                            //double value = Double.parseDouble(text);
                            String productiontext = rs.getString("production_amount");
                            double production = Double.parseDouble(productiontext);
                            double year = Double.parseDouble(yeartext);
                            series.add(year,production) ;
                            //dataset.addSeries(series);

                        }
                        dataset.addSeries(series);

                        JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot","Year","Paddy Production", dataset);

                        //CategoryPlot p = chart.getCategoryPlot();
                         //XYPlot xyplot = (XYPlot)jfreechart.getPlot();
                        //http://stackoverflow.com/questions/12417732/jfreechart-with-scroller
                        ChartPanel chartPanel = new ChartPanel(chart, false);
                        jPanel9.setLayout(new BorderLayout());
                        jPanel9.add(chartPanel, BorderLayout.EAST);
                        jPanel9.add(chartPanel);
                        SwingUtilities.updateComponentTreeUI(this);
                       // p.setRangeGridlinePaint(blue);

                        System.out.println("Database created successfully...");

                }catch(SQLException se){
                    //Handle errors for JDBC
                    System.out.println("Connect failed ! ");
                    se.printStackTrace();
//                    JOptionPane.showMessageDialog(MajorUI.this, err.getMessage());
                    }

    }

The output is:
http://i58.tinypic.com/29ynsxh.png

A: This complete example creates a suitable database table in memory, queries it into a JDBCXYDataset and displays the dataset in a scatter plot. Note how the first column becomes the domain, while successive columns become individual series.

import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Random;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.jdbc.JDBCXYDataset;

/**
 * @see http://stackoverflow.com/a/24592754/230513
 */
public class JDBCTest {

    private static final int N = 30;
    private static final Random r = new Random();

    private void display() {
        JFrame f = new JFrame("JDBCTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JDBCXYDataset jds = createDataset();
        JFreeChart chart = ChartFactory.createScatterPlot("Inventory",
            "Date", "Count", jds, PlotOrientation.VERTICAL, true, true, false);
        XYPlot plot = chart.getXYPlot();
        plot.setDomainAxis(new DateAxis("Date"));
        f.add(new ChartPanel(chart));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        for (int i = 0; i < jds.getItemCount(); i++) {
            System.out.println(new Date(jds.getX(0, i).longValue()));
        }
    }

    private JDBCXYDataset createDataset() {
        try {
            Connection conn = DriverManager.getConnection(
                "jdbc:h2:mem:test", "", "");
            Statement st = conn.createStatement();
            st.execute("create table inventory(when date, n1 integer, n2 integer)");
            PreparedStatement ps = conn.prepareStatement(
                "insert into inventory values (?, ?, ?)");
            Calendar c = Calendar.getInstance();
            for (int i = 0; i < N; i++) {
                ps.setDate(1, new Date(c.getTimeInMillis()));
                ps.setInt(2, N / 3 + r.nextInt(N / 3));
                ps.setInt(3, N / 2 + r.nextInt(N / 3));
                ps.execute();
                c.add(Calendar.MONTH, 1);
            }
            JDBCXYDataset jds = new JDBCXYDataset(conn);
            jds.executeQuery("select when, n1, n2 from inventory");
            return jds;
        } catch (SQLException ex) {
            ex.printStackTrace(System.err);
        }
        return null;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JDBCTest().display();
            }
        });
    }
}


text:
Q: Ruby — Get current return value in the local scope
Possible Duplicate:
which global variable is for last expression

There's nice way to get last return value in irb/console:
>> 2*3
=> 6
>> _ + 7
=> 13
>> _
=> 13

(Found it here)
This doesn't work outside irb so I wonder if there's similar variable in plain ruby so
you wouldn't have to assign result to some variable everytime?
For instance,
def catch_return_value
  rand(8) # => 7
  "It's #{*magic_variable*}!"
end

catch_return_value # => "It's 7!"

I know this looks super dumb, but I'm just asking.
Came up with that desire when was refactoring another ugly helper method with nested content_tags.


text:
Q: How to launch a Chrome Extension popup from a background thread? I want to write a Chrome Extension that will be monitoring for URI link clicks, and when it encounters that it is to launch its popup. I understand that the monitoring will be done in the background thread of the Extension, but I'm not sure how I can launch the popup from the background thread?
Think of the functionality like allowing a simple email editor in a popup - when someone clicks a mailto link, the popup appears to let user write an email and send it without taking them to a new browser window.

A: I don't think you can do that with registerProtocolHandler, but that doesn't mean you can't write your own content script:
window.addEventListener('click', function (e) {
    if (e.target.href && e.target.href.indexOf('mailto:') != -1) {
        var email = e.target.href.replace('mailto:', '');
        // open your popup when an email is clicked
        window.open(...);
    }
}, false);