text:
Q: org.springframework.beans.factory.BeanCreationException in Spring boot application I have created a spring boot application with spring tool suite. I get following error when running as 'Spring boot app'
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController':
Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: public com.frameworkonly.webapp.service.TaskServiceInterface com.frameworkonly.webapp.controller.HomeController.taskServiceInterface;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.frameworkonly.webapp.service.TaskServiceInterface] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
    at com.frameworkonly.webapp.SpringBootDemoApplication.main(SpringBootDemoApplication.java:10) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException:
Could not autowire field: public com.frameworkonly.webapp.service.TaskServiceInterface com.frameworkonly.webapp.controller.HomeController.taskServiceInterface;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.frameworkonly.webapp.service.TaskServiceInterface] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    ... 17 common frames omitted

HomeController.java
package com.frameworkonly.webapp.controller;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.frameworkonly.webapp.domain.Task;
import com.frameworkonly.webapp.service.TaskServiceInterface;

@Controller
public class HomeController {
    @Autowired
    public TaskServiceInterface taskServiceInterface;

 @RequestMapping("/home")
 public String home(Model model) {
     model.addAttribute("allTasks", (ArrayList<Task>)taskServiceInterface.getAllTasks());
     System.out.print("calling tasks");
  return "tasks";
 }
}

TaskServiceInterface
package com.frameworkonly.webapp.service;

import java.util.Collection;

import com.frameworkonly.webapp.domain.Task;

public interface TaskServiceInterface {

    public Task saveTask(Task task);

    public Boolean deleteTask(Long taskId);

    public Task editTask(Task task);

    public Task findTask(Long taskId);

    public Collection<Task> getAllTasks();
}

TaskServiceImplementation
package com.frameworkonly.webapp.service;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;

import com.frameworkonly.webapp.domain.Task;
import com.frameworkonly.webapp.repository.TaskRepository;

public class TaskServiceImplementation implements TaskServiceInterface{

    @Autowired
    protected TaskRepository taskRepository;

    @Override
    public Task saveTask(Task task) {
        return taskRepository.save(task);
    }

    @Override
    public Boolean deleteTask(Long taskId) {
        Task temp = taskRepository.findOne(taskId);
        if(temp!=null){
             taskRepository.delete(temp);
             return true;
        }
        return false;
    }

    @Override
    public Task editTask(Task task) {
        return taskRepository.save(task);
    }

    @Override
    public Task findTask(Long taskId) {
        return taskRepository.findOne(taskId);
    }

    @Override
    public Collection<Task> getAllTasks() {
        Iterable<Task> itr = taskRepository.findAll();
        return (Collection<Task>)itr;
    }

}

SpringBootDemoApplication
package com.frameworkonly.webapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoApplication.class, args);
    }
}

it runs fine when I remove @Autowired annotation from HomeController but get NullPointerException when launching the app as localhost:8080/home
java.lang.NullPointerException: null
    at com.frameworkonly.webapp.controller.HomeController.home(HomeController.java:21) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_77]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_77]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_77]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_77]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) ~[spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832) ~[spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743) ~[spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961) ~[spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895) ~[spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967) ~[spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858) ~[spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.0.33.jar:8.0.33]

A: You are missing an annotation on your implementation. It should be annotated with @Service or another @Component annotation for spring to pick it up using component-scanning.


text:
Q: How to add PHP PDO drivers for Oracle to my Microsoft IIS Express 8 installation? I'm currently using IIS Express 8 to run my PHP project locally, and Oracle SQL Developer for the database.  I need to add PDO support to IIS so I can access SQL.

*

*Which driver(s) would be needed for this and where could I obtain them?

A: Never used any of them, however the file should be in the ext/ directory of the PHP install.  You would just need to uncomment this line in php.ini and restart IIS (I assume):
extension=php_pdo_oci.dll

redpajama_set_name: RedPajamaStackExchange


text:
Q: T-SQL - How to Select and Group Multiple Records (in multiple columns) for Each Employee? We have a table that looks like following:
DATAID Last_Name    First_Name   ADDRESS
1         Smith        John         5000 Street
2         Smith        John         6666 Street
3         Doe          Jim          1111 Street
4         Doe          Jim          2222 Street

As you can see, DATAID is a unique field. Same employee has multiple addresses listed in multiple columns. There are many other columns with unique data for each employee which I didn't include in the example table above. For e.g., phone number, email, etc.
How can I group multiple records for each employee by employee's first and last name? I tried to do a JOIN and didn't get desired results. I also couldn't figure out how to return desired results by running DISTINCT on first_name and last_name only and displaying relevant data for each employee from multiple columns.

A: You can do this:
SELECT
  t1.First_Name,
  t1.Last_Name,
  STUFF((
    SELECT ', ' + t2.Address
    FROM Tablename AS t2
    WHERE t1.First_Name = t2.First_name AND t1.Last_Name = t2.Last_Name
    FOR XML PATH(''))
  ,1,2,'') AS Address
FROM tablename AS t1
GROUP BY t1.First_Name,
         t1.Last_Name;

This will give you the results grouped by First_name and Last_Name with the address coma separated.
See it in action here:

*

*SQL Fiddle Demo
This will give you:
| FIRST_NAME | LAST_NAME |                  ADDRESS |
-----------------------------------------------------
|        Jim |       Doe | 1111 Street, 2222 Street |
|       John |     Smith | 5000 Street, 6666 Street |


text:
Q: SqlDataSource configure programmatically from code I am using in my app in SqlDataSource to fill  a dropdownlist ,i configure it in the web design in Visual studio.
i want that this dropdownlist will change dynamically by a couple of table in the sql.
it is possible to change the  SqlDataSource programmatically from code?

A: SqlDataSource source = new SqlDataSource(connectionString);
source.SelectCommand = String.Format("SELECT id, type FROM {0}" selectedTable)
source.DataBind();


