text:
Q: C code performance comparison, why is one of them much faster Recently I started solving problems from an online judge: http://coj.uci.cu/
And I solved one problem about calculating the least power of two of a number
(Full description: http://coj.uci.cu/24h/problem.xhtml?pid=1158)
SAMPLE INPUT
2    // This means we want to perform the algorithm twice for the next input
4
192

SAMPLE OUTPUT
4
64

After you solve you can compare your answer with the others so this are two different codes that solve the same problem (the basic idea is to keep dividing by two until the modulus is different from zero, then we find the minimum power and make 2*minimum to find the answer)
MY SOLUTION
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a,result;
    int i = 0;
    int leastPow = 1;
    scanf("%d",&a);             // Read the number of conversions
    for(i = 0; i < a; i++){
        scanf("%d",&result);    // Read the number to calculate the least pow
        while(result!=0){       // While there is still divisions to make...
            if(result%2!=0)
                break;          // hence we break the loop, we are done...
            result = result/2;  // Otherwise we can keep on dividing
            leastPow *= 2;
        }
        printf("%d\n",leastPow);// Print the result
        leastPow = 1;          // Re initialize for next number
    }
    return 0;
}

One of the top solutions (by nilre)
#include<stdio.h>

int main()
{
    long long pot,n;
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%Ld",&n);
        pot = 1;
        while(n)
            if(n%2 == 0)
            {
                pot *= 2;
                n /= 2;
            }else break;
        printf("%Ld\n",pot);
    }
    return 0;
}

For me the codes look very similar but the online judge gives the following performance results
MY SOLUTION
Time: 37 ms
Mem:  1 MB
Size: 1 KB

OTHER SOLUTION
Time: 0 ms
Mem:  270 bytes
Size: 348 bytes

I am very curious about what makes such a great difference in performance


text:
Q: logstash file input plugin configuration is not working I have a problem with logstash when i want to print logs to a file.
This is my output configuration
if "ERROR" in [log]
{
  file
  {
    path => "/home/yasmine/Bureau/elk/tri.text" codec => line
    {
      format => "Log: %log
    }"
  }
}

