text:
Q: JPA - How to update child object in OneToMany relationship? I have a Customer class where each customer can have multiple Products. The class is as follow:
@Entity
@Table(name = "customer")
public class Customer {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "firstName")
private String firstName;

@Column(name = "lastName")
private String lastName;

@OneToMany(targetEntity=Product.class, mappedBy = "customer", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
@JsonManagedReference
private List<Product> products = new ArrayList<>();

//getters and setters here

}

and the Product class holds OneToOne relation with other Classes and it is as follows:
@Entity
@Table(name = "product")

public class Product {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne(targetEntity=Customer.class, fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id")
@JsonBackReference
private Customer customer;

@OneToOne(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
@JsonManagedReference
private SomeType1 someType1;

@OneToOne(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
@JsonManagedReference
private SomeType2 someType2;

@OneToOne(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
@JsonManagedReference
private SomeType3 someType3;

@OneToOne(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
@JsonManagedReference
private SomeType4 someType4;

//getters and setters here

    }

I am trying to achieve following functionality with this:
Given Customer ID and Product ID, update the values in SomeType1, SomeType2, SomeType3 classes. I am getting the updated SomeType1, SomeType2, SomeType3 objects from UI and I want to update the values in DB. I already have PUT method in place for this.
Here's the PUT method:
@PutMapping(value = "customer/{id}/product/{product_id}")
@ResponseBody
public ResponseEntity<Product> updateProduct(@PathVariable final String id,
        @PathVariable final String product_id, @RequestBody final Product product) {
    Optional<Customer> customerInDb = customerService.getCustomerById(id);
    if (!customerInDb.isPresent()) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND,
                MessageFormat.format("Customer with id {0} does not exist.", id));
    } else {
        product.setId(Long.valueOf(product_id));
        product.setCustomer(customerInDb.get());
        Product savedProduct = customerService.createProduct(product);
        return ResponseEntity.ok(savedProduct);
    }
}

I am getting following error for this REST call:
javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [com.myapp.arg.entities.SomeType2#12]

What could be the reason for this?
createProduct method:
@Override
public Product createProduct(Product product) {
    Product savedProduct = productRepository.save(product);
    return savedProduct;
}

JSON input to the PUT method:
{
   "id":9,
   "someType1":{
      "id":9,
      "avg":20,
      "total":20
   },
   "someType2":{
      "id":9,
      "circum":45.0,
      "strength":45.0,
      "totalNav":0.0
   },
   "someType3":{
      "id":9,
      "tensile":87,
      "pull":128,
      "push":56,
      "upward":28.0
   },
   "measuredBy":"SJ",
   "addedDate":"2021-05-23",
   "type":"Prime"
}

A: you are using the same id for all of your entities. ID must be unique


text:
Q: Would have gotten loose(rope) Let's say you are watching an Indiana Jones movie, wherein Indiana Jones would have died if the rope was unloosen during a cliff climbing scene, which was a life-and-death situation. Can you say:

Oh! He would have been dead by now, if the rope was unloosen.

*

*(after reading the corrections) Oh! He would have been dead by now, if the rope had come loose.

*Oh! He would have been dead by now, if the rope was loosened.

Or

If the rope would have gotten loose, he will probably die.

*

*(''Have'' changed into ''had'') If the rope had gotten loose, he will probably  die.

I am not sure if I correctly used the verb loose, are they both correct?

A: If the rope had come loose, he would have died.
If the rope had come untied, he would have died.
If the rope had become untethered, he would have died.
A rope comes loose when it is tethered (secured) by a piton to a rock or tied around a rock and then comes undone where it is anchored. It becomes untethered.
A rope is loosened, when you are tied up by a bad guy (for example), and the bad guy makes the rope tying you up, looser, not so tight.

A: Loosen is an unusual word, in that loosen and unloose are synonyms, even though they look like they might be antonyms.
Two verbs you can use in your scenario are to loosen or to unloose. Again, even though they appear like they are antonymns, they can be used synonymously:

When he comes home from work, Ted loosens his tie.
When he comes home from work, Ted unlooses his tie.

To make matters even more confusing, the word loose can be used as a verb or as an adjective.
So, you could write your sentences in many ways, including:

He would have died if the rope was unloosed.
He would have died if the rope had loosened.
If the rope had loosed, he probably would have died.
If the rope had become loose, he probably would have died.

Quick definitions (all adapted from Macmillan, taken from OneLook):

*

*unloose (v.) to untie something, or to make it looser

*loosen (v.) to become or make something less tightly fastened or less firmly fixed

*loose (v.) to become or make loose, looser, or less tight

*loose (adj.) not firmly fixed or tied

redpajama_set_name: RedPajamaStackExchange


text:
Q: Took C/C++ code from Linux to Windows is really slow I have a program very basic with just functions and variables and performs some calculations. The build part is fine. there is only cout, adding, multiplying etc very elementary stuff.
On linux, program runs fine on eclipse cdt, (runs in about 3-4 seconds)
When the program runs on windows 7 on visual studio 2010 c++, took 163 seconds
when the program runs on windows 7 eclipse c++ with MinGW, alot
What is going on here??!!?!
EDIT: lets not call it c++, its just alot of C functions here, here is the code from the main()
    foutput1 = fopen(FILENAME1, "w");
foutput2 = fopen(FILENAME2, "w");
solveSystem();
OutputStepToFile();
iter++;
do
{
    temporalExternalChange(tim);
    do
    {
        solveSystem();
        iter++;
    } while (iter<T_FOUT);
    iter = 0;
    OutputStepToFile();
    tim+=dt*T_FOUT;
    if (fmod(tim,T_PRINT)<=0.0){cout << "\nt=" << tim << "ms";};
} while(tim<T_TOTAL);

SolveSystem() is the following (partial) which just functions that do calculations to some variables:
      void solveSystem()
      {

fsGCcGMPformation();        // !cGMP formation
falp1AdAct_IP3form();       // !Norepinephrine receptor
fIVoCC();                   // !Voltage dependent calcium current I_CaL
fIKv();                     // !Delayed rectifier current I_K
fIBKCa();                   // !Calcium-activated potassium
    ...
    ...
    ...
fVoltageChange();
performODEstep();
}

OutputStepToFile() function is simply using C style file output
   void OutputStepToFile()
   {
    fprintf(foutput1,"%g %g %g %g %g %g %g %g ",V_m, tim, Ca_i, Na_i, K_i, Cl_i, Ca_u, Ca_r);                                                       // 1
    fprintf(foutput1,"%g %g %g %g %g %g %g ",d_L, f_L, BKCa_a, KvD_a, KvD_i_slow, KvD_i_fast, KCNQ_a);      // 8
    fprintf(foutput1,"%g %g %g %g ",P_SOC, R_01, R_10, R_11);   // 15
    fprintf(foutput1,"%g %g %g %g %g %g %g %g %g\n", h_IP3, RS_G, RS_PG, G, IP3, PIP2, DAG, V_cGMP, cGMP);  // 22

    // Store Ca,K,Cl,Na ion channels
    fprintf(foutput2,"%g %g %g %g %g %g %g %g %g ", I_CaL,  I_CaT,  I_BKCa, I_KvD, I_KCNQ, I_K2P, I_Kir, I_KATP, I_CaCC);
    // Store ROCs/SOCs
    fprintf(foutput2,"%g %g %g %g %g %g %g ",   INa_NSC, IK_NSC, ICa_NSC, I_NSC, I_SOCNa, I_SOCCa, I_SOC);
    // store SR dynamic currents, co-transporters, pumps and exchangers
    fprintf(foutput2,"%g %g %g %g %g %g %g %g ",    I_up, I_tr, I_rel, I_IP3, I_PMCA, I_NaK, I_NCX, I_NaKCl_Cl);
    fprintf(foutput2,"%g %g %g %g %g %g\n",     I_stim, V_cGMPbar,  I_Catotm,   I_Natotm,   I_Cltotm,   I_Ktotm);
   }

A: The only reliable way to find out where your program is spending all that time is to profile it. That would show you the time spent in each method/function and you should be able to track down the delay. If you cannot use a profiler for some reason, you might just try inserting a few timing calls in critical stages of your code to isolate the location of the problem.
That said, my guess would be on the I/O part of your program (cout, printf ...). The calculations should compile to similar code on both architectures and, unless your are using external libraries, they should not be affected by the porting process. The I/O calls, on the other hand, could be affected by differences in the standard library and in how each OS handles buffering and I/O in general. Conceivably, there might also be some library function that is not well implemented on Windows.
An important piece of information would be how your program is behaving during those 160+ seconds. Is it burning the CPU at 100%, or is it idling waiting for something to happen?

A: One of the functions called inside solveSystem() may be behaving differently for some reason.
I suggest, you start by commenting out all the functions in solveSystem(). Check if it still take 160+ seconds on VC++. Enable one after the other the functions in solveSystem().


text:
Q: Why Angular's $http.get service not working? I'm having trouble with an example I found on W3Schools about Angular services, on this specific case $http.get one.
I have a json.php file where I have the next JSON:
{
  "bands": [
    {
      "name": "Red hot chilli peppers",
      "year": "2009",
    },
    {
      "name": "Maroon 5",
      "year": "2005",
    },
    {
      "name": "ACDC",
      "year": "2000",
    }

  ]
}

And the Angular and HTML code which should iterate over the object and show the data in it, but it's not working:
JavaScript
 var serviceTestApp = angular.module('myapp3', []);
    serviceTestApp.controller('controller3', function($scope, $http){
        $http.get('json.php').then(function(response){
            $scope.myData = response.data.bands;
        });
    });

HTML

      {{x.name}}

What am I doing wrong here? I use Angular 1.5.0

A: When you mean not working what exactly do you mean? Do you mean it's successful but doesn't return what you want? In which case you're probably pointing at the wrong thing in the object.
Or does it throw an error?
You should structure it like this:
$http.get('json.php').then(function(response){
   // Place a debugger statement here to see if it's successful
   $scope.myData = response.data.bands;
}, function(error) {
   // No breakpoint needed as you'll see the error in the console window
   console.error(error);
});

One other reason could be that you don't have the file in the right place. json.php means that I'd expect it to be in the same folder as the controller.


text:
Q: When and why does NSUserDefaults' synchronize method fail? When and why does NSUserDefaults' synchronize method fail? What is the best way to make sure that my values are actually written and commited to NSUserDefaults, so I wouldn't have any problems restoring state after application restart?

A: The synchronize method is a higher level API wrapper around the CFPreferencesSynchronize function. There's nothing about it in the documentation but I presume that synchronize just returns the result of CFPreferencesSynchronize. Since this CoreFoundation function can be used to synchronize host (admin) and network based preferences it can fail in some cases.
In the most common case where an app just synchronizes its user domain preferences (in the Library directory of the current user), the function usually does not fail. I think it's safe to just ignore the return value of synchronize. But that's just my opinion.

A: In some cases, my app was trying to write a nil value with a certain key, and that was causing synchronize to fail. Now I'm checking that value for nil before the save and the problem is fixed.

A: In my cases, I wrongly use NSUserDefaults, and it will fail.
  For example, I define my own object, and put it into NSUserDefaults or NSDictionary, it can be put, but it will fail when synchronize. Because NSUserDefaults doesn't support every kind of object.
 As I know, NSString, NSNumber, NSDictionary....you can google it how to make custom class can be stored in NSUserDefaults.


text:
Q: SP2010 Modal Dialog for Content Type "New" Form When you create a new document set, you are presented with a modal dialog such as the following:

I want to have this kind of "New Form" (modal) for my custom content type (with custom form).
Now, I know that I can create my own modal dialogs using the Javascript API (e.g. http://www.chakkaradeep.com/post/Using-the-SharePoint-2010-Modal-Dialog.aspx). Also there is the NewFormUrl property for a content type, where I can redirect the user upon creating a new item from my content type ( http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spcontenttype.newformurl.aspx) - this is not the same, because I think it is nicer to stay on the same page.
I still don't know how I would get Javascript to fire upon creating a new item from my content type, so I could call the modal dialog api. What I basically want is this:
New > MyContentType > User is presented with a form as in the Screenshot above > User enters some metadata > Item based on MyContentType is created with metadata entered by user.
Also when creating my own content type new form, would I need to recreate everything Microsoft has done so nicely for the Document Set (i.e. Save Button, Check-In, Copy/Paste)?

EDIT:
And then there is that: How to Open a List Form in a Modal Dialog Box

A: You should not have to worry about how the dialog launches, it should happen seamlessly from the ribbon new button no matter the content type. I would check two things:

*

*Is the site operating with v4 (sp2010) visual styles?

*Is the list configured to show forms in a dialog.
List Settings -> Advanced -> Dialogs -> Launch forms in a dialog? -> Yes
The list forms, NewForm.aspx, DispForm.aspx, EditForm.aspx are all full pages with master page wrappers and everything. SharePoint 2010 magic happens when "Launch forms in a dialog?" is turned on, and only the content of the form is displayed in the dialog.

A: try this
New Item:
javascript:EditItem2(event,"/_layouts/listform.aspx?ListId={YOUR_LIST_ID} &RootFolder=YOUR_ROOT_FOLDER &ContentTypeId=ITEM_CONTENTTYPE_ID");

but check this out
http://tuan-tomy.blogspot.com/2010/09/redirect-to-link-to-new-item-with.html


text:
Q: Ranking data in excel without skipping ranks I have a dataset of over 5000 line items. I need to calculate ranks based on various parameters. Currently I'm using the formula for ranking {=SUM(IFERROR(1/COUNTIF(H$5:H$194,IF(H$5:H$194<H5,H$5:H$194)),0))+1}
However, due to large dataset size, it is very inefficient and is taking hours to run. Can anyone suggest any alternate code for this?
Example:
If scores are given, I want the rank as displayed in Rank Column
Score    Rank
  88       9
   7       2
  45       6
  23       5
   2       1
  56       7
   7       2
  98      10
  12       3
  45       6
  23       5
  56       7
  86       8
  19       4

A: Yes, you can put the entire table into a PivotTable, and then keep pivottable sorted by value, with a serial number column next to it. Then run a
=VLOOKUP(...)

on the Pivottable values and pull-in the column of serial number for rank.
A bit convoluted but better than waiting for hours.


text:
Q: Quotient of finite pointed CW complex is a CW complex Let $X$ be a finite pointed CW complex (where the basepoint forms a $0$-cell) and $A$ be a CW subcomplex of $X$ containing its basepoint.
I am trying to determine if $X/A$ is also a finite pointed CW complex, and have had some issues with checking the Hausdorff property. I am aware that in many cases the quotient of a Hausdorff space is not necessarily Hausdorff.
It is clear that if $[x]$, $[y]$ are equivalence classes with a single point outside of $A$, then there exist disjoint $U$, $V$ open in $X/A$ with $[x]\in U$ and $[y]\in V$. With the remaining case where $[x]\neq A$ and $[y]=A$, it looks like I need to find disjoint $U,V$ open in $X$ with $x\in U$, $0_X\in V$ and $A\subseteq V$.
We have that $x\in e$ for some cell $e$ disjoint from $A$ and can use the attaching map $\Phi_e:D^n\to X$ to obtain $U$ open in $X$ with $U\cap e$ corresponding to a subset of an open ball centred at $x$ in $D^n$. I am puzzled about this because the closure of a cell outside of $A$ could include points inside $A$. How I can I prove that $X/A$ is Hausdorff? Have I missed something?


text:
Q: Como salvar o input radio dentro de uma tabela Laravel
Como dar um update no banco no caso o id=54 atualizando os inputs radio atender com value=a / compra com value=c.
Obs:

Essa e uma requisição de compra feita pelo usuario, eu gostaria de dar
  um update apenas no campo atendecompra de acordo com input radio
  acima.

                   @foreach($detalhes as $detalhe)

                          Atender <input type="radio" name="atendecompra[{{ print $i}}]" value="a" checked="true">

                          Comprar<input type="radio" name="atendecompra[{{ print $i}}]" value="c">

                      <?php $i++;?>
                      @endforeach

Controllher
public function update(Request $request, $id){

       $idproduto=$request->get('idproduto');
      $atendecompra=$request->get('atendecompra');
       $cont = 0;
        while($cont < count($idproduto)){
          $detalhe = new RequisicaoDet();
          $detalhe->idrequisicao=$id;
          $detalhe->atendecompra=String($atendecompra)[$cont];
          $detalhe->update();
          $cont=$cont+1;
        }
         return Redirect::to('almoxarifado/requisicao');
      }

Model
class RequisicaoDet extends Model
{
   protected $table         ='requisicaodet';
   protected $primaryKey    ='idrequisicaodet';
   public $timestamps       =false;
   protected$fillable       =[
   'idrequisicao',
   'idproduto',
   'qnt',
   'detalhe',
   'idcentrocusto',
   'atendecompra'
    ];
   protected $guarded       =[];
}

A: Para atualizar a instancia do Model no Laravel, você pode usar a seguinte sintaxe:
RequisicaoDet::find($id)->update([
  'atendecompra' => $request->get('atendecompra')
]);

Não ficou muito claro o motivo de você ter feito esse while aí com o idproduto, mas com o comando acima resolverá a sua pergunta, que é como atualizar o atendecompra para o id específico.
Se houver alguma duvida, diga que melhorarei a resposta.


text:
Q: How to get the global variable inside the method  class sample
 {
     public int i; //global variable
     public int[] arr = new int[10];
     public void fun(int i, int val)
     {
         Console.WriteLine(this.i); //I got Output is 11
         arr[i] = val;
         Console.WriteLine(arr[i]);
     }
 }

 class Program
 {
     static void Main(string[] args)
     {
         sample s = new sample();
         s.i = 1;
         s.fun(1, 7);
         Console.ReadLine();
     }
 }

How to get the global variable i inside the fun() method

Here the function variable name and global variable name are the same.

A: To access the field i within the fun() method, you can use the this keyword. For example:
class sample
{
    public int i; //global variable
    public int[] arr = new int[10];
    public void fun(int i, int val)
    {
        this.i = i; // assign the value of the function parameter to the field
        arr[i] = val;
        Console.WriteLine(arr[i]);
    }
}

Alternatively, you can also use a different name for the function parameter to avoid the naming conflict. For example:
class sample
{
    public int i; // field
    public int[] arr = new int[10];
    public void fun(int j, int val)
    {
        i = j; // assign the value of the function parameter to the field
        arr[j] = val;
        Console.WriteLine(arr[j]);
    }
}


text:
Q: How to initialize a variable of data type const WCHAR* GdipCreateFontFamilyFromName first parameter expects a const WCHAR*, how I could initialize the value of opt.fontName with it?
struct GDImDrawText
{
    HWND hWnd;
    ARGB fontColor;
    int fontSize;
    int fontStyle = 0;
    WCHAR* fontName;  // <--- Do i need to use another data type? which?
    int x = 0;
    int y = 0;
    int w;
    int h;
};

//...

GDI gdip;
GDImDrawText opt;

opt.fontColor = 0xffffff;
opt.fontSize = 14;
opt.fontName = L"Tahoma"; // <--- ???
opt.hWnd = hWnd;
opt.x = 20;

gdip.mDrawText(g, opt);

//...

void GDI::mDrawText(GpGraphics* g, GDImDrawText opt)
{
    GpFontFamily* fontFamily;
    GdipCreateFontFamilyFromName(opt.fontName, 0, &fontFamily);
    //...
}

Do I need to modify the declaration of fontName into the struct?

A: WCHAR is a wide character normally representing 16 bit instead of the default 8 bit of a char. It is used e.g to represent encoding standards like UTF-16 which can not be encoded with only 8 bits (like ASCII).
You initialized your wide char array correctly by specifying it with the L in front of the string. This tells the compiler that the string is in fact a wide char array instead of a "normal" char array.


text:
Q: nativebase Select is not taking _focus and _hover props I'm trying to create a custom dropdown component with nativebase but the Select component is not taking my _focus and _hover props.
Here is my component
import { Select } from 'native-base';
import { IDropdown } from './type';
import { styles } from './Dropdown.style';
import { Input } from '../Input/Input.component';

export const Dropdown = ({ options = [], ...props }: IDropdown) => {
    return (
        <Select
            variant="unstyled"
            _focus={{
                borderColor: 'ambar.500', // this right here
            }}
            {...props}
        >
            {options.map(({ label, value: optionValue }, index) => (
                <Select.Item
                    key={`dropwn-item-key-${label}-${index}`}
                    label={label}
                    value={optionValue}
                />
            ))}
        </Select>
    );
};

and my type.ts
import { ISelectProps } from 'native-base';

export interface IDropdownOption {
    label?: any;
    value?: any;
}

export interface IDropdown extends ISelectProps {
    /**
     * Defines if input is disabled
     */
    isDisabled?: boolean;

    /**
     * Defines if input value is invalid
     */
    isInvalid?: boolean;

    /**
     * Defines if input is read-only
     */
    isReadOnly?: boolean;

    /**
     * Defines input placeholder
     */
    placeholder?: string;

    /**
     * Defines dropdown options
     */
    options?: IDropdownOption[];
}

I've tried the https://docs.nativebase.io/select select and customize it with the _focus and _hover properties and it worked but not in my project. I need this to work in react and react-native


text:
Q: System requirements: What is the lightest impacting ubuntu flavor? I have been looking for a Linux alternative to windows due to the OS constantly eating up my system's memory and CPU usage, and i'm somewhat familiar with Ubuntu systems, but i want to know what flavor might be the best for my light-weight system.
Here are my specs:
Acer Aspire A114-32-C1YA
Processor Manufacturer  Intel®
Processor Type Celeron®
Processor Model N4000
Processor Speed 1.10 GHz
Processor Core Dual-core (2 Core™)

Display & Graphics
Graphics Controller Manufacturer Intel®
Graphics Controller Model UHD Graphics 600
Graphics Memory Technology DDR4 SDRAM
Graphics Memory Accessibility Shared
Standard Memory 4 GB
Memory Technology DDR4 SDRAM

Storage
Optical Drive Type No
Flash Memory Capacity 64 GB

Please let me know what flavors i should consider, thanks!

A: Lubuntu is generally considered the lightest Ubuntu distribution
you can download it here: https://lubuntu.net/downloads/


text:
Q: Compilation error with a boost::spirit parser I have a strange problem with a calculator made using boost::spirit. This calculator is supposed to take a string as argument representing a series of arithmetical expression separated by commas, like "a+4*5,77,(b-c)*4". It also allows the string "?" and returns the array containing a -1 in this case. The calculator is initialized with a SymTable, which is a template class argument to describe any class offering the [string] -> int operator (example: a map), to resolve the value of variables.
The following code works on my Ubuntu 10.4 with both gcc 4.6.2 and gcc 4.4, and both boost 1.47 and 1.48. It also worked in the past on a Cray Linux machine with gcc 4.5.3 and boost 1.47.
#include <boost/bind.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>

namespace sp = boost::spirit;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

namespace Damaris {

template <typename Iterator, typename SymTable>
struct Calc : qi::grammar<Iterator, std::vector<int>(), ascii::space_type>
{
        qi::rule<Iterator, std::vector<int>(), ascii::space_type> start;
        qi::rule<Iterator, int(), ascii::space_type> expr;
        qi::rule<Iterator, int(), ascii::space_type> qmark;
        qi::rule<Iterator, int(), ascii::space_type> factor;
        qi::rule<Iterator, int(), ascii::space_type> simple;
        qi::rule<Iterator, std::string(), ascii::space_type> identifier;
        qi::rule<Iterator, int(SymTable), ascii::space_type> value;

        /**
         * \brief Constructor.
         * \param[in] sym : table of symboles.
         */
        Calc(SymTable &sym) : Calc::base_type(start)
        {
                identifier = qi::lexeme[( qi::alpha | '_') >> *( qi::alnum | '_')];

                value   = identifier[qi::_val = qi::labels::_r1[qi::_1]];

                simple  = ('(' >> expr >> ')')
                        | qi::int_
                        | value(boost::phoenix::ref(sym));

                factor  %= (simple >> '*' >> factor)[qi::_val = qi::_1 * qi::_2]
                        |  (simple >> '/' >> factor)[qi::_val = qi::_1 / qi::_2]
                        |  (simple >> '%' >> factor)[qi::_val = qi::_1 % qi::_2]
                        |   simple;

                expr    %= (factor >> '+' >> expr)[qi::_val = qi::_1 + qi::_2]
                        |  (factor >> '-' >> expr)[qi::_val = qi::_1 - qi::_2]
                        |   factor;

                qmark   = qi::char_('?')[qi::_val = -1];

                start   = qmark
                        | (expr % ',');
        }
};

}

Today I tried again compiling the same code on the Cray machine (which has been upgraded since then, I think), I tried with gcc 4.6.2 and gcc 4.5.2, and both with boost 1.48 and 1.49, and I always get the same compilation error that I don't understand :
/nics/b/home/mdorier/damaris-0.4/common/Calc.hpp:74:3:   instantiated from 'Damaris::Calc<Iterator, SymTable>::Calc(SymTable&) [with Iterator = __gnu_cxx::__normal_iterator<const char*, std::basic_string<char> >, SymTable = Damaris::ParameterSet]'
/nics/b/home/mdorier/damaris-0.4/common/MetadataManager.cpp:45:79:   instantiated from here
/nics/b/home/mdorier/deploy/include/boost/spirit/home/qi/detail/assign_to.hpp:123:13: error: invalid static_cast from type 'const boost::fusion::vector2<int, int>' to type 'int'

The line 74 in Calc.hpp corresponds to the line "factor = ...".
The instantiation line indicated (MetadataManager.cpp:45) is the following:
layoutInterp = new Calc<std::string::const_iterator,ParameterSet>(*parameters);

with layoutInterp being of type Calc* and parameters being of type ParameterSet*.
Any idea where this error comes from? Thanks

A: I'm pretty sure you might have been rearranging stuff in your rules. In fact, the %= auto-rule expression assignments won't work because the synthesized type of the parser expression doesn't resemble an int.
Basically, you'd change
factor %= (simple >> '*' >> factor)[ _val = _1 * _2 ]
    |  (simple >> '/' >> factor)[ _val = _1 / _2 ]
    |  (simple >> '%' >> factor)[ _val = _1 % _2 ]
    |   simple;

expr   %= (factor >> '+' >> expr)[ _val = _1 + _2 ]
    |  (factor >> '-' >> expr)[ _val = _1 - _2 ]
    |   factor;

into
factor  = (simple >> '*' >> factor)[ _val = _1 * _2 ]
        | (simple >> '/' >> factor)[ _val = _1 / _2 ]
        | (simple >> '%' >> factor)[ _val = _1 % _2 ]
        | (simple) [_val = _1 ];

expr    = (factor >> '+' >> expr)[ _val = _1 + _2 ]
        | (factor >> '-' >> expr)[ _val = _1 - _2 ]
        | (factor) [_val = _1 ];

I have fixed up some small issues and created a SSCCE of your post that works, as far as I can tell 1:
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix.hpp>

namespace sp = boost::spirit;
namespace qi    = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace karma = boost::spirit::karma;
namespace phx   = boost::phoenix;

namespace Damaris {

    template <typename Iterator, typename SymTable>
    struct Calc : qi::grammar<Iterator, std::vector<int>(), ascii::space_type>
    {
        qi::rule<Iterator, std::vector<int>(), ascii::space_type> start;
        qi::rule<Iterator, int(), ascii::space_type> expr;
        qi::rule<Iterator, int(), ascii::space_type> qmark;
        qi::rule<Iterator, int(), ascii::space_type> factor;
        qi::rule<Iterator, int(), ascii::space_type> simple;
        qi::rule<Iterator, std::string(), ascii::space_type> identifier;
        qi::rule<Iterator, int(SymTable), ascii::space_type> value;

        Calc(SymTable &sym) : Calc::base_type(start)
        {
            using namespace qi;

            identifier = lexeme[( alpha | '_') >> *( alnum | '_')];

            value   = identifier[ _val = _r1[_1] ];

            simple  = ('(' >> expr >> ')')
                    | int_
                    | value(boost::phoenix::ref(sym));

            factor  = (simple >> '*' >> factor)[ _val = _1 * _2 ]
                    | (simple >> '/' >> factor)[ _val = _1 / _2 ]
                    | (simple >> '%' >> factor)[ _val = _1 % _2 ]
                    | (simple) [_val = _1 ];

            expr    = (factor >> '+' >> expr)[ _val = _1 + _2 ]
                    | (factor >> '-' >> expr)[ _val = _1 - _2 ]
                    | (factor) [_val = _1 ];

            qmark   = char_('?')[ _val = -1 ];

            start   = qmark
                | (expr % ',');

            BOOST_SPIRIT_DEBUG_NODE(start);
            BOOST_SPIRIT_DEBUG_NODE(qmark);
            BOOST_SPIRIT_DEBUG_NODE(expr);
            BOOST_SPIRIT_DEBUG_NODE(factor);
            BOOST_SPIRIT_DEBUG_NODE(simple);
            BOOST_SPIRIT_DEBUG_NODE(value);
            BOOST_SPIRIT_DEBUG_NODE(identifier);
        }
    };

}

int main(int argc, const char *argv[])
{
    typedef std::map<std::string, int> SymTable;
    SymTable symbols;
    Damaris::Calc<std::string::const_iterator, SymTable> calc(symbols);

    symbols["TheAnswerToLifeUniverse"] = 100;
    symbols["Everything"] = -58;

    std::string input = "3*4+5/4, TheAnswerToLifeUniverse + Everything";
    std::string::const_iterator f(input.begin()), l(input.end());
    std::vector<int> data;

    if (qi::phrase_parse(f,l,calc,ascii::space,data))
        std::cout << "output: " << karma::format(karma::int_ % ", " << karma::eol, data);
    else
        std::cout << "problem: '" << std::string(f,l) << "'\n";

    return 0;
}

Output:
output: 13, 42

1 gcc 4.6.1, boost 1_48


text:
Q: Message: javascript error: missing ) after argument list in execute script When I run the following:
self.driver.execute_script("document.getElementByXpath('//input[@id='someid']').value='someValue';

It gives an error
selenium.common.exceptions.JavascriptException: Message:
javascript error: missing ) after argument list

A: You are using the same kind of quote in two different levels of parsing, and so '//input[@id=' is interpreted as one string literal, after which someid is unexpected.
Change:
document.getElementByXpath('//input[@id='someid']')

To:
document.getElementByXpath('//input[@id=\"someid\"]')


text:
Q: Paginação de Texto em PHP e Mysql Tenho um texto grande com muitos caracteres e preciso fazer ele ficar em umas 5 páginas com opção de PROXIMA PÁGINA e PÁGINA ANTERIOR.
Pesquisei e não encontro nenhum tutorial sobre o assunto, alguém pode me ajudar?
Preciso de uma maneira diferente de javascript que encontrei aqui.
O código abaixo está reduzido para testes.

<?
include("config/config.php");

////////////////NOVO MYSQLI////////////////
$seleciona = "SELECT * FROM news_ind where id = '$idnoticias2'";
$result = $conecta->query($seleciona);
$ver = $result->fetch_array(MYSQLI_ASSOC);
////////////////NOVO MYSQLI////////////////

$noticia = $ver["noticia"];

?>

<? echo $noticia; ?>

A: A "páginação" pode ser feita tanto na sua base de dados quanto no código. Independentemente de onde for feita, a lógica é a mesma.
O 1o passo é determinar o tamanho de letras de cada página e isso pode ser fixo no seu código. O 2o passo é calcular a quantidade de páginas. O 3o é fazer a páginação e pegar o conteúdo da página atual.
Considerando que as páginas têm até 100 caracteres e um texto com 450 caracteres, poderia ser feito:
$tam_pagina = 100;
$tam_texto = strlen($noticia); // ex: 450
$pagina_atual = 2; // iniciando em 0; neste caso vai até 4
$total_paginas = ceil($tam_texto / $tam_pagina);
$inicio_pagina = $pagina_atual * $tam_pagina;

$texto_pagina = substr($noticia, $inicio_pagina, $tam_pagina);

Ressalva:

*

*É preciso considerar que a notícia tem somente textos (não sejá HTML ou markdown, por exemplo, pois parte de um marckup pode ficar numa página e a outra parte em outra página.

Alternativas:

*

*Vc pode criar um marcador próprio para definir onde o conteúdo é dividido em páginas, permitindo ter markups no conteúdo (como o "leia mais" do Wordpress - <!--more-->);

*Vc pode criar um controle na sua tabela (ou em outra tabela) indicando os índices do substring, permitindo ter páginas com tamanhos diferentes, por exemplo.


text:
Q: IDE para desenvolvimento em VueJS Estou a iniciar-me no vueJS e gostava de saber que IDE aconselham?
Eu uso o netbeans para HTML, PHP, JS, etc. Dá para integrar o vueJS no netbeans?
Existem alguns pluing para isso?

A: Alguns editores de vueJS:

*

*Atom408 com language-vue730

*Sublime Text 3203 com vue-syntax-highlight432

*Vim ou Neovim213 com vim-vue214
Uso Pessoal
Eu particulamente utilizo o Sublime, acho bem leve e gosto muito dos atalhos que ele proporciona.
vue no Netbeans
O arquivo .vue é um tipo de arquivo html, você pode adicionar destaque de sintaxe no Netbeans:
Tools > Options > Miscellaneous > Files
Adicione uma nova extensão de arquivo:
Extensão de arquivo: vue
Tipo de arquivo associado (MIME): arquivos HTML (texto / html)
Não é perfeito, mas parece que não há nenhum plugin realizar algo melhor que isso.


text:
Q: How to right set height of NSTableCellView with NSTextField? Greets!
I have a View-based NSTableView with Custom View as a cell (NSTableCellView class).
There is NSTextField inside custom cell.
I need to display 3 lines of text inside NSTextField and after clicking on cell content must grow up to fit full text.
So, I need to increment height of NSTextField and height of NSCTableCellView by click in other words.
Alghoritm is:

*

*Handle click on NSTableCellView

*Calculate new sizes of NSTextField and NSTableCellView

*SetFrameSize to NSTextField through IBOutlet

*Store new NSTableCellView height value in class and invoke function "RowHeightChanged" through Notification Center

*Set new row height from class value

This is a code snippet: (i erased some unusefull things)
TickCellTableView:
    @implementation TickCellTableView

    // Other Constants
    @synthesize textFieldInitHeight = _textFieldInitHeight;
    @synthesize rowHeight           = _rowHeight;
    @synthesize rowIndex            = _rowIndex;

    - (void)mouseDown:(NSEvent *)theEvent {

        if (![self.superview isKindOfClass:[NSTableCellView class]])
            [super mouseDown:theEvent];

        CGFloat TextFieldFitHeight = [self getHeightForStringDrawing: self.textField.stringValue
                                                          withFont:[self.textField font]
                                                      forTextWidth:[self.textField frame].size.width + 10.0];

        if ([self.textField frame].size.height < TextFieldFitHeight)
        {
            NSSize size = [self.textField frame].size;
            size.height = TextFieldFitHeight;

            [self.textField setFrameSize:size];

            self.rowHeight = [self frame].size.height + (TextFieldFitHeight - _textFieldInitHeight);

            [[NSNotificationCenter defaultCenter] postNotificationName:@"RowHeightChanged"

                                                                   object:self.rowIndex];
            }
        }
@end

NSTableView Delegate:
@implementation DisplayTicksView

- (void)awakeFromNib
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(RowHeightChanged:)
                                                 name: @"RowHeightChanged"
                                               object:nil];
 }

-(void)RowHeightChanged:(NSNotification *)notification
{
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:[notification.object integerValue]];

    [tableView noteHeightOfRowsWithIndexesChanged:indexSet];
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    return [ticksArray count];
}

@end

The problem is when i clicked on the NSTextField it's frame grow up just for the second and return to init size, after that starts animation to set property height of cell.
In result - Cell height is up, but NSTextField none. I tried to disable animation - no result. How can i fix that?
Appologise my English :)


text:
Q: Parallel ForEach using a ConcurrentBag not working as expected I have this code that processes items in a list:
    static readonly object _Lock = new object();

