text:
Q: Drag and Drop moving controls instead of copying I have two panels and one on load gets populate with controls. When the users drags the controls to the other panel it moves the control from the original panel to the new panel, I would rather like a copy to be made of the control and place in the other panel. I need to be able to drag the same control in to the panel multiple times.How can I go about achieving this? I have tried changing the drag effect to copy but this does not seem  to do the trick.
void panel_DragEnter(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Copy;
    }

 void panel_DragDrop(object sender, DragEventArgs e)
    {

        Button data = (Button)e.Data.GetData(typeof(Button));
        FlowLayoutPanel _destination = (FlowLayoutPanel)sender;
        FlowLayoutPanel _source = (FlowLayoutPanel)data.Parent;

        if (_source != _destination)
        {
            // Add control to panel
            data.Size = new Size(_destination.Width, 85);
            _destination.Controls.Add(data);

            // Reorder
            Point p = _destination.PointToClient(new Point(e.X, e.Y));
            var item = _destination.GetChildAtPoint(p);
            int index = _destination.Controls.GetChildIndex(item, false);
            _destination.Controls.SetChildIndex(data, index);

            // Invalidate to paint!
            _destination.Invalidate();
            _source.Invalidate();
        }
        else
        {
            // Just add the control to the new panel.
            // No need to remove from the other panel, this changes the Control.Parent property.
            Point p = _destination.PointToClient(new Point(e.X, e.Y));
            var item = _destination.GetChildAtPoint(p);
            int index = _destination.Controls.GetChildIndex(item, false);
            _destination.Controls.SetChildIndex(data, index);
            _destination.Invalidate();
        }

    }

A: If you want to copy the control, then you'll need to actually take a copy of the control being copied. The best place to do this is probably in the place where you change the mode from move to copy. You can either leave the copy in the original location and continue to move the original or move the copy.
So where you have:
Button data = (Button)e.Data.GetData(typeof(Button));

you'll need to either clone the button or create a new Button and set the properties manually. Cloning would be the better solution.


text:
Q: Process reg query with spaces I'm trying to read a registry key value and use it within a variable latter on in the program however my registry key contains spaces and now I cant get it to work, dose anybody know hoe to process keys with spaces?
for /f "tokens=3" %%a in ('reg query "HKEY_CLASSES_ROOT\Software\VTS\TREADSTONE LT\Main" /v EXECUTE ^| find /i "REG_SZ"') do set UserNm=%%a

MSG * %UserNm%
pause

I'm using Windows batch.

A: To use double quotes you need to use usebackq in your for loop and change your ''s to back ticks.
for /f "usebackq tokens=3" %%a in (`reg query "HKEY_CLASSES_ROOT\Software\VTS\TREADSTONE LT\Main" /v EXECUTE ^| find /i "REG_SZ"`) do set UserNm=%%a

redpajama_set_name: RedPajamaStackExchange


text:
Q: gremlin query for the last element of multi property value of vertex I want to modele data using vertex with multi-properties which has meta-properties, for exemple:
the multi-property "date" : [12/12/2012, 13/12/2012, 19/12/2012, 24/12/2012]
and meta property for each value of date, for example, date: 12/12/2012 ("alimented" : "no").
How can I query the vertex to get the value of the last date inserted for given vertex. In the example, date: 24/12/2012 with the corresponding meta-property.
Thank you.

A: You can use order() step:
gremlin> g = TinkerGraph.open().traversal()
==>graphtraversalsource[tinkergraph[vertices:0 edges:0], standard]
gremlin> v = g.addV().next()
==>v[0]
gremlin> v.property(list,'date',1, "alimented", "no")
==>vp[date->1]
gremlin> v.property(list,'date',2, "alimented", "yes")
==>vp[date->2]
gremlin> v.property(list,'date',3, "alimented", "no")
==>vp[date->3]
gremlin> g.V(v).properties('date').order().by(value,decr).limit(1).valueMap(true)
==>[key:date, value:3, alimented:no, id:3]

Obviously your "date" field needs to be something that can be sorted on via Comparable.


text:
Q: Django UnicodeEncodeError when logging sql with unicode from BinaryField Django 1.11, Python 3.5, Windows OS
I have a Django model with a BinaryField. When I save an instance of the model to the database Django prints out an error message like this:
UnicodeEncodeError: 'charmap' codec can't encode character '\ufffd' in position 216: character maps to <undefined>

The last line of the traceback indicates that the error is occurring in django.db.backends.utils.py -- I've added a comment to the offending line:
class CursorDebugWrapper(CursorWrapper):

    # XXX callproc isn't instrumented at this time.

    def execute(self, sql, params=None):
        start = time()
        try:
            return super(CursorDebugWrapper, self).execute(sql, params)
        finally:
            stop = time()
            duration = stop - start
            sql = self.db.ops.last_executed_query(self.cursor, sql, params)
            self.db.queries_log.append({
                'sql': sql,
                'time': "%.3f" % duration,
            })
            ##### Error is reported from the logger.debug statement
            logger.debug(
                '(%.3f) %s; args=%s', duration, sql, params,
                extra={'duration': duration, 'sql': sql, 'params': params}
            )

So I think what's happening is that when Django tries to print the SQL insert statement it hits a non-printable Unicode character and throws an error. I don't want to disable Django debug logging while I'm developing (it is disabled in production, of course).  Any way to work around this issue?

A: Setting the encoding of the log handler to utf-8 seems to work. If there's a better way please advise.
LOGGING = {
    # other config omitted
    'handlers': {
        'django-debug': {
            'level': 'DEBUG',
            'class':'logging.FileHandler',
            'filename': os.path.join(LOCAL_LOGGING_PATH,'django-debug.log'),
            'formatter': 'standard',
            'encoding':'utf8', # this fixes UnicodeEncodeError
        }
    }
}

Things I tried that didn't work. These all still produce UnicodeEncodeError:

*

*Add from __future__ import unicode_literals at the top of settings.py

*Add the Byte Order Mark (BOM) character \ufeff to the formatter as suggested by the python 3 logging cookbook

*Use %r instead of %s in the log formatter

*Use the python unicode string on the formatter 'format': u'%(asctime)-s %(levelname)s [%(name)s]: %(message)s', and then logging._defaultFormatter = logging.Formatter(u"%(message)s") as suggested in this thread


text:
Q: Rails routing misconfiguration I get the following error
No route matches [POST] "/events"

with this setup:
config/routes.rb
namespace :admin do
  #...
  resources :events
  #...
end

(...)admin/events_controller.rb
class Admin::EventsController < Admin::AdminController
  def index
    @events = Event.all
  end

  def new
    @event = Event.new
  end

  def create
    @event = Event.new(params[:event])

    if @event.save
      redirect_to [:admin, admin_events_url]
    else
      render :action => "new"
    end
  end

  def edit
    @event = Event.find(params[:id])
  end
end

(...)admin/events/_form.html.erb
<%= form_for([:admin, @event]) do |f| %>

I can't figure out what I am doing wrong!
Update
I get this error when I try to POST the from data while creating a new event entry

Update 2
The opening form tag inside events/new:
<form accept-charset="UTF-8" action="/admin/events" enctype="multipart/form-data" id="new_event" method="post">

the result of rake routes:
 admin_events GET    /admin/events(.:format)             admin/events#index
              POST   /admin/events(.:format)             admin/events#create

Navigating to /admin/events/ using GET works just fine.

Update 3
It works fine on Windows 8 x64 bit with Ruby 1.9.3, Rails 3.2 and Mongrel. It doesn't work with Ruby 1.8.7, Rails 3.2 and Phusion Passenger on a linux server (the host).
Update 4
Oh. It appears Rails isn't very happy if you send it a form with multipart/form-data encoding! Removing the file-upload fixed this issue.

A: For what it's worth the only thing that looks fishy to me about your controller is your redirect. You should be able to just do:
redirect_to admin_events_path

A: Please try setting up your form this way:
form_for(@event, { url: admin_events_path, method: "POST" }) do


text:
Q: Laravel 5.7 Auth::attempt return false Auth::attempt always return false , can't understand why .

web.php

Route::post('/login','SessionsController@store');
Route::post('/register','RegisterController@store');

RegisterController.php

public function store()
{
    $this->validate(\request(),[
        'name' => 'bail|required|min:3|max:30|string',
        'email' => 'bail|required|email',
        'password' => 'required|confirmed'

    ]);
    $user = User::create(request(['name','email','password']));
    $user->fill([
        'password' => Hash::make(\request()->newPassword)
    ])->save();
    auth()->login($user);
    return redirect()->home();
}

SessionsController.php

 public function store(Request $request)
{
    $credentials = $request->only('email', 'password');

    if (! Auth::attempt($credentials)) {
        return back()->withErrors(['message'=>'Email and Password doesn\'t match']);

    }
    return redirect()->home();
}

create.blade.php (Login Page)

<form action="/login" method="post">
            @csrf

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

                Password :
                <input type="password" class="form-control" id="password" name="password" required>

            <input type="submit" class="btn btn-primary float-right" value="Register">
        </form>

Every thing is okay with registration and database , passwords is hashed .
Auth::attempt always return false .
Can't understand why , posted it after few hours of searching .. most of code is just copied from documentation.
Thanks in advance.

A: just changing
$user = User::create(request(['name','email','password']));
$user->fill([
    'password' => Hash::make(\request()->newPassword)
])->save();

to
 $user = User::create([
        'name' => request('name'),
        'email' => request('email'),
        'password' => bcrypt(request('password'))
    ]);


text:
Q: How to set startIndex property in CountableRange Is there a way to allow modifying startIndex?
var range = 0..<array.count
range.startIndex = midIndex + 1

Cannot assign to property 'startIndex' is a get only property


text:
Q: C# пробелы после значения в таблице после загрузки из локальной базы данных В Visual Studio 2015 сгенерировал локальную базу данных, добавил datagrid и привязал его к bindingSource. Все данных сохраняются и загружаются, но после загрузки добавляются пробелы к тексту. К примеру:
в поле nchar(10) "hhhh__________".Там где "_" это пробелы.
Спасибо

A: для nvarchar память выделяться во время заполнения строки символами, для vchar - она уже выделена размерностью.
nchar [ ( n ) ]

Строковые данные постоянной длины в Юникоде. Параметр n определяет длину строки и должен иметь значение от 1 до 4000. Размер при хранении составляет удвоенное значение n в байтах. Если кодовая страница параметров сортировки использует двухбайтовые символы, размер хранения остается равным n байт. В зависимости от символьной строки для хранения n символов может понадобиться менее n байт. По стандарту ISO синонимами для nchar являются national char и national character..
nvarchar [ ( n | max ) ]

Строковые данные переменной длины в Юникоде. Параметр n определяет длину строки и должен иметь значение от 1 до 4000. Значение max указывает, что максимальный размер при хранении составляет 2^31-1 байт (2 ГБ). Размер хранилища в байтах вдвое больше числа введенных символов + 2 байта. По стандарту ISO синонимами для типа nvarchar являются типы national char varying и national character varying.