After running logstash it shows me this error
An unexpected error occurred! {:error=>#<Errno::EEXIST: File exists...

A: Try this:
if "ERROR" in [log]
{
  file
  {
    path => "/home/yasmine/Bureau/elk/tri.text"
    codec => line { format => "Log: %{log}"}
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where are npm scripts actually run from? If I run

npm run client

in my_directory, it will translate to:

webpack -w --mode production --config ./webpack.config.js

However, if I am in my_directory and I manually type in the above command, I get:

zsh: command not found: webpack

Also, can I change things so that I can run from my_directory.  This is a two part question if possible.
I was expecting to be able to run webpack manually without an npm script.

A: webpack is installed in node_modules/.bin/, so you can do
node_modules/.bin/webpack -w --mode production --config ./webpack.config.js

A: if you visit node_modules/.bin directory, you will see all the executables in your project are stored here. Those binaries are symlinked to the package's directory inside node_modules. When you run npm run, local node_modules/.bin directory is added to the PATH. When you execute the script, it actually executes from local node_modules/.bin.
If you want to manually write webpack to terminal you should install webpack globally, its executable directory will be added to PATH so that you can run it from terminal. Since you did not install webpack globally, it has no executable in your machine.
 sudo npm i -g webpack

this will install webpack in your actual machine, not in your project.
npm root -g

this will show where your global modules installed.
But installing packages globally is not a good practice. let' 's say your app works with webpack5 now but in the future webpack6 is released and you upgraded webpack to 6 (or someone cloned your project and its system has webpack6) but your old project might break because of breaking changes in webpack6 version.


text:
Q: How to migrate Github Private server to another server in Azure Migration We have Private Github server in Ubuntu running in Azure subscription and requirement is to migrate Github to another private github server. Decided to migrate Azure from one Subscription to another subscription taking the image.
So,What are the steps/process has to be done pre and post activities for Private Github server migration from Azure to Azure subscription?

A: You mean : You have a Private Git server not a Private GitHub server in Ubuntu I am right?
These links might to help you?
https://azure.microsoft.com/en-gb/documentation/articles/web-sites-publish-source-control/
https://azure.microsoft.com/en-us/blog/azure-welcomes-parse-developers/
Changing a remote's URL
https://help.github.com/articles/changing-a-remote-s-url/
replace remote repository with local repo, but keep commit history of remote


text:
Q: Linux open source 2d GUI engine comparable to WPF I am looking for a 2d open source GUI engine on Linux, to eliminate our reliance on Windows. Our current application is written in C# + WPF, which is incredibly slow and costly. It is stopping us to do anything awesome. If there is anything in Linux that can offer what WPF could offer (easy to use designer, animations, layout and component controls, etc) I would rather rewrite my entire code base in C++/Java in Linux.
Qt is one option but I am a little bit worried about its support in the future, given recently Nokia fired the entire team.

A: You can check out Moonlight:

Silverlight implement a subset of the WPF APIs and is available on
  Windows, MacOS X and through our own open source effort Moonlight it
  is available on Linux and other Unix systems.
Silverlight does not have all the capabilities of WPF, but both
  technologies are converging API-wise.
Silverlight can now be used outside of the browser, and Moonlight can
  be configured to be used with the full .NET API outside of the
  browser.

more...

A: I would still suggest Qt. Even if Nokia destroys all of their support for it, Qt is under the LGPL. That means that the source will still be available and free (libre), and the KDE community will keep it going. They already are to a degree anyway. Also, although Qt is still C++, it is a very modified extension of C++ through the meta object compiler (moc), a special sort of preproccessor. I think you won't regret the choice to use Qt.
Of course, if you want to stay on C# and .NET, there is the open source Mono initiative, who are trying to create a drop in replacement for .NET and C# that is mostly compatible. I don't know if they support anything besides Win Forms, but there are bindings for almost every graphics lib out there, so you can use GTK (a binding called GTK#), Qt, WxWidgets, and a lot of other things.
Also, there are GNOME's Glib and GTK+, which are the other major interface libraries for Linux. They are C oriented, so you might have a harder time adapting your code though.


text:
Q: How to add an option to create a new file with a specific extension in right click menu The title says all. I would like to have this option in right click menu on the desktop or in nautilus. I know that is possible, but I don't remember how to do this.

A: You may want to use Templates directory (or how is called in your language) from your home directory in this sense. Files from this folder will appear in the New Document menu. So, add the files with the extension what you want in this folder and you can create them after files with the same extension from the right click menu:

Moreover, if you add some predefined text in these files from Templates folder, the new files which you will create them from the right click menu will contain that text.
See also: What is the "Templates" folder in the home directory for?


text:
Q: Python OGR code for creating layer and then adding field not working This works...
fp = "C:\\LiDAR\\MyLayer.shp"
layer = "MyLayer"
driver = ogr.GetDriverByName("ESRI Shapefile")
data_source = driver.CreateDataSource(fp)
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
layer = data_source.CreateLayer(layer, srs, ogr.wkbPoint)

field_name = ogr.FieldDefn("Ben", ogr.OFTString)
field_name.SetWidth(24)
layer.CreateField(field_name)
layer = None

but this does not (Error 6: CreateField() not supported by this layer).
Anyone know why and know what I need to do to fix?
def createLayer(fp,layer):
    driver = ogr.GetDriverByName("ESRI Shapefile")
    data_source = driver.CreateDataSource(fp)
    srs = osr.SpatialReference()
    srs.ImportFromEPSG(4326)
    return data_source.CreateLayer(layer, srs, ogr.wkbPoint)

layer = createLayer("C:\\LiDAR\\MyLayer.shp","MyLayer")

field_name = ogr.FieldDefn("Ben", ogr.OFTString)
field_name.SetWidth(24)
layer.CreateField(field_name)
layer = None

A: This seems to work for me:
def createLayer(fp,layer):
    driver = ogr.GetDriverByName("ESRI Shapefile")
    data_source = driver.CreateDataSource(fp)
    srs = osr.SpatialReference()
    srs.ImportFromEPSG(4326)
    return(data_source.CreateLayer(layer, srs, ogr.wkbPoint),data_source)

layer,ds=createLayer('MyLayer.shp','MyLayer')
field_name = ogr.FieldDefn('Ben', ogr.OFTString)
field_name.SetWidth(24)
layer.CreateField(field_name)

it appears the datasource should be passed back - otherwise it is likely deallocated after the function completes, upon which the layer depends.
It works - but you might also consider renaming your function something other than 'createLayer' - i would be concerned it could cause confusion or worse, overloading.


text:
Q: Method attribute of NoneType object I'm going through a tkinter tutorial, and I'm having a hard time understanding the self.master.title() call.  It seems like master is assigned a default value of None during construction.  master is then assigned to self.master thereby making self.master a NoneType object.   Where does the self.master.title attribute come from?
import tkinter as tk

class Window(tk.Frame):

    def __init__(self, master = None):
        tk.Frame.__init__(self, master)
        self.master = master
        self.init_window()

    def init_window(self):
        self.master.title("GUI")
        self.pack()

A: While master does have a default value of None this default will only matter if no arguments were specified (i.e. thing = Window()).
If an argument is specified (i.e. thing = Window(SomeTKinterObject)) then self.master will be equal to the argument (in this case SomeTKinterObject).


text:
Q: Hibernate sequence going in infinite loop while saving object I am using apache derby db with hibernate. I am using two classes FoodOrderDBO.java and FoodOrderDetailsDBO.java having one to many relationship from FoodOrderDBO class to FoodOrderDetailsDBO class.
When I am saving object of FoodOrderDBO the sequence generation is happening repetitively.
FoodOrderDBO.java and FoodOrderDetailsDBO.java are as below
package rest.food.ordering.dbo;

import java.util.Date;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonManagedReference;

import rest.food.ordering.enums.PaymentMethod;
import rest.food.ordering.enums.PaymentStatus;

@Entity
@Table(name="FOOD_ORDER")
public class FoodOrderDBO {

    @Id
    @Column(name="FOOD_ORDER_ID",nullable = false)
    private String foodOrderId;

    @Column(name="CUSTOMER_ID",nullable = false, length = 100)
    private String customerId;

    @Column(name="PAYMENT_METHOD",nullable = false)
    @Enumerated(EnumType.STRING)
    private  PaymentMethod paymentMethod;

    @Column(name="PAYMENT_STATUS",nullable = false)
    @Enumerated(EnumType.STRING)
    private PaymentStatus paymentStatus;

    @Column(name="PURCHASE_TIME_STAMP",nullable = false)
    private Date purchaseTimeStamp;

    @Column(name="TOTAL_PRICE",nullable = false)
    private double totalPrice;

    @OneToMany(fetch=FetchType.LAZY, mappedBy="foodOrder", cascade = CascadeType.ALL)
    @JsonManagedReference
    private Set<FoodOrderDetailsDBO> setOfOrderDetails;

    @OneToOne
    @JoinColumn(name="SERVING_LOCATION",nullable = false)
    private ServingLocationDBO servingLocation;

    public Set<FoodOrderDetailsDBO> getSetOfOrderDetails() {
        return setOfOrderDetails;
    }

    public void setSetOfOrderDetails(Set<FoodOrderDetailsDBO> setOfOrderDetails) {
        this.setOfOrderDetails = setOfOrderDetails;
    }

    public String getFoodOrderId() {
        return foodOrderId;
    }

    public void setFoodOrderId(String foodOrderId) {
        this.foodOrderId = foodOrderId;
    }

    public ServingLocationDBO getServingLocation() {
        return servingLocation;
    }

    public void setServingLocation(ServingLocationDBO servingLocation) {
        this.servingLocation = servingLocation;
    }

    public String getCustomerId() {
        return customerId;
    }

    public void setCustomerId(String customerId) {
        this.customerId = customerId;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    public PaymentMethod getPaymentMethod() {
        return paymentMethod;
    }

    public void setPaymentMethod(PaymentMethod paymentMethod) {
        this.paymentMethod = paymentMethod;
    }

    public PaymentStatus getPaymentStatus() {
        return paymentStatus;
    }

    public void setPaymentStatus(PaymentStatus paymentStatus) {
        this.paymentStatus = paymentStatus;
    }

    public Date getPurchaseTimeStamp() {
        return purchaseTimeStamp;
    }

    public void setPurchaseTimeStamp(Date purchaseTimeStamp) {
        this.purchaseTimeStamp = purchaseTimeStamp;
    }

}

    package rest.food.ordering.dbo;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.ManyToOne;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;

    import com.fasterxml.jackson.annotation.JsonBackReference;

    @Entity
    @Table(name="FOOD_ORDER_DTLS")
    public class FoodOrderDetailsDBO {

        @Id
        @GeneratedValue(generator = "FOOD_ORDER_DTLS_SEQ", strategy = GenerationType.SEQUENCE)
        @SequenceGenerator(name = "FOOD_ORDER_DTLS_SEQ", sequenceName = "FOOD_ORDER_DTLS_SEQUENCE", allocationSize=1)
        @Column(name="FOOD_ORDER_DETAILS_ID",nullable = false)
        private int foodOrderDetailsId;

        @Column(name="FOOD_QUANTITY",nullable = false)
        double foodQuantity;

        @ManyToOne
        @JoinColumn(name="FOOD_ORDER_ID",nullable = false)
        @JsonBackReference
        private FoodOrderDBO foodOrder;

        @ManyToOne
        @JoinColumn(name="FOOD_ID",nullable = false)
        private FoodDBO food;

        public double getFoodQuantity() {
            return foodQuantity;
        }

        public void setFoodQuantity(double foodQuantity) {
            this.foodQuantity = foodQuantity;
        }

        public FoodOrderDBO getFoodOrder() {
            return foodOrder;
        }

        public void setFoodOrder(FoodOrderDBO foodOrder) {
            this.foodOrder = foodOrder;
        }

        public FoodDBO getFood() {
            return food;
        }

        public void setFood(FoodDBO food) {
            this.food = food;
        }

        public long getFoodOrderDetailsId() {
            return foodOrderDetailsId;
        }

        public void setFoodOrderDetailsId(int foodOrderDetailsId) {
            this.foodOrderDetailsId = foodOrderDetailsId;
        }
    }

Creating object of FoodOrderDBO as below:-
try {
            ServingLocationDBO servingLocation=new ServingLocationDBO();
            servingLocation.setLocationId(1);

            FoodDBO foodDBO=new FoodDBO();
            foodDBO.setFoodID(1);

            FoodOrderDBO foodOrderDBO=new FoodOrderDBO();

            Set<FoodOrderDetailsDBO> setFoodOrderDetailsDBO=new HashSet<FoodOrderDetailsDBO>();

            foodOrderDBO.setCustomerId("123456789");
            foodOrderDBO.setFoodOrderId("123456789");
            foodOrderDBO.setPaymentMethod(PaymentMethod.CASH);
            foodOrderDBO.setPurchaseTimeStamp(new Date());
            foodOrderDBO.setPaymentStatus(PaymentStatus.SUCCESS);
            foodOrderDBO.setServingLocation(servingLocation);
            foodOrderDBO.setTotalPrice(95.00);

            FoodOrderDetailsDBO foodOrderDetailsDBO=new FoodOrderDetailsDBO();
            foodOrderDetailsDBO.setFoodQuantity(5);
            foodOrderDetailsDBO.setFood(foodDBO);
            foodOrderDetailsDBO.setFoodOrder(foodOrderDBO);
            setFoodOrderDetailsDBO.add(foodOrderDetailsDBO);

            foodOrderDBO.setSetOfOrderDetails(setFoodOrderDetailsDBO);

            new FoodOrderingDaoImpl().saveFoodOrder(foodOrderDBO);

        } catch (RestClientException e) {
            e.printStackTrace();
        }

Logs I am getting while inserting object into DB is
2019-01-15 11:23:29 DEBUG SQL:109 - values next value for FOOD_ORDER_DTLS_SEQUENCE
2019-01-15 11:23:29 DEBUG SequenceGenerator:127 - Sequence identifier generated: BasicHolder[java.lang.Integer[-2147474786]]
2019-01-15 11:23:29 DEBUG SQL:109 - values next value for FOOD_ORDER_DTLS_SEQUENCE
2019-01-15 11:23:29 DEBUG SequenceGenerator:127 - Sequence identifier generated: BasicHolder[java.lang.Integer[-2147474785]]
2019-01-15 11:23:29 DEBUG SQL:109 - values next value for FOOD_ORDER_DTLS_SEQUENCE
2019-01-15 11:23:29 DEBUG SequenceGenerator:127 - Sequence identifier generated: BasicHolder[java.lang.Integer[-2147474784]]
2019-01-15 11:23:29 DEBUG SQL:109 - values next value for FOOD_ORDER_DTLS_SEQUENCE
2019-01-15 11:23:29 DEBUG SequenceGenerator:127 - Sequence identifier generated: BasicHolder[java.lang.Integer[-2147474783]]
2019-01-15 11:23:29 DEBUG SQL:109 - values next value for FOOD_ORDER_DTLS_SEQUENCE
2019-01-15 11:23:29 DEBUG SequenceGenerator:127 - Sequence identifier generated: BasicHolder[java.lang.Integer[-2147474782]]

hibernate.properties file is as below:-
hibernate.connection.driver_class=org.apache.derby.jdbc.ClientDriver
hibernate.connection.url=jdbc:derby://localhost:1527/D://db/foodappdb;create=true;user=food;password=food
hibernate.connection.username=food
hibernate.connection.password=food
hibernate.dialect=org.hibernate.dialect.DerbyTenSevenDialect
hibernate.hbm2ddl.auto=update
hibernate.id.new_generator_mappings=false
show_sql=true

How to stop this hibernate sequence generation to going into infinite times evaluation of next sequence value?


text:
Q: How to assign an error message when adding css class validation rule I have added a css class validation rule for jquery validator as follows:

jQuery.validator.addClassRules({
        requiredDatepicker: {
            required: true,
            date: true
        }
    });

However, when doing this I get the default error messages.  How can I assign custom error messages when using addClassRules()?

A: See the Refactoring rules section on  how to add custom messages.

A: You can't do this generally with the rule set, since class rules are just combinations of basic rules (for example even required is really required: { required: true } underneath) and those have the error messages.  To get custom errors you'll have to set them per-element, or use the meta-data plugin to put the rules on the element directly.


text:
Q: How to use Dompdf in Codeigniter 3 I am trying to create/generate pdf from my application, I have planned to use dompdf but I am facing some challenges.
I have downloaded the dompdf from here https://github.com/dompdf/dompdf
I have created a file in /application/libraries directory Pdf.php
Pdf.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');

require_once APPPATH.'third_party/dompdf/dompdf_config.inc.php';

use Dompdf\Dompdf;
class Pdf extends DOMPDF
{
    protected function ci()
    {
        return get_instance();
    }

    public function load_view($view, $data = array())
    {
        $dompdf = new Dompdf();
        $html = $this->ci()->load->view($view, $data, TRUE);

        $dompdf->loadHtml($html);

        // (Optional) Setup the paper size and orientation
        // $dompdf->setPaper('A4', 'landscape');

        // Render the HTML as PDF
        $dompdf->render();
        $time = time();

        // Output the generated PDF to Browser
        $dompdf->stream("welcome-". $time);
    }
}

Note: dompdf is in my /application/thirdparty directory
And in My Controller
    function pdf_test(){
        $this->load->library("pdf");
        $this->pdf->load_view('invoice_template');
    }

I am getting the below error
Message: syntax error, unexpected '='
When I fix above issue i get
file_exists(): open_basedir restriction in effect.

A: Use composer to get the library then in your class add this.
require 'vendor/autoload.php';

Path to your autoload.php may differ so check it to be sure. Also libraries should be placed within the libraries dir.


text:
Q: How to define a style of new dictionary in ruamel yaml? As the question Is there a way to preserve order while round-trip dumping YAML in Python? got solved, data structures are correctly imported, with  style attributes set properly, etc.
I've wrote some code to insert a nested CommentedMap() dictionary (sw-99-54321), which contains  some dictionaries and lists, like:
  dc01:
    sw-06-50001:  # existing entry
      servers:
      - {ip: 10.255.206.12, port: 50001, weight: 100}
      - {ip: 10.255.206.13, port: 50001, weight: 90}
      virtual: {ip: 192.168.1.4, port: 50001}

    sw-99-54321:  # the entry I am trying to add
      servers:
      - ip: 192.168.1.1
        port: '65535'
        weight: 100
      - ip: 192.168.1.2
        port: '65534'
        weight: 90
      virtual:
        ip: 192.168.1.1
        port: 65532

I want to format "sw-99-54321" in the same manner as existed "sw-06-50001.
I know the style is bound to <var>.fa.__flow_style attribute, but I can't change it directly:
data['services']['dc01']['sw-99-54321']['servers'].fa.set_flow_style='True'
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'Format' object attribute 'set_flow_style' is read-only

Is there a way to set it, or to define block style for some elements in other way?

A: Since your example has flow style you can do two things
1) Set flow style explicitly:
import sys
import ruamel.yaml

yaml_str = """\
dc01:
  sw-06-50001:  #existed entry
    servers:
    - {ip: 10.255.206.12, port: 50001, weight: 100}
    - {ip: 10.255.206.13, port: 50001, weight: 90}
    virtual: {ip: 192.168.1.4, port: 50001}
"""

yaml = ruamel.yaml.YAML()
# yaml.indent(mapping=4, sequence=4, offset=2)
# yaml.preserve_quotes = True
data = yaml.load(yaml_str)
data['dc01']['sw-99-54321'] = n = {}
n['servers'] = l = []
l.append(ruamel.yaml.comments.CommentedMap([('ip', '192.168.1.1'), ('port', '65535'), ('weight', 100)]))
l[-1].fa.set_flow_style()
l.append(ruamel.yaml.comments.CommentedMap([('ip', '192.168.1.2'), ('port', '65534'), ('weight', 90)]))
l[-1].fa.set_flow_style()
n['virtual'] = x = ruamel.yaml.comments.CommentedMap([('ip', '192.168.1.1'), ('port', '65532')])
x.fa.set_flow_style()

yaml.dump(data, sys.stdout)

which gives:
dc01:
  sw-06-50001:  #existed entry
    servers:
    - {ip: 10.255.206.12, port: 50001, weight: 100}
    - {ip: 10.255.206.13, port: 50001, weight: 90}
    virtual: {ip: 192.168.1.4, port: 50001}
  sw-99-54321:
    servers:
    - {ip: 192.168.1.1, port: '65535', weight: 100}
    - {ip: 192.168.1.2, port: '65534', weight: 90}
    virtual: {ip: 192.168.1.1, port: '65532'}

2) Set all leaf nodes to flow style globally:
import sys
import ruamel.yaml

yaml_str = """\
dc01:
  sw-06-50001:  #existed entry
    servers:
    - {ip: 10.255.206.12, port: 50001, weight: 100}
    - {ip: 10.255.206.13, port: 50001, weight: 90}
    virtual: {ip: 192.168.1.4, port: 50001}
"""

yaml = ruamel.yaml.YAML()
yaml.default_flow_style = None

data = yaml.load(yaml_str)
data['dc01']['sw-99-54321'] = n = ruamel.yaml.comments.CommentedMap()
n['servers'] = l = []
l.append(ruamel.yaml.comments.CommentedMap([('ip', '192.168.1.1'), ('port', '65535'), ('weight', 100)]))
l.append(dict(ip='192.168.1.2', port='65534', weight=90))
n['virtual'] = ruamel.yaml.comments.CommentedMap([('ip', '192.168.1.1'), ('port', '65532')])

yaml.dump(data, sys.stdout)

which gives:
dc01:
  sw-06-50001:  #existed entry
    servers:
    - {ip: 10.255.206.12, port: 50001, weight: 100}
    - {ip: 10.255.206.13, port: 50001, weight: 90}
    virtual: {ip: 192.168.1.4, port: 50001}
  sw-99-54321:
    servers:
    - {ip: 192.168.1.1, port: '65535', weight: 100}
    - {ip: 192.168.1.2, port: '65534', weight: 90}
    virtual: {ip: 192.168.1.1, port: '65532'}

with this method it is not necessary to create CommentedMap() instances, you can use normal dicts

A: Finally,
data['services']['dc01']['sw-99-54321']['servers'].fa.set_block_style()
did the formatting I wanted. While
data['services']['dc01']['sw-99-54321']['servers'].fa.set_flow_style()
makes the opposite.


text:
Q: Unable to create database in sybase ASE 15.7 I'm trying to create db in sybase ase using command
create database au on default ="0.5g"

but it returns
Could not execute statement.
CREATE or ALTER DATABASE failed because the device 'default' has no
space available either for log or for data.
Sybase error code=1816
Severity Level=16, State=1, Transaction State=0
Line 1
create database au on default ="0.5g"
Size of my master db is 10 gb and it's all free
How to increase the size of the device 'default'?

A: Run sp_helpdevice and check which devices are listed as 'default disk'. If your device is not listed as such, you can make it a default device by running sp_diskdefault <devicename>, defaulton.
BTW, it's generally not recommended to create additional databases on the master device, for reasons of recoverability in case of failures that will require rebuilding the server.


text:
Q: reportlab dynamic data-driven header outputs wrong subtitle I have created some fictitious, though representative, clinical trial type data using Pandas, and now come to some test reporting in ReportLab.
The data has a block (~50 rows) where the treatment column is 'Placebo' and the same amount where the treatment is 'Active'. I simply want to list the data using a sub-heading of 'Treatment Group: Placebo' for the first set and 'Treatment Group: Active' for the second.
There are some hits on a similar topic, and, indeed I've used one of the suggested techniques, namely to extend the arguments of a header functions using partial from functools.
title1 = "ACME Corp                                                                                CONFIDENTIAL"
title2 = "XYZ123 / Anti-Hypertensive                                                                                Draft"
title3 = "Protocol XYZ123"

title4 = "Study XYZ123"
title5 = "Listing of Demographic Data by Treatment Arm"
title6 = "All subjects"
def title(canvas, doc, bytext):
    canvas.saveState()
    canvas.setFont(styleN.fontName, styleN.fontSize)
    canvas.drawString(DOCMARGIN, PAGE_HEIGHT*.975, title1)
    canvas.drawString(DOCMARGIN, PAGE_HEIGHT*.950, title2)
    canvas.drawString(DOCMARGIN, PAGE_HEIGHT*.925, title3)
    canvas.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT*.900, title4)
    canvas.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT*.875, title5)
    canvas.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT*.850, title6)
    canvas.drawString(DOCMARGIN, PAGE_HEIGHT*.825, "Treatment Group:" + bytext)
    canvas.restoreState()