    public class Item
    {
        public string Name;
        public string ID;
    }

    static void Main(string[] args)
    {
        var items = new List<Item>
        {
            new Item { Name = "One", ID = "123" },
            new Item { Name = "Two", ID = "234" },
            new Item { Name = "Three", ID = "123" }
        };

        var itemsProcess = new ConcurrentBag<Item>();
        Parallel.ForEach(items, (item) =>
        {
            Item itemProcess = null;
            // lock (_Lock)
            {
                itemProcess = itemsProcess.FirstOrDefault(a => a.ID == item.ID);
            }
            if (itemProcess != null)
            {
                Console.WriteLine($"Item [{item.Name}] was already processed as [{itemProcess.Name}]");
            }
            else
            {
                itemsProcess.Add(item);
                Console.WriteLine($"Processing item [{item.Name}]");
                Thread.Sleep(1000); // do some work...
            }
        });

        Console.ReadKey();
      }

I am basically using the ConcurrentBag to check for the existence of an object based on several conditions.
I am expecting to always get an output like (order may vary):
Processing item [One]
Item [Three] was already processed as [One]
Processing item [Two]

But I sometimes get an output, which suggests my code is not thread safe:
Processing item [Three]
Processing item [One]
Processing item [Two]

So my assumption that itemsProcess.FirstOrDefault() will block was wrong.
Using the lock does not change anything. obviously, something is wrong here, and I really can't understand why?
I know I can "solve" this in other ways (one is to prepare the list before entering Parallel.ForEach()), but I really like to know why is this behavior?

A: You have 2 independent operations within your parallel loop: FirstOrDefault and Add.
ConcurrentBag cannot ensure thread-safety between these 2 operations.
An alternative would be ConcurrentDictionary, which has a GetOrAdd method that will only add an item when the key is not present:
var itemsProcess = new ConcurrentDictionary<string, Item>();
Parallel.ForEach(items, item =>
{
    // Returns existing item with same ID or adds this item
    var itemProcess = itemsProcess.GetOrAdd(item.Id, item);
    if (!object.ReferenceEquals(item, itemProcess))
    {
        Console.WriteLine($"Item [{item.Name}] was already processed as [{itemProcess.Name}]");
    }
    else
    {
        Console.WriteLine($"Processing item [{item.Name}]");
        // do some work...
    }
});

If you then need the processed Items as an ICollection, they can be accessed via itemsProcess.Values.

A: The reason why, is because there is still a data race... 2 threads can still read and add to the ConcurrentBag in a non-thread safe manner. Using any of the concurrent collections only means you have a structure which is self-consistent, but it doesn't protect you from writing other non-thread safe code
You had the right idea with a lock
var itemsProcess = new Dictionary<string, Item>();
Parallel.ForEach(items, (item) =>
{

   lock (_Lock)
   {
      if (itemsProcess.TryGetValue(item.ID, out var val))
      {
         Console.WriteLine($"Item [{item.Name}] was already processed as [{val.Name}]");
         return;
      }

      itemsProcess.TryAdd(item.ID, item);
   }

   Console.WriteLine($"Processing item [{item.Name}]");
   Thread.Sleep(1000); // do some work...

});

Note : You could also filter list for duplicates before you process it in parallel, this saves needing a lock or collection at all

A: Without resorting to a lock, you can "abuse" a ConcurrentDictionary and avoid all locking here to ensure uniqueness.
Add items to your dictionary by their ID, the data structure will stay consistent and once that's done you can work with the dictionary.Values field to get the unique items.
P.S.: I feel like your example is much more involved because no one does a Distinct() using Parallel.ForEach() which is what your code amounts to.
Finally, to address the reason why this is happening, when it comes to concurrency this is almost always an anti-pattern and doesn't do what the author meant here.
if(!collection.Contains(item))
      collection.Add(item);

By the time that Contains() has executed and returned false another thread could have executed the same, raced ahead and added the same item.
This race condition is why nearly all collection modifying operations come in two flavors: you either have a collection.TryAdd() which will try to atomically add an item and return true/false to tell you the outcome or you have things like GetOrAdd() and AddOrUpdate() which again atomically insert an item and get/update it afterwards.


text:
Q: Function to delete a property from object in javascript I want to write a function which will return true if property of the
object is deleted and for others it should return me false.The
function accepts two parameters, object and the property name.This can
be more clear withe the below code:-

var removeObjectProp = function(obj, propName) {
  if (obj.hasOwnProperty(propName)) {
    return delete obj.propName;
  }
  return false;
}
var emp = {
  name: 'jack',
  age: 12
};

console.log(removeObjectProp(emp, 'name'));
console.log(emp)

output:

    True
    {name: "jack", age: 12}
    age:12
    name:"jack"
    __proto__:
    Object
   }

So again I am getting the same object.If I modify the function:-
 var removeObjectProp = function(obj, propName){
         return delete obj.propName;
    }

and call the
console.log(removeObjectProp (emp,'salary'));

Always it is returning true. How can i write the function to delete the property of an object passed as parameter?

A: In order to delete a property, if the property name is a string you have in a variable, you need to use bracket notation to delete the property:
return delete obj[propName];

You would use
delete obj.propName;

only when propName was the literal name of the property, eg with
{ name: 'jack', propName: 'foo' }

var removeObjectProp = function(obj, propName) {
  if (obj.hasOwnProperty(propName)) {
    return delete obj[propName];
  }
  return false;
}
var emp = {
  name: 'jack',
  age: 12
};

console.log(removeObjectProp(emp, 'name'));
console.log(removeObjectProp(emp, 'propThatDoesNotExist'));
console.log(emp)


text:
Q: How to use sed to change references to directories? So I know how to use sed -i 's/string/new-string/g' *.* but I'm trying to change all references to a directory structure and I don't know the proper format for the command.
Example: I want to change 'myfolder/mysubfolder' to 'myfolder'.
So if there's a string in a file that says 'myfolder/mysubfolder/file.txt' I want it to say 'myfolder/file.txt'.