text:
Q: how to store values of foreach as array <?php
  $samgri = $this->crud_model->get_puja_samagri_by_puja_order($param1,$param);

  foreach ($samgri as $row){
    $puja_samagri = $row['puja_samagri'];
  }
  $puja_sam = explode(',', $puja_samagri);

  foreach ($puja_sam as $samagri_id){
    $samg  = $this->crud_model->get_puja_samagri_by_id($samagri_id);
  }

  if(sizeof($samg) == 0){
    echo '
No samagari available
';
  }else{
    foreach ($samg as $row){

?>

but it was fetching only the last record not total records

A: You should add brackets after the array name like:

<?php
$samgri = $this->crud_model->get_puja_samagri_by_puja_order($param1,$param);

//Declare the arrays
$puja_samagri = new array();
$samg = new array();

foreach ($samgri as $row){

$puja_samagri[] = $row['puja_samagri'];

}

$puja_sam     = explode(',', $puja_samagri);

foreach ($puja_sam as $samagri_id){

$samg[]  = $this->crud_model->get_puja_samagri_by_id($samagri_id);
}

if(sizeof($samg) == 0){

echo '
No samagari available
';

}else{

foreach ($samg as $row){

?>

It will use the automatic int position (from 0 going up untill you have all the results). Also it might be a good idea to declare them as arrays before using them.

A: You have to take array after every foreach veriable as like follows :
<?php
$samgri = $this->crud_model->get_puja_samagri_by_puja_order($param1,$param);

foreach ($samgri as $row){

$puja_samagri[] = $row['puja_samagri'];

}

$puja_sam     = explode(',', $puja_samagri);

foreach ($puja_sam as $samagri_id){

$samg[]  = $this->crud_model->get_puja_samagri_by_id($samagri_id);
}

if(sizeof($samg) == 0){

echo '
No samagari available
';

}else{

foreach ($samg as $row){

?>

Hope this will help you :)


text:
Q: Can the solution be improved? PROBLEM STATEMENT

It is the wedding day of Sanchi, the beautiful princess of Byteland.
  Her fiance Krishna is planning to gift her an awesome ruby necklace.
  Krishna has currently b -blue rubies, g -green rubies, r-red rubies
  and y -yellow rubies. He has to arrange the rubies next to each other
  in a straight line to make the necklace. But, there are a couple of
  rules to be followed while making this necklace:

*

*A blue ruby should be followed by either a blue ruby or a red ruby

*A green ruby should be followed by either a green ruby or a yellow ruby

*A red ruby should be followed by either a green ruby or a yellow ruby

*A yellow ruby should be followed by either a blue ruby or a red ruby

*If it is possible, we should always start a necklace with a blue or a red ruby

  Can you tell what is the maximum possible length of the necklace that
  Krishna can make. The length of a necklace is the number of rubies in
  it.
Input Format

*

*The first line contains an integer representing b.

*The second line contains an integer representing r.

*The third line contains an integer representing y.

*The fourth line contains an integer representing g.

  Constraints

*

*0 <= b, r, y, g <= 2000

*At least one of b, r, y, g is greater than 0

  Output Format

*

*A single integer which is the answer to the problem.

  Sample TestCase 1
Input
1
1
1
0
Output
3

My Solution :
package ruby;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class CandidateCode {

public static void main(String[] args) {
    try {
        BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
        Integer b = new Integer(br.readLine());
        Integer r = new Integer(br.readLine());
        Integer y = new Integer(br.readLine());
        Integer g = new Integer(br.readLine());

        if (b + r + y + g > 0 && b <= 2000 && b <= 2000 && r <= 2000 &&
g <= 2000 && y <= 2000 && b >= 0 && r >= 0
                && g >= 0 && y >= 0) {

            ArrayList<Character> necklace = new ArrayList<Character>();
            CandidateCode rn = new CandidateCode();
            int length = rn.calculateLengthofNecklace(b, r, y, g,
necklace);
            System.out.println(length);
        }
    } catch (Exception e) {
    }

}

private int calculateLengthofNecklace(Integer b, Integer r, Integer y, Integer g, ArrayList<Character> necklace) {
    if (anyRemaining(b))
        necklace = addBlue(b, r, y, g, necklace);
    else if (anyRemaining(r))
        necklace = addRed(b, r, y, g, necklace);
    else if (anyRemaining(g))
        necklace = addGreen(b, r, y, g, necklace);
    else if (anyRemaining(y))
        necklace = addYellow(b, r, y, g, necklace);
    // System.out.println("necklace :" + necklace.toString());
    return necklace.size();
}

private ArrayList<Character> addRed(Integer b, Integer r, Integer y, Integer g, ArrayList<Character> necklace) {
    char lastruby = necklace.size() > 0 && necklace.get(necklace.size() - 1) != null
            ? necklace.get(necklace.size() - 1) : 'z';
    if (anyRemaining(r) && (lastruby == 'y' || lastruby == 'b' || lastruby == 'z')) {
        necklace.add('r');
        r = r - 1;
        // System.out.println("in addRed\n b:" + b + " r: " + r + " y: " + y
        // + " g: " + g);
    } else {
        return necklace;
    }
    ArrayList<Character> n1 = new ArrayList<Character>(necklace);
    ArrayList<Character> n2 = new ArrayList<Character>(necklace);
    n1 = addGreen(b, r, y, g, n1);
    n2 = addYellow(b, r, y, g, n2);
    necklace = n1.size() > n2.size() ? n1 : n2;
    return necklace;

}

private ArrayList<Character> addYellow(Integer b, Integer r, Integer y, Integer g, ArrayList<Character> necklace) {
    char lastruby = necklace.size() > 0 && necklace.get(necklace.size() - 1) != null
            ? necklace.get(necklace.size() - 1) : 'z';
    if (anyRemaining(y) && (lastruby == 'r' || lastruby == 'g' || lastruby == 'z')) {
        necklace.add('y');
        y = y - 1;
        // System.out.println("in addYellow\n b:" + b + " r: " + r + " y: "
        // + y + " g: " + g);
    } else {
        return necklace;
    }
    ArrayList<Character> n1 = new ArrayList<Character>(necklace);
    ArrayList<Character> n2 = new ArrayList<Character>(necklace);
    n1 = addBlue(b, r, y, g, n1);
    n2 = addRed(b, r, y, g, n2);
    necklace = n1.size() > n2.size() ? n1 : n2;
    return necklace;
}

private ArrayList<Character> addGreen(Integer b, Integer r, Integer y, Integer g, ArrayList<Character> necklace) {
    char lastruby = necklace.size() > 0 && necklace.get(necklace.size() - 1) != null
            ? necklace.get(necklace.size() - 1) : 'z';
    if (anyRemaining(g) && (lastruby == 'r' || lastruby == 'g' || lastruby == 'z')) {
        necklace.add('g');
        g = g - 1;
        // System.out.println("in addGreen\n b:" + b + " r: " + r + " y: " +
        // y + " g: " + g);
    } else {
        return necklace;
    }
    ArrayList<Character> n1 = new ArrayList<Character>(necklace);
    ArrayList<Character> n2 = new ArrayList<Character>(necklace);
    n1 = addGreen(b, r, y, g, n1);
    n2 = addYellow(b, r, y, g, n2);
    necklace = n1.size() > n2.size() ? n1 : n2;
    return necklace;

}

private ArrayList<Character> addBlue(Integer b, Integer r, Integer y, Integer g, ArrayList<Character> necklace) {
    char lastruby = necklace.size() > 0 && necklace.get(necklace.size() - 1) != null
            ? necklace.get(necklace.size() - 1) : 'z';
    if (anyRemaining(b) && (lastruby == 'y' || lastruby == 'b' || lastruby == 'z')) {
        necklace.add('b');
        b = b - 1;
        // System.out.println("in addBlue\n b:" + b + " r: " + r + " y: " +
        // y + " g: " + g);
    } else {
        return necklace;
    }
    ArrayList<Character> n1 = new ArrayList<Character>(necklace);
    ArrayList<Character> n2 = new ArrayList<Character>(necklace);
    n1 = addBlue(b, r, y, g, n1);
    n2 = addRed(b, r, y, g, n2);
    necklace = n1.size() > n2.size() ? n1 : n2;
    return necklace;

}

private boolean anyRemaining(Integer b) {
    return b > 0;

}

}

Can this solution be made better?

A: TL;DR: you can calculate it simply as b + g + max(2 * min(r, y), 1 + 2 * min(r - 1, y))
The problem with your implementation is that it branches like crazy: if you have a large number of beads, it will take each of the choices - lots of choices - and so it will take a really long time to finish.
I think that the actual construction of longest necklaces is actually pretty simple (even if it results in dull necklaces). I've implemented this here, if you want to try it out.
You can construct a graph of all the possible transitions:
digraph G {
  "B" -> "B"
  "B" -> "R"
  "G" -> "G"
  "R" -> "G"
  "R" -> "Y"
  "G" -> "Y"
  "Y" -> "B"
  "Y" -> "R"
}

You can only visit each of these nodes a certain number of times: you can visit the B node b times, G node g times etc.
If you have at least one of each bead, you have to start at B or R. So,the longest necklace is given by:
(all B)+R+(all G)+Y+R+Y+R+...
  or
R+(all G)+Y+R+Y+R+...+(all B))

where ... means to repeat the Y/R alternation until you run out of beads.
So the length is max(b + 2*min(r, y) + g, 1 + g + min(r-1, y) + b).
Similarly, you can think about the best path if some of the numbers are zero.
If you have zero of one kind:

*

*If b=0, start at R: the maximum length is 2*min(r, y + 1) + g

*If r=0, start at B: the maximum length is b

*If g=0, start at B: the maximum length is b + 2*min(r,y)

*If y=0, start at B: the maximum length is v + 1 + g
If you have zero of two kinds:

*

*If b=r=0, start at G: the maximum length is g + 1

*If b=g=0, start at R: the maximum length is 2*min(r, y + 1)

*If b=y=0, start at R: the maximum length is 1 + g

*If r=g=0, start at B: the maximum length is b

*If r=y=0, start at B: the maximum length is b

*If g=y=0, start at B: the maximum length is b + 1
If you have zero of three kinds (or, rather, only one kind is non-zero):

*

*If b != 0, start at B: the maximum length is b

*If r != 0, start at R: the maximum length is 1

*If g != 0, start at G: the maximum length is g

*If y != 0, start at Y: the maximum length is 1.

You never have zero of all 4 kinds, so there is no case to consider there.
So, a far more efficient solution would be simply to check each of these cases.
However, if you compare all of the logic here, you can find that there is a simple expression which covers all the cases:
b + g + max(2 * min(r, y), 1 + 2 * min(r - 1, y));

So, just implement that! This runs effectively instantly, unlike the original code.
This tells you the length of the longest necklace; but it wouldn't be hard to construct a necklace satisfying the length.


text:
Q: Custom Font installation in Laravel TCPDF I am trying to add custom unicode font(http://www.freebanglafont.com/catetory.php?b=173) with Laravel TCPDF. But it throwing error like
"TCPDF ERROR: Could not include font definition file:"
My controller code:
$pdf->setFontSubsetting(true);
$fontname = TCPDF_FONTS::addTTFfont(public_path().'/fonts/SolaimanLipi.ttf', 'TrueTypeUnicode', '', 32);
$pdf->SetFont($fontname, '', 14, '', true);
$pdf->AddPage();

I have put my font in "public/fonts" and followed the documentation
http://www.tcpdf.org/fonts.php

A: Try placing your font in the tcpdf/fonts folder or setting the K_PATH_FONTS constant to the location of your font. Either way, it is unnecessary (and probably unwise) to keep your font folder in the public folder.

A: Check the TCPDF tools folder, there is a script for adding font. You will find the instruction and example in convert_fonts_examples.txt.

*

*First, copy the .ttf font file in tcpdf\tools\

*In a terminal go to tcpdf\tools folder run the following code

php tcpdf_addfont.php -b -t TrueTypeUnicode -i arial.ttf

*Then, the script will notify you if the font was successfully added.

>>> Converting fonts for TCPDF:
*** Output dir set to ./TCPDF/fonts/
+++ OK   : ./TCPDF/tools/arial.ttf added as arial
>>> Process successfully completed!

Then in you project try to use the added font.

A: *

*Install / download / require the tcpdf library into your project.

*Open the library folder (for example mine was: ./vendor/tecnickcom/tcpdf).

*Notice and enter to the tools folder.

*Copy the TTF file(s) into this tools folder.

*Run this command from the terminal (still from the tools folder): $ PHP
tcpdf_addfont -i BOOKOS.TTF (Replace BOOKOS.TTF with your own fonts)

*Repeat step (5) for each fonts desired.
Coding time..
To change between fonts from your php code, use the following scripts.
$pdf->SetFont($font_family = 'bookos', $variant = '', $fontsize = 11);


text:
Q: The
* Doesn't move inside to the footer even though it is? The  list doesn't move inside the footer even though it is inside the
 tag.
I Tried looking into another useful site and some
of the threads here in SO but no luck....
I also tried putting float:left, etc...

HTML:

Home

Services

Contact

About us

CSS:
   footer {
       background: #444;
   }

   /* First Section */

   .f-sec1 h5 {
       color: #FFFFFF;
   }

   .h-sec {
       font: 22px Arial, Helvetica;
   }

   .sec {
       font: 9px, Arial, Helvetica;
   }

   .fl-li {
       list-style-type: none;
   }
   .f-li li a {
       color: #000000;
       float: right;
   }

   .f-li .current {
       color: #A9A9A9;
       text-decoration: underline;
   }

A: It works fine when you close the footer instead of the section.

footer {
  background: #444;
}

/* First Section */

.f-sec1 h5 {
  color: #FFFFFF;
}

.h-sec {
  font: 22px Arial, Helvetica;
}

.sec {
  font: 9px, Arial, Helvetica;
}

.f-li {
  list-style-type: none;
}

.f-li li a {
  color: #000000;
  float: right;
}

.f-li .current {
  color: #A9A9A9;
  text-decoration: underline;
}

Home

Services

Contact

About us

A: You have not closed the footer tag.

Home

Services

Contact

About us

A: I Added clearfix, and it worked:

Home

Services

Contact

About us


text:
Q: Datasheet View to include overlay data Is there a way to include the data from the calendar overlays in the datasheet view? I am trying to aggregate the data from the different calendars into a table or datasheet format.

A: It doesn't seem possible out of the box, but you can code the data requests you need and the presentation you need. I'll mark this answer community wiki so anyone can improve and add details as needed.


text:
Q: Import a Powershell Module on a Remote Server in a C# Runspace I need to be able to import a module that resides on a remote machine through a C# runspace.
To be clear what I mean by this:  The service I'm creating resides on server A.  It creates a remote runspace to server B using the method below.  Through the runspace I'm trying to import a module on server B.
Here's the method I'm using to make the remote call:
internal Collection<PSObject> RunRemoteScript(string remoteScript, string remoteServer, string scriptName, out bool scriptSuccessful)
    {
        bool isLocal = (remoteServer == "localhost" || remoteServer == "127.0.0.1" || remoteServer == Environment.MachineName);

        WSManConnectionInfo connectionInfo = null;

        if (!isLocal)
        {
            connectionInfo = new WSManConnectionInfo(new Uri("http://" + remoteServer + ":5985"));
        }

        PsHostImplementation myHost = new PsHostImplementation(scriptName);

        using (Runspace remoteRunspace = (isLocal ? RunspaceFactory.CreateRunspace(myHost) : RunspaceFactory.CreateRunspace(myHost, connectionInfo)))
        {
            remoteRunspace.Open();
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.Runspace = remoteRunspace;

                Pipeline pipeline = remoteRunspace.CreatePipeline();

                pipeline.Commands.AddScript(remoteScript);

                Collection<PSObject> results = pipeline.Invoke();

                remoteRunspace.Close();

                scriptSuccessful = myHost.ScriptSuccessful;
                return results;
            }
        }
    }

"remoteScript" is set to the Powershell script I want to run.  For example:
"Import-Module Modulename;CustomCommand-FromModule -parameter(s) -ErrorAction stop"

The module is not packedged together it's a psd1, psm1, and a bunch of script files that reside in C:\\Powershell\ModuleName on the remote server (server B) and I have tested and made sure that it is calling the ModuleName.psd1 file in the C:\\Powershell\ModuleName directory.
Inside the ModuleName.psd1 file is the line:
ModuleToProcess = 'ModuleName.psm1'

However I get a very weird error if I try to run it through the c# runspace.
If I send in the following as a parameter to "remoteScript":
"Import-Module Modulename"

I get the following error:

System.Management.Automation.RemoteException: The module to process 'ModuleName.psm1', listed in field 'ModuleToProcess' of module manifest 'C:\Powershell\ModuleName\ModuleName.psd1' was not processed because no valid module was found in any module directory.

The module does exist in one of the "$env:PSModulePath locations and does show up if you run:
get-module -listAvailable

I have also tried putting in the fully qualified path to the ModuleName.psm1 file inside the psd1 file.  When I do that (or what was suggested by x0n below) I get almost the exact same error:

The module to process 'C:\Powershell\ModuleName\ModuleName.psm1', listed in field 'ModuleToProcess' of module manifest 'C:\Powershell\ModuleName\ModuleName.psd1' was not processed because no valid module was found in any module directory.

At this point I'm really not sure where to go or even if this is actually possible.  I've searched everywhere and found some things that seem related, but were never quite the same and tended to be problems I've already overcome or just haven't (to my knowledge) come up against yet.  Any help would be appreciated!  Thanks!

A: I suspect you need to do two things:

*

*Use the absolute path to the .psd1 file: otherwise only modules found in $env:PSModulePath will be considered (it matters not where the script doing the loading is running).

*Ensure you can load the remote script. The default or RemoteSigned execution policies will block remote scripts unless signed.

A: I found that if your module is built on a newer .net runtime(say .net 4.0) and you were trying to load it in powershell 2.0(based on .net 3.5) this can be an issue..to work around this, you need to make sure to load powershell or calling process in .net 4.0 clr.
You can do this by adding an enty for supported runtime in *.exe.config( Create powershell.exe.config if one does not exist already) as applicable.

I tested this works great for the above issue.

A: It's been a little bit since I solved this so I apologize for the delay.  The solution for this actually turned out to be rather easy, though a little weird.
To fix this, in ModuleName.psd1 I commented out:
ModuleToProcess = 'ModuleName.psm1'

And I Added it to NestedModules instead:
NestedModules = Join-Path $psscriptroot 'ModuleName.psm1'

Frankly, I'm not exactly sure why this let the module load successfully, but it worked for me.
It has been a little while since I solved this so it is possible there is some tiny step I missed here.  If this doesn't work for you, let me know what problem you run in to and then I can let you know if it was something additional I had to do.  I am fairly certain this was all though.


text:
Q: Ubuntu 20.04: Wifi adapter not found My wifi stopped working on my laptop. Running a software update using the updater did not work.
Ubuntu: 20.04.1 TLS
Adapters seem to be enabled.
sudo lshw -C network
  *-network UNCLAIMED
       description: Network controller
       product: Killer Wi-Fi 6 AX1650i 160MHz Wireless Network Adapter (201NGW)
       vendor: Intel Corporation
       physical id: 14.3
       bus info: pci@0000:00:14.3
       version: 30
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix cap_list
       configuration: latency=0
       resources: memory:81430000-81433fff
  *-network
       description: Ethernet interface
       product: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:01:00.0
       logical name: enp1s0
       version: 15
       serial: b4:a9:fc:9d:59:fe
       capacity: 1Gbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8169 firmware=rtl8168h-2_0.0.2 02/26/15 latency=0 link=no multicast=yes port=MII
       resources: irq:16 ioport:2000(size=256) memory:81304000-81304fff memory:81300000-81303fff
  *-network
       description: Ethernet interface
       physical id: 2
       bus info: usb@3:3
       logical name: usb0
       serial: 4a:bd:98:cd:db:2b
       capabilities: ethernet physical
       configuration: broadcast=yes driver=rndis_host driverversion=22-Aug-2005 firmware=RNDIS device ip=192.168.42.83 link=yes multicast=yes

Reinstalling bcmwl-kernel-source did not work.
Does this one work in Ubuntu 20.04?
More debug information (see here):
lspci -knn | grep Net -A3; rfkill list
00:14.3 Network controller [0280]: Intel Corporation Killer Wi-Fi 6 AX1650i 160MHz Wireless Network Adapter (201NGW) [8086:34f0] (rev 30)
    Subsystem: Intel Corporation Killer Wi-Fi 6 AX1650i 160MHz Wireless Network Adapter (201NGW) [8086:0000]
    Kernel modules: wl
00:15.0 Serial bus controller [0c80]: Intel Corporation Ice Lake-LP Serial IO I2C Controller #0 [8086:34e8] (rev 30)
    Subsystem: Lenovo Ice Lake-LP Serial IO I2C Controller [17aa:3852]
0: ideapad_wlan: Wireless LAN
    Soft blocked: no
    Hard blocked: no
1: ideapad_bluetooth: Bluetooth
    Soft blocked: no
    Hard blocked: no
2: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no

Additional Information:
Usually, I am able to use the F-NUMBER keys, e.g. F1 to turn of the volume. Right now they do not work.
Installed kernels:
dpkg -l | grep linux-image; dkms status
rc  linux-image-5.4.0-26-generic               5.4.0-26.30                           amd64        Signed kernel image generic
rc  linux-image-5.4.0-37-generic               5.4.0-37.41                           amd64        Signed kernel image generic
rc  linux-image-5.4.0-39-generic               5.4.0-39.43                           amd64        Signed kernel image generic
rc  linux-image-5.4.0-40-generic               5.4.0-40.44                           amd64        Signed kernel image generic
rc  linux-image-5.4.0-42-generic               5.4.0-42.46                           amd64        Signed kernel image generic
rc  linux-image-5.4.0-45-generic               5.4.0-45.49                           amd64        Signed kernel image generic
rc  linux-image-5.4.0-47-generic               5.4.0-47.51                           amd64        Signed kernel image generic
rc  linux-image-5.4.0-48-generic               5.4.0-48.52                           amd64        Signed kernel image generic
rc  linux-image-5.4.0-51-generic               5.4.0-51.56                           amd64        Signed kernel image generic
rc  linux-image-5.4.0-52-generic               5.4.0-52.57                           amd64        Signed kernel image generic
ii  linux-image-5.4.0-53-generic               5.4.0-53.59                           amd64        Signed kernel image generic
ii  linux-image-5.4.0-54-generic               5.4.0-54.60                           amd64        Signed kernel image generic
ii  linux-image-generic-hwe-20.04              5.4.0.54.57                           amd64        Generic Linux kernel image
bcmwl, 6.30.223.271+bdcom, 5.4.0-54-generic, x86_64: installed


text:
Q: Defining interest rate array in python I am trying to create a mortgage calculator on python that can cope with multiple interest rate changes.
I want it to recalculate the repayment formula every month, with a new interest rate.
What is the best way to define an array of interest rates?
Say I had a 20 year mortgage, this array would need 240 entries, which could change at any time, it seems there must be a quicker way than typing out y=(0.01,0.01,0.01,0.015,0.015,0.02,0.015,0.02,0.02..) etc


text:
Q: Rails 3 + JQuery-File-Upload + Nested Model I've been searching for some examples, but have come up short:
I'm trying to implement JQuery-File-Upload on a project I'm working on, but am getting lost as to how to get it to work with nested attributes.
Quick overview:
2 Models:
Comment [has_many :attachments]
Attachment [belongs_to :comment]

Comment accepts_nested_attributes_for :attachments.  Also - I'm using Dragonfly.
I've reviewed the Rails 3 guides on the JQuery-File-Upload site, but they assume it's a singular model, so it's all built around a form.  Does anyone have any examples of their implementation or is there an existing tutorial that I haven't yet stumbled across?
I'm sure someone has had a similar issue... is JQuery-File-Upload to appropriate tool or should I look at something else?

A: I just wanted to throw my answer in here as well as Stone's. I spent nearly two solid days getting this to work (Stone was right, it was a PITA!), so hopefully my solution will help someone. I did it just a touch different than Stone.
My app has Features (a comic, puzzle, text-column, etc) and FeatureAssets (individual comic panels/color versions, question & answer files for a specific crossword, etc). Since FeatureAssets are solely related to one Feature, I nested the models (as you'll see in my upload form).
The biggest problem for me was realizing that my params[:feature_asset] that was being sent to the server was actually an array of my uploader'd file objects, instead of just the one I was used to working with. After a bit of fiddling with iterating through each file and creating a FeatureAsset from it, it worked like a charm!
Hopefully I'll translate this clearly. I'd rather provide a bit too much information than not enough. A little extra context never hurts when you're interpreting someone else's code.
feature.rb
class Feature < ActiveRecord::Base
  belongs_to :user
  has_many :feature_assets

  attr_accessible :name, :description, :user_id, :image

  accepts_nested_attributes_for :feature_assets, :allow_destroy => true

  validates :name,    :presence => true
  validates :user_id, :presence => true

  mount_uploader :image, FeatureImageUploader
end

feature_asset.rb
  belongs_to :user
  belongs_to :feature

  attr_accessible :user_id, :feature_id, :file, :file_cache

  validates :user_id,     :presence => true
  validates :feature_id,  :presence => true
  validates :file,        :presence => true

  mount_uploader :file, FeatureAssetContentUploader

  # grabs useful file attributes & sends them as JSON to the jQuery file uploader
  def to_jq_upload
    {
      "file" => file,
      "file_name" => 'asdf',
      "url" => file.url,
      "delete_url" => id,
      "delete_type" => "DELETE"
    }
  end

feature_assets_controller.rb
  def create
    @feature = Feature.find(params[:feature_id])

    params[:feature_asset]['file'].each do |f|
      @feature_asset = FeatureAsset.create!(:file => f, :feature_id => @feature.id, :user_id => current_user.id)
    end

    redirect_to @feature
  end

And not that it probably helps that much, but my feature_asset_uploader.rb is below. It's pretty stripped down.
class FeatureAssetContentUploader < CarrierWave::Uploader::Base

  storage :file

end

features _form.html.erb (similar to Stone's, but not quite)
<%= form_for [@feature, @feature_asset], :html => { :multipart => true  } do |f| %>

        <%= t('feature_assets.add_files') %>...
        <%= hidden_field_tag :feature_id, @feature.id %>
        <%= hidden_field_tag :user_id, current_user.id %>
        <%= f.file_field :file, :multiple => true %>

      <button type="submit" class="btn btn-success">Start Upload</button>
      <button type="reset" class="btn btn-warning">Cancel Upload</button>
      <button type="button" class="btn btn-danger">Delete Files</button>

It doesn't have error handling or any of the niceties it should have, but that's the barebones version of it.
Hopefully that helps someone out there. Feel free to ask me if you have any questions!
Kyle

A: I have a similar setup running with Carrierwave. Here's what I have. I'm using Images as a nested resource for Projects.
Project.rb:
has_many :images, :dependent => :destroy
accepts_nested_attributes_for :images, :allow_destroy => true

Image.rb:
 include Rails.application.routes.url_helpers
  mount_uploader :image, ImageUploader

  belongs_to :project

  #one convenient method to pass jq_upload the necessary information
  def to_jq_upload
  {
    "name" => read_attribute(:image),
    "size" => image.size,
    "url" => image.url,
    "thumbnail_url" => image.thumb.url,
    "delete_url" => image_path(:id => id),
    "delete_type" => "DELETE"
   }
  end

Images_controller.rb:
 def create
    @image = Image.new(params[:image])
    @image.project_id = params[:project_id]
    @project = Project.find(params[:project_id])
    @image.position = @project.images.count + 1
    if @image.save
      render :json => [ @image.to_jq_upload ].to_json
    else
      render :json => [ @image.to_jq_upload.merge({ :error => "custom_failure" }) ].to_json
    end
  end

Be aware, this was a *!@^%! to get working.
UPDATE:
projects/_form.html.erb

    <%= form_for Image.new, :html => {:multipart => true} do |f| %>

                Add files...
                <%= hidden_field_tag :project_id, @project.id %>
                <%= f.file_field :image %>

            <button type="submit" class="start">Start Upload</button>
            <button type="reset" class="cancel">Cancel Upload</button>
            <button type="button" class="delete">Delete Files</button>

    <% end %>

Drop Image Files Here

A: I have coped with this problem and made a demo app to show how to do this.
In short I have two models: item and upload.
item.rb:
has_many :uploads
accepts_nested_attributes_for :uploads, :allow_destroy => true

upload.rb:
belongs_to :item
    has_attached_file :upload, :styles => { :large => "800x800", :medium => "400x400>", :small => "200x200>" }

I added uploads_attributes to item controller.
Now you can add jquery-file-upload form to your view, but there is one problem: it sends each photo in separate requests. So there is my jquery-file-upload initializer, which uploads all photos in one request (creating item model) and then redirecting to the root of your app (you need to use item form):


text:
Q: Simple AngularJS App won´t work. How to debug this? I´m tryinng to improve our giant js (jquery) legacy with angularjs.
Now my first problem, starting with the simplified code:
angularApp.js:
angular.module('ngSomeApp', [])

    // changed interpolate provider to avoid smarty cancer
    .config(['$interpolateProvider', function ($interpolateProvider) {
        $interpolateProvider.startSymbol('[[');
        $interpolateProvider.endSymbol(']]');
    }])

    // getting party started
    .controller('ngSomeController', ['$scope', '$http', function($scope, $http) {
        $scope.test = 'Hello World';
        console.log($scope.test);
    }]); // module closed

DOM:

        // loading angular.min.js (1.4.6)
        // loading angularApp.js

            [[2+2]]

                [[2+2]]
                [[test]]

My problem is, that:

*

*[[2+2]] and [[test]] are not rendered

*there is no error in console (and no "Hello World")

*{literal}{{2+2}}{/literal} (we use smarty) and non-modified interpolate povider also don´t work

*If i console.log(angular.module('ngSomeApp')); at the end of the angularApp.js:

Object {_configBlocks: Array[0], _runBlocks: Array[0], requires: Array[0], name: "ngSomeApp", requiresOriginal: undefined}

The code is so simple and i don´t see the issue. Do you have any idea? Do you see any problem in my code?

A: Your code works with 1.2.23, even with 1.4.2
Note: I have not changed anything, apart from creating snippet.

angular.module('ngSomeApp', [])

// changed interpolate provider to avoid smarty cancer
.config(['$interpolateProvider',
  function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
  }
])

// getting party started
.controller('ngSomeController', ['$scope', '$http',
  function($scope, $http) {
    $scope.test = 'Hello World';
    console.log($scope.test);
  }
]);

  [[2+2]]

    [[2+2]] [[test]]


text:
Q: Cutting edge technologies for .NET web application? If you would want to build the most expensive possible web application what would you use?
Without buying Microsoft products except VS2010 and SQL Server database.
Does the value increase lie in the technologies that you use and in architectural patterns applied?
If so, what to use among .NET technologies in all application layers to increase the website value?
I am asking this because I have business opportunity and I have no money to invest thus I want to cover my partner's investment with technology contribution.
Thanks a lot.

A: IMHO I would not try to increase my website value by investing into expensive technologies :-)
I think you should put the working hours together it tooks to build this website and multiply this with a factor, which corresponds to your value.

A: I think you would be on your way using ASP.NET MVC development (Possibly MVC3 with EF 4.0 as ORM) using VWD Express 2010 and Sql Server Express (If you are hosting on your own, else the hosting company will give you Sql Server Db) now then then move on to Sql Server 2008 and visual studio after you start making money and the website hits increase. It may also be possible to continue using the same if you think the performance is alright.
Of course this is a simplistic answer, Mariusz is right as well.

A: Bob Muglia of Team Silverlight posted a blog entry after Microsoft's PDC conference.  In regards to rich web applications, Microsoft has dubbed Silverlight its technology of choice (i.e. to compete with Flash). However, with the emergence of HTML 5, Microsoft may be switching its decision.
What does this all mean? Silverlight / HTML5 are Microsoft's technologies of choice for rich web applications. This does not mean that ASP.NET (including MVC) loses its value, but as users' demand for richer, more interactive web applications continues to increase, I would invest more in the tools that will help me with SL and HTML 5.
And this does not change the value add of Visual Studio / SQL Server.

A: Cutting edges are the first thing to get blunted.
I would go further that Mariusz and say that actually, while there are marketing advantages just in being able to talk about the cutting-edge tech that you use, in terms of the long-term value (whether to a customer or an investor), the use of cutting-edge technology is something that has to be justified, as much as it is a selling point.
Firstly, some cutting-edge tech requires the use of someone else's software. Even if it's open-source you are now dependant upon that other supplier. If it's proprietary, you are even more dependant (the possibility of forking off a custom version that suits just you has gone - not something you'd want to do with any software, but at least there is the possibility if you have the source).
At the same time as that issue, if it's licensed for a fee, then this adds to the TCO of you system in a way that doesn't benefit you (i.e. if each installation has third-party software that costs X dollars to set up, that's X dollars you have to include in your price that you never get any value from as a vendor).
Secondly, today's cutting edge technology can be tomorrow's fish-and-chip wrapper*. Indeed, one can say with absolute certainty that some of it will, while some of it becomes a common part of many people's toolkits, and some of it finds a niche in which it remains important while never becoming a tech that a very large number of people use.
That's a safe prediction. The tricky prediction is which will do which. The factors affecting this are a mixture of technological, psychological, social, political and marketing factors in a competitive landscape where it's hard to judge which of the current players will dominate and there's nothing to say that something new will kill all of what's there.
Now, none of this means that you should shy away from the cutting edge. None of it means that you should shy away from using third-party tech (whether proprietary or open). It does mean that you should be sure you are getting value out of it. If you use what's been tried and tested for the last ten years, the chances of it still being just as reliable (and perhaps further improved) in five year's time is much greater than if you use something that is six-months old.
The way to turn cutting edge technologies into a competitive advantage is not to use them, but to use them to do something that you couldn't do, or couldn't do as well (reliably, cheaply, quickly, efficiently all count as "well") as you could otherwise. Even here, if you can think of a good way to turn older tech to the use that someone else is putting newer tech, you may be able to compete with a cheaper and more dependable product.
It is also important to stay aware of tech relevant to your field that you choose not to use - the flip-side of it being hard to predict what will survive and grow is that tech you decided not to use might become tech that you later do want, or even need, to use.
In the end, all technical decisions become both assets and liabilities to future development and the value to customers and investors. You can't expect the tech to sell itself, you can only make sound technical decisions, so that the people who sell the tech (whether that is someone else, or you in a different role) have an easier job when talking up the assets.
*In days of less heavily regulated hygiene practices, it used to be common in Britain and Ireland to wrap fish and chips in old newspapers. I'm not sure how well the idiom about today's news being tomorrow's fish and chips translates to readers in the rest of the world.


text:
Q: Biased logistic regression in pytorch My model has decently high AUC=90%, but is biased, underestimating the probability $y=1$. This is systematic across some of the input features as well. How can I nudge the bias term, or otherwise address this issue? I am surprised that the model ends up being biased, despite it having an intercept (bias term).
My dataset is very unbalanced, only 3% positives (1s) vs 97% 0s. But in y_hat, the number of 1s is closer to 2.5%.


text:
Q: Using vh and wh as responsive units is giving my img a margin, on mobile I fixed one responsive design problem and introduced another. I've made a cool svg and in it I've included some text. I know, I know – I should've added text via HTML/CSS. But my website is due today and I've spent too much time on graphics, so I can't afford to turn the SVG into a responsive div.
At first, using max-width 100% would make the vector text far too large on a computer monitor and far too tiny on mobile. I designed the vector for mobile-first, so It is long and vertical (2300px with 3000px)
I managed to fix that dilemma by including vh and wh as units.
But now, the image is moved down when it goes to mobile-view. Mobile-view introduces empty white space between the element above and the image.
No margins, no paddings on image div. The elements above don't have any. The body also doesn't have any.
Any clue as to what could be introducing this?
Thank you so much in advance!
HTML

CSS
    width: 95wh;
    height: 100vh;
    padding: 0px;
    margin: 0px;

A: First of all, you have set two classes, "vector" and "vector-img", and that might cause the problem. Please provide more code if possible. You also have typo in your css, change width: 95wh; to width: 95vh;

A: Note that on at least some mobiles eg iOS vh is not necessarily the viewport height, it is a fixed height so that when the user scrolls and some of the chrome at the top of the browser window disappears there isn't a sudden jump for the user.
This makes it hard not to get gaps, or some info cut off at the bottom of the window.
If you could put a working example up in your answer we would be able to see more clearly whether this is causing your problem or not.
Note: you are setting the width to a wh unit. I suspect you mean vw, but that is probably not causing the problem you describe.


text:
Q: linker command failed with exit code 1 in old source code I have an old project that was developed few years ago. Now when I compile it in latest Xcode 8.3.1 than its giving me some errors. I also googled it but didn't get success.

Here is the screenshot of logs so any help would be highly appreciated.

A: Answer for the original question "BitCode Signature failure":
Possible duplicate of the question:
Bitcode signature failure in Xcode
Please find the answer there :)
Answer for duplicate symbols error:
Possible duplicate of the question:
duplicate symbols for architecture armv7
Please find the answer there :)


text:
Q: Sending email from specific vhost, bad for spam? Essentially, I have a server that contains many vhosts. One vhost in particular is required to send mail from the address invitations@vhost.com, however the reverse DNS for that server resolves to hosting.server.com, and various fields in the email header pertain to the server instead of the vhost.
The software involved is PHP / Apache / Sendmail / CentOS 5.5
The domain vhost.com uses an email provider on a different server, so mx.vhost.com has no links to hosting.server.com or www.vhost.com other than by the domain name.
My concern is that this will increase the likelihood that email from this vhost is flagged as spam. Am I worrying too much about this or is this a real possibility.
Does anybody advice on how to configure a server or domain setup in this instance?
Also, can these references to hosting.server.com be alleviated within the PHP application sending the emails at all, or is it purely a server configuration issue?
Thanks!

A: I'd say it's a distinct possibility.  You can limit the damage by ensuring that you have as many hints as possible that your server is a legitimate sender for the domain vhost.com by configuring correct DKIM and SPF records, but it won't be a panacea.
As far as removing references to hosting.server.com in the e-mail, it's mostly a server configuration issue -- the two big ones are HELO name and and the rDNS
The really important thing to remember, though, is to not send spam.  E-mail service providers hate that.


text:
Q: "Errors while handling" kernel packages after dist-upgrade I did an apt-get dist-upgrade, now everytime I do something using apt-get, e.g. installing something, it gives me that there are errors while handling the following packages:
linux-image-extra-3.13.0-35-generic
linux-image-generic
linux-generic

My system still works correctly, but is this normal? And what should I do? Should I do anything? Have I done the wrong thing by doing a dist-upgrade? (Beginner-like instructions please, I'm not an expert. Using Xubuntu 14.04.) Here is the full output of dist-upgrade, as someone asked for it:
Pakketlijsten worden ingelezen... Klaar
Boom van vereisten wordt opgebouwd
De status informatie wordt gelezen... Klaar
Opwaardering wordt doorgerekend... Klaar
De volgende pakketten zullen opgewaardeerd worden:
  google-chrome-beta openjdk-7-jre openjdk-7-jre-headless
3 pakketten opgewaardeerd, 0 pakketten nieuw geïnstalleerd, 0 te verwijderen en 0 niet opgewaardeerd.
3 pakketten niet volledig geïnstalleerd of verwijderd.
Er moeten 88,8 MB aan archieven opgehaald worden.
Door deze operatie zal er 480 kB extra schijfruimte gebruikt worden.
Wilt u doorgaan? [J/n] j
Ophalen:1 http://be.archive.ubuntu.com/ubuntu/ trusty-updates/main openjdk-7-jre amd64 7u65-2.5.1-4ubuntu1~0.14.04.1 [183 kB]
Ophalen:2 http://dl.google.com/linux/chrome/deb/ stable/main google-chrome-beta amd64 37.0.2062.94-1 [49,2 MB]
Ophalen:3 http://be.archive.ubuntu.com/ubuntu/ trusty-updates/main openjdk-7-jre-headless amd64 7u65-2.5.1-4ubuntu1~0.14.04.1 [39,5 MB]
88,8 MB opgehaald in 15s (5.793 kB/s)
(Database inlezen ... 386009 files and directories currently installed.)
Preparing to unpack .../google-chrome-beta_37.0.2062.94-1_amd64.deb ...
Unpacking google-chrome-beta (37.0.2062.94-1) over (37.0.2062.76-1) ...
Preparing to unpack .../openjdk-7-jre_7u65-2.5.1-4ubuntu1~0.14.04.1_amd64.deb ...
Unpacking openjdk-7-jre:amd64 (7u65-2.5.1-4ubuntu1~0.14.04.1) over (7u55-2.4.7-1ubuntu1) ...
Preparing to unpack .../openjdk-7-jre-headless_7u65-2.5.1-4ubuntu1~0.14.04.1_amd64.deb ...
Unpacking openjdk-7-jre-headless:amd64 (7u65-2.5.1-4ubuntu1~0.14.04.1) over (7u55-2.4.7-1ubuntu1) ...
Processing triggers for man-db (2.6.7.1-1) ...
Processing triggers for gnome-menus (3.10.1-0ubuntu2) ...
Processing triggers for desktop-file-utils (0.22-1ubuntu1) ...
Processing triggers for bamfdaemon (0.5.1+14.04.20140409-0ubuntu1) ...
Rebuilding /usr/share/applications/bamf-2.index...
Processing triggers for mime-support (3.54ubuntu1) ...
Processing triggers for hicolor-icon-theme (0.13-1) ...
Instellen van linux-image-extra-3.13.0-35-generic (3.13.0-35.62) ...
Running depmod.
update-initramfs: deferring update (hook will be called later)
initrd.img(/boot/initrd.img-3.13.0-35-generic
) points to /boot/initrd.img-3.13.0-35-generic
 (/boot/initrd.img-3.13.0-35-generic) -- doing nothing at /var/lib/dpkg/info/linux-image-extra-3.13.0-35-generic.postinst line 491.
vmlinuz(/boot/vmlinuz-3.13.0-35-generic
) points to /boot/vmlinuz-3.13.0-35-generic
 (/boot/vmlinuz-3.13.0-35-generic) -- doing nothing at /var/lib/dpkg/info/linux-image-extra-3.13.0-35-generic.postinst line 491.
Examining /etc/kernel/postinst.d.
run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 3.13.0-35-generic /boot/vmlinuz-3.13.0-35-generic
run-parts: executing /etc/kernel/postinst.d/initramfs-tools 3.13.0-35-generic /boot/vmlinuz-3.13.0-35-generic
update-initramfs: Generating /boot/initrd.img-3.13.0-35-generic

gzip: stdout: No space left on device
E: mkinitramfs failure cpio 141 gzip 1
update-initramfs: failed for /boot/initrd.img-3.13.0-35-generic with 1.
run-parts: /etc/kernel/postinst.d/initramfs-tools exited with return code 1
Failed to process /etc/kernel/postinst.d at /var/lib/dpkg/info/linux-image-extra-3.13.0-35-generic.postinst line 1025.
dpkg: error processing package linux-image-extra-3.13.0-35-generic (--configure):
 subproces installed post-installation script gaf een foutwaarde 2 terug
dpkg: dependency problems prevent configuration of linux-image-generic:
 linux-image-generic is afhankelijk van linux-image-extra-3.13.0-35-generic; maar:
  Pakket linux-image-extra-3.13.0-35-generic is nog niet geconfigureerd.

dpkg: error processing package linux-image-generic (--configure):
 vereistenproblemen - blijft ongeconfigureerd
Er is geen apport-verslag weggeschreven omdat de foutmelding volgt op een eerdere mislukking.
          dpkg: dependency problems prevent configuration of linux-generic:
 linux-generic is afhankelijk van linux-image-generic (= 3.13.0.35.42); maar:
  Pakket linux-image-generic is nog niet geconfigureerd.

dpkg: error processing package linux-generic (--configure):
 vereistenproblemen - blijft ongeconfigureerd
Er is geen apport-verslag weggeschreven omdat de foutmelding volgt op een eerdere mislukking.
              Instellen van google-chrome-beta (37.0.2062.94-1) ...
Instellen van openjdk-7-jre-headless:amd64 (7u65-2.5.1-4ubuntu1~0.14.04.1) ...
Installeren van nieuwe versie van configuratiebestand /etc/java-7-openjdk/sound.properties ...
Installeren van nieuwe versie van configuratiebestand /etc/java-7-openjdk/jvm-amd64.cfg ...
Instellen van openjdk-7-jre:amd64 (7u65-2.5.1-4ubuntu1~0.14.04.1) ...
Fouten gevonden tijdens behandelen van:
 linux-image-extra-3.13.0-35-generic
 linux-image-generic
 linux-generic
E: Sub-process /usr/bin/dpkg returned an error code (1)

A: I had the same issue.
I had so space left at /boot, so I rm some old files and retry.
It works for me.


text:
Q: Shorthand syntax gutters being ignored for span mixin I've set global settings for susy:
$susy: (
    columns: 8,
    gutters: 1/4,
);

I want to override the gutters for a couple of span
.tile-left {
    @include span(1 of 2 1px);
}
.tile-right {
    @include span(1 at 2 of 2 1px);
}

Generated css
.tile-left {
  width: 44.44444%;
  float: left;
  margin-right: 11.11111%;
}

.tile-right {
  width: 44.44444%;
  float: right;
  margin-right: 0;
}

I've also tried these and these don't seem to be working either
@include span(1 of 2 no-gutters);

&
@include span(1 of 2 (gutter-override: 1px));

A: Looks like the "1px" argument didnt work because gutters can only be defined by a ratio value; Documentation
Furthermore, I've solved my issue of wanting fluid elements and a static gutter by
doing this:
.tile-left {
    @include span(1 of 2 (gutter-override: no-gutters, gutter-position: inside-static));
    border-right: 1px solid #E5E5E5;
}
.tile-right {
    @include span(1 of 2 (gutter-override: no-gutters, gutter-position: inside-static));
}

It looks like when you remove the gutters by passing "gutter-override: no-gutters" it calculates the width with gutters, but then removes the margins; By putting the gutters/margin inside by passing "gutter-position: inside-static" the with is calculated to span to 100% without gutters.

A: It's not entirely clear in your post what you are trying to achieve. @include span(1 of 2 no-gutters); should remove the gutter output, but won't change the math. If your goal is to change the math so there are no gutters, @include span(50% no-gutters); might be the best option. Or @include span(1 of 2 (gutters: 0)); should give you the same output.
UPDATE: even @include span(1 of 2 0); seems to work. The 0 is understood as a valid gutter ratio.


text:
Q: AWS Snapshots As Only Backup Is only using AWS snapshots as a backup solution viable. I've a a few ELBs, EC2s, S3 buckets and RDS databases.
They are all in the one AZ so I don't have multi AZ fail over. What's the best solution? I'm used to the traditional backup solution file system snapshots and backup to tape weekly, monthly, yearly and then rotating them but what's the best solution for cloud only.
Just started a new job and it's all cloud based.

A: Snapshots aren't backups. Period. To have proper DR plan you should follow so-called 3-2-1 backup rule which is "3 copies of data, two different formats, and one off-site copy".
https://knowledgebase.starwindsoftware.com/explanation/the-3-2-1-backup-rule/
https://www.veeam.com/blog/how-to-follow-the-3-2-1-backup-rule-with-veeam-backup-replication.html
https://www.backblaze.com/blog/the-3-2-1-backup-strategy/
If you run your workload in AWS "offsite copy" means non-AWS cloud.


text:
Q: Change visibility timeout for an SQS message using ruby aws-sdk [ruby newbie] could someone help with an example how to change visibility timeout for an sqs message using ruby aws-sdk ?
here is the code that I've used for my tests using the method batch_change_message_visibility, but I get the error "undefined method 'batch_change_message_visibility'"
require 'rubygems'
require 'aws-sdk'

sqs = AWS::SQS.new(
    :access_key_id => access_key,
    :secret_access_key => access_secret)

queue = sqs.queues.named(queue_name)

messages = []
messages << { :message => message_handle, :visibility_timeout => 5 }
queue.batch_change_message_visibility(messages)

Any Idea? Any help would the very welcome :)
Thanks

A: You have to use the splat operator when passing the messages array parameter to the batch_change_message_visibility method.
As shown in the docs here, you should write (note the * before the messages parameter):
messages = []
messages << { :message => 'handle1', :visibility_timeout => 5 }
messages << { :message => 'handle2', :visibility_timeout => 10 }

queue.batch_change_visibility(*messages)


text:
Q: refresh page once checkbox is checked (in the background) How can I refresh the page (in the background, seamlessly) when a user checks a checkbox so that once the checkbox is checked off, that div or task is then moved to another location because it's completed?
I have separated them like so
  def home
    if current_user
        @todos = current_user.todos.where(completed: false)
    end
  end

  def complete
    if current_user
        @todos = current_user.todos.where(completed: !false)
    end
  end

So that once the checkbox is checked it is moved, and this works - but the page has to be refreshed to see that the task has been moved.
In my todos controller where I mark the task complete it looks like this
  def completed
    if @todo.update_attribute(:completed, !@todo.completed)
      flash[:success] = "Congratulations, it was successful."
      redirect_to dashboard_path
    else
      flash.now[:error] = "ERROR: Please try again."
      render :new
    end
  end

And my view is as so
<% @todos.each do |todo| %>

            <%= todo.title %>

<%= todo.item %>

            <%= check_box_tag 'todo[completed]', todo.id, todo.completed, data: { remote: true, url: url_for(controller: :todos, action: :completed, id: todo), method: "POST" }, id: todo.id, :onclick => "Materialize.toast('Todo Completed, Grats!', 4000)" %>
            <%= label_tag todo.id, "COMPLETE", :class => 'strikethrough' %>

<% end %>

But how can I refresh the page, or the div when the checkbox is checked so the task disappears seamlessly?

A: Use removeChild() with the div id to remove it, just put this in an onClick handler for the checkbox.
If desired:
Save the div when you delete it (from the return value of removeChild) in a variable, so if the checkbox is unchecked, you can use the div in createChild().

A: Give your div a unique ID based on the todo id value so that you can select it for removal:
<div class="card hoverable" id="todo_container_<%= todo.id %>">

Add a class to your check box so that you can specify a click handler:
check_box_tag 'todo[completed]', todo.id, todo.completed, class: 'todo_completed', data: { remote: true, url: url_for(controller: :todos, action: :completed, id: todo), method: "POST" }, id: todo.id, :onclick => "Materialize.toast('Todo Completed, Grats!', 4000)"

Then (assuming you are using jQuery) specify the click handler:
$(".todo_completed").click(function(){
  // it looks like you've got all the info you need for your ajax call in the data attributes attached to the checkbox, so I think the call just looks like this:
  $.ajax($(this).data());
});

Finally your controller needs to render a .js template instead of redirecting - just call it completed.js.erb and it should be rendered automatically. In that template put the javascript to remove the container div from the DOM:
// completed.js.erb
$("todo_container_<%= @todo.id %>").remove();


text:
Q: Generate .d.ts files with webpack and angular-cli in prod folder Good morning;
I am using angular 4 with angular-cli and I am wondering how to generate the .d.ts files of my components in prod environnement.
In angular 2 I used this tutorial to accomplish this
https://medium.com/@OCombe/how-to-publish-a-library-for-angular-2-on-npm-5f48cdabf435
package json file
{
  "name": "zippy",
  "version": "1.0.0",
  "license": "MIT",
  "main": "zippy.bundle.js",
  "jsnext:main": "zippy.module.js",
  "module": "zippy.module.js",
  "types": "zippy.module.d.ts",

  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "core-js": "^2.4.1",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.0.0",
    "@angular/compiler-cli": "^4.0.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.2.0"
  },
  "angularCompilerOptions": {
    "skipTemplateCodegen": true
  }
}

tsconfig file
{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist",
    "baseUrl": "src",
    "sourceMap": true,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ],
    "declaration": true,
    "files": [
      "./src/app/zippy.moodule.ts"
      ]
  }
}