This is then called as follows. n_groups has the value of 2 from a summary query and 0 maps to 'Placebo' and 1 maps to active.
def build_pdf(doc):
    ptemplates = []
    for armcd in range(n_groups):
        ptemplates.append(PageTemplate(id = 'PT' + str(armcd), frames = [dataFrame,],
                     onPage = partial(title, bytext=t_dict[armcd]),
                     onPageEnd = foot))
    doc.addPageTemplates(ptemplates)

    elements = []
    for armcd in range(n_groups):
        elements.append(NextPageTemplate('PT' + str(armcd)))
        sublist = [t for t in lista if t[0] == (armcd+1)]
        sublist.insert(0,colheads)
        data_table = Table(sublist, 6*[40*mm], len(sublist)*[DATA_CELL_HEIGHT], repeatRows=1)
        data_table.setStyle(styleC)
        elements.append(data_table)
        elements.append(PageBreak())
    doc.build(elements)

The report produces 6 pages. The first 3 pages of placebo data are correct, pages 5 & 6 of active data are correct, but page 4 - which should be the first page of the second 'active' group has the sub-title 'Treatment Group: Placebo'.
I have re-organized the order of the statements multiple times, but can't get Page 4 to sub-title correctly. Any help, suggestions or magic would be much appreciated.
[Edit 1: sample data structure]
The 'top' of the data starts as:
[
   [1, 'Placebo', '000001-000015', '1976-09-20', 33, 'F', 'Black'],
   [1, 'Placebo', '000001-000030', '1959-04-26', 50, 'M', 'Asian'],
   [1, 'Placebo', '000001-000031', '1946-02-07', 64, 'F', 'Asian'],
   [1, 'Placebo', '000001-000046', '1947-11-08', 62, 'M', 'Asian'],

etc for 50 rows, then continues with
   [2, 'Active', '000001-000002', '1962-02-28', 48, 'F', 'Black'],
   [2, 'Active', '000001-000008', '1975-10-20', 34, 'M', 'Black'],
   [2, 'Active', '000001-000013', '1959-01-19', 51, 'M', 'White'],
   [2, 'Active', '000001-000022', '1962-01-12', 48, 'F', 'Black'],
   [2, 'Active', '000001-000036', '1976-10-17', 33, 'F', 'Asian'],
   [2, 'Active', '000001-000045', '1980-12-31', 29, 'F', 'White'],

for another 50.
The column header inserted is:
['Treatment Arm Code',
        'Treatment Arm',
        'Site ID - Subject ID',
        'Date of Birth',
        'Age (Years)',
        'Gender',
        'Ethnicity'],

[Edit 2: A solution - move the PageBreak() and make it conditional:]
def build_pdf(doc):
    ptemplates = []
    for armcd in range(n_groups):
        ptemplates.append(PageTemplate(id = 'PT' + str(armcd), frames = [dataFrame,],
                     onPage = partial(title, bytext=t_dict[armcd]),
                     onPageEnd = foot))
    doc.addPageTemplates(ptemplates)

    elements = []
    for armcd in range(n_groups):
        elements.append(NextPageTemplate('PT' + str(armcd)))
        if armcd > 0:
            elements.append(PageBreak())
        sublist = [t for t in lista if t[0] == (armcd+1)]
        sublist.insert(0,colheads)
        data_table = Table(sublist, 6*[40*mm], len(sublist)*[DATA_CELL_HEIGHT], repeatRows=1)
        data_table.setStyle(styleC)
        elements.append(data_table)

    doc.build(elements)


text:
Q: marcar todos los Checkbox de un DataTable con style bootstrap-Switch con jquery deseo agregar un input tipo checkbox que me permita marcar como "chequeados" todos los los checkbox que se encuentran en un dataTable, estos checkbox tienen un estilo de bootstrap-switch a como pongo se muestra en la siguiente imagen

al hacer click en Seleccionar todos todos se cambien su estado a checked
he probado esto pero no me funciona
$('#table_Permisos input[type="checkbox"]').each(function(){
        // toggle checkbox
        $(this).prop('checked',!$(this).prop('checked'));
        // toggle class
        $(this).parents('label').toggleClass('active');
    });c

});
cualquier opinion me sera de mucha ayuda de ante mano gracias
parte del codigo html
agrego captura de como agrego los inputs al data table

A: De acuerdo a la documentación solo necesitas ejecutar el método .bootstrapToggle() para asignar el nuevo estado on => activo o checked u off => inactivo o !checked y no se requiere que esté dentro de una etiqueta:

// Marcar o desmarcar todos los checkboxes
$("#todos").on('click', function() {
    // Obtener valor que se aplicará todos en la tabla
    let checked = ($(this).prop('checked')) ? 'on' : 'off';
    $('#table_Permisos input[type="checkbox"]').bootstrapToggle(checked);
});

// Solo para verificar que se actualizan los valores
$('#table_Permisos input[type="checkbox"]').on('change', function() {
    console.log($(this).prop('checked'));
});
label.active {
  background:#00a;
}
<link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css" rel="stylesheet">

    <input type="checkbox" data-toggle="toggle">
    <input type="checkbox" data-toggle="toggle">
    <input type="checkbox" data-toggle="toggle">

<input type="checkbox" id="todos"> Marcar / desmarcar todos


text:
Q: Python: select random values for a column from csv I have a problem to print random values from a csv for a given column name/index (my second day in Python world :) )
I have so far managed to write the following -
#!/usr/bin/python

import csv   # This will help us reading csv formated files.

import random # This will random method

load_file= open('<filename>',"rb")

reader= csv.reader(load_file) #The reader method will put each line
                             # of the csv file into a list of columns

for row in reader:

        from random import shuffle
        shuffle(row[2])

        print row[2]

load_file.close();

It is printing a shuffled (random) values from the third column in the file.
objectives -
. define the number of values 1000,2000,50000 etc.
. The values are highly skewed how to ensure uniform distribution ? e.g. if the column has got mostly 0s & few 1s I want to see both values in the output for any sample size.
. write this into a file. (not urgent at this point)
I am using python 2.6.6

A: Here is an unrelated example to show you how the shuffle and pop methods can be used:
from random import shuffle

a = [1,2,3,4,5]
shuffle(a)
print a
[5,1,4,2,3]
print a.pop()
3
print a
[5,1,4,2]

The pop method without any arguments deletes the last element from a list and then returns it. However, since you are shuffling the list before hand, you will get a random sequence everytime.

A: From what I understand, you want to do this:

*

*Read a CSV file with an unknown number of rows;

*Gather all the items in a given column, say column 2;

*Choose at random one row from that column.

If that is correct, it is fairly easy to do.
Suppose we have a CSV file like so:
1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16

Usually you would deal with a CSV file row by row. Since you want all the data from a column, you need to read the entire file before you have a set of data you can work with since the total number of rows is not known.
Here is a way:
import csv

col=2
with open(fn, 'r') as f:
    reader=csv.reader(f)
    data=[row[col] for row in reader]

print data
# ['3', '7', '11', '15']

Then if you want a single random number out of that list, use random.choice(data)