A: You are on right track, just need to escape the /
sed -i 's/myfolder\/mysubfolder/myfolder/g' *.*

A: sed -i 's#myfolder/mysubfolder#myfolder#g' *.*

I used a delimiter other than / to avoid having to escape the / in the string.


text:
Q: How to traverse all the paths between two specified vertices in a graph? Given the graph is a directed graph. I want to find the most efficient algorithm.
Thanks for help!
Maybe we could do it in O(V+E)

A:
Consider this graph. The number of paths between s and t is 2^(number of diamonds), where each diamond is a rectangle. Since, 3*(no. of diamonds) + 1 = n, no. of diamonds = (n-1)/3. So, there are 2^(n-1/3) paths between s and t.
This proves that your problem can never be done in linear time.


text:
Q: Get quota details in my code side of a GCP Project enabled with Google Maps APIs I am working on a SugarCRM plugin integrated with Google Maps and want to get the quota details of GCP Project in my code side. Is there any way to get the quota details if I have checked any of these i.e Directions Api or Places Api
reference screenshot
 ?

A: You can find usage for Maps API on "APIs & Services Dashboard":
https://console.cloud.google.com/apis/enabled
Here is an example report. In your case it will include JavaScript Maps API:

Your account will be billed for usage according to the current price list:
https://developers.google.com/maps/documentation/javascript/usage-and-billing


text:
Q: Do interference rings disappear in an interferometer if the path lengths are identical? Consider a standard Michelson Interferometer (I took the picture from http://en.wikipedia.org/wiki/Interferometer)

The incident beam is split into two parts, where the two parts travel on different paths to the screen. If the paths are of different length and the incident wave is a spherical one, one sees the interference ring pattern at the detector. I now have three questions:
1.) What happens if the path lengths are exactly identical. Do I then still see the interference pattern?
2.) How does the patter on the screen change if I then slowly change one of the path lengths?
3.) What happens if I use plane waves instead of spherical ones? If the difference between the two paths corresponds to a phase difference of $\Delta \phi= \pi$ do the plane waves cancel out at the screen?