text:
Q: Wordpress Menu Disappears when $query->query_vars['meta_key'] is set I've set some meta variables on my WP posts. I want to be able to sort by these variables, and everything is working great except when I sort by either "views" or "likes". When I sort by either of those two fields, WP doesn't generate my nav (wp_nav_menu).
I've tried "resetting" the $wp_query variable surrounding my wp_nav_menu call:
$old_query = $wp_query;
$wp_query = new WP_Query( array('post_type' => 'any') );
wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) );
$wp_query = $old_query;

But that does not solve it. The only thing that does work is commenting out the line starting $query->query_vars['meta_key'], but obviously that negates the sort as well.
Any help would be appreciated.
// Before a query is run, modify the sort order
function jh_popularity_sort_query($query) {
  $sort = $_GET['sort'];
  if ($sort == "title") {
    $query->query_vars['orderby'] = 'title';
    $query->query_vars['order'] = 'ASC';
  } else if ($sort == "date") {
    $query->query_vars['orderby'] = 'date';
  } else if ($sort == "views") {
    $query->query_vars['meta_key'] = 'jh_page_views';
    $query->query_vars['orderby'] = 'meta_value';
    $query->query_vars['order'] = 'DESC';
  } else if ($sort == "likes") {
    $query->query_vars['meta_key'] = 'jh_page_likes';
    $query->query_vars['orderby'] = 'meta_value';
    $query->query_vars['order'] = 'DESC';
  }

  return $query;
} add_action('pre_get_posts', 'jh_popularity_sort_query');

A: Closing this and moving to https://wordpress.stackexchange.com/ per allaire's suggestion.
For anyone who has this problem, helenhousandi had the solution right on. https://wordpress.stackexchange.com/a/52408/16201


text:
Q: Removing the "offset" of rotation between two THREE.js objects I have two separate sensors that are broadcasting (every 50ms) their rotation in the form of a quaternion to my three.js webapp. The sensors are attached together so they are rotating together however their internal (relative) coordinates are different so my two three.js object don't "sync up".
What I want to do is to store the difference of their rotation on a button press and use that to "correct" one of the object's rotation continuously after that.
What I tried to do:

*

*Calculate the difference on a button press:
let q1 = object1.getWorldQuaternion();
let q2 = object2.getWorldQuaternion();
qDiff = q1.multiply(q2.inverse());

*Add that difference to object1 when I update its rotation:
q = recieveQuaternionFromSensor();
object1.setRotationFromQuaternion(q.multiply(qDiff));

The above method doesn't work and I'm not sure what should I do differently.


text:
Q: installing synaptic package manager from outside the repos I have been facing some problems in installing software with ubuntu software center, due to the fact that I have not been able to run no proxy for the whole system, I have tried all methods prescribed in various websites to do the same but i always get 407  Proxy Authentication Required. So I want to install synaptic package manager through source code or .deb file which can be downloaded from the internet and then installed manually. Please post the link from which the same can downloaded and also steps to install it manually.
As suggested in one of the answers when i download the .deb package and perform
sudo dpkg -i synaptic_0.81.2_amd64.deb in the terminal this is what happens...

I am not able to make out where there has been a mistake.

A: A lot of packages that Synaptic depends on are not installed on your system. You'll need to install these first. However, installing Synaptic will not help with your proxy problem. You should solve that first, because installing packages manually is a pain (that's why package managers exist).
Make sure you've read the available resources on getting APT to work with a proxy that requires authentication, starting with How to configure proxy authentication to work with Ubuntu Software Center? If you can't get your proxy to work, then:

*

*If possible, seek support from your system administrators.

*Check all available documentation from your organization. Often someone somewhere has documented how to use the proxy with applications other than the major web browser, but it might take a bit of hunting down.

*You can ask on this site. We'll need to have as much information you can provide about the proxy: the name of the proxy software if you have it (it's probably displayed on the page that asks for your password), the exact settings you're using, copy-paste all prompts and error messages, etc.