If you want to shuffle all the items in that column, use random.shuffle(data) then print it as a column using something like print '\n'.join(data) if all the elements of data are strings.

A: Thanks @dawg, @sshashank124 and others -
here is the code -
#!/usr/bin/python

import csv   # This will help us reading csv formated files.

import random # random method

col=2

with open('<filename>','r') as f:
        reader=csv.reader(f)
        data=[row[col] for row in reader]

from random import shuffle

shuffle(data)

print '\n'.join(data[:100])

f.close();

It is giving me output in the form of a column.
I am going to try to write it as a function and add other features next. I might start a separate thread for that.


text:
Q: Android mjpeg stream to Video MP4 I have a ip camera that gives 30 frames mjpeg per second. I want to record that frames to a mp4 file. I have already a library that record it to avi file but its not preferred. I try to convert video to mp4 after record it avi but its a bit slower.
Can you help please

A: here you go https://github.com/bytedeco/javacv
Android Sample: https://github.com/bytedeco/sample-projects/tree/master/JavaCV-android-example
FFmpegFrameGrabber g = new FFmpegFrameGrabber("textures/video/anim.mp4");
g.start();

for (int i = 0 ; i < 30 ; i++) {
    ImageIO.write(g.grab().getBufferedImage(), "png", new File("frame-dump/video-frame-" + System.currentTimeMillis() + ".png"));
}

g.stop();


text:
Q: Crazy LDAP (AD) password update problem (php) I am having a crazy Problem when updating the password of an AD user via PHP ldap API.
This is the function (part of a class) I use for updating the pw:
function updatePassword($newPassword){ // works only with LDAPS (LDAP WITH SSL/TLS ENCRYPTION)
    $newPassword = "\"". $newPassword. "\"";
    $newPassw = "";
    $len = strlen($newPassword);
    for($i = 0; $i < $len; $i++){
        $newPassw .= "{$newPassword{$i}}\000";
    }
    $newPassword = $newPassw;
    //$newPassword = mb_convert_encoding($newPassword, "UTF-16LE");
    $newEntry = array("unicodePwd" => $newPassword);
    $dn = $this->getUserInformation()["distinguishedname"];
    if(ldap_mod_replace($this->connection, $dn, $newEntry)){
        return true;
    }
    return ldap_error($this->connection);
}

After a user updates his password, the new one is working, but for quite some time, the old password is still working too. So the user is able to login to our web application and also into windows with his new password, as well as his old password...
Does someone has an idea or knows what the problem could be?
(Some Background Information:

*

*AD DC Server: Windows Server 2019 / Windows Server 2016

*Webserver: Debian 9 with Apache 2 (2.25)

*PHP Version 7.4
)

A: If someone faces the same problem:
A few days ago I read an article, in which the reason for the described behavior was mentioned
It's an Windows AD "feature", that keeps the user's old password valid for one hour after the password is changed


text:
Q: Time reversal and the solutions to Maxwell equations
The standard Lienard-Wiechert potentials describe the electromagnetic field at a point $P$ at time $t$ due to an arbitrarily moving charge $q$ at the retarded time $t-r/c$. An electromagnetic influence is assumed to travel, with the velocity of light $c$, from the moving charge $q$ at time $t-r/c$ to the field point $P$ at time $t$ while the charge moves along its path. This situation is illustrated on the left-hand side of the diagram. Physically the charge $q$ is in arbitrary motion whereas the field point $P$ is at rest in an inertial frame.
But the laws of electromagnetism are assumed to be time reversible. Therefore the time reverse of this process should occur in Nature. This is shown on the right-hand side of the diagram. Have I got this right? Basically all velocities are reversed including that of the electromagnetic influence.
Thus we have a picture in which an electromagnetic influence travels from a field point $P$ at time $t$ and intercepts a moving charged particle $q$ at a later time time $t+r/c$.
Note that I am not assuming that a signal goes backwards in time. I am "only" assuming that a physical process exists in which cause and effect are switched around in the temporal order. Instead of first moving charge then later field effect we have first field effect then later moving charge.
So to what physical situation does the advanced description correspond?
I believe that it might describe the situation in which the charge $q$ is at rest in an inertial frame and the point $P$ is in arbitrary motion. Thus, relative to an observer moving with point $P$, charge $q$ has an apparent motion illustrated by the right-hand diagram. The observer, at point $P$ and time $t$, measures a kind of inertial electromagnetic field that is determined by the apparent position of the charge at the advanced time $t+r/c$.
Could this be the answer to the meaning of the advanced solutions to Maxwell's equations?

A: The laws of electromagnetism are indeed time-reversal invariant, but this can sometimes be in a fairly restricted sense, particularly when dealing with causality as regards the Liénard-Wiechert potentials.
Consider the following situation. A charged particle is travelling under the influence of some force $\mathbf F_\text{ext}(t)$ which is due to a time-reversible interaction with an external system. At a certain time $t_0$ this interaction causes a bend in the particle's trajectory. This acceleration causes it to emit radiation, which we know will be described by the retarded Liénard-Wiechert potentials. This radiation will exert a back-reaction force on the particle, which alters the trajectory from what the single force  $\mathbf F_\text{ext}(t)$  would have shaped.
$\qquad\qquad$
Let's look, on the other hand, at the time-reversed situation. The particle now traverses its trajectory in the opposite sense, but the really important thing is that your initial conditions now include an incoming pulse of radiation. This pulse will coincide with the particle at the bend in the trajectory. After that, it will destructively interfere with the pulse radiated by the particle, and that will leave no radiation in the end. The combination of both pulses will exert the extra force to make the particle what it should, instead of what the time-reversed $\mathbf F_\text{ext}$ would have shaped.
Your dynamics are therefore completely time-reversal invariant. By a weird "coincidence", you can describe the incoming pulse of radiation in the time-reversed version using the advanced Liénard-Wiechert potentials. Here it's important to note that this is because the pulse would have been described by the potential
$$\text{advanced LWP}-\text{retarded LWP},$$
which is a regular solution to the Maxwell equations, and has no singularity at the particle.

Thus far for the classical understanding of this topic. The above shows that classical EM is indeed time-reversal invariant, but that this invariance requires that you consider the fields to be physical entities in themselves, and time-reverse them as well, boundary conditions and all. While this is not unsatisfactory, it has been a persistent itch on the side of a number of theorists because you can't measure the fields directly. Should it not be possible to make a time-reversal invariant description of electromagnetism purely in terms of the position of the charges?
This is the essence of the Wheeler-Feynman absorber theory, which has its own problems and is not really taken very seriously AFAIK, but is quite beautiful. This postulates that all charges radiate both forward and backward in time, and that the radiation reaction force on a given particle is not an interaction with its own field, but with the advanced radiation 'sent from the future' by the particles that will be influenced by the 'physical' retarded radiation. Again, not something that's currently a part of standard physics, but it's definitely something to read up on.


text:
Q: Switching from full to half wave rectification The Context:
Multiple manufacturers of electro-magnetic brakes offer rectifier modules to switch their DC brakes with an AC feed. This can often be tied to the same phases turning the motor, so that the brake lifts when the motor is powered:

(Image from Mayer document linked below)
They often also offer these modules with an "over-excitation" option. The idea being that half wave rectification provides enough power to lift the brake, but by briefly using full wave rectification, the RMS voltage is higher and the brakes lift more quickly.
Both Mayr and Precima offer the same sort of module:
Precima (p.g. 5 of the pdf)
Mayr (p.g. 4 of the pdf)
The Question:
Using only a 2 phase supply, how do you switch from full wave rectification to half wave after a specified time period?
So far, a thyristor seems like a fairly good choice for switching 'off' the full wave rectifier. In the example below, if the switch is closed, the thyristor conducts as a diode, when open, it blocks current both ways.

simulate this circuit – Schematic created using CircuitLab
Tested here (as Circuit Lab cannot simulate thyristors): Falstad Circuit
How can I add some sort of RC network/similar to the thyristor's control pin that would allow operation similar to the devices talked about above, with a resistor value setting a time for the full wave rectification to be active before the 'switch' opens and the thyristor turns off?

A:
Using only a 2 phase supply, how do you switch from full wave
rectification to half wave after a specified time period?

It's probably conceptually easier if you always use a full wave rectifier and then, on the DC side, use a MOSFET to activate the brake solenoid, and, after a short while, deactivate the MOSFET for every other half cycle.
If you see the reasoning here; the "control" circuit is located on the DC side of the rectifier and you can more easily derive a logic supply for a timer so that after a short while of operating full-wave, you revert to half wave. It also means that you can control back-emfs more reliably compared to the situation of your control circuit being on the AC side of the rectifier.


text:
Q: why I cant access a public method from a class? (java) I have the following method in  MapViewActivity.java
 public void startMapEditActivity() {
        Intent intent = new Intent(MapViewActivity.this, MapEditActivity.class);
        intent.putExtra(EXTRA_MESSAGE_FLOOR, mSelectedMap);
        startActivity(intent); // start map edit mode
    }

I'm trying to access the method from MapActivity.java as:
startMapEditActivity();

but it doesn't work that way it throws the following message:
The method startMapEditActivity() is undefined for the type MapActivity

A: change your usage to a static method with a parameter of context and pass whatever mSelectedMap is too, this way you can use this one method in your entire app to start this activity by passing in a valid context (like an activity) and the info that is represented by mSelectedMap:
static public void startMapEditActivity(final Context context, boolean mSelectedMap) {
    Intent intent = new Intent(context, MapEditActivity.class);
    intent.putExtra(EXTRA_MESSAGE_FLOOR, mSelectedMap);
    startActivity(intent); // start map edit mode
}

Example Usage (from a view clicklistener):
    setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            MapEditActivity.startMapEditActivity(view.getContext(), aSelectedMapObject);
        }
    }));

Example usage from some method in MapViewActivity:
  private void gotoMapEditActivity(){
      MapEditActivity.startMapEditActivity(MapViewActivity.this, aSelectedMapObject);
  }

A: That method doesn't belong to MapActivity, it belongs to MapViewActivity.  You can't call it from outside MapViewActivity.
The easiest way to solve your problem would be to copy the method startMapEditActivity into the class MapActivity.  This way MapActivity has it's own version of startMapEditActivity that you can use from within that class.


text:
Q: Can I add USB 3.0 support to the front of my old PC? I have a Dell XPS 720. I want to add USB 3.0 support to it, ideally on the front of the PC. Is this possible?
The built in media card reader is the 4th bay. Can I replace it with  one of these? would it fit?

A:
I have a Dell XPS 720. I want to add USB 3.0 support to it, ideally on
  the front of the PC. Is this possible?

Yes it is possible. If you do not already have a USB 3 pin header on your mother board, you can apply hardware in the form of a PCI e cards that have 19/20 pin headers on the card, such as this as an example SYBA USB 3.0 External 2-port, 19-pin Header PCI-e Card. Look at specs needed, usualy a PCIe x4 up to x16 is needed on your board.

The built in media card reader is the 4th bay. Can I replace it with
  one of these? would it fit?

The "one of these" in your post is:

Yes it can fit in one of two ways:
This is designed to fit into a 3.5" space in your towere's front panel area. Your tower has two 3.5" panels and it would fit there if you have nothing else residing in these spaces.
If the "4th bay" is 5.25", you would need an adaptor bracket similar to this:

These can be made of plastic or metal and you can shop around for your prefrence.
Front View

*

*front I/O connectors

2. 3.5-inch drive bays (2) Can hold an optional Media Card Reader or floppy drive.
3-6  5.25-inch drive bays (4) Can hold an optical or SATA hard drive in a 5.25-inch drive bay carrier.
NOTE: The hard drive carrier is only for use in the 5.25-inch drive bays. The floppy-drive/Media Card Reader and hard drive carriers are not interchangeable.
7 front panel LEDs (4)
8 optical drive tray eject button (4)
9 front panel LEDs (4)
10 power button
11 power light
12 computer stand

A: There are two ways to get USB 3.0 on an old PC without having to reach around the back side every time.
One option is to get a PCI-E USB 3.0 card, and then run a USB 3.0 extension cable or hub up to the front of your computer. This will probably be the easier option to set up, but maybe not as convenient to use. There are a lot of these available from online electronics retailers.
The other option is to get a PCI-E USB 3.0 card with an internal 20-pin connector, and then get a USB 3.0 faceplate for the front of your computer. This would fit into the spot where floppy drives went in older computers, and memory card multi-readers often go in newer computers.

I found a couple items on Amazon that would probably work; you might be able to find something similar for a better price elsewhere.

*

*PCI-E internal USB 3.0 card(Required for either option below)

*USB 3.0 front panel (2 USB ports)

*USB 3.0 front panel (1 USB port + card combo reader)

A: You can add a third party USB 3.0 card to an open PCie slot  Startech makes several and there are others.  Most will want power from a SATA power conenctor.


text:
Q: How to echo individual css classes for li's?

<?php
    include('dbconnect.php');

    $result=mysqli_query($con,"SELECT tip_unitate,tip_id FROM tipunitate ORDER BY tip_id ASC");
    while($row = mysqli_fetch_array($result))
    {
        $pid=$row['tip_id'];
        $unitate=$row['tip_unitate'];
        $count=mysqli_query($con,"SELECT COUNT(*) AS num FROM unitate WHERE tip_id='$pid'");
        $rowss = mysqli_fetch_array($count);
        $number=$rowss['num'];
        echo "
".$unitate."(".$number.")
";

    }
    mysqli_close($con);
?>

This is my code. What I need is to assign individual classes to the li's in that OL. There are 8 li's. I've seen a lot of answers about similar questions but could not do it by myself due to my low PHP knowledge.

A: Have you considered using CSS for the task at hand?
please have a look at http://www.w3schools.com/cssref/sel_nth-child.asp
simple and quick example to be found here http://jsfiddle.net/2r3kxr8g/
li:nth-child(2) {
  background: #d70;
  padding: 9px;
}

The only thing you must bear in mind is that you should limit the elements you want to style by explicitly defining them in CSS

A: If you need a unique identifier for each li tag, the simplest solution is to assign the $pid variable as the id of the element. So like this:
echo '
...
';

Then you can assign styles to these elements according to their unique ID's. For example:

You only need classes for styles shared across multiple elements. In that case, you could do something like this:
// array keys should be the PIDs associated with the classes you wish to assign
// define this array outside your loop
$styles = array(
    0 => 'style1',
    8 => 'style8',
);

Then inside your loop:
echo "
{$unitate}({$number})
";

A: Why don't you do
    echo "".$unitate."(".$number.")";
$i is a counter

A: I might create a custom function for this, especially if there's going to be the potential for more than 2 or 3 different classes. This way you help maintain the readability of your code and compartmentalize it a bit.
In the example below I used $pid as the reference point to determine which class to use. Your actual use case may be different.
function get_li_class( $pid ) {

     switch ( $pid ) :
          case 1:
               return 'apple';
               break;
          case 2:
               return 'house';
               break;
          case 'apple':
               return 'dog';
               break;
          // more and more options if you'd like
          default:
               return ""; // or some other class
               break;
     endswitch;

}

while ( $row = mysqli_fetch_array($result) ) {
     // your code here
     $class = get_li_class($pid);
     echo '
...
';
}


text:
Q: Angular multiselect is not getting displayed properly I am using Angular-multiselect of version 4.2.2. On UI it is coming like this.
When I deselect Items and add once again then it is coming properly.

My HTML code

                Specializations:
                <angular2-multiselect [data]="specializations" [(ngModel)]="selectedSkills" [settings]="sOptions"
                  name="skills">
                </angular2-multiselect>

My TS file
  ngOnInit() {
    this.sOptions = {
      singleSelection: false,
      text: "Select specializations",
      selectAllText: 'Select All',
      unSelectAllText: 'DeSelect All',
      enableSearchFilter: true,
      classes: "myclass custom-class ml-md-3 input-length",
      maxHeight: 100
    };}

Pls help me in fixing this.

A: if you are using angular +7 , try angular material or nebular ( i used them and they work perfectly )
if you decided to use those materials , nb-select tag or mat-select , have multiple attribute , and make sure you use placeholder attribute
for nebular theme , template going to be like this :
<nb-select formControlName="formControl"><nb-option [value]="value">label</nb-option></nb-select>


text:
Q: youtube video is not playing from from html5 using ng-src directive I am creating an online course application and storing the video on YouTube. When a user clicks on courses then They should see the embedded YouTube videos. However It just creates the video frame and video doesn't play.
Here is my angular controller code. courses.client.controller.js
(function() {
'use strict';

angular
.module('courses')
.controller('CoursesController', CoursesController);

CoursesController.$inject = ['$scope', 'courseResolve',  'Authentication', '$sce'];

function CoursesController($scope, course, Authentication, $sce, $timeout) {
var vm = this;

vm.course = course;
vm.authentication = Authentication;

$scope.params = {
videoUrl: $sce.trustAsResourceUrl('https://youtube.com/embed/gZNm7L96pfY')
};
}
}());

Here is my html code. view-course.client.view.html. I have tried to two different approaches. Both Failed.

Posted on

by

Deleted User

  <video id="movie", ng-src="{{vm.course.courseLecture}}" width="500", height="300" controls>
  </video>

  <video style="width:300px;height:240px" controls preload="none" >
     <source ng-src="{{params.videoUrl}}" type="video/mp4">
  </video>

  link1

Please let me know, where I am going wrong here.

A: Try adding this and instead of video control load it inside an iframe,
app.config(function($sceDelegateProvider) {
  $sceDelegateProvider.resourceUrlWhitelist([
    'self',
    'https://www.youtube.com/**'
  ]);
});

DEMO

var app = angular.module('myApp', []);
app.config(function($sceDelegateProvider) {
  $sceDelegateProvider.resourceUrlWhitelist([
    'self',
    'https://www.youtube.com/**'
  ]);
});

app.controller('videoController', ['$scope',
  function MyCtrl($scope) {

    $scope.product = {
      name: 'some name',
      description: 'some description',
      media: [{
        src: 'gZNm7L96pfY'
      }]
    };

    $scope.getIframeSrc = function(src) {
      return 'https://www.youtube.com/embed/' + src;
    };
  }
]);

<!DOCTYPE html>


text:
Q: Checking host reachability on windows command line How can I check in batch-file if host is reachable or not? The problem is that ping returns 0 not only on success, but also on Destination host unreachable error:
C:\>ping 192.168.1.1 -n 1

Pinging 192.168.1.1 with 32 bytes of data:
Reply from 192.168.1.1: bytes=32 time=3ms TTL=64

Ping statistics for 192.168.1.1:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 3ms, Maximum = 3ms, Average = 3ms

C:\>echo %errorlevel%
0

C:\>ping 192.168.1.105 -n 1

Pinging 192.168.1.105 with 32 bytes of data:
Reply from 192.168.1.102: Destination host unreachable.

Ping statistics for 192.168.1.105:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),

C:\>echo %errorlevel%
0

Is there any way to do it with ping or any other build-in-Windows tool? I would prefer not to install anything if that's possible...

A: Next code snippet should work:
set "_ip=localhost"
set "_ip=192.168.1.1"
ping %_ip% -n 1 -4 | find /i "TTL=">nul
if errorlevel 1 (
    echo ping %_ip% failure
) else (
    echo ping %_ip% success
)

*

*-4 to force using IPv4 (as e.g. ping localhost replies IPv6 with no TTL= output)

*| find /i "TTL=" as find command raises errorlevel well

*>nul to suppress undesired output

A: Do something like this:
PING 192.168.1.1 -n 1 | FIND /I "Reply from "

Then you can check errorlevel
Edit: To accommodate "Destination host unreachable error you could do this:
PING 192.168.1.1 -n 1 | FIND /I /V "unreachable" | FIND /I "Reply from "

A: I think tracert is what you need.Sets errorlevel on 1 if cant find the host.And should use the same port as ping.-h 2 is to reduce wait time ,as the complete route is not needed.
tracert -h 2 somehost.com >nul 2>nul && (
  echo reachable host
) || (
  echo unreachable host
)

EDIT: to print correct errorlevel in the brackets you need delayed expansion.Here's more advanced example :
@echo off

setlocal enableDelayedExpansion

echo checking google.com
tracert -h 1 google.com >nul 2>nul && (
  echo reachable host
  echo !errorlevel!
  rem prevent execution of negative condition
  color 22
) || (
  echo unreachable host
  echo !errorlevel!
)

echo checking asdasdjjakskwkdhasdasd
tracert -h 1 asdasdjjakskwkdhasdasd >nul 2>nul && (
  echo reachable host#
  echo !errorlevel!
   rem prevent execution of negative condition
   color
) || (
  echo unreachable host#
  echo !errorlevel!
)


text:
Q: Microsoft Access 2013 Validation Rule with Literal Asterix How do I add a validation rule to a column in MS Access 2013, where the column value can either be "A" or "*"?  When I try to add the validation rule:

"A" Or "*"

The MS Access Expression Builder changes it to:

"A" Or Like "*"

Which doesn't constrain the value at all.  I have tried the following, and all are modified by the expression builder to include the word "Like":

"A" Or "*"
  'A' Or '*'
  "A" Or "\*"

I have been able to trick Access into treating my text as a string literal using the following kludge:

"A" Or UCase("*")

But that seems incredibly cumbersome to do something so simple.  Does anyone know the "clean" way to add such a validation rule to Access 2013?

A: Access supports an "In" operator, which would allow for the following validation rule syntax:

In("A","*")

If the column also supports null values, then simply add that exception before the "In" operator:

Is Null Or In("A", "*")