A: The answer is no, you don't get any interference rings if both arms of the Michelson are identical and the beamsplitter is perfectly flat.
The answer with real optics is somewhat more complicated.  Real laser beams have curved wavefronts (as opposed to plane) whose curvature changes as they propagate.  If you take two laser beams of the same frequency but different curvatures and overlap them on a camera, then you will get interference rings like shown in your wikipedia diagram, two laser beams of the same curvature give an interference pattern with no rings.
In a Michelson interferometer the things which could cause the two returning beams to have different curvatures are numerous but the most common ones are: path length differences between the arms, curvature of the two end mirrors, or curvature of the beamsplitter.

A: First consider only the center point of the screen.

*

*Identical lengths: red dot.

*Length differ by $\lambda/2$: black
dot.

Light source is a laser then you can add any natural number of wavelengths to one distance, and still result will be the same. If light source is for example lightbulb with lens making parallel rays and a "pupil" making the beam narrow, then the effect will disappear when difference of lengths is around or grater than length of a single wave packet. If I recall correctly one wave packet from lightbulb has length around $100 {\mu}m$.
Ad 2) Separation of interference fringe will not change, but fringes will gradually move from center or to center.
Ad 3) There will be no interference fringes. Whole screen will have the same intensity as the center point.

A: In order to not to see the interference patterns you would need a precision of micrometers in the arms distances (order of the laser wave-lengh). If you have this precision in you measurements I would go with the "curved wave-form" explanation, if not, you just don't have the same arm distances: in a very controlled Michelson interferometer the arms are slightly different so one can account for the changes in the interference patters as the mobile arm moves.

A: Whether the centerline path length is identical or differs by a whole number of wavelengths does not matter.  You will still get a bright spot in the center.  If the setup is perfect as you show, with the beamsplitter exactly at $45^\circ$ and incidence on the mirrors and screen perfectly perpendicular, you will not have any fringes because all lengths do not change.  Fig 1 in the Wikipedia article has a sketch that shows the angles not perfect.  In that case, the path length will vary over the area and you will see fringes.

A: You will always have destructive and constructive lines. The best you can do is one of each. The Michelson interferometer produces two images, the one that is usually enlarged and viewed on a screen, the main image. But   another image is projected back onto the light source, usually a laser. This image is always the opposite of the other. So if you get total destructive on one screen the other will be constructive. There is no way to get dark in one without getting light in the other.


text:
Q: Passing time as argument in django url in my view I have an argument of time to be passed but how do i pass it through a django url
my view is
def create_event(check):
TimeSlots.objects.create(start=check)
return HttpResponseRedirect("index.html")

and i tried a url
url(r'^new/(?P<time>\d{2}:\d{2}:\d{2})/$', views.create_event, name='check'),

I called it as
click

but it doesnt work and gives error
Could not parse the remainder: ':30:00' from '08:30:00'

A: The problem is that you pass 08:30:30 as a "raw expression". But Django templates fail to understand what you do with that colon.
You need to pass the parameter as a string, like:
click

Since your URL contains a time parameter, you need to handle it in the view:
def create_event(request, time):
    TimeSlots.objects.create(start=time)
    return HttpResponseRedirect("index.html")
Note that this view makes changes to the entities, and therefore this normally should be handled by a POST request. GET requests are normally not supposed to make (significant) changes.


text:
Q: Visual Studio 2010 debug not starting, F5 or click on "Play" not working, not doing anything. Waiting 2-3 minutes solves the issue I have a relatively simple C# (Framework 4) console application. When I click the "Play" icon or hit F5 (i.e. start the program in debug mode), the icon becomes gray for a second, then goes back to green, but nothing happens. If I wait 2 or 3 minutes and try again, the debug session starts up normally, breakpoints are hit and everything.
Things I have tried without success:

*

*Cleaning the solution, then rebuilding.

*Renaming the output assembly.

*Restarting Visual Studio.

The only thing that works is just waiting. I don't see any related processes still running during these 2-3mins (svchost, conhost, *.vshost or cmd).

A: I've seen this problem when my network connection is flakey and I've set the debugger to automatically download symbols from Microsoft's symbol server.  It tries for a long time, then times out, then life proceeds.  There should be clues in the Output window (where it normally lists all the modules being loaded and whether it got symbols for them).

A: Its happened for me.The cause was because i had my project open in 2 times in 2 differents visual studio and one was waiting for me to answers a question in a message box. The message was about files file was modified outside source editor and was asking me if I wanted to load change. Hope it will help some people and sorry for my english.

A: try this:
open Task Manager, go to processes tab and look for process named after your app. if its there just kill the bastard and try to debug again. for me it worked like miracle

A: I my case, it's due to the use of a vshost. I don't clearly understand yet why. It's possibly due to the running platform (a Win7 x64 where I am not - and may not be - administrator) combined with other factors
But I can debug (using F5) if I disable the use of vshost via the "Project Properties > Debug tab > "Enable the Visual Studio hosting process".

A: This issue can also occur if you disable "Application Experience" service in Windows, as many system optimization sites suggest.
The service can be re-enabled using msconfig or services.msc, this completely solved the issue for me.

A: I had a problem like this. I was having problems using "run" when the network was involved.
I moved all of the files related to the program/solution to my local hard-drive (C:);  they were on a network drive.  Be sure to check the "References" (Look under the "Project" pull-down for the properties;  then look for "References").
I would make sure all references are on you local hard-drive and set the "Path" correctly (to the reference on you local hard-drive) in the References tab.  This seemed to fix the issue.

A: Check the Project Properties in the Compile tab, select the Advanced Compile Options.

If you are targeting the .NET Framework 4 Client Profile, you cannot
  reference an assembly that is not in the .NET Framework 4 Client
  Profile.

More information about the .Net Framework 4 Client Profile here

A: Apparently there are many root causes for this. In my case - opened an old application for the first time in VS2010. The solution was upgraded. Everything compiles without error - but app won't start. There are half a dozen class libraries linked to the application. Turns out one of them was still compiling to .Net Framework 3.5, whereas all the others had automatically upgraded to .Net Framework 4. Likely there was an error message in the conversion log, whose import I didn't heed at the time. Once I changed that last library to use 4 instead of 3.5, everything ran smoothly.

A: "Function Lock" ( Fn Lock) on some keyboards.  This was completely unexpected, as I'd assumed I'd accidentally unset a key binding or something similar.  Not so! - None of the function keys worked, then I noticed the tiny glimmering and baleful light of the Fn Lock key....

A: Enabling the Application Experience Service will do, i'm new to VB and encountered that one.

A: See what happens if you try "Release" instead of "Debug".
If release works, then its because of a process (that you can find in Task Manager) which name is {Name of your Project}.vshost.exe

It's description is "vshost32" so you can sort by description alphabetically to find it easies.

A: It can also happen if an another application is attached to the debug process. Once, I attached ants memory profiler to the visual studio(VS2012) debug process. Later, I stopped the debugging and try to run it again, but VS2012 didn't allow me to debug. Only after stopping the ants profiler session, I was able to debug again.

A: I went to the services, found the service called "Application Experience" it was active.
I updated the service on right-click, and then right-click again, press "Reboot".
This worked for me. I am using Visual Studio 2015 on Windows 7 SP1 32bits.
But in the past I was using my application on Visual Studio 2015 at Windows 10 64bits.


text:
Q: How can we describe a group of things as having just the right number, i.e., not too many, not too few? I'd like to use a single word or an idiomatic expression to express that the school's breaks are well-spaced and not too many. Is there an adjective that mean just the appropriate number?

A: You could use optimum/optimal

best; most likely to bring success or advantage; best; the best or most effective possible in a particular situation (Cambridge)

As in this medical article:

Is there an optimum number of night shifts?

You could say that the school's breaks have optimal frequency or distribution.

A: Many options:

There are the ...

*

*perfect

*ideal

*appropriate

*right

*correct

*optimal

... number of breaks

You need to describe the number not the breaks. So I don't think that there is an expression The breaks are .


text:
Q: Lift UInt64 limits with strings in Delphi I'm reaching my limit with UInt64 and I was wondering if there are functions which do simple operating options such as +/- , etc. with just strings because they can store just as much RAM as you have... (theoretically)
For example I would like to calculate
24758800785707605497982484480 + 363463464326426 and get the result as a string.
I kinda know how to solve this problems with strings using the number system 0123456789 and kinda do digit by digit and overflow the next position - which would cost a lot more power, but I wouldn't mind this issue...
I would like to have this ability to do such calculations until my RAM just blows up (which would be the real limit...)
Are there such functions which already do that?

A: Arbitrarily large integers are not supported at the language level in Delphi, but a bit of Googling turns up http://www.delphiforfun.org/programs/Library/big_integers.htm, which can support them as alibrary.