and i run ng build --prod command
Cordially
Webpack config file
const path = require('path');
const ProgressPlugin = require('webpack/lib/ProgressPlugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');
const postcssUrl = require('postcss-url');

const { NoEmitOnErrorsPlugin, LoaderOptionsPlugin } = require('webpack');
const { GlobCopyWebpackPlugin, BaseHrefWebpackPlugin } = require('@angular/cli/plugins/webpack');
const { CommonsChunkPlugin } = require('webpack').optimize;
const { AotPlugin } = require('@ngtools/webpack');

const nodeModules = path.join(process.cwd(), 'node_modules');
const entryPoints = ["inline","polyfills","sw-register","styles","vendor","main"];
const baseHref = "";
const deployUrl = "";

module.exports = {
  "devtool": "source-map",
  "resolve": {
    "extensions": [
      ".ts",
      ".js"
    ],
    "modules": [
      "./node_modules"
    ]
  },
  "resolveLoader": {
    "modules": [
      "./node_modules"
    ]
  },
  "entry": {
    "main": [
      "./src/main.ts"
    ],
    "polyfills": [
      "./src/polyfills.ts"
    ],
    "styles": [
      "./src/styles.css"
    ]
  },
  "output": {
    "path": path.join(process.cwd(), "dist"),
    "filename": "[name].bundle.js",
    "chunkFilename": "[id].chunk.js"
  },
  "module": {
    "rules": [
      {
        "enforce": "pre",
        "test": /\.js$/,
        "loader": "source-map-loader",
        "exclude": [
          /\/node_modules\//
        ]
      },
      {
        "test": /\.json$/,
        "loader": "json-loader"
      },
      {
        "test": /\.html$/,
        "loader": "raw-loader"
      },
      {
        "test": /\.(eot|svg)$/,
        "loader": "file-loader?name=[name].[hash:20].[ext]"
      },
      {
        "test": /\.(jpg|png|gif|otf|ttf|woff|woff2|cur|ani)$/,
        "loader": "url-loader?name=[name].[hash:20].[ext]&limit=10000"
      },
      {
        "exclude": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.css$/,
        "loaders": [
          "exports-loader?module.exports.toString()",
          "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
          "postcss-loader"
        ]
      },
      {
        "exclude": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.scss$|\.sass$/,
        "loaders": [
          "exports-loader?module.exports.toString()",
          "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
          "postcss-loader",
          "sass-loader"
        ]
      },
      {
        "exclude": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.less$/,
        "loaders": [
          "exports-loader?module.exports.toString()",
          "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
          "postcss-loader",
          "less-loader"
        ]
      },
      {
        "exclude": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.styl$/,
        "loaders": [
          "exports-loader?module.exports.toString()",
          "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
          "postcss-loader",
          "stylus-loader?{\"sourceMap\":false,\"paths\":[]}"
        ]
      },
      {
        "include": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.css$/,
        "loaders": ExtractTextPlugin.extract({
  "use": [
    "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
    "postcss-loader"
  ],
  "fallback": "style-loader",
  "publicPath": ""
})
      },
      {
        "include": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.scss$|\.sass$/,
        "loaders": ExtractTextPlugin.extract({
  "use": [
    "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
    "postcss-loader",
    "sass-loader"
  ],
  "fallback": "style-loader",
  "publicPath": ""
})
      },
      {
        "include": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.less$/,
        "loaders": ExtractTextPlugin.extract({
  "use": [
    "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
    "postcss-loader",
    "less-loader"
  ],
  "fallback": "style-loader",
  "publicPath": ""
})
      },
      {
        "include": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.styl$/,
        "loaders": ExtractTextPlugin.extract({
  "use": [
    "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
    "postcss-loader",
    "stylus-loader?{\"sourceMap\":false,\"paths\":[]}"
  ],
  "fallback": "style-loader",
  "publicPath": ""
})
      },
      {
        "test": /\.ts$/,
        "loader": "@ngtools/webpack"
      }
    ]
  },
  "plugins": [
    new NoEmitOnErrorsPlugin(),
    new GlobCopyWebpackPlugin({
      "patterns": [
        "assets",
        "favicon.ico"
      ],
      "globOptions": {
        "cwd": "/home/riadh/WebstormProjects/zipdemo/src",
        "dot": true,
        "ignore": "**/.gitkeep"
      }
    }),
    new ProgressPlugin(),
    new HtmlWebpackPlugin({
      "template": "./src/index.html",
      "filename": "./index.html",
      "hash": false,
      "inject": true,
      "compile": true,
      "favicon": false,
      "minify": false,
      "cache": true,
      "showErrors": true,
      "chunks": "all",
      "excludeChunks": [],
      "title": "Webpack App",
      "xhtml": true,
      "chunksSortMode": function sort(left, right) {
        let leftIndex = entryPoints.indexOf(left.names[0]);
        let rightindex = entryPoints.indexOf(right.names[0]);
        if (leftIndex > rightindex) {
            return 1;
        }
        else if (leftIndex < rightindex) {
            return -1;
        }
        else {
            return 0;
        }
    }
    }),
    new BaseHrefWebpackPlugin({}),
    new CommonsChunkPlugin({
      "name": "inline",
      "minChunks": null
    }),
    new CommonsChunkPlugin({
      "name": "vendor",
      "minChunks": (module) => module.resource && module.resource.startsWith(nodeModules),
      "chunks": [
        "main"
      ]
    }),
    new ExtractTextPlugin({
      "filename": "[name].bundle.css",
      "disable": true
    }),
    new LoaderOptionsPlugin({
      "sourceMap": false,
      "options": {
        "postcss": [
          autoprefixer(),
          postcssUrl({"url": (URL) => {
            // Only convert root relative URLs, which CSS-Loader won't process into require().
            if (!URL.startsWith('/') || URL.startsWith('//')) {
                return URL;
            }
            if (deployUrl.match(/:\/\//)) {
                // If deployUrl contains a scheme, ignore baseHref use deployUrl as is.
                return `${deployUrl.replace(/\/$/, '')}${URL}`;
            }
            else if (baseHref.match(/:\/\//)) {
                // If baseHref contains a scheme, include it as is.
                return baseHref.replace(/\/$/, '') +
                    `/${deployUrl}/${URL}`.replace(/\/\/+/g, '/');
            }
            else {
                // Join together base-href, deploy-url and the original URL.
                // Also dedupe multiple slashes into single ones.
                return `/${baseHref}/${deployUrl}/${URL}`.replace(/\/\/+/g, '/');
            }
        }})
        ],
        "sassLoader": {
          "sourceMap": false,
          "includePaths": []
        },
        "lessLoader": {
          "sourceMap": false
        },
        "context": ""
      }
    }),
    new AotPlugin({
      "mainPath": "main.ts",
      "hostReplacementPaths": {
        "environments/environment.ts": "environments/environment.ts"
      },
      "exclude": [],
      "tsConfigPath": "src/tsconfig.app.json",
      "skipCodeGeneration": true
    })
  ],
  "node": {
    "fs": "empty",
    "global": true,
    "crypto": "empty",
    "tls": "empty",
    "net": "empty",
    "process": true,
    "module": false,
    "clearImmediate": false,
    "setImmediate": false
  }
};

A: You need to pass --declaration flag to tsConfig file to let it generate d.ts file for corsponding js file.
Read more on official docs

A: For everyone interrested about how to build a library with angular 2/4, you will find the answer in this link
http://blog.angular-university.io/how-to-create-an-angular-2-library-and-how-to-consume-it-jspm-vs-webpack/


text:
Q: How can i Linking the Protocol Buffer(C++) into the Xcode I added the protobuf class "xxx.pb.h","xxx.pb.cc" in Project.
I added a path"/usr/local/include" in Header Search Paths,
and added a path"/usr/local/lib" in Library Search Paths.
Now I encountered a problem,
The following error at Build:
ld: warning: ignoring file /usr/local/lib/libprotobuf.dylib, file was built for unsupported file format ( 0xcf 0xfa 0xed 0xfe 0x 7 0x 0 0x 0 0x 1 0x 3 0x 0 0x 0 0x 0 0x 6 0x 0 0x 0 0x 0 ) which is not the architecture being linked (i386): /usr/local/lib/libprotobuf.dylib
ld: warning: ignoring file /usr/local/lib/libprotoc.dylib, file was built for unsupported file format ( 0xcf 0xfa 0xed 0xfe 0x 7 0x 0 0x 0 0x 1 0x 3 0x 0 0x 0 0x 0 0x 6 0x 0 0x 0 0x 0 ) which is not the architecture being linked (i386): /usr/local/lib/libprotoc.dylib
Undefined symbols for architecture i386:
"google::protobuf::DescriptorPool::generated_pool()", referenced from:
      protobuf_AssignDesc_person_2eproto() in person.pb.o
"google::protobuf::DescriptorPool::InternalAddGeneratedFile(void const*, int)", referenced from:
      protobuf_AddDesc_person_2eproto() in person.pb.o
"google::protobuf::MessageFactory::generated_factory()", referenced from:
      protobuf_AssignDesc_person_2eproto() in person.pb.o

...
...
NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "vtable for google::protobuf::Message", referenced from:
      google::protobuf::Message::Message() in person.pb.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Image

A: Follow the steps mentioned in this answer -> https://stackoverflow.com/a/10279656/1383704
There are a few pitfalls here and there, for which you may check my own answer for the same qn.
These were the steps I followed differently

*

*instead of giving header search path till google directory, i gave the search path till the "src/" directory

*In whichever you import your xxx.pb.h you have to rename the .m to .mm
In Xcode 4.5 i was still getting some linker errors :

symbols not found for architecture i386

Because of this I wasn't able to run on simulator. But the code will run on actual device.


text:
Q: How to create an endpoint in Sequelize.js that receives any random JSON in the model? I have created a simple endpoint on an Express server using Sequelize and Postgresql. This endpoint should receive a simple POST request with a JSON Object registering Events as a callback. The thing is, this will be a JSON object with lots of strings and numbers that I can't write a specific model for.
I have two problems with my current model.
I can only receive events that are directed to Event.event when in fact I want to receive whatever JSON that should not start with a key "event" like I wrote on my model. However, I don't actually know how to create a model that allows us to send any unspecified JSON to my table Events.
If I receive those callbacks trying to POST JSONs to this endpoint they are naturally coming as NULL, since they do not fit with Event.event
Here's the model:
const Sequelize = require('sequelize');
const sequelize = require('../db');

const Event = sequelize.define(
    'Event',
    {
        event: {type: Sequelize.JSON, allowNull: false}
    }
);

module.exports = Event;

And the router:
const { Router } = require("express");
const Event = require("./model");
const router = new Router();

router.get("/event-receiver", (req, res, next) => {
  const limit = req.query.limit || 25;
  const offset = req.query.offset || 0;

  Event.findAll({ limit, offset })
    .then(allEvents => res.json(allEvents))
    .catch(next);
});

router.post("/event-receiver", (req, res, next) => {
  Event.create(req.body)
    .then(newEvent => res.status(201).json(newEvent))
    .catch(next);
});

module.exports = router;

My actual question is how could I write a model that takes any type of unspecified JSON that is sent to that endpoint?
For example:
{
AnyRandomJSON: {type: Sequelize.JSON, allowNull: False}
}

Without actually having to give it a name like "event", but simply receiving anything that is sent to "/event-receiver" and registering on a specific column on my postgresql called Events or Data, anything like that.
By reading the documentation and other related help articles don't enlighten me on how to do that in a simple way.

A: I had a similar issue when storing JSON data for restaurants from Yelp. While the data is JSON, its structure was irrelevant.
To avoid incompatibilities (some SQL engines don't support JSON), I ended up storing it as Sequelize.TEXT:
    restaurant_yelp_info: Sequelize.TEXT()

What you name the column is not that important.
I use JSON.stringify() to convert to JSON before storing, if necessary.
I use JOSN.parse() to convert the JSON to an object after retrieval.

A: In the end I managed to fix it by adding a Data to Event.create(). Easier than what I thought.
router.post("/signrequest-event-receiver", (req, res, next) => {
  Event.create({
    Data: req.body
  })
    .then(console.log(req.body))
    .then((newEvent) => res.status(201).json(newEvent))
    .catch(next);
});

With my Model using JASONB
const Event = sequelize.define(
    'Events',
    {
        Data:
        {
            type: Sequelize.JSONB,
        }
    }
);


text:
Q: Constraint template parameter depending on passed functor I want to constraint a template parameter depending on the functor passed. Consider this FoldLeft function, from some container type:
template<typename F, typename R>
R FoldLeft(F&& functor, R initialValue) {
    R r = initialValue;
    /* assume that this is a range of uint64_t's */
    while (first != last) {
        r = std::forward<F>(functor)(r, *(first++));
    }
    return r;
}

This function can be called like this:
auto sum = FoldLeft([](uint64_t i, auto& e) { return e + i; }, 0);

Here, the problem is that R is deduced from the initialValue parameter, which is 0 in this case and thus leads to int. Similarly decltype(sum) also gives int.
I want to have R deduced as the return type of the functor, which may be a lambda or any other callable type. I already tried using the method from this answer, but always run into this error:
error:  decltype cannot resolve address of overloaded function
struct function_traits
       ^~~~~~~~~~~~~~~
note:   substitution of deduced template arguments resulted in errors seen above

The code for my attempt (fuction_traits copied from the linked answer):
template<typename T>
using LamRet = typename function_traits<T>::result_type;

template<typename F>
LamRet<F> FoldLeft(F&& functor, LamRet<F> initialValue) {
    LamRet<F> r = initialValue;
    /* assume that this is a range of uint64_t's */
    while (first != last) {
        r = std::forward<F>(functor)(r, *(first++));
    }
    return r;
}

A: Function traits as described are, in my experience, nearly useless, and using them gets in binds like this, because callables in C++ don't have traits like function traits claim they have.
(The one large exception is where you are doing almost a problem specific sublanguage and intentionally cooperating with the traits in order to invoke DRY and not have to repeat types in two spots).
Only a subset of callables have such traits only.  And the more you write C++14 and C++17 style lambdas, the fewer the callables qualify.
Do determine the return value, you need to know what the type you are iterating over is.  Then examine decltype( lambda( argument, iterated_type ) ) (which can also be written as a result_of_t or invoke_result_t template type).
Suppose your iterated type is T, and your argument is A:
template<class F, class A>
using LamRet = std::decay_t<std::result_of_t<F&&( A&&, T& )>>;

Then we can check our lambda argument type with:
template<class F, class A>
using LamArgGood = std::is_convertible< A&&, LamRet<F, A> >;

and
template<class F, class A>
using LamRetGood = std::is_convertible< LamRet<F, A>, LamRet< F, LamRet<F, A > >;

which ensures that the return type of the iterations works.
template<class F, class A,
  class dA = std::decay_t<A>,
  std::enable_if_t< LamArgGood<F, dA>{} && LamRetGood<F, dA>{}, bool> =true
>
LamRet<F, dA> FoldLeft(F&& functor, A&& initialValue) {
  LamRet<F, dA> r = std::forward<A>(initialValue);
  /* assume that this is a range of uint64_t's */
  while (first != last) {
    r = std::forward<F>(functor)(r, *(first++));
  }
  return r;
}

this isn't quite right, but will catch 99% of type errors.  (I assign, not construct, in the iteration; and I convert from A&& to LamRet, not dA&&).


text:
Q: Continuous cache-misses from Cloudfront when using HTML img tag, but getting cache-hits with Postman/browser requests I have a Cloudfront distribution with a S3 origin bucket (using Cloudformation/SAM to delegate resources) that's acting strangely. The S3 bucket only stores images.
Whenever I request an image through the src attribute, the network tab in dev-tools shows that the Cloudfront resource was a cache-miss (remains even after repeated refreshing). However, when sending a GET request through Postman or a browser, after one refresh I start seeing Cache-hits from the respective request sender.
Client-side, I'm using React with styled-components for the image tag. No query strings are being appended and Cloudfront has been told to disregard them as well.
Not sure if this is an issue with my Cloudformation setup or an issue with cached responses from the server, but any guidance would be much appreciated!
My template.yaml file:
UserAssetsDistributionIdentity:
    Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
    Properties:
      CloudFrontOriginAccessIdentityConfig:
        Comment: 'Origin identity.'
  UserAssetsDistribution:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Origins:
          - DomainName: // Domain name removed
            Id: user-assets-bucket
            S3OriginConfig:
              OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/${UserAssetsDistributionIdentity}'
        Enabled: 'true'
        Comment: Projects microservice to distribute user uploaded assets
        DefaultCacheBehavior:
          AllowedMethods:
            - GET
            - HEAD
          CachedMethods:
            - GET
            - HEAD
          CachePolicyId: b2884449-e4de-46a7-ac36-70bc7f1ddd6d
          TargetOriginId: user-assets-bucket
          ViewerProtocolPolicy: allow-all
        ViewerCertificate:
          AcmCertificateArn: // arn removed
          SslSupportMethod: sni-only
          MinimumProtocolVersion: TLSv1
        Aliases:
          - uploads.phazia.com
  UserAssetsBucket:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: PublicRead

A: The issue was Chrome caching response headers for repeat-requests to resources.
Devtools shows a status code of 200 for the requested resource along with a (from disk cache) message- led me to believe that the status code AND the response headers were being cached. Tried clearing the browser cache and got the expected Cloudfront header.


text:
Q: Possible to Drag Shapes Within a GridPane with JavaFX Am I correct in thinking it is not possible to drag Shapes within a GridPane? Here's a link to some code that allows the user to drag shapes around the screen: Drag and Drop Shapes
I want my shapes to have the same behavior as above, but I want them in a GridPane (eventually I'd like their movement to be locked to the X or Y axis to be moved on to adjacent shapes).
I added the below code to the "start" method. It creates circles using the same method as the example code but instead adds them to a grid. Surprisingly, this removed the ability for them to be dragged around.
GridPane grid = new GridPane();
grid.setLayoutX(300);
grid.setLayoutY(100);

int n = 3;
int m = 3;
for (int r = 0; r < n; r++) {
    for (int c = 0; c < m; c++) {

        Circle circle = createCircle(100, 50, 30, Color.BLACK);
        grid.add(circle, c, r);
    }
}
root.getChildren().add(grid);

If you want to test this just add the above code to the "start" method of the example code, just above these lines:
primaryStage.setScene(scene);
primaryStage.show();

My theory is the GridPane, because it locks the circles to certain positions, doesn't allow this dragging behavior.
Any input on how I can achieve movement of the circles along the X and Y axis when dragged?

A: In general, layout panes such as GridPane manage the placement of their content. Changing the layout coordinates will not affect nodes that are placed in these panes. You may find it better to use a plain Pane and manage the layout yourself for functionality such as this.
If you do want to use a GridPane, transformations (such as translations, etc) are applied after layout coordinates are computed, so you can use a translation (e.g. the one built-in with the translateX and translateY properties) to manage dragging in a layout pane.
So you can do:
circle.setOnMouseDragged((t) -> {
  double offsetX = t.getSceneX() - orgSceneX;
  double offsetY = t.getSceneY() - orgSceneY;

  // No idea why they are doing this. c is just circle
  Circle c = (Circle) (t.getSource());

  c.setTranslateX(c.getTranslateX() + offsetX);
  c.setTranslateY(c.getTranslateY() + offsetY);

  orgSceneX = t.getSceneX();
  orgSceneY = t.getSceneY();
});


text:
Q: Change Posts per page count In the wordpress settings => Reading => Blog pages show at most  [input field] posts
I have it set to 3 posts at the moment.
On my index, date archives, tag archives, category archives, search results, etc... All pages that use the loop and paging, it shows 3 posts per page now.
My goal is to be able to have different number of results for different pages.  ON my index maybe have 3 posts but on search results or archives, show a different number of results per page.
Any ideas how to do this?

A: This will do it: (add to your theme's functions.php)
add_action( 'pre_get_posts',  'set_posts_per_page'  );
function set_posts_per_page( $query ) {

  global $wp_the_query;

  if ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_search() ) ) {
    $query->set( 'posts_per_page', 3 );
  }
  elseif ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_archive() ) ) {
    $query->set( 'posts_per_page', 5 );
  }
  // Etc..

  return $query;
}

A: Improving on the answer above: hook pre_get_posts is fetched by reference, thus it does not require a global call or a returncall.
add_action( 'pre_get_posts',  'set_posts_per_page'  );
function set_posts_per_page( $query ) {

  if ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_search() ) ) {
    $query->set( 'posts_per_page', 3 );
  }
  elseif ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_archive() ) ) {
    $query->set( 'posts_per_page', 5 );
  }
  // Etc..

}