text:
Q: Ajax request going out of range $(function(){
var imgClass = $('.caruselWrap').find('img');
imgClass.eq(1).addClass('pro');
var hasPro = $('.caruselWrap').find('img.pro');
var count = 3; // "position" of images, security for not breaking out
var imgLoaded = 3;
var flag = true;
var arr = [];

var ajax = function() {
    var url = 'gallery/img' + count + '.jpg';

    var request = new XMLHttpRequest();
    request.open('GET', url);
    request.onreadystatechange = function() {
        if ((request.readyState === 4) && (request.status === 200)) {
            arr[imgLoaded] = '<img class="addedImg" src="' + url + '" />';
            $('.caruselWrap').append(arr[imgLoaded]);
            flag = true;

            $('.addedImg').click(function(){
                var img = $(this);
                check(img);

                console.log("count: " + count);
                console.log("images loaded: " + imgLoaded);
                console.log(flag);
            })

        }
    }
    request.send();
    imgLoaded++;
}

var change = function(string) {
    if((string == "left") && (count >= 3)) {
        hasPro.prev().addClass('pro').next().removeAttr('class');
    } else if (string == "right") {
        hasPro.next().addClass('pro').prev().removeAttr('class');
    }
}

var check = function(a){
    var add = imgClass.outerWidth(true);
    hasPro = $('.caruselWrap').find('img.pro');

    if(hasPro.index() > a.index()){
        if(count > 3) {
            --count;
            change("left");

            $('.caruselWrap').animate({
                left: '+=' + add,
            })
        }
    } else if(hasPro.index() < a.index()) {
        if(flag) {
            ++count;
            if(imgLoaded < count) {
                ajax();
            }
            change("right");
            $('.caruselWrap').animate({
                left: '-=' + add,
            })
        }
    } else {
        console.log("Center image clicked! Full screen view");
    }
}

$('.caruselWrap img').click(function(){
    var img = $(this);
    check(img);

    console.log("count: " + count);
    console.log("images loaded: " + imgLoaded);

})

})

Hi, i need advice in modifying my code. Main assumption is that carousel has 3 images visible, center image always has class "pro".
Main problem here is that with loading images via ajax i'm getting out of range with images avaible for gallery. It stops on next (non existing) element/img in folder.
Click for preview
Any advices would be appreciated.

A: You are using Jquery, Then use jquery version of ajax. Take a look
     // get ajax request

     $.get('url',{param:value,param2:value},function(response){
         // do your stuff with response;
     });

     // post ajax request
     $.post('url',{param:value,param2:value},function(response){
         // do your stuff with response;
     });

   // another version
     $.ajax({
         url:'',
         method:'POST/GET',
         success: function(response){
                      // do your stuff with response;
        }
     });


text:
Q: How to add simple image upload to a form? I have a html form. I want to add a simple image upload feature to it and it will be send the image to a php page called "next.php". Any suggestions on how to do it?

A: Create an HTML form like the following:

<form action="next.php" method="post" enctype="multipart/form-data">
Image:
<input type="image" name="image" id="image" />

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

Your "next.php" file could handle the image similar to this:
<?php

if ($_FILES["file"]["error"] > 0)
    echo "Error: " . $_FILES["image"]["error"] . "
";
else
{
    echo "Upload: " . $_FILES["image"]["name"] . "
";
    echo "Type: " . $_FILES["image"]["type"] . "
";
    echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb
";
    echo "Stored in: " . $_FILES["image"]["tmp_name"];
}

At this point, you can make it more secure by checking the type and ensuring it's only jpg, gif, png, or of the sort. I would recommend copying the image into 2 or 3 sizes (thumb, medium, original), and deleting it from the temporary directory. You could use ImageMagick to resize the images and then use the filesystem functions to move around and delete temporary uploads.

A: I'm not aware of any means to interact with a file input on the client-side, so you'll need to verify/validate the uploaded file server-side (within the 'next.php' script), but this should be enough:
<form action="path/to/next.php" method="post" enctype="multipart/form-data">
    <fieldset>
        <input type="file" name="picture" id="picture" />
    </fieldset>
</form>


text:
Q: Bower is not updating in Visual Studio 2015 CTP 6 I have just installed React using Bower inside Visual Studio 2015 CTP6.
In Dependencies -> Bower -> React (0.13.0)
I do have React package.(js files are also in bower_components/react folder on disk)
When I try to add script  <script src="~/lib/ I do not have React in my list of scripts.
Intelligence not working and JavaScript is not loaded.

A: I think you have configure the exportsOverride section in the bower.json

A: in this sample I added a simple rule to copy all the .js files:
{
    "name": "WebApplication",
    "private": true,
    "dependencies": {
        "bootstrap": "3.0.0",
        "jquery": "1.10.2",
        "jquery-validation": "1.11.1",
        "jquery-validation-unobtrusive": "3.2.2",
        "hammer.js": "2.0.4",
        "bootstrap-touch-carousel": "0.8.0",
        "react": "~0.13.1"
    },
    "exportsOverride": {
        "bootstrap": {
            "js": "dist/js/*.*",
            "css": "dist/css/*.*",
            "fonts": "dist/fonts/*.*"
        },
        "bootstrap-touch-carousel": {
            "js": "dist/js/*.*",
            "css": "dist/css/*.*"
        },
        "hammer": {
            "": "hammer.{js,min.js}"
        },
        "react": {
            "":  "*.js"
        }

    }
}

the result is that when you run install bower task you'll find inside the wwwroot/lib a directory named react with just the ,js files.