A: On super computers, its called BCD math (Binary Coded Decimals) and each half-byte of RAM represents a decimal digit [0..9] - not an efficient use of RAM, but huge computations take minimal time (i.e. about 3 mSecs to multiply 2 million digit numbers. A BCD Emulator on a fast PC takes 5 or 6 minutes.
I never need to add big numbers, but I do multiply. Actually I call this routine iteratively to compute for example, 1000000 factorial (a 5,565,709 million digit answer. Str6Product refers to how it chops up a pair of string numbers. s1 and s2 have a practical length limit of about 2^31. The function is limited by what a "string can hold". Whatever that limit is, I've never gotten there.
//==============================================================================
function Str6Product(s1: string; s2: string): string;     //    6-13  5:15 PM

var
  so,snxt6          : string;
  z1,z3, i, j, k    : Cardinal;      // Cardinal is 32-bit unsigned
  x1,x3,xm      : Cardinal;
  countr            : Cardinal;
  a1, a2, a3        : array of  Int64;
  inum, icarry      : uInt64;        // uInt64 is 64-bit signed
begin

s1 := '00000'+s1;
s2 := '00000'+s2;
z1 := length(s1);                            // set size of Cardinal arrays
z3 := z1 div 6;
x1 := length(s2);                            // set size of Cardinal arrays
x3 := x1 div 6;

xm := max(x3,z3);
SetLength(a1,xm+1);
SetLength(a2,xm+1);

                                       // try to keep s1 and s2 about the
                                       // same length for best performance
for i := 1 to xm do begin              // from rt 2 lft - fill arrays
                                       // with 4-byte integers
   if i <= z3 then a1[i]  := StrToInt(copy (s1, z1-i*6+1, 6));
   if i <= x3 then a2[i]  := StrToInt(copy (s2, x1-i*6+1, 6));
   if i  > z3 then a1[i]  := 0;
   if i  > x3 then a2[i]  := 0;
end;

k := max(xm-x3, xm-z3);                      // k prevents leading zeroes
SetLength(a3,xm+xm+1);

icarry := 0;     countr := 0;
icMax  := 0;     inMax  := 0;

for i := 1 to xm do begin             // begin 33 lines of "string mult" engine
   inum := 0;
   for j := 1 to i do
      inum := inum + (a1[i-j+1] * a2[j]);

   icarry := icarry + inum;
   if icMax < icarry then icMax := icarry;
   if inMax < inum   then inMax := inum;
   inum   := icarry mod 1000000;
   icarry := icarry div 1000000;
   countr := countr + 1;
   a3[countr] := inum;
end;
if xm > 1 then begin
   for i := xm  downto k+1 do begin                      // k or 2
      inum := 0;
      for j := 2 to i  do
         inum := inum + (a1[xm+j-i] * a2[xm-j+2]);

      icarry := icarry + inum;
      if icMax < icarry then icMax := icarry;
      if inMax < inum   then inMax := inum;
      inum   := icarry mod 1000000;
      icarry := icarry div 1000000;
      countr := countr + 1;
      a3[countr] := inum;
   end;
end;
if icarry >= 1 then begin
   countr     := countr + 1;
   a3[countr] := icarry;
end;

so := IntToStr(a3[countr]);
for i := countr-1 downto 1 do begin
    snxt6 := IntToStr(a3[i]+1000000);
    so := so+ snxt6[2]+ snxt6[3]+ snxt6[4]+ snxt6[5]+ snxt6[6]+ snxt6[7];
end;

while so[1] = '0' do                       // leading zeroes may exist
    so := copy(so,2,length(so));

result := so;
end;

//==============================================================================
Test call:
StrText := Str6Product ('742136061320987817587158718975871','623450632948509826743508972875');

A: I should have added that you should be able to add large numbers using the same methodology - From right to left, fragment the strings into 16 byte chunks then convert those chunks to uInt64 variables. Add the least significant digits first and if it produces a 17th byte, carry that over to the 2nd least significant chunk, add those two PLUS any carry over etc. When otherwise done, convert each 16-byte chunk back to string and concatenate accordingly.
The conversions to and from integer to string and vice-versa is a pain, but necessary for big number arithmetic.


text:
Q: Sending results of MStest (from XML) to my manager I am using Selenum Webdriver using .Net bindings, Selenium Grid, MStest framework, testing our web application.
My manager does not want to have to scan an XML file, which is the output format from MStest logs. He also doesn't want to open the .trx file in Visual Studio (doesn't have VS studio installed).
I want to provide a way for him to easily see the results of automated testing by fetching the info himself, like through a web URL or other method.
I could write a perl script to parse the XML into a webpage. But I don't want to reinvent the wheel. This seems like a really common need.
I already have built in functionality that emails my boss if there is a failure.
Isn't there some standard way for people to read the results of their tests in a layman readable format? I am writing this post knowing it may attract a bunch of ads for specific plugins. But what I really want to know is whether there is some tried and true standard method.
My output looks like this:
-<UnitTestResult outcome="Passed" testListId="8c84fa94-04c1-424b-9868-57a2d4851a1d" executionId="4554a086-ffc9-48a3-81a3-1c97da18a32f" testId="14f288b2-4758-186e-8101-87acd599e23c" relativeResultsDirectory="4554a086-ffc9-48a3-81a3-1c97da18a32f" testType="13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b" endTime="2013-05-23T17:58:26.9575999-07:00" startTime="2013-05-23T17:57:51.6000645-07:00" duration="00:00:35.1400076" computerName="myMachineName" testName="mySmokeTest">
  -<Output>
    <StdOut>Hello pappy! System.Environment.MachineName=CCI-SKYN outFilePath is W:\\CCI_SMOKE_TESTS-CCI-SKYN-firefox.csv</StdOut>
  </Output>
</UnitTestResult>

And I want my manager to be able to call a web address or open a file and it to look something like this:
mySmokeTest
Passed
StartTime:2013-05-23T17:57:51.6000645-07:00
endTime=2013-05-23T17:58:26.9575999-07:00
duration=00:00:35.1400076

But I am open to any standard solution that fits the framework I am using.

A: You could apply an XSLT to he xml to display somthing pretty in the brower...
http://rhysc.blogspot.com/2009/02/mstest-xslt.html
Whip a little script to search the contents of the XML and you are good to go.


text:
Q: Boost UDP multicast receiver: set_option: The requested address is not valid in its context I am following Boost's UDP Time server tutorial here
.  I modify the code with these for predefined values:
short multicast_port = 13;  // (in class receiver)

and in main():
//if (argc != 3) and the code for argv that follows are commented out
receiver r(io_context, boost::asio::ip::make_address("127.0.0.1"), boost::asio::ip::make_address("127.0.0.1")); //

This error is thrown:
set_option: The requested address is not valid in its context

I have tried "0.0.0.0" and "127.0.0.1" and other values. Still get the same error. Could someone please help me figuring out what went wrong?
To clarify things, this is the code I use:
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <array>
#include <string>
using boost::asio::ip::udp;
using std::cout;
using std::cin;
using std::endl;

class receiver
{
private:
    boost::asio::ip::udp::socket socket_;
    boost::asio::ip::udp::endpoint sender_endpoint_;
    std::array<char, 1024> data_;
    short multicast_port = 13000;

public:
    receiver(boost::asio::io_context& io_context,
        const boost::asio::ip::address& listen_address,
        const boost::asio::ip::address& multicast_address)
        : socket_(io_context)
    {
        // Create the socket so that multiple may be bound to the same address.
        boost::asio::ip::udp::endpoint listen_endpoint(
            listen_address, multicast_port);
        socket_.open(listen_endpoint.protocol());
        socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
        socket_.bind(listen_endpoint);

        // Join the multicast group.
        socket_.set_option(
            boost::asio::ip::multicast::join_group(multicast_address));

        do_receive();
    }

private:
    void do_receive()
    {
        socket_.async_receive_from(
            boost::asio::buffer(data_), sender_endpoint_,
            [this](boost::system::error_code ec, std::size_t length)
        {
            if (!ec)
            {
                std::cout.write(data_.data(), length);
                std::cout << std::endl;

                do_receive();
            }
        });
    }
};

int main(int argc, char* argv[])
{
    try
    {
        boost::asio::io_context io_context;
        receiver r(io_context, boost::asio::ip::make_address("127.0.0.1"), boost::asio::ip::make_address("127.0.0.1"));
        io_context.run();
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}

A: The third parameter to the constructor is a multicast group address.
127.0.0.1 is not a multicast group address, and neither is 0.0.0.0.
Refer to your source.

A: Maybe a bit too long ago to answer, but I've had the same problem and maybe someone else faces the same problem. So this is probably not the best solution, but at least some way to get it to work.
Basically you join the multicast group with the ethernet adapters IP, which seems more natural than opening all ethernet adapters on the port you're listening to.
Be careful to use a valid IP because boost throws an exception if not. The only solution I found so far is using a try / catch around the receiver method call.
When you try to join a multicast group it seems you need the IP address of one of your ethernet adapters. I recommend editing it and use a static IP address (System > Network > Ethernet Connections).
As for the code, only this line needs to be changed into:
// Join the multicast group.
socket_.set_option(
  boost::asio::ip::multicast::join_group(multicast_address.to_v4(), listen_address.to_v4()));

I'm not sure if the .to_v4() is needed but it didn't hurt.


text:
Q: problem met when checking collision between circle and polygon using SAT I try to use SAT to check collision between circle and polygon, it works well when the circle is near the edges (of polygon), however when circle is closet to the corners (of polygon), it is push inside, and outside after that.
under this it failed

but under such cases it works well

How to solve this?
the algorithm looks like this:
double mtv = DBL_MAX; // minimum translation vector
Vector2 minAxis;
foreach(Edge e in p.Edges)
{
    var axis = e.normal;
    var circleInterval = ProjectInterval(c, axis);
    var polygonInterval = ProjectInterval(p, axis);
    float overlap = OverlapIntervals(circleInterval, polygonInterval);
    if(overlap < 0)
    {
        //the intervals overlap if it returns a positive number
        return -1.0f;
    }

    if(overlap < mtv)
    {
        mtv = overlap;
        minAxis = e.normal;
    }
}

and my code is here:

static AS_UNUSED inline AS_Bool AS_SAT_test_polygon_circle(AS_Polygon *poly, AS_Circle *circle, AS_Result *result) {

AS_Vector *axis_normed = AS_vector_create(0, 0);
if (result) {
    result->is_overlapping = AS_TRUE;
    result->shape_a = poly;
    result->shape_b = circle;
    result->type_a = AS_POLYGON;
    result->type_b = AS_CIRCLE;
}

for (int i = 0; i < array_len(poly->coords); i++) {
    AS_Vector *coord1 =poly->coords[i];
    AS_Vector *coord2 = poly->coords[i + 1 >= array_len(poly->coords) ? 0 : i + 1];
    axis_normed->x = coord1->x - coord2->x;
    axis_normed->y = coord1->y - coord2->y;

    AS_vector_perp(axis_normed);
    AS_vector_norm(axis_normed);

    double min1 = DBL_MAX, max1 = -DBL_MAX;
    double dot_product;
    for (int j = 0; j < array_len(poly->coords); j++) {
        dot_product = AS_vector_dot(poly->coords[j], axis_normed);
        if (dot_product > max1) max1 = dot_product;
        if (dot_product < min1) min1 = dot_product;
    }

    double b = AS_vector_dot(circle->position, axis_normed);
    double a = b - circle->radius, c = b + circle->radius;
    double min2, max2;
    min2 = a < b ? a : b;
    min2 = min2 < c ? min2 : c;
    max2 = a > b ? a : b;
    max2 = max2 > c ? max2 : c;

    if (result) {
        double overlap;
        if (min1 < min2) {
            result->a_in_b = AS_FALSE;
            if (max1 < min2) {
                result->is_overlapping = AS_FALSE;
                return AS_FALSE;
            } else if (max1 < max2) {
                overlap = max1 - min2;
            } else {
                double option1 = max1 - min2;
                double option2 = max2 - min1;
                overlap = option1 < option2 ? option1 : option2;
            }
        } else {
            result->b_in_a = AS_FALSE;
            if (max2 < min1) {
                result->is_overlapping = AS_FALSE;
                return AS_FALSE;
            } else if (max2 < max1) {
                overlap = max2 - min1;
            } else {
                double option1 = max2 - min1;
                double option2 = max1 - min2;
                overlap = option1 < option2 ? option1 : option2;
            }
        }

        if (overlap < result->overlap) {
            result->overlap = overlap;
            result->overlap_x = axis_normed->x;
            result->overlap_y = axis_normed->y;
        }
    } else {
        if (min1 > max2 || min2 > max1) {
            return AS_FALSE;
        }
    }
}
return AS_TRUE;
}

A: Simply add add a check about closest point of the polygon, that will be okay.


text:
Q: Boostrap Styling Tabletools is not working The output in Chrome and Firefox is different. When in Chrome, I was able to see all the button but it doesn't work. In Firefox just the print button.
What's the problem here? I just follow the example in their documentation.
Here is the JSFiddle.
I am using AJAX to get the data from my server, just a snippet:
 $.ajax({
     url: 'tbl/',
     dataType: 'json',
     success: function(s) {
         //alert(s.length);
         tbl_barangay.fnClearTable();
         for (var i = 0; i < s.length; i++) {
             tbl_barangay.fnAddData([
                 s[i]['loc'],
                 s[i]['countlow'] || 0,
                 s[i]['countmedium'] || 0,
                 s[i]['counthigh'] || 0
             ]);
         }
     },
     error: function(e) {
         alert(e.responseText);
     }
 });


text:
Q: django "GeometryField" widget type to accept coordinates in floating point format I'm trying to make a django form for user to specify the coordinates on a map and i did this by including small map widget where it's possible to choose geometry type as well as put it on map. But i'm looking for some widget where i can choose geometry type (like LineString, Point, Polygon) and specify values in separate field. Is there any existing solutions for this or i should add my own custom fields?
Now i have this form field:
geometry = forms.GeometryField(required=False)


text:
Q: How to cut off text that is longer than the space available and show '...'? I have a title of video that is a long title and I would like to display this in a single line like this:
Title: TxT TxT TxT ...
But is displaying like this for now:
Title: TxT TxT TxT TxT TxT TxT
       TxT TxT TxT TxT TxT TxT
here is a Div code

<%# Eval("Title")%>

and her is a css:
.vid-title {
  font-size: 20px; font-weight: bold; margin: 0px;
}

I would like the text to cut off when there is no more space, and show '...' at the end. How to achieve this?

A: Try this
div {
    width: 120px;
    text-overflow: ellipsis;
    white-space:nowrap;
    overflow:hidden;
    color: red;
}

JS Fiddle Demo


text:
Q: IEnumerator in F# continued This is the question about the earlier Persistence class that I was trying to expose as an enumerator. I realized that I need to pass by reference really to change the value of of the object that I am trying to populate. I guess I am going about this in a C++ way (As most may have guessed I am an F# beginner). However, I want to be as efficient in terms of memory foot print as I can. Ideally I would like to reuse the same object over and over again when I read from a file.
I am having a problem with this code where it does not allow me to pass by reference in the call to the function serialize. I am again reproducing the code here. I thank you in advance for your help.
The error I get:

error FS0001: This expression was expected to have type byref<'T> but here has type 'T

If I change the call to serialize(& current_, reader_) I get the following error:

persistence.fs(71,6): error FS0437: A type would store a byref typed value. This is not permitted by Common IL.
persistence.fs(100,29): error FS0412: A type instantiation involves a byref type. This is not permitted by the rules of Common IL.
persistence.fs(100,30): error FS0423: The address of the field current_ cannot be used at this point

The CODE:
type BinaryPersistenceIn<'T when 'T: (new : unit -> 'T)>(fn: string, serializer: ('T byref * BinaryReader) -> unit) =
let stream_ = File.Open(fn, FileMode.Open, FileAccess.Read)
let reader_ = new BinaryReader(stream_)
let mutable current_ = new 'T()

let eof() =
     stream_.Position = stream_.Length

interface IEnumerator<'T> with

    member this.Current
        with get() = current_

    member this.Dispose() =
        stream_.Close()
        reader_.Close()

interface System.Collections.IEnumerator with

    member this.Current
        with get() = current_ :> obj

    member this.Reset() =
        stream_.Seek((int64) 0., SeekOrigin.Begin) |> ignore

    member this.MoveNext() =
        let mutable ret = eof()
        if stream_.CanRead && ret then
            serializer( current_, reader_)

        ret

A: You can circumvent this by introducing a mutable local, passing it to serialize, and then assigning back to current_:
 member this.MoveNext() =
    let mutable ret = eof()
    if stream_.CanRead && ret then
        let mutable deserialized = Unchecked.defaultof<_>
        serializer( &deserialized, reader_)
        current_ <- deserialized

    ret

But now this is becoming really, really unsettling. Notice the use of Unchecked.defaultof<_>? There is no other way to initialize a value of unknown type, and it's called "unchecked" for a reason: the compiler can't guarantee safety of this code.
I strongly advise that you explore other ways of achieving your initial goal, such as using a seq computation expression instead, as I have suggested in your other question.

A: With respect to memory footprint, let's analyze the sequence option:

*

*You have an instance of the seq. That's going to be some class implementing IEnumerable<'T>. This one will be held until you no longer need the seq, i.e. not reallocated each time.

*You hold a Stream as part of the seq, with the same lifetime.

*You hold a BinaryReader as part of the seq, with the same lifetime.

*eof : unit -> bool is a compiler-generated function class as part of the seq, with the same lifetime.

*The loop will use a bool for the while loop and the if condition. Both of which are stack-allocated structs and needed for the branching logic.

*And finally, you yield an instance that you already got from the serializer.

Conceptually, that's as little memory consumption as you can have for a lazily evaluated seq. Once an element is consumed, it can be garbage collected. Multiple evaluations will do the same thing again.
The only thing you can actually play with, is what the serializer returns.
If you have your serializer return a struct, it is copied and stack-allocated. And it should not be mutable. Mutable structs discouraged. Why are mutable structs "evil"?
Structs are good with respect to the garbage collector as they avoid garbage collection. But they are typically to be used with very small objects, in the order of say 16-24 bytes max.
Classes are heap-allocated and are passed by reference always. So if your serializer returns a class, say a string, then you just pass that around by reference and overhead of copying will be very small as you only ever copy the reference, not the content.
If you want your serializer side-effecting, i.e. overwriting the same object (class, i.e. reference type is to be used for this), then the whole approach of IEnumerable<'T> and consequently seq is wrong. IEnumerables always give you new objects as result and should never modify any pre-existing object. The only state with them should be the information, at what place in the enumeration they are.
So if you need a side-effecting version, you could do something like (pseudo-code).
let readAndOverwrite stream target =
    let position = // do something here to know the state
    fun target ->
        target.MyProp1 <- stream.ReadInt()
        target.MyProp2 <- stream.ReadFloat()

Passing as byref does not seem very reasonable to me, as you then anyway allocate and garbage collect the object. So you can just as well do that in an immutable way. What you can do, is just modifying properties on your object instead.


text:
Q: center div of arbitrary width inside another div Please help me center a div that does not have a predefined width, inside another div. Please see the code below (or on jsbin at http://jsbin.com/ufivif). Thanks.
EDIT: the problem is that I need the caption below the image to be aligned to the left edge of the image. So text-align: center on the container does not work for me.

<!DOCTYPE html>

<meta charset=utf-8 />

test image

A: A combination of display: inline-block; and text-align:center
http://jsbin.com/ufivif/5
  body {
    padding: 0;
    margin: 0;
  }
  .container
  {
    border: 1px solid gold;
    padding: 10px;
    text-align: center;
  }

  .container .image
  {
    border: 1px solid silver;
    padding: 10px;
    display: inline-block;
    text-align: left;
  }
  .container .image img
  {
      border: 1px solid #9C6963 ;
      padding: 10px;
  }

A: So you need the image centered and not the text here's a way to fix it.

Image Text

While this doesn't get the borders to line up properly this does get the image centered and the text to the left of the image.

A: Try this:
div.image { margin: auto }

A: If you're only interested in centering on this one div, you can use the text-align: center in the parent:
#arbitrary
{
    width: 750px;
    border: 1px solid #000000;
    text-align: center;
}

A: If you are trying to center .image div the Try using this CSS:
.container
{
    overflow: hidden;
    margin: 0 auto
}

.container .image
{
    margin: 0 auto
}


text:
Q: status bar goes black while showing bottom sheet dialog how do I prevention the status bar from loosing it's color while a bottom sheet is showing up?
I use a bottom sheet view with custom layout.
tried modify the style of the dialog but still no luck
here is my code
   if (position == 1) {
                View modalbottomsheet = getActivity().getLayoutInflater().inflate(R.layout.others_sheet, null);
                dialog = new BottomSheetDialog(getActivity());
                dialog.setContentView(modalbottomsheet);
                dialog.setCanceledOnTouchOutside(true);
                dialog.setCancelable(true);
                dialog.show();

                contact_num = (EditText) modalbottomsheet.findViewById(editText);
                choose_contact = (Button) modalbottomsheet.findViewById(choose);
                choose_contact.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == choose_contact.getId()) {
                            Intent intent = new Intent(Intent.ACTION_PICK,
                                    ContactsContract.Contacts.CONTENT_URI);
                            startActivityForResult(intent, REQUEST_CODE);
                        }

                    }
                });
                hidetext = (EditText) modalbottomsheet.findViewById(R.id.hidetext);
                recharge_btn = (Button) modalbottomsheet.findViewById(R.id.rechargeothers_btn);
                recharge_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId()== recharge_btn.getId()){
                            String phone = ((EditText) dialog.findViewById(R.id.editText)).getText().toString();
                            String hidden = ((EditText) dialog.findViewById(R.id.hidetext)).getText().toString();
                            String pre = "*805*2";
                            String hash = "%23";
                            String dail = "tel:" + pre + phone + hidden + hash;
                            startActivity(new Intent(Intent.ACTION_CALL, Uri.parse(dail)));
                            dialog.hide();
                        }
                    }
                });
            }