Furthermore you're trying to install a package for the wrong version of Ubuntu. Synaptic 0.81.2 is the version in the upcoming Ubuntu 14.10. You have libapt-pkg4.12 0.9.7.5, which is the version in Ubuntu 12.10. You can't mix packages from different versions of Ubuntu (well, you can try, but most of the time you'll run into dependency errors like this one).
Ubuntu 12.10 is no longer supported, and most mirrors no longer carry it. You can still obtain packages from old-releases.ubuntu.com in a pinch, but you won't get any more security updates or other bug fixes. You need to upgrade as soon as possible. Direct upgrades from 12.10 to 14.04 are not supported; normally you need to upgrade version by version or from an LTS release to another LTS release, but there's an exception: you can go 12.10 → 13.10 → 14.04.


text:
Q: string to list of string and integers I have a string '3,M,8,M' and want to convert it into a list [3, 'M', 8, 'M']. Does anyone have any idea how I can do this?
Thank you very much in advance!

A: You can combine split with list comprehension:
'3,M,8,M'.split(',')
# Out[4]: ['3', 'M', '8', 'M']

[int(x) if x.isdigit() else x for x in '3,M,8,M'.split(',')]
# Out[5]: [3, 'M', 8, 'M']


text:
Q: dom doc to string I have a method in java that has 2 String parameters and it writes string to a file, now I have dom doc that holds value that I need to write to a file but its not string type, how can I convert it to a string here is my code :
import java.io.*;

import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class RemoveBlock {

    public static boolean saveStringToFile(String fileName, String saveString)
    {
        boolean saved = false;
        BufferedWriter bw = null;

        try {
            bw = new BufferedWriter(new FileWriter(fileName));

          try {
              bw.write(saveString);
              saved = true;
          }
          finally {
              bw.close();
          }
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
        return saved;
    }

  static public void main(String[] arg) {
    try{
      String xmlFile = "Management.xml";
      File file = new File(xmlFile);
      String remElement = "Physical_Order_List_Array";
      if (file.exists()){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer tFormer = tFactory.newTransformer();
        Element element = (Element)doc.getElementsByTagName(remElement).item(0);
//        Remove the node
        element.getParentNode().removeChild(element);
//              Normalize the DOM tree to combine all adjacent nodes
        doc.normalize();
        Source source = new DOMSource(doc);
        Result dest = new StreamResult(System.out);
        tFormer.transform(source, dest);
       // System.out.println();
       // saveStringToFile("emir.xml", "dsds"); -> write method
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch (Exception e){
      System.err.println(e);
      System.exit(0);
    }
  }
}

A: Why do you want to convert it to String? Just to write it to a file later? Why not only do
 Result dest = new StreamResult(new FileOutputStream("foo.xml"));

If you need a String:
StringWriter w = new StringWriter();
Result dest = new StreamResult(w);
tFormer.transform(source, dest);
String xmlString = w.toString();

A: here is the solution :
import java.io.*;

import org.w3c.dom.*;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class RemoveBlock {

     public static void removeAll(Node node, short nodeType, String name) {
            if (node.getNodeType() == nodeType &&
                    (name == null || node.getNodeName().equals(name))) {
                node.getParentNode().removeChild(node);
            } else {

                NodeList list = node.getChildNodes();
                for (int i=0; i<list.getLength(); i++) {
                    removeAll(list.item(i), nodeType, name);
                }
            }
        }

  static public void main(String[] arg) {
    try{
      String xmlFile = "Management.xml";
      File file = new File(xmlFile);
      String remElement = "Physical_Order_List_Array";
      if (file.exists()){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer tFormer = tFactory.newTransformer();
        // Obtain a node
        Element element = (Element)doc.getElementsByTagName(remElement).item(0);

        element.getParentNode().removeChild(element);

        removeAll(doc, Node.ELEMENT_NODE, remElement);

        doc.normalize();
        Source source = new DOMSource(doc);
        Result dest = new StreamResult(new FileOutputStream("Management.xml"));
        tFormer.transform(source, dest);
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch (Exception e){
      System.err.println(e);
      System.exit(0);
    }
  }
}


text:
Q: How do I get `npx mrm lint-staged` working I am aware of lint-staged not running on precommit but none of the solutions helped me.
I ran npx mrm lint-staged, but the pre-commit hook is not running. I went to check .git/hooks, and no hook was created here by husky. I have tried uninstalling and reinstalling husky. Not sure if it matters, but I am using yarn as my package manager. Also not sure if it matters, but my npx is on version 6 instead of the version 10 (and I am unable to upgrade it, an issue I raised in another stackoverflow question).


text:
Q: Hide KendoUI Dropdownlist I am trying to hide/show a KendoUI Dropdownlist depending on the user's level of access; so that it would be only visibile for AdminUsers
@if (User.IsInRole(Constants.Admin))
{

        Filter by Staff:

        @(Html.Kendo().DropDownList().Name("UserDropDownList").BindTo(Model.Users)
                .DataTextField("User").DataValueField("UserId")
                .SelectedIndex(Model.Users.IndexOf(Model.Users.FirstOrDefault(x => x.UserId == Model.Default)))
                .Events(e => e.Change("SelectedUserChanged")))

}

Now this wont work when the user is not an admin because as you see, this Dropdownlist has a Change event which feeds a Grid. I wonder if there is anyway that you're aware of to resolve this issue. Many thanks.

A: You could bring the dropdown hidden and at document ready of javascript call a action on controller that tells you if you can show or not the dropdown ($("#UserDropDownList").show() you can also use .hide()). And if you need you can trigger manually.
 $("#UserDropDownList").data("kendoDropDownList").trigger("change");


text:
Q: Python gspread create sheet if not exist I am trying to create a new sheet called "BOT: output". However, if I run the code once it works fine, but when I run the code again and that sheet exist it gives me an error. I tried to create an if condition to see if the sheet exist just identify it as wks2, but this will give an error if the sheet itsn't there in the first place.
 try:
     wks2 = mySheet.worksheet("BOT: output")
 except notFound:
     wks2 = mySheet.add_worksheet("BOT: output","999","20")

A: your issue is located at the exception you catch. It's not the right one.
According to gspread documentation it raises the WorksheetNotFound exception of it does not exists.
So your code should look like this (with simplifications)
try:
    wks = mySheet.worksheet("BOT: output")
except NWorksheetNotFound:
    wks = mySheet.add_worksheet("BOT: output","999","20")


text:
Q: how to create a query in mybatis_dynamic_sql for TO_CHAR(USE_BY_DATE - ?,'YYYYMMDD') >=TRUNC(SYSDATE) I want to achieve the below sql query in mybatis_dynamic_sql.
select * from xyz where TO_CHAR(some_date_col - ?,'YYYYMMDD') >=TRUNC(SYSDATE)

A: if you use a mapper.xml, your select could look like the following. please take care, to not declare a specific paramterType:
<select
    id="myQueryInXml"
    resultType="[replace with your type]"
    resultMap="[replace with the name of your resultMap]">
    select * from ${tabName} where TO_CHAR(${colName} - #{paramName},'YYYYMMDD') >=TRUNC(SYSDATE)
</select>

the corresponding Interface-method could look like this
boolean myQueryInXml(
        @Param("colName") final String colName,
        @Param("tabName") final String tabName,
        @Param("paramName") final String paramName
        );

if you use annotations, your Interface-method could look like this
@Select("select * from ${tabName} where TO_CHAR(${colName} - #{paramName},'YYYYMMDD') >=TRUNC(SYSDATE)")
boolean myQuery(
        @Param("colName") final String colName,
        @Param("tabName") final String tabName,
        @Param("paramName") final String paramName
        );

explanation
@Param("[replace with a parameter-name]") makes the passed parameter available under the given name in the annotation
$ in mapper.xml or (for example) @Select("[query]")-annotation tells myBatis to print/use the plain parameter-content. on the other hand, # tells myBatis to 'guess' the database type. Strings, for example, become edged in '' automatically. so there is no need to do it manually
please also take a look at:
mybatis – MyBatis 3 | Mapper XML Files
mybatis – MyBatis 3 | Dynamic SQL


text:
Q: Injecting JavaScript via browser extension Is it possible to inject JavaScript into a web-page with the help of a browser extension and guarantee that the page cannot override it? If this is not possible can the extension somehow check if its injected JavaScript is not used or something?
I want to deliver a JavaScript library over a safe channel, but I don't want it on a webserver.

A: Sounds like a job for chrome extensions. There you'll have a way called "Content Scripts". I hope thats that what youre looking for!


text:
Q: What's the purpose of MergeField '\v' switch in MS Word The Office documentation for MergeField only mentions the following:

\v
Enables character conversion for vertical formatting.

and the same is copied to a bunch of websites, but without real explanation.

A: What's the purpose of MergeField '\v' switch?
It appears that the \v option is meant for East Asian language
documents where the characters are laid out vertically.
This might help your understanding:

As far as I know the \v switch is intended for East Asian language
  documents where the characters are laid out vertically.
In that case
  text in Latin character sets can be displayed in two formats. It can
  either be written so the characters are in their "normal" orientation
  , but one character below the next, e.g.
l
i
k
e

t
h
i
s

or the entire text can in effect be rotated through 90 degrees, so
  that (if you like) you would have to turn your head sideways to read
  the text.
Because different characters are used depending on which way you do
  it, \v is used to "convert" the characters for the first layout, and
  no \v does the second layout.
So using \v you would only get the vertical layout you want if you
  selected Page Setup-Document Grid-Text direction-Vertical and

*

*(a) you may only get to see that option if you have an East Asian language enabled in Office (or in Vista, in Control Panel-Regional
  settings) and

*(b) this sets up the entire page for vertical text.

Source  Default mail merge -vertical orientation of data


text:
Q: Is it possible to scroll beyond the end of a file in the less pager? Is it possible to scroll past the bottom in less?
Ideally, I'd like to be able to see the last line of the file I am viewing at the top of my terminal window (the rest of the screen may be filled with tildes (~), which mean empty line/nothing to see here in less).

A: The -c option also creates "scroll past EOF" behavior in some circumstances.
Without -c, when you are near the end of file (the remaining part after the part you currently see is less than a screen height), the space scrolls down just enough to put the last line of the file on the last line of the screen. space can be equivalent to j if there's only one more line to show.
With -c, as long as you aren't at EOF already, space always scrolls forward a full screen height. The top line on the screen after space will be the line after the one that was at the bottom before the space. This can leave some portion of the screen unused, and it is filled with the ~ markers.
In -c mode, to make the last line the only visible line, G K space is all you need.
...unless the last line in the file is wider than the screen width, in which case you need to repeat the K.

A: Yes, using J (as in ShiftJ). So you can go to the end of the file with G, then scroll down past the end with J until the last line of the file is at the top of the screen (less won't let you scroll any further).
K and Y do the same at the top of the file, scrolling up past the beginning until the first line is at the bottom of the screen.
As David Ongaro points out, you can use repeat specifiers to avoid having to press J multiple times: G99J will thus scoll down until the last line is at the top of the screen (unless your terminal has a very large number of rows).


text:
Q: Yii2 updating two related models does not show data of the second I have two related models in hasToMany relation. The first is Invoices and the second is InvoiceItems. As a prototype process, I'm trying to conjugate the two models through the update view of the InvoicesController using the following code in actionUpdate of InvoicesController:
...
use common\models\Invoices;
use common\models\InvoicesSearch;
use common\models\InvoiceItems;
...

public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $invoiceItems = new InvoiceItems();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $invoiceItems->invoice_id = $model->id;
            if ($invoiceItems->load(Yii::$app->request->post()) && $invoiceItems->save()){
              return $this->redirect(['view', 'id' => $model->id]);
            }
            else{
              // return false;
            }
        } else {
          $invoiceItems->invoice_id = $model->id;
            return $this->render('update', [
                'model' => $model,
                'invoiceItems' => $invoiceItems,
            ]);
        }
    }

The following in update view:

<?= Html::encode($this->title) ?>

    <?= $this->render('_form', [
        'model' => $model,
        'invoiceItems' => $invoiceItems,
    ]) ?>

Finally, the following in _form view:

    <?php $form = ActiveForm::begin(); ?>
    <?= $form->field($model, 'created')->textInput() ?>
    <?= $form->field($model, 'type')->textInput(['maxlength' => true]) ?>

    <?= $form->field($invoiceItems, 'item_id')->textInput();?>
    <?= $form->field($invoiceItems, 'unit_id')->textInput();?>
    <?= $form->field($invoiceItems, 'qty')->textInput();?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>

The above code succeeded in saving data in invoice_items table. However, the update view form has empty fields for InvoiceItems model. i.e item_id, unit_id and qty are empty in the update form after saving.
Notice: This is initial code, i.e I will work later to be able to add many items to the invoice, but now I just try to have one item related to the invoice.

A: Seems the update view is empty because you render and empty  InvoceItmes ..
 $invoiceItems = new InvoiceItems();

you render update view in else section and this section the value posted are not loaded
    $model = $this->findModel($id);
    $invoiceItems = new InvoiceItems();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        $invoiceItems->invoice_id = $model->id;
        if ($invoiceItems->load(Yii::$app->request->post()) && $invoiceItems->save()){
          return $this->redirect(['view', 'id' => $model->id]);
        }
        else{
          // return false;
        }
    } else {//****** here the $invoceItems is empty (It has just been created) ***
      //$invoiceItems->invoice_id = $model->id;
      $invoceItems= findInvoceItmesModel($model->id);
        return $this->render('update', [
            'model' => $model,
            'invoiceItems' => $invoiceItems,
        ]);
    }

for populate the data for $invoceItems you need somethings like
protected function findInvoiceItemsModel($id)
{
    if (($model = InvociceItems::findOne($id)) !== null) {
        return $model;
    } else {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

Obviously this is for a single model.. you must refactory form more than one..


text:
Q: robocopy, make destination folders and files all lowercase I am using robocopy as part of a content pipeline (for app development). First i run it mirroring only the directory structure. Then i run it several times with /e (making use of /xf /xd etc).
For purposes of this question, imagine that my folder structure looks like:
C:\projects\projectname\Data\IrregularlyCasedFile.ext
C:\projects\projectname\Data\SubData\CamelCaseSucks.ext
And I am using robocopy to:

*

*mirror all folder structure

*

*below: C:\projects\projectname\Data\

*to: C:\projects\projectname\packages\data

*copy all .ext files, recursively
eg, output would be:
C:\projects\projectname\packages\data\irregularlycasedfile.ext
C:\projects\projectname\packages\data\subdata\camelcasesucks.ext
Now I know how to do all of this with robocopy ~except~ the rename to lower case part, which is currently a totally separate step i had to resort to using a powershell script for.
Unfortunately this is quite slow compared to robocopy as it has to yet again iterate every single file in the output directory and do a rename operation.
Can this be accomplished via robocopy alone?


text:
Q: different colors for rows in barh chart from pandas dataframe python I have the following pandas dataframe:
              a   b
    bob      23  25
    john     13  21
    paul     20  19
    david    17  14
    michael  14  24
    neil     22  11

    df.plot(kind='barh')

I used the pandas plot function.
I want to make a barh chart with all the rows(names) having a different colors is there a way to do this?
 I need all person to have different colored bars.

A: It appears that Pandas only supports using the colormap attribute, which applies the same map to each row in your chart, e.g.:
df.plot(kind='barh', colormap='RdBu')

For your purposes, you need to use Matplotlib directly.
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'a':[23, 13, 20, 17, 14, 22],
                   'b':[25, 21, 19, 14, 23, 11]},
                   index=['bob', 'john', 'paul', 'david', 'michael', 'neil'])

a_vals = df.a
b_vals = df.b
ind = np.arange(df.shape[0])
width = 0.35

# Set the colors
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'g']

def autolabel(bars):
    # attach some text labels
    for bar in bars:
        width = bar.get_width()
        ax.text(width*0.95, bar.get_y() + bar.get_height()/2,
                '%d' % int(width),
                ha='right', va='center')

# make the plots
fig, ax = plt.subplots()
a = ax.barh(ind, a_vals, width, color = colors) # plot a vals
b = ax.barh(ind + width, b_vals, width, color = colors, alpha=0.5)  # plot b vals
ax.set_yticks(ind + width)  # position axis ticks
ax.set_yticklabels(df.index)  # set them to the names
ax.legend((a[0], b[0]), ['a', 'b'], loc='center right')

autolabel(a)
autolabel(b)

plt.show()

Please refer to the following examples:
1 - matplotlib bar charts
2-  changing individual colors on bar chart


text:
Q: Duplicate methods in Java My question is probably quite basic but something I've never had to do before, so I'm assuming it's possible in Java (I'm sure it is and I just don't know how). Essentially I have 3 objects which I want to manipulate (3 BufferedImages). For example I want to be able to change the brightness and contrast, which I can do. By doing this I've had to create a separate method for each image where the code is exactly the same. For example:
public void increaseBrightnessGreen() {
    RescaleOp rescaleOp = new RescaleOp(1.0f, 10, null);
    rescaleOp.filter(greenImage, greenImage);
    updateGreen();
}

Which is then repeated for red and blue but then also duplicated 3 more times to decrease the brightness which is quite a lot of code which is doing very similar stuff. Of course, this applies quite frequently and the brightness example is just 1 of many, the methods to import the images are the same except for changing a few variables and contrast is similar to the above too. I don't know if it matters but all of my code is in one individual class.
As I say, I'm sure there's a way to reduce all this excess duplication of code, I just don't know how.

A: Have the method take in the parameter that it should modify. It could also take in the RescaleOp so you don't need to create it 3 times (and allow for different RescaleOps.
public void increaseBrightness( BufferedImage image )
{
     RescaleOp rescaleOp = new RescaleOp( 1.0f, 10, null );
     rescaleOp.filter( image, image );
     // Don't know what updateGreen does but you could probably do something similar there
     updateImage( image );
}

Then you call the method with the image you want to increaseBrightness on.
increaseBrightness( greenImage );
increaseBrightness( redImage );
increaseBrightness( blueImage );

public void increaseBrightness( BufferedImage image, RescaleOp rescaleOp )
{
     rescaleOp.filter( image, image );
     // Don't know what updateGreen does but you could probably do something similar there
     updateImage( image );
}

and call after you create the RescaleOp
RescaleOp rescaleOp = new RescaleOp( 1.0f, 10, null );
increaseBrightness( greenImage, rescaleOp );
increaseBrightness( redImage, rescaleOp );
increaseBrightness( blueImage, rescaleOp );

A: Well, of course there is a way to not duplicate methods and make a more versatile one! But you have to repeat enough code in this example too..
first of all make 3 statics in your class:
static int GREEN = 1;
static int RED = 2;
static int BLUE = 3;

then make your ONE method for ALL
public void adjustBrightness(int color, boolean increase) {

    if (increase){
         if (color == BLUE){

        //code for blue increment

        }
         if (color == GREEN){

        //code for green increment

        }
         if (color == RED){

        //code for red increment

        }
    else{    //decrease brightness

         if (color == BLUE){

        //code for blue

        }
         if (color == GREEN){

        //code for green

        }
         if (color == RED){

        //code for red

        }

    }
 }

you can call this method pretty nicely with
    adjustBrightness(BLUE, true);
or if you want it more like native speech make 2 more statics:
static boolean INCREASE = true;
static boolean DECREASE = false;

so now you can have:
adjustBrightness(BLUE, INCREASE);

and be the same with the last one;


text:
Q: How to sort NScollectionview in ascending order with arrayController? I have a collection View XIB in Xcode and this is binding to an array controller.
I need to display the items in the array controller to the collection view in ascending order but it doesn't working. It displays in random order(i guess).
Additionally, the items in the array controller have two string variables "title" and "tag".
How can I solve this problem?

A: This is my solution. It is pretty easy, huh? I should practice a lot more.
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject: sorter];
[self.clipArtArrayController setSortDescriptors:sortDescriptors];


text:
Q: Dropbox Selective Sync Config File I have dual boot - Windows 8.1 and Ubuntu 16.04. I use Dropbox on both systems. I use the same folder using ubuntu fstab.
Which file in Windows AppData contains Selective Sync config? I want to symlink it to Ubuntu. Is it possible?


text:
Q: Can a pure gradient be made equal to an arbitrary function? This question must have a really simple answer that I'm not seeing, since I'm reading it just stated in an undergrad textbook without any proof. It's about fluid dynamics, but the physics of it is actually irrelevant.
It's stated that the following equation
$$\nabla p + \rho\nabla\phi = 0$$
where $p$, $\rho$ and $\phi$ are smooth scalar functions on $\mathbb R^3$, has no solution if $\rho$ is not a constant, since the pressure term $p$ is a pure gradient, and the second term is not.
If $\rho$ is constant then of course there is the trivial solution $p=-\rho\phi + C$ for a constant $C$.
Can someone explain why it cannot have a solution if $\rho$ is not constant? I have some intuition about it, but can't see the statement to be trivial for any arbitrary functions $\rho$ and $\phi$.

A: This is false; for example $p, \phi$ could be constants and then $\rho$ could be arbitrary. I imagine the intended interpretation is that it generally has no solutions if $\rho$ is not constant, because gradients must be conservative and if $\rho$ is not constant $\rho$ times a conservative vector field generally won't be conservative.

A: Just to be clear, extending an aspect of @QiaochuYuan's answer: there is the very basic equality-of-mixed-partials criterion, that if $F(x,y,z)=(f_x,f_y,f_z)$ for some scalar-valued $f$, then (because under mild hypotheses $(f_x)_y=(f_y)_x)$, etc.), the partial with respect to $y$ of the first component of $F$ must be equal to the partial with respect to $x$ of the second component of $F$, and so on.
In your set-up, this gives a necessary condition on $\rho$.
In fact, locally this is also a sufficient condition, but some of the interesting cases are definitely not local...


text:
Q: Is Recent Activity superfluous? What about the other user pages? I'm not saying there shouldn't be a Recent Activity page, but the way it's currently implemented feels a bit... out of place. It's currently separate from the user page (/users/recent/481512342 vs. normal /users/481512342?tab=recent) and could be condensed into the user page, in my opinion.
The additional tabs that are on the Recent Activity page feels to me like they are mostly there for looking at historical data, because usually you go to the overview often enough not to miss anything important. They could be made accessible in some other way than tabs, because I think there's too many tabs on the user page already.
Speaking of the tabs on the user page, there are a lot of them, and some of them show little more than trivia (a detailed listing of all the up/down votes I've placed?) The prefs and accounts tabs belong in another section, because you do not need quick access to them, and they will also be growing in the future. A viable solution might be to change the edit link to something like manage account which in turn has profile, prefs and linked accounts tabs or something like that.
Those are all my thoughts. Discuss!

A: It's the only place that I can find links to the questions I've commented on. Often, I'll leave a comment on a question asking the OP for more info or what have you. I use my Recent page to find that comment again to check and see if the OP had responded.
Now, if there were a Comments section of the main page, that'd be fantastic, but I'm making due just fine with the current layout.

A: The Recent Activity page is a good way to follow todays changes to your rep and conversations, but more importantly, it is great if you have asked questions, as the answers (and links to them) and comments will be posted there.  I use that page more than I do my 'user' page.
However, you bring up a very good point.  Should thee two be consolidated?  I think so.  For one thing, finding the Recent Activity page is not intuitive, while there are multiple access methods to your user page (through the Users view or clicking on your username link wherever you see it on the page).  Also, when you get down to it, the two are really describing the same thing: you and your stats.
Just as you have custom views on your own user page as opposed to when you are looking at another user's page (votes and prefs, for example), the Recent Activity data could be rolled into a custom tab on your user page.  I would argue that it should be the default view of my user page, and not be available when looking at another user's page.

A: I think it's weird to "hide" Recent Activity where it is. When I was a newbie I had no idea how to find my recent answers and comments. I was expecting a my.stackoverflow.com or another tab or something.


text:
Q: Python - Locating the closest timestamp I have a Python datetime timestamp and a large dict (index) where keys are timestamps and the values are some other information I'm interested in.
I need to find the datetime (the key) in index that is closest to timestamp, as efficiently as possible.
At the moment I'm doing something like:
for timestamp in timestamps:
    closestTimestamp = min(index,key=lambda datetime : abs(timestamp - datetime))

which works, but takes too long - my index dict has millions of values, and I'm doing the search thousands of times. I'm flexible with data structures and so on - the timestamps are roughly sequential, so that I'm iterating from the first to the last timestamps. Likewise the timestamps in the text file that I load into the dict are sequential.
Any ideas for optimisation would be greatly appreciated.

A: datetime objects are comparable to each other, so make a sorted list of your key/value pairs like this:
myPairs = list(dict.iteritems())
myPairs.sort()

For each element myPairs[i], myPairs[i][0] is the datetime key and myPairs[i][1] is the value.
You can search this list efficiently using bisect_left:
import bisect
i = bisect.bisect_left(myPairs, targetDatetime)

The element myPairs[i] is the element with the lowest datetime no earlier than targetDatetime. But the prior element (if there is one) might be closer in time to targetDatetime.  Or targetDatetime might be later than any time in myPairs. So you need to check:
if i > 0 and i == len(myPairs):
    i -= 1
elif i > 0 and targetDatetime - myPairs[i-1][0] < myPairs[i][0]- targetDatetime:
    i -= 1

A: Dictionaries aren't organized for efficient near miss searches.  They are designed for exact matches (using a hash table).
You may be better-off maintaining a separate, fast-searchable ordered structure.
A simple way to start off is to use the bisect module for fast O(log N) searches but slower O(n) insertions:
def nearest(ts):
    # Given a presorted list of timestamps:  s = sorted(index)
    i = bisect_left(s, ts)
    return min(s[max(0, i-1): i+2], key=lambda t: abs(ts - t))

A more sophisticated approach suitable for non-static, dynamically updated dicts, would be to use blist which employs a tree structure for fast O(log N) insertions and lookups.  You only need this if the dict is going to change over time.
If you want to stay with a dictionary based approach, consider a dict-of-lists that clusters entries with nearby timestamps:
 def get_closest_stamp(ts):
      'Speed-up timestamp search by looking only at entries in the same hour'
      hour = round_to_nearest_hour(ts)
      cluster = daydict[hour]         # return a list of entries
      return min(cluster, key=lambda t: abs(ts - t))

Note, for exact results near cluster boundaries, store close-to-the-boundary timestamps in both the primary cluster and the adjacent cluster.

A: If your list is truly sorted and not just "roughly sequential", you can use a binary search. Have a look at the bisect module documentation for more information.


text:
Q: Workaround Kotlin Code Style restriction in Android Studio I would like to set more spaces options for Kotlin. In many other languages there is the "Within" options:

It seems they are hidden for Kotlin. Is there some way of unlocking them? What I already tried is to put following line in the codeStyle Project.xml:
<option name="SPACE_WITHIN_IF_PARENTHESES" value="true" />

But Android studio seems to ignore this for Kotlin.
Can anybody give me a hint where in the source code of android-studio these options are restricted?

A: In the Kotlin YouTrack, there is already a request to add this option (https://youtrack.jetbrains.com/issue/KT-17741) follow it for updates.


text:
Q: Java on Heroku/Jetty I am developing a DB based application on Heroku + Jetty stack. I am using Heroku Postgres as database. I have a DB utility class that connects to database and returns connection. However, I keep getting following errors:
If I run the following code, I get "No suitable driver found for jdbc:postgresql://ec2-54-243-131-210.compute-1.amazonaws.com/d4s7l8b2vf1o8c" error.
            URI dbUri = new URI(System.getenv("DATABASE_URL"));
            String username = dbUri.getUserInfo().split(":")[0];
            String password = dbUri.getUserInfo().split(":")[1];
            String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();
            System.err.println("***** dbUrl IS CREATED ******");
            con = DriverManager.getConnection(dbUrl, username, password);
            System.err.println("***** CONNECTION IS CREATED ******");

I came across some comments suggesting adding following code to load the driver
Class.forName("org.postgresql.Driver");

If I do this, I get a Null Pointer Exception after the line.
Please help in identifying the error if someone have had similar challenge earlier. Thanks in advance.
Regards,
Vineet

A: Thanks for following up but I just resolved the issue.
Had dependency missing from pom file.
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.0-801.jdbc4</version>
</dependency>

Thanks.


text:
Q: Xcode 9 - TvOS - Launch images not working - Interface Bug? Please help, my Launch screen images are not showing up. I have checked EVERYTHING and the only thing that looks out of place is in the interface the options for "Launch Image Source" is missing the "e" on source. I also think it should be showing "Launch Image File" but thats not there because I think it is failing to read this correctly out of some file and parse it.
My images are PNGs, with no Alpha layer, and the correct pixel sizes. I have tried cleaning and reloading, re-installing, etc. I have no warnings in Xcode.
I have tried to delete and recreate the Assets.xcassets folder, and delete and create the LaunchImage itself. I have tried removing the file extensions from the images as some suggested. The missing "e" in the interface seems to be the only thing out of place!


text:
Q: Poll MySQL DB in Socket IO & Node JS I am attempting to poll a MySQL DB by iterating every 2 seconds and retrieving all records created less than 2 seconds ago.
If I use setInterval it seems to occasionally miss a record. If I use setTimeout it only fetches the first iteration.
How can I fetch the data more reliably to include all data?
io.on('connection', function(socket) {
    authorize (socket, function(shop_id) {
        setInterval(function() {
            var sql = "SELECT * FROM `stats` WHERE `shop_id` = " + connection.escape(shop_id) +
            " AND `created` > DATE_SUB(NOW(), INTERVAL 2 SECOND)";
            var query = connection.query(sql, function(err, rows, fields) {
                if (err == null) {
                    console.log (rows);
                    socket.emit('newData', rows);
                }
            });
        }, 2000);
     });
});

A: MySQL is not designed to be pulled every 2 seconds. This is not a godo system architecture and you will experience more issues later on, definitely in regards to scalability.
setInterval is not precise and does not guarantee it will sleep for absolute 2000 ms, it may sleep for 2001, 2200, or even 50 hours.
To resolve this, store the most recent created that your NodeJS script fetched in a variable, and fetch all rows that are created AFTER your last received created. This will get every single record and won't miss records.
io.on('connection', function(socket) {

 authorize (socket, function(shop_id) {
        setInterval(function() {
            var lastCreated = toMySQLDate(new Date());
            var sql = "SELECT * FROM `stats` WHERE `shop_id` = " + connection.escape(shop_id) +
            " AND `created` > " + lastCreated + " ORDER BY `created` DESC";
            var query = connection.query(sql, function(err, rows, fields) {
                if (err == null) {
                    if (rows.length) {
                        lastCreated = toMySQLDate(rows[0].created);
                    }
                    console.log (rows);
                    socket.emit('newData', rows);
                }
            });
        }, 2000);
     });
});

function toMySQLDate(date) {
    return date.toISOString().slice(0, 19).replace('T', ' ');
}


text:
Q: Compute Instagram shortcode from an image filename Is it possible from an image filename compute a post's shortcode containing this image?
For example, for 130603078_209367414109482_797155749429813539_n.jpg the expected result is CIvvID_MEXO. (https://www.instagram.com/p/CIvvID_MEXO/)


text:
Q: How Do I create a Json Array in a Json Array? Here is my server that I am trying to parse
    [
  {
   "Hello": "How are You?",
"GoodBye": "I will see you later",
"Today": "How is it outside today",
"Date": "what is the date today",
"Weather": "10 degrees",
"Subcategory": [
  {
    "text": "Text goes here",
          }
{
    "text": "Text goes here",
          }
{
    "text": "Text goes here",
          }]
  [
  {
   "Hello": "How are You?",
"GoodBye": "I will see you later",
"Today": "How is it outside today",
"Date": "what is the date today",
"Weather": "10 degrees",
"Subcategory2": [
{
    "text": "Text goes here",
          }
{
    "text": "Text goes here",
          }
{
    "text": "Text goes here",
          }]
  [

Additionally, below I have my JSON parse for the text alone, however, I would like to get the text of the weather.

A: text key is inside Subcategory JSONArray, so need to get JSONArray first then get text String from it:
JSONObject currentQuestions = response.getJSONObject(x);
JSONArray arrSubcategory=currentQuestions.optJSONArray("Subcategory");
for (int y = 0; y < arrSubcategory.length(); y++) {
   JSONObject objectSubcategory = arrSubcategory.getJSONObject(y);
   String text = objectSubcategory.optString("text");
}

NOTE:
if Subcategory JSONArray key name is dynamic like Subcategory,Subcategory1,... then do it as:
JSONObject currentQuestions = response.getJSONObject(x);
Iterator<String> iter = currentQuestions.keys();
while (iter.hasNext()) {
    String key = iter.next();
    JSONArray arrSubcategory=currentQuestions.optJSONArray(key);
    for (int y = 0; y < arrSubcategory.length(); y++) {
       JSONObject objectSubcategory = arrSubcategory.getJSONObject(y);
       String text = objectSubcategory.optString("text");
    }
}

A: Just do like this.
JSONArray array=new JSONArray(Your JSONObject);

Now the above is the Main JSONArray.
JSONArray newArray=new JSONArray();
for(int i=0;i<array.length();i++){
 JSONObject objmain=array.getJSONObject(i);
 JSONObject obj=new JSONObject();
 obj.put("your key","your value");
 newArray.put(obj);
 objmain.put("New array key",newArray);
}


text:
Q: TS2451: Cannot Redeclare Block-scoped Variable In a main specification (core.spec.ts) file I have the following:
const reqCtx = require.context('.', true, /.+\.spec\.ts$/);
reqCtx.keys().forEach(reqCtx);
module.exports = reqCtx;

This results in the following error:

Cannot redeclare block-scoped variable 'reqCtx'.ts(2451)
  core.spec.d.ts(2, 15): 'reqCtx' was also declared here.

Does anyone know how to resolve this? Configuration file tsconfig.json follows:
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [],
    "allowJs": false,
    "checkJs": false,
    "jsx": "preserve",
    "declaration": true,
    "sourceMap": true,
    "outDir": "./bin",
    "rootDir": "./src",
    "removeComments": true,
    "noEmitOnError": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "inlineSourceMap": false,
    "inlineSources": false
  },
  "exclude": ["node_modules"]
}

A: try first to basically run npm ci it works with me all the time when ESLint show this error.
However adding this option "skipLibCheck": true to your compilerOptions will disable checking


text:
Q: Load photos from JSON one by one I have a JSON service, where I use some photos. I want to make a thumbnail gallery from it:
    -(void)fillPhotos:(NSMutableArray *)json{
    _loadingLabel.alpha=0;
    [SV setScrollEnabled:YES];
    if(json.count>0){
        NSDictionary *json_dictionary=[json objectAtIndex:0];
        NSInteger i=0;
        for(i=0;i<[[json_dictionary objectForKey:@"Photos"] count];i++){
        NSDictionary *photosDic =[[json_dictionary objectForKey:@"Photos"] objectAtIndex:i] ;
        NSString *imageUrl = [photosDic objectForKey:@"URI"];
        UIImageView* photo;
        CGRect viewRect;
            if(i % 2){
            viewRect = CGRectMake(164,146*(i/2)+10*(i/2), 146, 146);
            NSLog(@"par");
            }else{
            viewRect = CGRectMake(10,146*(i/2)+10*(i/2), 146, 146);
                NSLog(@"impar");
            }
            photo = [[UIImageView alloc] initWithFrame:viewRect];
            photo.image=[UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString: imageUrl]]];
            [SV addSubview:photo];
            SV.contentSize=CGSizeMake(320,146*i+146);
            [SV reloadInputViews];
        }
    }
}

It works Okay, but I have two problems. First I want the view to load photo by photo, so the user don't have to wait for the end ond the cicle to view all the photos at once. Second I want the photo to crop in the center, but just occupy the 146x146 frame. But if I put the Top in contentmode the photo pulls out from his frame.
Can you help me with that?

A: For the first question, you need to load the images asynchronously. Exactly how to do this is a little beyond the scope of an answer (and partly up to you), but you probably want to look into either NSURLConnection or NSOperation and NSOperationQueue.
For the second question, just set photo.clipsToBounds = YES.


text:
Q: pdo order by relevance, then order by another field I have a query that selects from my database and then orders by relevance:
select * from `table` where MATCH (`name`) AGAINST (:search IN BOOLEAN MODE) order by MATCH (`name`) AGAINST (:search2 IN BOOLEAN MODE) desc LIMIT :start, :limit

When these results are shown I want the user to have an option of filtering by price.  How can I do this when ORDER BY is already used for the relevance?
Can I create a view of the results and then query the view to filter by price?

A: you can Order by as many columns as you want. Syntax is:
ORDER by column1 desc, column2 asc, column3 desc ...

So you might want to have:
select * from `table` where MATCH (`name`) AGAINST (:search IN BOOLEAN MODE) order by MATCH (`name`) AGAINST (:search2 IN BOOLEAN MODE) desc, `price` asc LIMIT :start, :limit

If you want a price Range you have to build it into an WHERE clause
select * from `table` where MATCH (`name`) AGAINST (:search IN BOOLEAN MODE) AND `price` >= 5 AND `price` < 10 order by MATCH (`name`) AGAINST (:search2 IN BOOLEAN MODE) desc, `price` asc LIMIT :start, :limit


text:
Q: Maintain text color in selected option I have created a HTML form with 3 separate drop downs for  "Program", "Unit", "Location", I want the selected option text to maintain the text color when selected (defaults to black).
There 20+ programs, 100+units, 60+ locations. Program color matches corresponding Unit and Location colour.
This will allow form users to find selections easier and to proof there selections before submitting. (Do the colors match?)

    Program:
    <select type="list" name="Program">
        <option style="color:#000000">Select One</option>
        <option style="color:#FF0000">Select One</option>
        <option style="color:#000099">Select One</option>
    </select>

A: I would use jQuery for this: see http://jsfiddle.net/n9bzwy8m/1/
Create a function that runs every time the select is changed and change the color based on the value of the new selection.
jQuery:
var select = $('#program');

select.change(function() {
    if (select.val() == "One") {
        select.css('color','#000000');
    }
    else if (select.val() == "Two") {
        select.css('color','#ff0000');
    }
    else {
        select.css('color','#00ff00');
    }
});

HTML (I just added an id of #program to your select element):

    Program:
    <select type="list" name="Program" id="program">
        <option style="color:#000000">One</option>
        <option style="color:#FF0000">Two</option>
        <option style="color:#000099">Three</option>
    </select>

CSS:
select {
   -webkit-appearance: none;
   -moz-appearance: none;
   appearance: none;
}

The above CSS removed default browser styling from the select element, which I think might be the problem you have with the color defaulting to black. You can then add your own styling to the select - padding, border-radius, border, background etc.


text:
Q: My selected time from time picker is not set on TextEditingController? I use time picker. When I select time it selects but not display on the text-editing controller
Future _selectTime(BuildContext context) async {
    var picked = await showTimePicker(
        context: context,
      initialTime: selectTime,
     );
    setState(() {
      selectTime = picked;
      print('selectTime:$picked');
      _timecontroller.value = TextEditingValue(text: picked.toString());
    });
  }

A: Either of the following two options will work for you.
_timecontroller.value = TextEditingValue(text: selectTime.format(context).trim());

or
_timecontroller.value = TextEditingValue(text: selectTime.hour.toString()+":"+selectTime.minute.toString()));


text:
Q: Pass parameter from v-for to dynamically update b-tab title Only about 6 weeks into using vuejs and haven't looked at components at all, so sorry if this is a dumb question.
I am attempting to make the b-spinner component for tabs from bootstrap-vue update dynamically inside a v-for loop, with the parameter from the v-for being past to a computed property.
It works fine when not in a v-for.

  <template v-slot:title>
      Tab Title
  </template>
  ...

But when I try to pass the player property from the v-for, it breaks. When I try to pass player to the title slot, the entire parent component gets passed.

  <template v-slot:title="{player}">
     {{player['player-name']}}
  </template>
  ...

updateDone is a computed property as follows:
updateDone: function (player) {
  return _.every(Object.values(this.someObject[player['player-name']]), Boolean)
    },

But updateDone is never returned b/c player is an entire Vue object (presumably the parent component)
Hoping for some insight on this.

SOLUTION
  Thanks to Antonio

  <template v-slot:title>
     {{player['player-name']}}
  </template>
...

A: According to your comments, I realized that updateDone is a computed property.
Do not use computed property in this case.
You have to use method instead of computed property.
Why?
computed properties are cached and change only when their dependencies change.
In your case, there's no change in player while looping to render tabs. That means it will show the same results of updateDone property. :(
But a method will evaluate every time it's called. :)


text:
Q: How to disable image loading in capybara-webkit? Poltergeist driver has the feature where you can turn image loading off, how can I achieve the same with capybara-webkit?
This would make my app faster since we load some images using vanity urls.

A: I was debugging some request tests and I switched back and forth from capybara-webkit to poltergeist to selenium. There is a nice feature poltergeist has which is disable image loading and I discover this awesome dude made it possible for capybara-webkit.
https://github.com/thoughtbot/capybara-webkit/commit/646eabc68d5c6fe5bc0515492ee9ba04c5f49b8f
The problem is that is not well documented. Here is how you turn image loading off in capybara-webkit.
# spec_helper.rb
Capybara.register_driver :webkit do |app|
  driver = Capybara::Webkit::Driver.new(app)
  driver.browser.set_skip_image_loading true
  driver
end

A: Alan's answer didn't work for me but pointed me to this:
# spec_helper.rb
RSpec.configure do |config|
  config.before(:each, :type => :feature) do
    page.driver.browser.set_skip_image_loading true
  end
end

UPDATE: Actually, both settings seem to have no effect, or not always. Scratching my head...

A: Capybara docs suggest you want:
Capybara::Webkit.configure do |config|
  config.skip_image_loading
end


text:
Q: ASP.Net web service large URL We have to send a large packet to an ASP.Net web service through the URL. We cannot use POST for certain reasons, so we are URL encoding an XML package and we make a GET request to the service.
http://service.example.com/collect?content=AAAAAAAA...(+5000 characters)

The service responds with

Error 404 - File or directory not found.

I have read that there is no error code for max-content-length-exceeded so IIS sends back this 404 error. Knowing that, I have changed the configuration in the following way to allow large requests:
Changed query string length, max URL length, max request length and deactivated validation
<httpRuntime
    requestValidationMode="2.0"
    maxQueryStringLength="262144000"
    maxUrlLength="262144000"
    maxRequestLength="262144000" />
...
<pages validateRequest="false" />
...
<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="262144000" />
        </requestFiltering>
    </security>
</system.webServer>

I still receive the same error. How do I make a request to my web service with an extremely large/long URL?
Update 1
I am not sending images. The content is something like:
<packet date="1243235246436">
    <param type="1" id="45">
        5
    </param>
</packet>

without the new line characters and URL encoded.
Update 2
After setting the limits to a larger number in the IIS Request Filtering the 404 is now transformed to

HTTP Error 400. The size of the request headers is too long.

This is because the size of the headers is too large now. Tried to follow the instructions from this article by adding the MaxFieldLength and MaxRequestBytes registry entries, but I am still capped at 16k URL length.
What can I do to be able to send 1,000,000 long URLs? Is this even possible? What can I do to send at least 65k long URLs? This is the max length a header can have, but my settings are not taken into consideration.

A: The MSDN documentation of maxQueryStringLength also talks about IIS filtering in case of very long URLs. Have you checked this ?
The property names mentioned there are a bit different: maxQueryString, maxUrl.

A: A GET request is only limited by a browser's limit on the length of the URL string.
In IE it is 2,083 characters, minus the number of characters in the actual path. Other browsers do not have a clearly defined limit on the length of the URL string. These articles might be helpful to you.
http://www.boutell.com/newfaq/misc/urllength.html
http://support.microsoft.com/kb/q208427
RFC 2616, "Hypertext Transfer Protocol -- HTTP/1.1," does not specify any requirement for URL length, so browsers are free to stipulate what they deem fit.


text:
Q: How can I mock an ObjectMetadata object I have the below method:
private boolean success(String key) {
    if (cachedStatus.containsKey(key)) {
      return cachedJobsStatus.get(key).booleanValue();
    }
    String status = String.format("%s/%s", key, SUCCESS);
    ObjectMetadata meta = getMetadata(key);
    Boolean isOK = Boolean.FALSE;
    if (meta != null) {
      isOK = Boolean.TRUE;
   }
    cachedStatus.put(objectKey, isOK);
    return isOK.booleanValue();
}

I created this test:
public void successTest() throws Exception {
    String key = "data1-1-33-a.txt/part-00002-attempt_201711232056_0000_m_000002_2";

    //test when _SUCCESS exists
    boolean result = Whitebox.invokeMethod(APIClient, "success", key);
    Assert.assertEquals("successuccessful() failed even when _SUCCESS exists",
        true, result);

I believe the test is failing because meta never exists so isOK doesn't get set to true.
To get the test working properly I think I must create a mock for meta but I'm not sure how. Can anybody please advice?
This is the getMetadata() method:
protected ObjectMetadata getMetadata(String key) {
    try {
      ObjectMetadata m = client.getMetadata(bucket, key);
      return m;
    } catch (AmazonClientException e) {
      LOG.warn(e.getMessage());
      return null;
    }
}

A: Probably the most easy way would be to mock your client.
@RunWith(MockitoJUnitRunner.class)
public class MyTest {

   @Mock
   private AmazonS3Client client;   // or whatever

   @Mock
   private ObjectMetadata mockedObjectMetadata;

   @InjectMocks
   private MyClassToTest toTest; // Put your class that has "client" here

   @Test
   public void someTest() {
       Mockit.when(client.getMetadata(Mockito.anyString(), Mockito.anyString()).thenReturn( mockedObjectMetadata ); // voila

       boolean result = toTest("someRandomKey");
       ///etc.
   }

}


text:
Q: pivot with dynamic date columns in SqlServer 2012 & MySQL I have below data.
create table #temp
(
 date date primary key
 ,registrations int not null default(0)
 ,orders int not null default(0)
)

insert into #temp
(
date ,
registrations
,orders
)values('2017-05-01',30,40),('2017-05-02',60,30),('2017-05-03',109,98)

select * from #temp

for each date the data will keep on add. It is very dynamic. Is there anyway to pivot the data with dynamic dates if @from_dt and @to_dt provided as paramters. Output should look like below.
                 2017-05-01       2017-05-02        2017-05-03
registrations        30                 60              109
orders               40                 30              98

I have same data in SQLServer and MySQL databases.
any help is appreciated. Thanks in advance.

A: Declare @Date1 date = '2017-05-01'
Declare @Date2 date = '2017-05-02'  -- Notice only Two Days

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName([Date]) From #temp Where [Date] between @Date1 and @Date2  Order by 1 For XML Path('')),1,1,'')
Select  @SQL = '
Select *
From (
        select [Date]
              ,B.*
         From #temp
         Cross Apply (values (''Orders'',orders)
                            ,(''Registrations'',registrations)
                     ) B(Item,Value)
         Where [Date] between '''+convert(varchar(10),@Date1,120)+''' and '''++convert(varchar(10),@Date2,120)+'''
     ) A
 Pivot (sum(Value) For [Date] in (' + @SQL + ') ) p'
Exec(@SQL);

Returns
Item            2017-05-01  2017-05-02
Orders          40          30
Registrations   30          60


text:
Q: Bootstrap 3 - Where to place language toggler? I am converting my website to Bootstrap 3 and have a small 'language toggler' which I used to float on the right side. If you click on it the page 'magically' gets translated (it's just a redirect to another page)

The existing code, as shown below, is a bit annoying because the navbar-right element renders on two lines when there is not enough place. I haven't found any elegant solution for this, so I am considering moving the language toggler to another place on the page which won't be so affected by changes in size.
Is there a best practice for this?
Perhaps move it to another place, in the footer? I tried to see if there were any icons with flags, but no.

HOME

BLOG

SERVICES

REFERENCES

PARTNERS

CONTACT
                        US

                        en | de

A: Usually language changing put in the dropdown. Try like this:

HOME

BLOG

SERVICES

REFERENCES

PARTNERS

CONTACT
                        US

                Language

English

Deutch


text:
Q: How to write the argmax in a minimax problem? Suppose that $\mathcal{X} = \{x_{1},x_{2}\}$ and $\mathcal{Y}=\{y_{1},y_{2}\}$ are two sets, each containing two real numbers.
Now suppose I have some function $f: \mathcal{X} \times \mathcal{Y} \to \mathbb{R}$, and I want to solve the minimax problem:
\begin{align}\min_{x \in \mathcal{X}} \max_{y \in \mathcal{Y}} f(x,y).\end{align}
What is the proper notation for the value of $y^* \in \mathcal{Y}$ that obtains in the inner maximum? Would it be proper to write:
$$ y^* = \min_{x \in \mathcal{X}} \arg\max_{y \in \mathcal{Y}} f(x,y)?$$

A: Let:
$$y^{*}(x) = \arg \max_{y \in \mathcal{Y}} f(x,y)$$
Furthermore, let:
$$x^{*} = \arg\min_{x \in \mathcal{X}} f(x,y^{*}(x))$$
Then the value of $y$ that obtains in the inner maximum can be written as $y^{*}(x^{*})$.


text:
Q: How to display validation errors on form submit I have a simple form with only input field name, email. On my view page, I have form where customer's email can be entered and saved in ajax way. This is my view page:
_form.html.erb
   <%= form_for @customer, :remote=>true do |f| %>

        <%= f.text_field :email, :maxlength => 30, :placeholder => "Email", :id => "ecustomer" %>
        <%= f.submit "Save", :class => "btn btn-primary btn-large" %>
   <% end %>

This is my create.js.erb
  <% if @customer.errors.any? -%>
    $('<%= escape_javascript(render :partial => "error", :locals => {:target => @customer })%>').appendTo('#errors')
  <% else -%>
    $("<%= escape_javascript(render @customer) %>").prependTo("table.table.customers tbody");
  <% end -%>

I have put validation of presence and uniqueness on email. And for displaying validation error, i have partial, _error.erb:

<%= pluralize(@customer.errors.count, "error") %> prohibited this user from being saved:

  <% @customer.errors.full_messages.each do |msg| %>

<%= msg %>

  <% end %>

But still my validation errors are not visible. I am not getting whats going wrong here. Can anybody help me how to get it work?
Thank you.

A: Try adding a Try-Catch block to your JS view:
<% if @customer.errors.any? -%>
  try {
    $('<%= j(render :partial => "error", :locals => {:target => @customer })%>').appendTo('#errors');
  } catch( e ) {
    console.log( e );
  }
<% else -%>
  try {
    $("<%= j(render @customer) %>").prependTo("table.table.customers tbody");
  } catch( e ) {
    console.log( e );
  }
<% end -%>

If the block doesn't log, you're probably dealing with a syntax error.


text:
Q: jquery datepicker parse date wildcard I'm looking for the right wildcard character to use with jquery.datepicker.parseDate() in the doc
it says to use '...' for literal text and also "anything else - literal text". The problem comes when it hits the 'th', 'rd', 'nd', or 'st' that comes after the day number.
I have tried
$.datepicker.parseDate('M d... 2012', 'Jun 28th, 2012');

and it didn't work. Any suggestions?

A: Currently you can't do this with parseDate, see Adding "st, nd, rd, th" to jquery datepicker and the following pull request to add such functionality - https://github.com/jquery/jquery-ui/pull/438.
I would recommend removing 'st', 'rd', 'nd', and 'th' from the end of the day before calling parseDate and then using this.
$.datepicker.parseDate('M dd yy', 'Jun 28th 2012');

While not ideal this will work too.
var myDate;

try {
    myDate = $.datepicker.parseDate('M ddth yy', 'Jun 28th 2012');
} catch (e) {}
try {
    myDate = $.datepicker.parseDate('M ddst yy', 'Jun 28th 2012');
} catch (e) {}
try {
    myDate = $.datepicker.parseDate('M ddrd yy', 'Jun 28th 2012');
} catch (e) {}
try {
    myDate = $.datepicker.parseDate('M ddnd yy', 'Jun 28th 2012');
} catch (e) {}


text:
Q: Silex and Doctrine2: Class not found with YML entities I'm using Doctrine ORM with Silex via the Doctrine ORM Service Provider but I'm getting a MappingException with "class does not exist" each time I try to load data from the entity.
The exception:
MappingException in MappingException.php line 96: Class 'Project\Database\Mappings\Users' does not exist

File structure:
.
├───App
│   ├───Config
│   ├───Controllers
│   ├───Logs
│   └───Views
├───Doctrine
│   ├───Mappings
│   └───Repositories

I have my Entities in Doctrine\Mappings, defined as
Project\Database\Mappings\Users:
  type: entity
  repositoryClass: Project\Database\Repositories\UsersRepository
  table: users
  schema: transcribe
  id: [...]
  fields: [...]

I have the service registered like so (located in App/init.php):
// Register Doctrine ORM service
$app->register(new DoctrineOrmServiceProvider, [
    'orm.em.options' => [
        'mappings' => [
            [
                'type' => 'simple_yml',
                'namespace' => 'Project\Database\Mappings',
                'path' => __DIR__ . "/../Doctrine/Mappings",
            ]
        ]
    ],
]);

And in my sample controller (App/Controllers/HomeController.php),
class HomeController
{
    protected $twig;
    protected $repo;

    public function __construct(Twig_Environment $twig, EntityManager $em)
    {
        $this->twig = $twig;
        $this->repo = $em->getRepository("Project\Database\Mappings\Users");
    }
}

My route for the sake of completion (App/routes.php):
use Project\App\Controllers\HomeController;

// Register controllers
$app['home.controller'] = function () use ($app) {
    return new HomeController($app['twig'], $app['orm.em']);
};

// Define routes
$app->get("/", "home.controller:index");

I do have the autoloader configuration set in composer.json:
"autoload": {
    "psr-4": {
        "Project\\App\\": "App",
        "Project\\Database\\": "Doctrine"
    }
}

I wasn't able to find anything in the Doctrine or service provider documentation that stated I had to do anything special beyond that to make YAML entities work.


text:
Q: Estimating Irreducible error from kappa statistics for medical applications In many medical applications that involve some form of classification the data is annotated by expert humans (e.g. histopathologists, radiologists). This is then taken as the ground-truth. However, it is known that these experts often disagree with each other, and in the absence of a definitive label, we can rarely know who is correct. This disagreement is often quantified by Kappa statistics.
When assessing the performance of a machine learning classifier, it is useful to compare its performance (say using accuracy) to an expert human - this gives us an idea of the irreducible (Bayes) error, which can be a benchmark for classifier performance and give an idea of any degree of under-fitting. However, in the case where there is significant variation in experts' annotations, and with no recourse to the 'true' label, we do not have a direct measure for benchmark performance.
Hence, my question is whether we can use Kappa statistics to say anything useful about the irreducible error of a dataset?


text:
Q: How to get value from IMAP (hazelcast) given the list of keys? Problem we are trying to solve:
Give a list of Keys, what is the best way to get the value from IMap given the number of entries is around 500K?
Also we need to filter the values based on fields.
Here is the example map we are trying to read from.
Given IMap[String, Object]
We are using protobuf to serialize the object
Object can be say
Message test{ Required mac_address eth_mac = 1, ….// size can be around 300 bytes }

A: You can use IMap.getAll(keySet) if you know the keys beforehand. It's much better than single gets since it'll be much less network trips in a bulk operation.
For filtering, you can use predicates on IMap.values(predicate), IMap.entryset(predicate) or IMap.keyset(predicate) based on what you want to filter.
See more: http://docs.hazelcast.org/docs/latest/manual/html-single/index.html#distributed-query


text:
Q: How to block until one of two Receivers has available data? I'm new to Rust and trying to set up a one-directional graph of nodes using Senders and Receivers from std::sync::mpsc. Right now I have it working when each node has exactly one parent and one child, like this:
fn run(mut self) {
    let parent = self.parent.unwrap();
    loop {
        match parent.recv() {
            Ok(input) => {
                self.value = (self.next_value)(input);
                match self.kid {
                    Some(ref k) => { k.send(self.value).unwrap(); },
                    None => {}
                }
            },
            Err(_) => {}
        }
    }

}

But what I really want to do is have two parent nodes, where the next_value function is evaluated and the child nodes notified whenever either parent node sends out another value. I can't just use the blocking recv() method twice, and using polling and a non-blocking try_recv() call would probably work, but it seems really inefficient.
Is there a better way to do this?

A: You want to use select!()
fn run(mut self) {
    // obtain parents
    loop {
        select! {
           resp = parent1.recv() => match resp {...}
           resp = parent2.recv() => match resp {...}
        }
    }

}

If you have a dynamic number of channels to receive on, use mpsc::Select


text:
Q: Merton 1972 efficiency frontier solution using linear algebra This is a problem I can follow using summation notation as done in Merton (1972) but I'm having trouble finding the same solution using linear algebra methods.
The problem of finding the frontier of mean variance efficient portfolios has been summarized in matrix algebra form from Merton (1972) thus:
Let $\Omega$ be the matrix of covariances, and we assume it is positive definite and non-singullar.
\begin{align} (1) \qquad \min \omega '\Omega \omega \\ \text{s.t.} \quad & \omega ' \mu = \mu_p \\ & \omega ' \ \iota = 1 \\  \end{align}
where $\omega$ is a vector of porportions of each stock to be invested in the portfolio $\mu$ is the vector of expected returns for all assets in the portfolio and $\iota$ is the conforming vector of ones.
Using Lagrangian multipliers (1) can be written as
\begin{align} (2) \quad  L = \omega ' \Omega \omega + \gamma_1(\mu_p - \omega ' \mu) + \gamma_2(1 - \omega ' \iota) \end{align}
where γ1 and γ2 are lagrange multipliers.
The standard FOCs for a critical point are:
\begin{align} (3) \qquad 2 \Omega \omega - \gamma_1 \mu - \gamma_2 \iota = 0 \end{align}
combining the restrictions above we find the solution
\begin{align} (4) \qquad  \omega_p = g + h \mu_p \end{align}
Where
$$\begin{align}
\quad
g = \frac{1}{D}[B(\Omega^{-1} \iota) - A(\Omega^{-1} \mu)]
\\ \text{and}
\end{align}$$
$$\begin{align}
\qquad & \quad
h = \frac{1}{D}[C(\Omega^{-1} \mu) - A(\Omega^{-1} \iota)]
\qquad
\end{align}$$
and
$$\qquad  A = \iota ' \Omega^{-1}\mu \qquad$$
$$\qquad  B = \mu ' \Omega^{-1} \mu \qquad$$
$$\qquad  C = \iota ' \Omega^{-1}\iota \qquad$$
$$\qquad  D = BC - A^2 \qquad$$
Can anyone show me how we get from (3) to the solution (4)?

A: First solve (3) for the optimal weights by multiplying by the inverse $\frac{1}{2} \Omega^{-1}$ to obtain
$$\tag{*}\omega = \frac{\gamma_1}{2} \Omega^{-1}\mu + \frac{\gamma_2}{2} \Omega^{-1}\iota .$$
Enforcing the constaints provides two linear equations for the unknown multipliers $\gamma_1/2$ and $\gamma_2/2$,
$$\tag{**}\mu_p = \omega' \mu =  (\Omega^{-1}\mu)'\mu \frac{\gamma_1}{2}  + (\Omega^{-1}\iota)' \mu\frac{\gamma_2}{2}, \\  1 = \omega' \iota =  (\Omega^{-1}\mu)'\iota \frac{\gamma_1}{2}  + (\Omega^{-1}\iota)' \iota\frac{\gamma_2}{2}.$$
Since $\Omega = \Omega'$ , we have $$(\Omega^{-1}\mu)' = \mu'(\Omega^{-1})' = \mu' (\Omega')^{-1} = \mu' \Omega^{-1}, \\ (\Omega^{-1}\iota)' = \iota'(\Omega^{-1})' = \iota' (\Omega')^{-1} = \iota' \Omega^{-1}. $$
Hence, (**) can be rewritten as
$$\mu'\Omega^{-1}\mu \frac{\gamma_1}{2}  + \iota'\Omega^{-1}\mu\frac{\gamma_2}{2} = \mu_p, \\  \mu'\Omega^{-1}\iota \frac{\gamma_1}{2}  + \iota'\Omega^{-1} \iota\frac{\gamma_2}{2}= 1.$$
With $A$, $B$ and $C$ as given, and noting that $A = \iota'\Omega^{-1}\mu =\mu'\Omega^{-1}\iota $ (since a scalar equals its transpose), the system of equations becomes
$$B \frac{\gamma_1}{2} + A \frac{\mu_2}{2} = \mu_p, \\ A\frac{\gamma_1}{2} + C \frac{\mu_2}{2} = 1.$$
From here, you should be able to solve for $\gamma_1/2$ and $\gamma_2/2$, substitute into (*)  and obtain the optimal solution for $\omega$ which you write as $\omega_p$.


text:
Q: How does visual studio 2015 resolve TypeScript typings (.d.ts files) I added the typings for datatables.net via nuget. After that I kept getting errors like:

Error TS2322  Type '{ dom: string; }' is not assignable to type
  'Settings'.   Property 'oFeatures' is missing in type '{ dom: string;
  }'.

I finally realized that the nuget package dropped two typings files in /scripts/typings:

*

*jquery.dataTables-1.9.4.d.ts

*jquery.dataTables.d.ts

Commenting out the entire 1.9.4 file fixed my issue, but this made me ask the question: How did visual studio determine to include that file to begin with?  I expected to need ///reference declarations at the top of the file but apparently not.  Does vs2015 just pick up all d.ts files?  Is there a way to exclude a file other than deleting it or commenting it out?

A: Visual studio should be able to pick up definitions automatically.
To exclude definition from project use "exclude" section of : tsconfig.json to specify what files to exclude.

A: JQuery DataTables changed rather dramatically (and, in my opinion, much for the better) with version 1.10.x. This is the jquery.dataTables.d.ts file.
If you are planning to use only version 1.10.x, you should simply delete the 1.9.4 version, which I presume was included for those still using the older versions.


text:
Q: Java: Sort a list of characters by frequency only using arrays I'm trying to sort a list of characters and output them by the order of frequency with their associated frequency. For example, if the user puts in "beeeerr", I want it to out put "e freq: 4, r freq: 2, b freq: 1"
Here's what I have so far:
public static void sort(String charInput) {
    int frequency = 0;
    char [] charArray = charInput.toCharArray();

    for (char charValue = ' '; charValue <= '~'; charValue++) {
        frequency = 0;
        for (int i = 0; i < charInput.length(); i++) {
            char compare = charArray[i];
            //charInput.charAt(i)
            if (compare == charValue) {
                frequency += 1;
            }
        }
        if (frequency > 0) {
            System.out.println(charValue + " freq: " + frequency);
        }
    }

}

The problem with this is it outputs the frequencies in alphabetical order. I can't figure out how to sort the outputs by their frequency. I know how to easily do this with Hashmaps or Arraylists, but I'm not allowed to use them. Any help would be much appreciated

A: //128 is for ascii, change it to 256 for extended ascii
//I assume all characters in the input are in ascii or extended ascii
public void frequencySort(String s) {
    int n = s.length();
    List<Character>[]res = new ArrayList[n+1];
    int []cnt = new int[128];
    char []ss = s.toCharArray();
    for(int i=0;i<n;++i){
        res[i+1]=new ArrayList<>();
        cnt[ss[i]]++;
    }
    for(int i=0;i<128;++i){
        if(cnt[i]!=0){
            res[cnt[i]].add((char)i);
        }
    }

    for(int i=n;i>0;--i){
        if(!res[i].isEmpty()){
            for(char c:res[i])
            System.out.println("input has "+i+" " +c);
        }
    }
}
input has 4 e
input has 2 r
input has 1 b

A: With Java 8 Stream API, you can usually perform such operations with one liners:
    str.chars().mapToObj(e->(char)e).collect(Collectors.toSet()).stream()
        .collect(Collectors.toMap(ch -> ch, ch -> str.length() - str.replaceAll(ch.toString(), "").length()))
        .entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
        .forEach(e -> System.out.println(e.getKey() + " freq: " + e.getValue()));


text:
Q: Asynchronous function with multiple emit events (futures in meteor) My use case is to read RSS feed items asynchronously and load them into a meteor collection.
I have the feedparser npm module that does the parsing. It emits three events .on('error'), .on('meta') and .on('readable) with three different outputs.
When I run it in fixtures.js, with just console.log statements to run the output, its working fine.
When I use the same code to insert into a collection, I get errors related to asynchronocity of the function (assuming something to do with fibers)
So, I want to make it into a meteor method using futures as below -
http://www.discovermeteor.com/patterns/5828399
I tried but could not wrap my head around handling multiple events in Futures.

A: If you just want to push something to db at one point, it's enough to synchronize this call. Other than that, you can do whatever you want asynchronously. For example:
var Fiber = Npm.require('fibers');
var item = {};

var onInit = function() {
    // do whatever with item
};

var onData = function() {
    // do whatever with item
};

var onFinish = function() {
    new Fiber(function(){
        Documents.insert(item);
    }).run();
};

A: Although Meteor is a great tool, I think node and its async insight is brilliant, and the best tool for what you are doing.  Keep as a plan b having this part of your project be a straight node app.
Otherwise,
async from meteor
and


text:
Q: Filter array and match at least one condition I'd like to solve the following problem: I would like to filter an array by certain conditions with Vue.js and lodash (or pure JavaScript).
My objects

*

*I got a list of Items. Each item contains (optional) categories.

*The object Car can have a category.

Array of Objects Items
"data": [
    {
      "id": 1,
      "title": "Item 1",
      "categories": [
        {
          "id": 4,
          "title": "category 4",
          "description": "",
        },
        {
          "id": 5,
          "title": "category 5",
          "description": "",
        }
      ]
    },
    {
      "id": 2,
      "title": "Item 2",
      "categories": []
    },
    {
      "id": 3,
      "title": "Item 3",
      "categories": []
    }
  ]

Object Car
{
  "category": {
    "id": 5,
    "title": "category 5",
    "description": ""
  },
  "title": "Test"
}

My goal
I would like to only show those Items, which are passing at least one of these rules:

*

*The Item has at least one category that matches the category of the Car

*The Item has no category set

My approach
I am using a computed value to filter this.items:
computed: {
        filteredItems: function () {
            let vm = this;
            return _.filter (this.items, function (item) {
                return _.includes (item.categories, vm.car.category );
            });
        }
    },

Current result:
filteredItems is always empty.

A: You need to do one more level of checking on categories because you need to test against each item inside it. With regular javascript you can do that with some() which will return true if any of the items match.

let data = [{"id": 1,"title": "Item 1","categories": [{"id": 4,"title": "category 4","description": "",},{"id": 5,"title": "category 5","description": "",}]},{"id": 2,"title": "Item 2","categories": []},{"id": 3,"title": "Item 3","categories": []}]
let  car = {"category": {"id": 5,"title": "category 5","description": ""},"title": "Test"}

let filtered = data.filter(item => !item.categories || item.categories.length === 0 ||  item.categories.some(cat=> cat.id === car.category.id))
console.log(filtered)

A: With lodash you'd need something like
result = _.filter(data, ({categories}) =>
    _.isEmpty(categories) ||
    _.some(categories, cat => cat.id === car.category.id))

If you'd like to compare the whole category objects, not just ids, then
_.filter(data, ({categories}) =>
    _.isEmpty(categories) ||
    _.some(categories, cat => _.isEqual(cat, car.category)
    ))


text:
Q: Changing the positioning of elements using just css I have a webform that has inputs wrapped in divs that look something like this
Name
tbFirstName  lblFirstName  tbLastName lblLastName

Here is the html markup for it

   Name:

    <input id="LastName" name="LastName" type="text" value="" />
    Last Name

    <input id="FirstName" name="FirstName" type="text" value="" />
    First Name

I was wondering on how i could change the output to look like this instead using just css
Name
tbFirstName  tbLastName
lblFirstName lblLastName

Thanks for any help.

A: .editor-field span {float: left; margin-right: 10px;} // the margin is optional
.editor-field input {display: block;}

A: I moved your labels before the inputs.
.editor-field span {float:left;}
.editor-field span label {display:block;}

Markup

   Name:

    Last Name
    <input id="LastName" name="LastName" type="text" value="" />

    First Name
    <input id="FirstName" name="FirstName" type="text" value="" />


text:
Q: Yearly contribution to reach given stock (compound interest) I'm working on a calculator to compute the final stock given a yearly contribution (either a fixed contribution or with a linear growth). The user provides the contribution for the first year, if he wants to increase this contribution yearly (the growth value is fixed, the user only chooses if he wants it or not), the interest rate and the number of years (compounding frequency is always yearly).
Calculate the final stock given those imputs isn't difficult, I simply use the Compound Interest formula for each year from $zero$ to $t$ and accumulate the results:
$$F = Py(1+i)^t$$
Where:
$F =$ Final value
$Py =$ Contribution on year $y$ (same each year or increased by a percentage)
$i =$ Interest rate
$t =$ Remaining years
But I don't have a clue about how to calculate (or at least approximate) the other way around. I.e. calculate the needed yearly contribution to reach a desired final stock, given the interest rate and the number of years, either with fixed contributions or increasing ones.

A: Let g be the (constant) growth rate and  $G=1+g$ the growth factor. And let r be the interest rate and $q=1+r$. Then the future value of the growing contributions  is
$F_n=C\cdot  q^{n-1}+ C\cdot q^{n-2}\cdot G+\ldots + C\cdot q\cdot G^{n-2}+C\cdot  G^{n-1}$
$C\cdot  q^{n-1}:$ The first contribution has to be compounded n-1 times and no growth.
$C\cdot  G^{n-1}:$ The n-th contribution has grown n-1 times and no compounding.
$F_n=C\cdot \left[  q^{n-1}+  q^{n-2}\cdot G+\ldots + q\cdot G^{n-2}+  G^{n-1} \right]$
$q\cdot F_n=C\cdot \left[  q^{n}+  q^{n-1}\cdot G+\ldots + q^2\cdot G^{n-2}+ q \cdot G^{n-1} \right] \quad \quad \quad (1)$
$G\cdot F_n=C\cdot \left[ \ \ \quad  q^{n-1}\cdot G+  q^{n-2}\cdot G^2+\ldots + q\cdot G^{n-1}+  G^{n} \right] \quad (2)$
Substracting (2) from (1)
$(q-G)\cdot F_n=C\cdot (q^n-G^n)$
$\boxed{F_n=C\cdot\frac{q^n-G^n}{q-G}}$

A: Your formula is $\sum_{t=0}^n P_y(1+ i)^t$.  That is the same as the "geometric sum" $\sum_{t= 0}^n ar^t$ for which a formula is known:  $\frac{a(1- r^{n+1}}{1- r}$.    Here $a= P_y$ and r= 1+ I so that becomes
$F=\frac{P_y(1- (1+ i)^n)}{i}$.  So $P_y= \frac{Pi}{1- (1+i)^{n+1}}$

A: There is an exact formula for this (or rather, two formulas, one with the "growth value" and one without) which you might be able to deduce from the answer already posted. But here is another way of looking at the problem:
Consider the case where the user opts for a "growth value", since
you can easily deduce the "no growth value" solution by setting the
growth value to zero.
Now observe that the contribution in each successive
year is proportional to the initial amount.
That is, suppose two users try your program, and one enters $P_0 = 100$
and the other enters $P_0 = 200$.
It is easy to see (and not hard to prove) that in each successive year,
the second user's contribution will be exactly twice as much as the
first user's contribution.
(The exact formula is of the form $P_t = P_0 k^t$, where $k$ is a factor determined by the "growth value".)
Furthermore, as you already know, the final value of each year's contribution
is proportional to that year's contribution.
That is $F_y$ (final value for year $y$) is proportional to $P_y$.
But if $F_y$ is proportional to $P_y$, and $P_y$ is proportional to $P_0$,
then $F_y$ is proportional to $P_0$.
Moreover, since this is true for each of the $F_y$ individually, it is also
true for their sum.
So the final total, at the end, will be exactly proportional to $P_0$.
So one way to solve your problem without working out the complete
closed-form equation for the total at the end,
is simply to try the input $P_0 = 1$ and see what total you get at the end.
Then scale this up as needed to achieve the desired total.
For example, suppose that when you set $P_0 = 1$, the sum of all your
$F_y$, that is, your final stock, is $10$.
Then what $P_0$ will produce a final stock of $20$?
What if you want a final stock of $100$, then what should be $P_0$?
The same trick works if you find that the final stock is $15.31456$ when
$P_0 = 1$, and you want to find $P_0$ that will make the final stock be $5000$.
The only difference is that the answer would not be so easy to guess by
mental arithmetic as it was for my first couple of examples.