text:
Q: Waiting for two different REST/Network calls to complete I am making a lot of calls using REST and decided to separate these connection calls into a separate object, to be called from my UI classes.  Here is the function I am using, it will not wait for the requests to be complete.  I am not sure what I am doing wrong and have tried using many examples off stack and the net, including:
Wait until swift for loop with asynchronous network requests finishes executing
Waiting until the task finishes
//let loader = from Oauth2/p2_OAuth2 pod to load JSON
func ConnectionHandler()
{

        let dg = DispatchGroup()

        switch self.RequestType
        {
        case aRequest:
            //if I make a single call here, works fine
        case bRequest:
            //if I make a single call here, works fine
        case abRequest:
            //when making requests for both type a and b, can't get it to work
            dg.enter()

            loader.perform(request: self.userDataRequest)
            { response in
                do
                {
                    let json = try response.responseJSON()
                    self.structWrapper.aArray = self.loadAArray(dict: json)
                }
                catch let error {
                    self.didCancelOrFail(error)
                }
            }
            self.dexRequestType = DexRequestTypesEnum.glucoseValues
            //ignore last line.  should be removed.
            loader.perform(request: self.userDataRequest)
            { response in
                do
                {
                    let json = try response.responseJSON()
                    self.structWrapper.bArray = self.loadBArray(dict: json)                }
                catch let error {
                    self.didCancelOrFail(error)
                }
            }
            dg.leave()
            dg.notify(queue: .main)
            {
                //will print, but requests are not complete, arrays are empty, even though breakpoints hit in loading them.
              for x in self.structWrapper.aArray
               {
                 print(x.displayTime + ":" + x.units)
               }
               for y in self.structWrapper.bArray
               {
                print(y.displayTime + ":" + String(y.someNumber)
               }
                print("tasks complete")
             }

        }

    }

A: you have to use
dg.enter()  before call Task
dg.leave()  after task finished
Like that:
func ConnectionHandler()
{

    let dg = DispatchGroup()

    switch self.RequestType
    {
    case aRequest:
        //if I make a single call here, works fine
    case bRequest:
        //if I make a single call here, works fine
    case abRequest:
        //when making requests for both type a and b, can't get it to work
        dg.enter()

        loader.perform(request: self.userDataRequest)
        { response in
            do
            {
                let json = try response.responseJSON()
                self.structWrapper.aArray = self.loadAArray(dict: json)
            }
            catch let error {
                self.didCancelOrFail(error)
            }

           dg.leave()
        }
        self.dexRequestType = DexRequestTypesEnum.glucoseValues

        dg.enter()

        loader.perform(request: self.userDataRequest)
        { response in
            do
            {
                let json = try response.responseJSON()
                self.structWrapper.bArray = self.loadBArray(dict: json)                }
            catch let error {
                self.didCancelOrFail(error)
            }

          dg.leave()
        }

        group.notify(queue: .main)
        {
            //will print, but requests are not complete, arrays are empty, even though breakpoints hit in loading them.
          for x in self.structWrapper.aArray
           {
             print(x.displayTime + ":" + x.units)
           }
           for y in self.structWrapper.bArray
           {
            print(y.displayTime + ":" + String(y.someNumber)
           }
            print("tasks complete")
         }

    }

}


text:
Q: How to dynamically share data between MyAppUITests and the MyApp target? Within MyAppUITests I can pass some parameters to MyApp in following way:
app.launchEnvironment = ["my_param": "value"]
app.launch()

This is visible for MyApp and I can read this:
if let value = NSProcessInfo.processInfo().environment["my_param"] {
   //do sth with value
}

But this is how I can set it up BEFORE I launch the app. For some reason, I need to change "my_param" on runtime AFTER I launch the app. Any suggestions? I would appreciate any help.
Why do I need to do it for?
I need "my_param" to be able to change within MyAppUITests after I launch the app. "my_param" needs to be visible for MyApp in whatever place within MyApp. my_param might be mock response for my network client or whatever I need for that time.
NOTE:
Similar functionality is between App and its extension. There is solution with App Group and shared NSUserDefaults. What is here? Do I have to save it on device to share sth to another target?
UPDATE:
App Group doesn't work here.


text:
Q: Libgdx get scaled touch position I'm working at a android game using LIBGDX.
@Override
public boolean touchDown(int x, int y, int pointer, int button) {
    // TODO Auto-generated method stub

    return false;
}

Here, the x and y returns the position of the touch of the device screen, and the values are between 0 and the device screen width and height.
My game resolution is 800x480, and it will keep its aspect ratio on every device.
I want to find out a way to get the touch position, related to the game rectangle, this image can explain exactly:

Is there a way to do it?
I want to get the touch position related to my viewport..
I use this to keep the aspect ratio
http://www.java-gaming.org/index.php?topic=25685.0

A: In the newer version of LibGDX you can achieve it with the built in viewports.
Firstly choose your preferred viewport the one you want here is FitViewport.
You can read about them here:
https://github.com/libgdx/libgdx/wiki/Viewports
Next, you declare and initialize the viewport and pass your resolution and camera:
viewport = new FitViewport(800, 480, cam);

Then edit your "resize" method of the screen class to be like that:
@Override
public void resize(int width, int height) {
    viewport.update(width, height);

}

Now wherever you want to get touch points you need to transfer them to new points according to the new resolution. Fortunately, the viewport class does it automatically.
Just write this:
Vector2 newPoints = new Vector2(x,y);
newPoints = game.mmScreen.viewport.unproject(newPoints);

Where x and y are the touch points on the screen and in the second line "newPoints" gets the transformed coordinates. Now you can pass them wherever you want.

A: Unproject your touch.
Make a Vector3 object for user touch:
Vector3 touch = new Vector3();

And use the camera to convert the screen touch coordinates, to camera coordinates:
@Override
public boolean touchDown(int x, int y, int pointer, int button){

    camera.unproject(touch.set(x, y, 0)); //<---

    //use touch.x and touch.y as your new touch point

    return false;
}

A: After 1-2 paintful hours I finnaly found the solution..
if (Gdx.input.isTouched()) {
        float x = Gdx.input.getX();
        float y = Gdx.input.getY();
        float yR = viewport.height / (y - viewport.y); // the y ratio
        y = 480 / yR;

        float xR = viewport.width / (x - viewport.x); // the x ratio
        x = 800 / xR;

        bubbles.add(new Bubble(x, 480 - y));

    }

Edit: this is an old deprecared way to do it, so don't.


text:
Q: How to use Powershell to customize "Region and Language" settings in win7 or win2008 I am new to Powershell and I have searched the internet for whole day but still cannot find out how to customize "Region and Language" settings using Powershell in win7 or win2008.
I want to change the following settings within Powershell:

*

*Current System Locale

*Short Date and Long Date format

*Short Time and Long Time format

*Current Location
Anybody knows how to do that using Powershell? Cmd/Bat/.NET solutions also welcome!

A: I know your question was about Windows 7; this information may be helpful for those now running newer versions. Set-WinUserLanguageList, New-WinUserLanguageList and Get-WinUserLanguageList in Windows 8 and up let you control the installed languages. For example to add a language:
$list = Get-WinUserLanguageList
$list.Add("fr-FR")
Set-WinUserLanguageList $list

Set-Culture in PowerShell 3 lets you change culture, for example to choose defaults for Germany:
Set-Culture de-DE

Or, to set custom formats:
$culture = Get-Culture
$culture.DateTimeFormat.ShortDatePattern = 'yyyy-MM-dd'
$culture.DateTimeFormat.LongDatePattern = 'dddd, d MMMM yyyy'
$culture.DateTimeFormat.ShortTimePattern = 'h:mm tt'
$culture.DateTimeFormat.LongTimePattern = 'h:mm:ss tt'
Set-Culture $culture

To change the location, use Set-WinHomeLocation, for example to set the user's location to Austria:
Set-WinHomeLocation -GeoId 14

MSDN has a list of GeoIds and a TechNet has a reference for international settings cmdlets.

A: @bourne lead me to
& $env:SystemRoot\System32\control.exe "intl.cpl,,/f:`"c:\setKeyboardUK.xml`""

Note the lack of a space between the ,, and /f, the use of quotes around the whole thing and the back tick to escape the quotes around the path (that are necessary).
This is my setKeyboardUK.xml file
<gs:GlobalizationServices xmlns:gs="urn:longhornGlobalizationUnattend">
<!--User List-->
<gs:UserList>
    <gs:User UserID="Current" CopySettingsToDefaultUserAcct="true" CopySettingsToSystemAcct="true"/>
</gs:UserList>
<gs:UserLocale>
    <gs:Locale Name="en-GB" SetAsCurrent="true"/>
</gs:UserLocale>
<!--location-->
<gs:LocationPreferences>
    <gs:GeoID Value="242"/>
</gs:LocationPreferences>
<gs:InputPreferences>
    <!--en-GB-->
    <gs:InputLanguageID Action="add" ID="0809:00000809" Default="true"/>
</gs:InputPreferences>

To check if the settings are applied(because failures are silent) open Event Viewer and "Application and Services Logs" then "Microsoft", "Windows", "International","Operational" any successful changes or failures are logged here(the logging is enabled by default).
FYI I did all this on Powershell 3 on Windows 2008 R2 64bit. YMMV

A: Hey I know this is kind of old, but I had to do the same but I did it in a batch script.
I am now currently trying to figure out how to do it in powershell.
Check out my post here - https://superuser.com/questions/353752/windows-7-change-region-and-language-settings-using-a-script
The same should apply in Powershell using the following command:
PS C:\> & $env:SystemRoot\System32\control.exe "intl.cpl,, /f:path\to\xml\file\change_system_region_to_US.xml"

However, for me it doesn't work for some reason even though the
command executes without error, the changes don't actually take effect.
If you run the same command from a standard CMD window, the changes take effect immediately.
And if you remote the quotations to match the way you would run it in a CMD window you get
the following error:
PS C:\> & $env:SystemRoot\System32\control.exe intl.cpl,, /f:"path\to\xml\file\change_system_region_to_US.xml"
    Missing argument in parameter list.
    At line:1 char:50
    + & $env:SystemRoot\System32\control.exe intl.cpl,, <<<<  /f:"path\to\xml\file\change_system_region_to_US.xml"
        + CategoryInfo          : InvalidOperation: (,:String) [], RuntimeException
        + FullyQualifiedErrorId : MissingArgument

Powershell doesn't appear to like the comma's very much.
Doing so in a .bat file though works like a charm. Just make sure you get your country codes and stuff right. It might require a little tinkering to get the .xml file to change the parameters you want.


text:
Q: Laravel - How to Sum relative table with limit result? I have these 2 models.
I want to get sum of 12 columns comment_count in youtube_video_insights table.
How can I do that with Query Builder or Eloquent.
I try to use something like in my Repository this but it didn't work.
It's just sum all the comment_count columns.
$this->youtube_channel_insight
            ->join('youtube_video_insights',function ($q){
                $q->on('youtube_channel_insights.id','=','youtube_video_insights.youtube_channel_insight_id')
                    ->orderBy('youtube_video_insights.id','desc')
                    ->limit(12);
            })
            ->where('youtube_channel_insights.id',$id)
            ->select(\DB::raw(
                "SUM(youtube_video_insights.comment_count) as total_comment"
            ))->get();

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class YoutubeChannelInsight extends Model
{
    protected $guarded = ['id'];

    public function videos()
    {
        return $this->hasMany(YoutubeVideoInsight::class);
    }
}

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class YoutubeVideoInsight extends Model
{
    protected $guarded = ['id'];
}

A: I assume the structure of your tables are:
for youtube_channel_insights's table you have :
id | name
----------------------------------------
1  | channel_01
2  | channel_02

and for youtube_video_insights's table you have:
id | channel_id|    name    | comment_count
----------------------------------------
1  |     1     |  video_01  |      20
2  |     1     |  video_02  |      40
3  |     2     |  video_03  |      5
4  |     2     |  video_04  |      15

Now you should wright your query like this:
$sub1 = YoutubeVideoInsight ::select('comment_count', 'channel_id')
->whereRaw('channel_id = 2')->orderBy('id', 'Desc')->limit(2);

$sub2 = DB::table(DB::raw("({$sub1->toSql()}) as sub"))
->select(DB::raw('
SUM(`comment_count`) AS total_comment,
channel_id
'));

return $query = YoutubeChannelInsight ::joinSub($sub2,'sub2',function($join){
$join->on('channels.id','=','sub2.channel_id');
})->get();


text:
Q: Send the API Headers in Rest Assured using java API Headers have two parameter Content-Type=application/json and also accesstoken = "some_token"
I trying to automate the API using Rest assured but not successful.
Below is the code
RestAssured.baseURI = prop.getProperty("serviceurl1");

//2. define the http request:
RequestSpecification httpRequest = RestAssured.given()
                .filter(new ResponseLoggingFilter())
                .filter(new RequestLoggingFilter());

JSONObject requestParams = new JSONObject();
requestParams.put("longitude", eLongitude);
requestParams.put("latitude", eLaititude);
requestParams.put("country", eCity);

httpRequest.headers("Content-Type", "application/json");
httpRequest.headers("accesstoken", "some_token.");
httpRequest.body(requestParams.toJSONString());
int statusCode = response.getStatusCode();
System.out.println("the status code is: "+ statusCode);

Assert.assertEquals(statusCode, TestUtil.RESPONSE_CODE_200);

System.out.println("the status line is: "+ response.getStatusLine());

//6. get the headers:
Headers headers = response.getHeaders();
System.out.println(headers);

String contentType = response.getHeader("Content-Type");
System.out.println("the value of content-type header is: "+ contentType);

String contentLength = response.getHeader("Content-Length");
System.out.println("the value of Content-Length header is: "+ contentLength);

Getting error message as "Provide Application Token" and 404 error code display.

A: Your httpRequest.headers("accesstoken", "kggkgkgkgketdfgxgcccvcdftfty."); is wrong. It should be:
 httpRequest.headers("Authorization", "Bearer "+token);

A: can you try this once
Response resp = given().when().contentType(ContentType.JSON).header("accesstoken", "token").body(body).put("url");
You can pass the HashMap as body

A: These are the issues I can think of

*

*This might be an internal API and it is expecting "Provide Application Token" and not the "accesstoken"

*The error code you are getting is 404. So either the service is down or the URL you are using is not correct.

Hope this helps :)


text:
Q: Table of contents numbering is strange
Possible Duplicate:
ToC numbering problem

My LaTeX document is acting strangely. Here is a simplified version of it:
\documentclass{article}

\begin{document}

\tableofcontents
\newpage

\addcontentsline{toc}{part}{A Part of My Document}
\include{includedfile}

\end{document}

And in includedfile.tex:
\section{My Section Title}
Quack.

Clearly, in the table of contents, the heading for the part should precede the one for the section, but it doesn't! What's wrong?

A: Try \input instead of \include -- it's as if you typed in the contents of the file there. I believe \include does some additional processing, so maybe that's causing your problem.

A: The \include macro is intended for inputting chapters in long documents. Thus any file used with \include really should start
\chapter{Some-chapter}

It also automatically starts a new page (which will confuse the order of things with your \addcontentlines instruction, I think). What you want is \input. This simply places the contents of the subfile into the TeX source at the current location, with no additional stuff going on. If you replace \include with \input then all is well. (Note: I'm trying to 'flesh out' the answer given by Reid Priedhorsky here: the end result is of course the same.)

A: The problem is to do with the \newpage command.  If you remove it, I think you'll get exactly the output you're looking for.


text:
Q: html + css: horizontal scroll lanes? really simpel markup:

Headline 01

Lorem ipsum dolor...

Headline 02

Lorem ipsum dolor...

my css looks like this:
.horizontal {
    overflow-x:scroll;
    clear:both;
}

.horizontal p {
    float:left;
    width:500px;
    padding:0 20px 20px 0;
}

.horizontal p.image {
    width:1024px;
}

I have no idea how I can create horzizontal "frames" like the mockup beneath without using actual frames.
Right now, the images do not float because the with of .horizontal is 100% inside of #page-wrap. So they are aligned underneath each other. I want all images to be side by side within .horizontal. Each lane should have a seperate scrollbar that lets me scroll through the images.
I want to create this:

Any idea how to solve this?
Moreover I have a few more things I don't know how to solve... e.g. the scrollbars or each .horizontal should just appear if there is actual content that has to be scrolled (if there are no images the scollbar shouldn't be there)
thank you for your help
btw. I'm using jquery in my project, is this only possible with js?

A: From the mockup you have posted, I gather this:

*

*Even though the markup has each image in its own paragraph, you want them to be displayed inline, within the same line.

*You want that container to have a horizontal scroll bar.

*The images should use said scroll bar, by not wrapping onto multiple lines when their total width grows above the width of the container.
Such layout can be implemented using CSS like this:
.horizontal p.image {
    display: inline;         /* 1 */
}

.entry {
    overflow-x: scroll;      /* 2 */
    white-space: nowrap;     /* 3 */
}

Here's a demo using the above CSS with your markup (width/height constraints on images dropped to make it display better in a small window): http://jsfiddle.net/TT9hq/
Replace overflow-x: scroll with overflow-x: auto if the scroll bar is only to show up when there are (wide) enough images to require a scroll bar.

A: First, don't wrap your images in a p if you want them all in the same line, try putting them in spans. Or, dont' put them in anything and set the display:inline style on them. As for your scrolling problem, just set overflow-x: auto on that container div instead of overflow-x:scroll
EDIT: If you have to keep them in ps, put display:inline on the ps.


text:
Q: Como cambiar el tamaño de un input dentro de un td? Tengo el siguiente codigo

        $us Pto.
        Costo en $us
        costo en Bs.
        Costo Por Tonelada

        Zn
        <input size="7" style="text-align:center" type="text">
        Zn
        <input size="7" style="text-align:center" type="text" readonly>
        Zn
        <input size="7" style="text-align:center" type="text" readonly>
        <input size="7" style="text-align:center" type="text" readonly>
        <input size="7" style="text-align:center" type="text" readonly>

Como podran notar los input dentro de un td tienen un tamaño que hace sobrar espacios a la derecha e izquierda del td, esto lo consegui con el atributo size del input.
Pero quiero que los inputs ocupen el 100% del td, asi que mi pregunta es:

Como hacer que un input ocupe el 100% de un td?

A: Como te mencionaron en los comentarios puedes usar width: 100% pero esto no te funcionará bien si no cambias el box-sizing a border-boxpues el valor por defecto content-box hace que el calculo no sea correcto como puedes comprobar aquí

    $us Pto.
    Costo en $us
    costo en Bs.
    Costo Por Tonelada

    Zn
    <input style="text-align:center; width: 100%" type="text">
    Zn
    <input style="text-align:center; width:100%" type="text" readonly>
    Zn
    <input style="text-align:center; width:100%" type="text" readonly>
    <input style="text-align:center; width:100%" type="text" readonly>
    <input style="text-align:center; width:100%" type="text" readonly>

Poniendoselo a los inputs ya lo calcula correctamente

input {
  box-sizing: border-box;
}

    $us Pto.
    Costo en $us
    costo en Bs.
    Costo Por Tonelada

    Zn
    <input style="text-align:center; width: 100%" type="text">
    Zn
    <input style="text-align:center; width:100%" type="text" readonly>
    Zn
    <input style="text-align:center; width:100%" type="text" readonly>
    <input style="text-align:center; width:100%" type="text" readonly>
    <input style="text-align:center; width:100%" type="text" readonly>

Este reset se usa mucho para aplicarle esta corrección a todos los elementos pero puede afectarte un layout que ya esté establecido. Lo ideal es empezar a construirlo con el reset aplicado desde el principio
*, *::before, *::after {
    box-sizing: border-box;
}

Este es uno de los cambios que aplica por defecto Bootstrap cuando lo incluyes en tu sitio.


text:
Q: Vertical Algin Textarea Hi I have a text box inside a page and I need it horizontally AND vertically aligned middle.  I have been trying the "display table" method with not avail.
The problem is when I set the table-row my text box looses all formatting I have set on it and shrinks down to the smallest size,it also sticks to the left side of the page.
Any help is much appreciated!

          <textarea id="text" ></textarea>

CSS
#outer{
  display:table-row;
  height:230px;
}

#inner{
  display:table-cell;
  vertical-align:middle;
}

#text{
    background:#e9e9e9;
    padding:10px;
    resize: none;
    font-size: 10px;
    color: #000;
    height: 100px;
    width: 95%;
}

A: Try using display:table on the outer div and table-cell on the inner div.
jsFiddle example (border added to see alignment)
#outer {
    height:230px;
    border:1px solid #999;
    display:table;
    width:100%;
}
.inner {
    display:table-cell;
    vertical-align:middle;
    text-align:center;
}
#text {
    background:#e9e9e9;
    padding:10px;
    resize: none;
    font-size: 10px;
    color: #000;
    height: 100px;
    width: 95%;
}

A: Since you have declared the height of the element you want centered, you can use absolute centering, as described here. Simply add a
text-align: center

To add horizontal centering.


text:
Q: Adding a table to an existing PDF with itext5 in kotlin I'm a newbie to java/kotlin programming, and this is my first project.
I have an existing pdf, created in another activity (activity1) with itext, passed to another activity (activity2) with an intent as "pdfPath".
I want to open that pdf and append a table at the end of that pdf with data acquired in activity2.
But every time i try it, my program eliminates everything on that pdf and just create another pdf with the table.
Here's the code:
            val pdfPath = intent.getStringExtra("pdfPath")
            val mDoc = Document()
            var writer = PdfWriter.getInstance(mDoc, FileOutputStream(pdfPath))
            mDoc.open()

            var table = PdfPTable(2)
            var imgTec = Image.getInstance(StoredPath)
            var cell = PdfPCell(imgTec)
            table.addCell(cell)

            cell = PdfPCell(Phrase("Signature"))
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell)
            mDoc.add(table)
            mDoc.close()

A: Finally made it:
val pdfPath = intent.getStringExtra("pdfPath")
val reader = com.itextpdf.text.pdf.PdfReader(pdfPath)
val pdfName_write = "TEST_" + SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date()) + ".pdf"
val pdfPath_write = Environment.getExternalStorageDirectory().toString() + "/" + pdfName_write
val stamper = PdfStamper(reader, FileOutputStream(pdfPath_write))
val column = ColumnText(stamper.getUnderContent(1))

//Adjust the position of the rectangle
val rectPage = Rectangle(36F,36F,30F, 20F)

column.setSimpleColumn(rectPage)
var table = PdfPTable(2)

//Creating cell 1
var cell = PdfPCell(Phrase("TEST1"))
table.addCell(cell)
column.addElement(table)

//Creating cell 2
cell = PdfPCell(Phrase("TEST2"))
table.addCell(cell)
column.addElement(table)
column.go()

stamper.setFormFlattening(true)
stamper.close()
reader.close()


text:
Q: Updating serialized data in laravel 5 I have orders table where I have column named cart and data in that column are serialized from my cart.
Now I try to make order edit function for admins where they can edit orders and so far I can get my data such as quantity out of my serialized data.
My question is how to edit that data (in this case quantity) in my cart column without messing with the rest of data in it?
here is my update function (still nothing about quantity):
public function update(Request $request, $id)
    {
        $order = Order::find($id);
        $this->validate($request, array(
            'payment_id'=>'nullable',
            'orderstatus_id' => 'required|numeric',
            'address_id' => 'required|numeric',
        ));

        $order = Order::where('id',$id)->first();
        $order->payment_id = $request->input('payment_id');
        $order->orderstatus_id = $request->input('orderstatus_id');
        $order->address_id = $request->input('address_id');

        $order->save();

        return redirect()->route('orders.index',
            $order->id)->with('success',
            'Order updated successfully.');
    }

and here is how I show my order quantity in my order.edit page:
function
public function edit($id)
    {
        $order = Order::find($id);
        $order->cart = unserialize($order->cart);
        $statuses = Orderstatus::all();
        $addresses = Address::where('user_id', $order->user_id)->get();
        return view('admin.orders.edit', compact('order', 'statuses', 'addresses'));
    }

blade

   @foreach($order->cart as $item)

        {{ Form::label('quantity', 'Quantity') }}
        {{ Form::text('quantity', $item['quantity'], array('class' => 'form-control')) }}

   @endforeach

Thanks.
update
sample of my serialized code
O:32:"Darryldecode\Cart\CartCollection":1:{s:8:"�*�items";a:1:{i:29;O:32:"Darryldecode\Cart\ItemCollection":2:{s:9:"�*�config";a:4:{s:14:"format_numbers";b:0;s:8:"decimals";i:0;s:9:"dec_point";s:1:".";s:13:"thousands_sep";s:1:",";}s:8:"�*�items";a:6:{s:2:"id";i:29;s:4:"name";s:6:"effewf";s:5:"price";d:24524;s:8:"quantity";i:3;s:10:"attributes";O:41:"Darryldecode\Cart\ItemAttributeCollection":1:{s:8:"�*�items";a:0:{}}s:10:"conditions";a:0:{}}}}}

A: You can keep the data as JSON and use $casts property to make Laravel convert cart data from JSON to an array and back automatically:
protected $casts = [
    'cart' => 'array',
];

So, you will be able to work with $order->cart as with an array.

Once the cast is defined, you may access the attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the attribute, the given array will automatically be serialized back into JSON for storage

https://laravel.com/docs/5.5/eloquent-mutators#array-and-json-casting


text:
Q: Hide Authorization header from being displayed in Swagger3 I am using JWT Bearer token for authorization. I have added common authorization in SWAGGER UI which is working fine. But API level authorization RequestHeader is still showing in swagger UI. How can I hide it. Please refer to image 1.
Swagger UI Screenshot
Controller Code
@SecurityRequirement(name = "my-notes-api")
@Operation(description = "Update the existing note",
            summary = "Update Note",
            tags = "Notes")
@PutMapping(path = "/update-note",
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
public Notes updateNote(@RequestHeader("Authorization") String authToken,
                        @RequestHeader("note-id") String noteId,
                        @RequestBody @Valid NotePOJO note) throws BusinessException {

    return notesService.updateNote(jwtUtils.extractUserId(authToken.substring(7)), noteId, note);

}

I can not remove @RequestHeader("Authorization") String authToken from controller parameters as I am fetching the userId from this token only.


text:
Q: How do I round to up to two decimal points in MongoDB? I have the following documents in my MongoDB:
{
    name: "Brian"
    score: 7.8321234
}

{
    name: "Anna"
    score: 10.0
}

I'm trying to round to up to two decimals, so it would look like this:
{
    name: "Brian"
    score: 7.83
}

{
    name: "Anna"
    score: 10.0
}

Is it possible to do that in MongoDB?


text:
Q: Way to alter behavior based on caller using property getter without reflection or making caller a member in Python So I'm writing a test framework for a large website, and am currently working on modeling the UI driver.  I have a UI Session that abstracts a number of emulators and drivers for browsers and mobile devices.  this object also holds state information about the browser session, including a history of page objects, the top of which is the current page.  My problem is that I want my page objects to lazy load data from the browser (properties set up with getters that check whether we've extracted the data, if not, whether this is the current page, and if so, pulls the data from the browser and caches it in the page object), but that means they need access to the abstraction layer provided by the session.
The first idea of course was just sticking the session in the page, but that creates a circular reference, which is bad.  I also considered trying to define multiple interfaces for page, but I couldn't see how that would really work too well.  What I really want is to be able to intercept the call in session then have session redirect the call down to page to a hidden getter that also takes session as an argument, but I haven't been able to figure out how to do that.
Is there a good solution or design pattern that I could use here to get the info and access I need where I need it without having circular references or giving up lazy loading?  I don't want to make the interface more complicated by forcing users to sometimes call methods and sometimes call properties or members to access the same info (the idea is to hide the fancy footwork behind the scenes and make using the framework dead simple).
I actually do have a CurrentPage class that all it does is store the current_page in a class variable which is set by session on navigate events, so I suppose I could make current_page a magic global-esque accessor that would be the only way to actually get data off the page and have it use a special interface and store the session object as well, but that seems clunky to me.
Anyone have any suggestions?

A: You said:
"The first idea of course was just sticking the session in the page, but that creates a circular reference, which is bad."
But that's not true.  Circular references won't get garbage collected instantly the way non-circular ones will, and __del__ methods won't get called, but as long as you're aware of both of those limitations and don't have needs that conflict with them, circular references are fine.  See:
http://docs.python.org/reference/datamodel.html#object.__del__
Having pages store a reference to the session should be fine.
Edit: if session and page are in different files and circular imports become an issue, you can use an approach like this:
# session.py
import page
class Session(object):
    def __init__(self):
        self.page_list = []
    def addPage(self, url):
        self.page_list.append(page.Page(self, url))

# page.py
class Page(object):
    def __init__(self, session, url):
        self.session = session
        self.url = url

As long as you don't need to construct Sessions inside of page.py you won't need to import it at all, since there won't be a need for capital-S Session (the class).  If that changes, you can do something like:
# page.py
class Page(object):
    # ...
    def something(self):
        import session
        self.other_session = session.Session()