A: Using $GLOBALS['wp_query'] or just $wp_query
add_action( 'pre_get_posts',  'set_posts_per_page'  );
function set_posts_per_page( $query ) {

  if ( ( ! is_admin() ) && ( $query === $GLOBALS['wp_query'] ) && ( $query->is_search() ) ) {
    $query->set( 'posts_per_page', 3 );
  }
  elseif ( ( ! is_admin() ) && ( $query === $GLOBALS['wp_the_query'] ) && ( $query->is_archive() ) ) {
    $query->set( 'posts_per_page', 5 );
  }

  return $query;
}


text:
Q: In MIPS, why can a jump instruction set the program counter to a 28-bit target address In MIPS, a 32-bit jump instruction consists of 6-bits for the opcode and 26-bits for the target (destination) address that we want to set the program counter to.
However, it is possible to set the program counter to a 28-bit target address. How is this possible if we can only fit 26-bits in the jump instruction?

A: Instructions on MIPS are always 4-byte aligned, so the low 2 bits of any valid target address can only be zero. Thus, the 26 bits specified in jump instructions are always implicitly left shifted of 2 positions, hence setting the low 28 bits of the PC.


text:
Q: decrypt the encrypted PHP string to Android Java I want to encrypt the final grades of students in PHP and decrypt it in Android Java. I referred my codes here but it returns wrong value.
This is my PHP encryption function
function encode5t($value1){
      for($i=0;$i<3;$i++)
    {
        $value1=base64_encode(strrev($value1));
    }
    return $value1;
    }