text:
Q: Not displaying Category and subcategory from woocommerce Pluign I have installed woocommerce pluign but when I created categories that page is blank I want to display subcategories in that page and after we click on subcategory that should display all products under that subcategory.Can anyone please help me to solve this issue.
my design as follow particular category in that page all subcategories show display  then I will click or select 1 subcategory then that in that subcategory page all products should display.

A: You just need to change one option.
Follow steps:

*

*Go to "Appearance > Customize > WooCommerce > Product Catalog"

*Choose "Show subcategories" in "Category display" option

*Click "Publish" button


text:
Q: Random moving animation using prototypal inheritance pattern I'm making an animation that each list item will float randomly inside its wrapper. I'm trying to put together using prototypal inheritance pattern but it's not doing it. There are a couple of places that I think it may be cause to the problem but I need some advice to proceed.
function Menu($item) {
    this.item = $item;
};

Menu.prototype.makeNewPosition = function ($container) {
    var h = $container.height() - 50;
    var w = $container.width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];
};

Menu.prototype.move = function () {
    $.each(this.item, function(index, value) {
        var newq = this.makeNewPosition(value.parent());
        value.animate({
          top: newq[0],
          left: newq[1]
        }, 400, function() {
          this.move();
        });
    });
};

var $menu = new Menu($('.nav li'));
$menu.move();

Within move function, there is animate and within this I'm calling move again to run the animation indefinitely. If it's calling itself in prototypal structure, can it be called using this?
Not also sure about the use of $.each within move function.
Here is JSfiddle

A: Here's a cleaner version

*

*uses self instead of that - I use that, most people use self - I'm different :p

*set $value = $(value) ... DRY

.
function Menu($item) {
    this.item = $item;
};

Menu.prototype.makeNewPosition = function ($container) {
    var h = $container.height() - 50;
    var w = $container.width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];
};

Menu.prototype.move = function () {
    var self = this;
    $.each(this.item, function(index, value) {
        var $value = $(value);
        var newq = self.makeNewPosition($value.parent());
        $value.animate({
            top: newq[0],
            left: newq[1]
        }, 400, function() {
            self.move();
        });
    });
};

var $menu = new Menu($('.nav li'));
$menu.move();

original answer below - which contains explanation of changes

Here's ALL the errors fixed, not just the first
function Menu($item) {
    this.item = $item;
};

Menu.prototype.makeNewPosition = function ($container) {
    var h = $container.height() - 50;
    var w = $container.width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];
};

Menu.prototype.move = function () {
    var that = this; // added that because the this isn't the this you want in the $.each function
    $.each(this.item, function(index, value) {
        var newq = that.makeNewPosition($(value).parent());
        //         ^^^^                 ^^     ^
        //         that instead of this
        //                             $(value) instead of value
        $(value).animate({
      // ^^     ^
      // $(value) instead of value
            top: newq[0],
            left: newq[1]
        }, 400, function() {
            that.move();
          //^^^^ another this to that change
        });
    });
};