Call the function:
    foreach ($rows as $row){
        $post["cSemester"] = $row["cSemester"];
        $post["cSchoolYear"] = $row["cSchoolYear"];
        $post["cSubjectCode"] = $row["cSubjectCode"];
        $post["cDescription"] = $row["cDescription"];
        $post["nFGrade"] = encode5t($row["nFGrade"]);
        $post["nCGrade"] = $row["nCGrade"];
        $post["nCredit"] = $row["nCredit"];

        //update our response JSON data
        array_push($response["posts"], $post);
    }
    echo json_encode($response);

And this is my Java code.
    vGrades = json.getJSONArray(TAG_POSTS);
    for (int i = 0; i < vGrades.length(); i++) {
    JSONObject c = vGrades.getJSONObject(i);

    String cSemester = c.getString(TAG_SEMESTER);
    String cSchoolYear = c.getString(TAG_SCHOOLYEAR);
    String cSubjectCode = c.getString(TAG_SUBJECTCODE);
    String cDescription = c.getString(TAG_DESCRIPTION);
    String encrypted_string = c.getString(TAG_FINALGRADE);
    String nCGrade = c.getString(TAG_COMPLETIONGRADE);
    String nCredit = c.getString(TAG_CREDIT);
    HashMap<String, String> map = new HashMap<String, String>();

    try{
    byteArray = Base64.decode(encrypted_string, Base64.DEFAULT);
    decrypt = new String(byteArray, "UTF-8");
    }catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }  // this is where I want to decrypt it.

    nFGrade = decrypt;
    map.put(TAG_SEMESTER, cSemester);
    map.put(TAG_SCHOOLYEAR, cSchoolYear);
    map.put(TAG_SUBJECTCODE, cSubjectCode);
    map.put(TAG_DESCRIPTION, cDescription);
    map.put(TAG_FINALGRADE, nFGrade);
    map.put(TAG_COMPLETIONGRADE, nCGrade);
    map.put(TAG_CREDIT, nCredit);
    ViewGrades.add(map);
    }

The PHP encryption is running .. but when i decrypt it  the system returns another encrypted value .. for example the fGrade is 1.0.
the PHP encypted String value is: "PT1RVERSRGU="
the Java decrypted value is: "==QTDRDe"
where did I go wrong? I need help please ..thanks guys!

A: Base64 has no key, anyone can decode it, change it and replace it. But that may be all you need if you just want to thwart the casual user. You need to define who you are protecting against knowing that every scheme can be compromised.
To encrypt data use AES. Encryption is not easy to get correct. The PHP mcrypt encryption function is flawed, do not use it. Consider RNCryptor-php, it provides a full solution including authentication and key derivation.


text:
Q: Как раскрыть кавычки у + и - в Python? Есть функция, которая среди аргументов получает арифметическое действие. Оно естественно заключено в кавычки.
Расчёт для return происходит примерно так:
func_arg_1 = '10'
func_arg_2 = '5'
func_arg_3 = '+'
result = int(func_arg_1) +  func_arg_2 + int(func_arg_2)

Пробовал через eval но аргумент всё же раскрывает как строку
result = eval(int(func_arg_1) +  func_arg_2 + int(func_arg_2))

Возможно есть какое либо очевидное решение, но пока о нём не знаю (кодингом не так долго занимаюсь)
Пример взятый из моего кода:
def(self, status)
    self.cur.execute("SELECT reputation FROM profiles WHERE vkid = %s", [self.replay_id])
    rep = eval(str(self.cur.fetchall()[0][0])) + str(status) + str(self._karma(self.user_id))