var $menu = new Menu($('.nav li'));
$menu.move();

There's ways to clean up the code even more, but these changes should get you working at least
The working changes to your fiddle http://jsfiddle.net/wzmh63xb/16/

A: There is your mistakes. Try this. it is working.
Menu.prototype.move = function () {
     var self = this;
    $.each(this.item, function(index, value) {
        var newq = self.makeNewPosition($(value).parent());

        $(value).animate({
        top: newq[0],
        left: newq[1]
    }, 400, function() {
        self.move();
    });
    });
};

DEMO


text:
Q: Синхронизация потоков через Семафоры C#
«Библиотека». Первый поток моделирует взятие книги читателем. Второй
  поток моделирует сдачу книги. Количество книг в библиотеке ограничено.
  Потоки находятся в разных процессах.

Подскажите, как должно быть?
Делаю так:
 class Program
    {
        static Semaphore semaphoreObj = new Semaphore(4, 5, "my_semaphore");

        static void Main(string[] args)
        {
            Process.Start(@"C:\visual studio 2015_Projects\4p\bin\Debug\4p.exe");
            Thread.Sleep(133);
            Thread.CurrentThread.Name = "Поток 1";
            while (true)
                Count();

            Console.ReadLine();
        }
        public static void Count()
        {
            for (int i = 0; i < 1000; i++)
            {
                semaphoreObj.WaitOne();
                int el;
                using (FileStream fsr = new FileStream(@"C:\books.txt", FileMode.Open))
                using (BinaryReader br = new BinaryReader(fsr)) el = br.ReadInt32();
                using (FileStream fsr1 = new FileStream(@"C:\books.txt", FileMode.Open))
                using (BinaryWriter bw = new BinaryWriter(fsr1))
                {
                    el -= 1;
                    bw.Write(el);
                }
                Thread.Sleep(1000);
                int f = semaphoreObj.Release();
                Console.WriteLine("{0} взял книгу. Книг {1}", Thread.CurrentThread.Name, f);
            }

        }
    }

}

И так:
    class Program
    {
        static Semaphore semaphoreObj;

        static void Main(string[] args)
        {
             semaphoreObj = Semaphore.OpenExisting("my_semaphore");
            Thread.CurrentThread.Name = "Поток 2";
           while (true)
                Count();

              Console.ReadLine();
        }
        public static void Count()
        {
            for (int i = 0; i < 1000; i++)
            {
                semaphoreObj.WaitOne();
                int el;
                using (FileStream fsr = new FileStream(@"C:\books.txt", FileMode.Open))
                using (BinaryReader br = new BinaryReader(fsr)) el = br.ReadInt32();
                using (FileStream fsr1 = new FileStream(@"C:\books.txt", FileMode.Open))
                using (BinaryWriter bw = new BinaryWriter(fsr1))
                {
                    el += 1;
                    bw.Write(el);
                }
                Thread.Sleep(2500);
                int f=semaphoreObj.Release();
                Console.WriteLine("{0} сдал книгу. Книг {1}", Thread.CurrentThread.Name, f);

            }
        }
    }
}

Получается, что число книг не изменяется. В чем проблема не могу понять...

A:  class Program
{
    static Semaphore semaphoreObj = new Semaphore(4, 5);

    static void Main(string[] args)
    {

        Process.Start(@"C:\visual studio 2015_Projects\4p\bin\Debug\4p.exe");
        Thread.Sleep(133);
        Thread.CurrentThread.Name = "Поток 1";
        while (true)
            Count();

        Console.ReadLine();
    }
    public static async void Count()
    {
        for (int i = 0; i < 1000; i++)
        {
        await semaphoreSlim.WaitAsync();
        try
        {

            int el;
            using (FileStream fsr = new FileStream(@"C:\books.txt", FileMode.Open))
            using (BinaryReader br = new BinaryReader(fsr)) el = br.ReadInt32();
            using (FileStream fsr1 = new FileStream(@"C:\books.txt", FileMode.Open))
            using (BinaryWriter bw = new BinaryWriter(fsr1))
            {
                el -= 1;
                bw.Write(el);
            }
            Thread.Sleep(1000);
             }
        catch { }
        finally
        {
            semaphoreSlim.Release();
        }
            Console.WriteLine("{0} взял книгу. Книг {1}", Thread.CurrentThread.Name, f);
        }

    }
}

}


text:
Q: var_dump($_POST) returning nothing after submiting form to codeigniter controller my jquery is
$(document).on("click", ".addthisone", function (e) {
    var file_data = $(this).parent().parent().parent().find('input[type=file]').prop("files")[0];
    console.log(file_data);
    var form_data = new FormData();
    form_data.append("file", file_data);
    $.ajax({
        url: "<?php echo base_url('action/addimage');?>",
        //dataType: 'script',
        //cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        type: 'post',
        success: function (d) {
            console.log(d);
        }

    })
    e.stopPropagation();
});

console.log() is displaying file data correctly
but the problem is that it is not appending the file to formData(), nor i am able to var_dump() the $_post after submiting the form. on the controller action it show the empty array
please help me out

A: Can you please use serialize function instant of FormData ?

A: use $_FILES to get the uploaded files!!


text:
Q: Compare attribute with number literal I am trying to find all VMs with exactly 2 cores:
$ az vm list-sizes -o json --query "[?numberOfCores == 2]"
az vm list-sizes: error: argument --query: invalid query value: '[?numberOfCores == 2]'

As I suspected an error with the az command, I installed jp directly, but it also gives an error:
$ az vm list-sizes -o json | jp "[?numberOfCores == 2]"
SyntaxError: Invalid token: tNumber
[?numberOfCores == 2]

In the jmespath specification it looks like I have to use the backtick ` character, but instead of an error it just gives no results:
$ az vm list-sizes -o json | jp '[?numberOfCores == `2`]'
[]

This is the (abbreviated) returned json I'm trying to filter:
$ az vm list-sizes -o json | head -n 20
[
  {
    "maxDataDiskCount": 4,
    "memoryInMb": 123,
    "name": "Standard_DS1",
    "numberOfCores": 1,
    "osDiskSizeInMb": 456,
    "resourceDiskSizeInMb": 789
  },
  {
    "maxDataDiskCount": 8,
    "memoryInMb": 123,
    "name": "Standard_DS2",
    "numberOfCores": 2,
    "osDiskSizeInMb": 456,
    "resourceDiskSizeInMb": 789
  }
]

(I obfuscated the sizes because I don't want to be sued by MS for sharing trade secrets or something)

A: Your JMESPath query is correct, but there was an issue with the way the homebrew version of jp was built (it was using an outdated script for building the jp binary).  Now the homebrew installed version of jp will always used the signed release binaries from https://github.com/jmespath/jp/releases.  These binaries are tested on every commit.  You should be able to brew update && brew upgrade jp, or use a binary from https://github.com/jmespath/jp/releases if you're not using homebrew.

A: In my case, I was using double quotes with --query flag while executing office365 cli command same as @user3151902 is using .  Note:: Double quotes worked with the string values but throws error with number values.
Wrong Way::
m365 spo list list -o json --query "[?BaseTemplate==`100`]" -u https://{contoso}.sharepoint.com/sites/{siteName}

Right Way::
m365 spo list list -o json --query '[?BaseTemplate==`100`]' -u https://{contoso}.sharepoint.com/sites/{siteName}


text:
Q: How to Log Barcode Scanner Output? Is there a way to log a barcode scanner's output?
We have an issue with our barcode scanner.
I can't explain it well so I will just leave a picture here:
https://imgur.com/a/nRZ8en0
Unfortunately, this issue happens intermittently and the scanner does have carriage return set after every input (so that it can automatically jump to the next text box field).
We have 2 hypothesis for this issue:
1) Bug in the form
2) User scans faster than the PC can have time to process the carriage return
Are there anyway to have a script/service that log the output of the scanner into a txt file and at the same time enable the user to use the form normally?

A: It is likely that "2) User scans faster than the PC can have time to process the carriage return".
Using the setting barcode, adjust the barcode reading interval called "Good Read Delay" or "Reread Delay" etc. to a longer interval.


text:
Q: Cambiar la ruta de creacion de un excel con librería SpreadsheetLight Buenos días soy nueva en esto y estoy de prácticas,
trabajo con Visual Studio y tengo que crear un excel personalizandole.
Intento de miles de maneras poner la ruta donde quiero que se cree, pero solo se crea en la carpera debug.
Gracias de antemano.
Esto es el codigo que me funciona, pero lo agrga a Debug:

string pathFile = AppDomain.CurrentDomain.BaseDirectory + fileName + ".xlsx";

sl.SaveAs(pathFile);

A: Solucionado:
 string pathFile = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/INFORMES LONJA/" + fileName + ".xlsx";

sl.SaveAs(pathFile);


text:
Q: Sqlalchemy CAST equivalent of Double precision i am interested to know the Sqlalchemy equivalent of the following command
update tablename set field1 = cast(field2 as double precision[])
so far, i tried the following with no luck
from sqlalchemy import create_engine
metadata = sqlalchemy.MetaData(engine)
table = sqlalchemy.Table('tablename',md,autoload=true)
update_stmt = table.update(values={table.c.field1:cast(table.c.field2, **double precision[]**)})
engine.execute(update_stmt)

please help to resolve double precision equivalent in sqlalchemy. this is running update statement from python to postgresql

A: PostgreSQL-specific types are in sqlalchemy.dialects.postgresql.
double precision[] should be:
ARRAY(DOUBLE_PRECISION)


text:
Q: Attempt to find a synonym of word "old" Few weeks ago, while reading some texts a new vocabulary encountred. when translated it via English to English online dictionary, one of the synonym was the word "old"?
To have or to put the aforementioned word in a sensible sentences, it could be:

..for the sake of the OLD days.

The synonym found online it contains, as far as I remember, the letter "y".
Can any of you help me to find out what that synonm was?

A: From the MacOS thesaurus:

in the old days: bygone, past, former, olden, of old, previous, early, earlier, earliest; medieval, ancient, classical, primeval, primordial, prehistoric, antediluvian. ANTONYMS modern, recent.

I suspect bygone is the word you're looking for.


text:
Q: Files created by java API cannot be accessed through JSP In a web application, I will use both java API and Linux System Calls to create a new directory, copy an image inside it and finally create a XML file with outputWriter. Then I will create download links to these resources on a JSP page. So far everything goes fine but when users try to access the files they get :
Http Status 404 - The requested resource (/export/myfile) is not available.

Trying to solve this I realized that if I rename the file to for example 'a' then rename it back to the original title, the link starts working. My first guess was that it's some kind of permission problem, so I provided all available permissions 'chmod 777 file' but nothing changed.
Normally I did some research on the net which lead to finding out that after restarting tomcat, links start working. I guess Tomcat somehow holds(freezes) these newly created files and they will be released after restart.
Saying all this, is there anyway to find out what exactly is going on and how I can fix it.

A: I expanded my search criteria trying to find a solution without any luck. finally I switched to Apache tomcat 7.0.35 (from 7.0.22) and it did the trick.