p.s. функция self._karma возвращает int, но как видно из примера преобразуется в str
TraceBack следующий:
line 185, in restatus
    rep = eval(str(self.cur.fetchall()[
TypeError: unsupported operand type(s) for +: 'int' and 'str'

A: Если в примере с eval убрать int и не путаться с именами аргументов, то все заработает.


text:
Q: KVM switching back to Ubuntu 22.04 causes panic I just purchased a Ablewe 2 port HDMI KVM switch to toggle between an Ubuntu 22.04 laptop and another system.  Everything is working, except when I switch from the other system to the Ubuntu 22.04  laptop, the system panics and drops me back into the login screen.  I then have to re-login  and restart any applications I may have been using.
Here are 3 messages from journalctl -k right around the time this happens:

Lockdown: systemd-logind: hibernation is restricted; see man kernel_lockdown.7

audit: type=1107 audit(1666016175.825:318): pid=841 uid=103 auid=4294967295 ses=4294967295 subj=unconfined msg='apparmor="DENIED" operation="dbu> exe="/usr/bin/dbus-daemon" sauid=103 hostname=? addr=? terminal=?'

xhci_hcd 0000:2c:00.0: xHC error in resume, USBSTS 0x401, Reinit

I've tried different cable configurations and video driver combinations.
The product/manufacturer from journalctl -k is:

USB 2.0 BILLBOARD / VIA Technologies Inc.

Does anyone have any suggestions?