text:
Q: ThemeProvider does not change the theme of component, React I want to apply theme to React Component(Class Component). This theme works fine when i define the ThemeProvider and the CustomComponent in same file. When i separate the files, it stops working. It does not apply the theme to the component. Code is given below
ThemedComponent:
import React, { Component } from "react";
import TextField from "@material-ui/core/TextField";
import PropTypes from "prop-types";
import { makeStyles, createStyles } from "@material-ui/core/styles";
import { green } from "@material-ui/core/colors";
import { withStyles } from "@material-ui/styles";

const Styles = makeStyles(theme =>
  createStyles({
    root: {
      "&.Mui-focused": {
        border: "20px solid red",
        "& .MuiOutlinedInput-notchedOutline": {
          border: "none"
        }
      }
    }
  })
);
class ThemedComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      value: ""
    };
  }

  handlePasswordChange(event) {
    this.setState({ value: event.target.value });
  }
  render() {
    console.log("I am showing All Props", this.props);
    const { classes } = this.props;
    console.log("I am showing ", classes);
    return (
      <TextField
        onChange={event => this.handlePasswordChange(event)}
        variant="outlined"
        classes={{ root: classes.root }}
        InputProps={{ className: classes.root }}
      />
    );
  }
}
ThemedComponent.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(Styles)(ThemedComponent);

CustomTextField:
import React from "react";
import ThemedComponent from "./ThemedComponent";
import { orange } from "@material-ui/core/colors";
import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles";
import { green } from "@material-ui/core/colors";

const theme = createMuiTheme({
  status: {
    borderStyle: "20px solid red"
  }
});
function CustomTextField() {
  return (
    <ThemeProvider theme={theme}>
      <ThemedComponent/>
    </ThemeProvider>
  );
}

export default CustomTextField;

App.js:
 return (
    <div className="App">
      <CustomTextField />
    </div>
  );

Here is the link to CodeSandBox
Help would be appreciated. Thanks


text:
Q: 'Require()' module inside a function doesn't work? Issue
I'm currently trying to conditionally import an optional JavaScript module.
Meaning, I want to perform some behavior when module X is available, otherwise fallback to Y.
To reach such behavior, I put the require() into a try-catch block, to catch the error thrown by require() when a module couldn't be retrieved.
To reuse this logic and not have to put a try-catch block at the top of my files, I outsourced this logic into a function called optionalRequire().
But as soon as I put the require() into a function, it can't retrieve any package/module anymore. (See code sinppet and image below)
In the below code snippet I placed a normal require(), a require () inside a try-catch block and my optionalRequire() method next to each other. And as you can see in the below console image, everything works as expected, except the optinalRequire().
console.log('Debug: Optional Import Test');

// Require Package in the file
const requiredPackage = require('@agile-ts/proxytree');
console.log('Debug: Required Package', requiredPackage);

// Require Packae in a try catch
let tryCatchPackage = null;
try {
  tryCatchPackage = require('@agile-ts/proxytree');
} catch (e) {
  console.log('Debug: Failed');
}

console.log('Debug: TryCatch Package', tryCatchPackage);

// Require Package in a function
function optionalRequire(moduleName) {
  let requiredPackage = null;
  try {
    requiredPackage = require(moduleName);
  } catch (e) {
    console.log('Debug', e);
  }
  return requiredPackage;
}

const functionPackage = optionalRequire('@agile-ts/proxytree');
console.log('Debug: Function Package', functionPackage);

Question
Does anybody know why it can't require() any module inside a function?
Environment
"react": "^16.13.1"

https://github.com/agile-ts/agile/tree/master/examples/react/develop/functional-component-ts
Example
The weird thing is that it works fine in the codesandbox example.
Probably I have misconfigured anything in my current test project.
However, it would be nice to conditionally require() something, without configuring anything, since that would be an extra step for the people using the package I'm creating.
https://codesandbox.io/s/import-issue-o10cy?file=/src/core.js

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Convert XML Rows to Columns I have seen a few answers on how to convert rows to columns but they are rather specific to the questions and are difficult for me to transpose into my own solution.
The data starts out as a varchar, but I convert it to XML because I thought it would be easier to convert it to columns that way.
-- get xml
DECLARE @x XML

SET @x = '

Gas grill rotisserie

Fits the Genesis E-300 gas grill

Fits the Genesis S-300 gas grill

Includes a heavy-duty electric motor

Counterbalance for smooth turning and less motor wear

'

SELECT x.r.value('node()[1]','varchar(200)')
FROM @x.nodes('/ul/li') AS x(r)

This returns a results like the following; however, I now need to convert each row into a column.

I have tried variations using pivot and dynamic SQL, but haven't gotten very far.  How can I convert each row to a column (when the number of rows will be unknown).
Ref. Convert Rows to columns using 'Pivot' in SQL Server
Ref. How to convert row values to columns with dynamic columns count?

A: I was SOreadytohelp myself this time :) ...  The following query receives the HTML, converts it to XML, defines the column names and writes the dynamic SQL before executing it.
The end result is:

DECLARE @x XML,
 @limit int = 4,
 @ItemId NVARCHAR(10) = '11158',
 @cols AS NVARCHAR(MAX),
 @query  AS NVARCHAR(MAX)

-- get xml
SELECT @x = '

Gas grill rotisserie

Fits the Genesis E-300 gas grill

Fits the Genesis S-300 gas grill

Includes a heavy-duty electric motor

Counterbalance for smooth turning and less motor wear

'

-- convert rows to columns
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(name)
                    from
                    (
                      SELECT top (@limit)
                        bar.value('local-name(.)','VARCHAR(12)') + cast(row_number() over(order by bar.value('./.','VARCHAR(10)') asc) as varchar(10)) as name,
                        bar.value('./.','VARCHAR(255)') as value
                        FROM
                        @x.nodes('/ul/*') AS foo(bar)
                    ) d
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

-- create dynamic sql
set @query = '
            -- get xml
                DECLARE @x XML
                SELECT @x = ''

Gas grill rotisserie

Fits the Genesis E-300 gas grill

Fits the Genesis S-300 gas grill

Includes a heavy-duty electric motor

Counterbalance for smooth turning and less motor wear

''
            SELECT ' + @cols + '
             from
             (
               SELECT
                bar.value(''local-name(.)'',''VARCHAR(12)'') + cast(row_number() over(order by bar.value(''./.'',''VARCHAR(10)'') asc) as varchar(10)) as name,
                bar.value(''./.'',''VARCHAR(255)'') as value
                FROM
                @x.nodes(''/ul/*'') AS foo(bar)
            ) x
            pivot
            (
                max(value)
                for name in (' + @cols + ')
            ) p '

execute sp_executesql @query;


text:
Q: string variable and parameter evaluation function addRow(){
    var row=`<input name="car[].name">
    <input type='text' name='car[].defaultPrice'>
    `;
    $("#carsTable tbody").append(row);
}

How to pass a concatenate value passed to this function?
if I pass i=0
I would like to get
var row=`<input name="car[0].name"><input type='text' name='car[0].defaultPrice'></td>`;

A: var row=`<input name="car[${i}].name">
<input type='text' name='car[${i}].defaultPrice'>
`;

assuming you are using ES6, you can use ${i} in order to use the values of variables between the backticks.

A: Making use of string interpolation:
function addRow(i) {
    var row=`

            <input name="car[${i}].name">
            <input type='text' name='car[${i}].defaultPrice'>
        	`;
    $("#carsTable tbody").append(row);
}

Regular string:
function addRow(i) {
    var row="" +
                "<input name='car[" + i + "].name'>" +
                "<input type='text' name='car[" + i + "].defaultPrice'>" +
            "	";
    $("#carsTable tbody").append(row);
}

Though, if you want the name property to evaluate to the actual content of car[i].defaultPrice and name, you will need to do the following:
var car = [
    { name: 'Test', defaultPrice: 20000 },
    { name: 'Test2', defaultPrice: 25000 }
];

function addRow(i) {
    var row=`

            <input name="${car[i].name}">
            <input type='text' name='${car[i].defaultPrice}'>
        	`;
    $("#carsTable tbody").append(row);
}

Then call the function:
addRow(0);
addRow(1);

A: Pass the desired number as an argument to the function:
function addRows(number) {

    var row = '' +
        '' +
            '<input name="car[' + number + '].name">' +
            '<input type='text' name="car[' + number + '].defaultPrice">' +
        '	';

    $("#carsTable tbody").append(row);

}


text:
Q: Assigning IP addresses with multiple routers I have a 3 router setup in my house, and I've managed to get everything to work properly, but I'm still not sure if I have set the IP addresses that the routers assign to the clients properly.
Right now I have:

*

*A router in the garage that acts as the DHCP server and has an IP adress of 192.168.1.1. This router now assigns IP addresses from 192.168.1.100 to 192.168.1.133.

*The second router (192.168.1.2) assigns IP addresses from 192.168.1.134 to 192.168.1.165.

*And finally the third router (192.168.1.3) assigns IP addresses from 192.168.1.166 to 192.168.1.199.
All 3 routers have the same SSID and are six channels apart (1, 6 and 11) so I get great singal in the entire house.
What I've seen is that the clients (my phones, tablets and laptops) were assigned 192.168.1.10 - 12 - 14 etc, although they were getting the singnal from the second and third router.
Should I keep this setup or should I set all 3 routers to assign IP addresses 192.168.1.100 to 192.168.1.199?

A: I agree with RedGrittyBrick. If it was my network I would do his last suggestion, have one router do the DHCP.
Turn OFF DHCP on the other two routers (1.2 and 1.3).
Set the main 1.1 router with DHCP
192.168.1.100 - 192.168.1.199

Leave the static IP's you have for the routers the same
192.168.1.1, 1.2, 1.3

Run a cable from LAN port of 1.1 to LAN port of 1.2 and from 1.1 LAN port to 1.3 LAN port or you could go from 1.2 to 1.3 LAN ports or any combination as long as 1.1 connects to the internet. Do not use WAN ports on 1.2 and 1.3 (unless the routers have the option of changing that port to a LAN port, which they do sometimes).
Now you will be able to freely move about the entire network with your wireless devices and they won't be getting confused about what IP address they should have.

A: You must keep the DHCP ranges separate. Otherwise two PCs talking to different DHCP servers might get the same IP-address.
If your current arrangement works, I see no reason to change it.
Normally, for a small LAN, you'd have one router plus a couple of wireless extenders and have one router allocate the DHCP addresses.

A: 1.) Something else to keep in mind when creating DHCP ranges is the amount of device that will be connected to your SOHO network. If I only had a total of 15 devices then I would set the limit of addresses to 25 (Always have spares for clients, friends and fam). Its a rule of thumb to help lock down your system.
As for your router wireless DHCP setup, sounds like the only think you need to do is turn off the secondary DHCP servers as per @opsin @RedGrittyBrick but ensure that the primary router is still dishing out the correct gateways and DNS IP addresses. In your particular case in it would be:
GW:192.168.1.1 for connected devices.

*IP address class is the primary router.
**NB: You can specifiy a DNS or just use the same as your GW.
2.)Secondly as your using the same IP class it wouldn't matter what IP addresses the devices were given, only what gateway address.


text:
Q: Bitwise Manipulation Functions
Possible Duplicate:
How do you set, clear and toggle a single bit in C?

I'm studying for an upcoming final and I want to verify some questions from the study guide.
Some context:

*

*The Set() function sets a bit in a byte to 1

*The Unset() function sets a bit in a byte to 0

*The Flip() function "flips" the bit to the opposite of what it is
So some kid in our class took it upon himself to answer the study guide questions but I've already found some errors, and these answers sound fishy. Here's what he said:

Which operation is used for the Set? the or operator  |
Which operation is used for the Unset? Xor operator ^ Done twice
Which operation is used for the Flip? Xor operator  ^

Are these the correct bitwise operators to implement in the functions I've described above?

A: Set uses or
Unset uses And
Flip uses Xor
this was already answered here:
How do you set, clear, and toggle a single bit?

A: You are right for the first one, but for Unset() you should use an & with 0 in that bit

A:     00000000 |
    00000001 =
--------------
    00000001   // Sets

    00000001 &
    00000000 =
--------------
    00000000   // Unsets

    00000001 ^
    00000001 =
--------------
    00000000   // Flips

If bit is which bit is to be manipulated in the byte:
x |= (1 << bit);    // Sets
x &= ~(1 << bit);   // Unsets   00000001 becomes 11111110.
x ^= (1 << bit);    // Flips

A: for the nth bit in a number x...
int Set(x, n){
   return x | (1 << n);
}

int Unset(x, n){
   return (x ^ (1 << n)) ^ (1 << n);
}

int Flip(x, n){
   return x ^ (1 << n);
}


text:
Q: What Bluetooth profile/protocol is used for a carkit to know the signalstrength and/or batterylevel of connected phone I have Bluetooth embedded in my car its default mediasystem. When my phone (Nexus 4) is connected it displays the signalstrength and batterylevel of the phone on the display.
What Bluetooth profile/protocol is used for this? I've investigated the HFP and MAP profiles but couldn't find anything on signalstrength or batterylevel.
In the end I want to make an Android app which sends the batterylevel to the car its Bluetooth 'carkit' to enable a charging 'animation'.

A: Most probably this is using Hands Free Profile (see sections 4.5 and 4.7), where the Audio Gateway (your phone) can report both signal strength and battery level to the Hands Free (your car).
I'm not familiar with the internals of Android, but I would imagine the Audio Gateway is part of the platform and not programmatically modifiable - here's no good reason to let a developer modify the battery or signal strength being reported to other devices.


text:
Q: Make -j4 no longer compiles Device tree Binary for embedded Until few days ago, I made some modification to my .dtsi file for embedded, in order to enable/disable I/O pins etc.
After to set environment variables, I wrote the command:
make -j4

and all .dtb files were ready to be used.
After to enter in menuconfig (but I didn't modify it), it no possible to obtain the updated .dtb files. The following is the logout when I launch "make -j4":
  CHK     include/config/kernel.release
  CHK     include/generated/uapi/linux/version.h
  CHK     include/generated/utsrelease.h
make[1]: "include/generated/mach-types.h" è aggiornato.
  CHK     include/generated/bounds.h
  CHK     include/generated/asm-offsets.h
  CALL    scripts/checksyscalls.sh
  CHK     include/generated/compile.h
  Kernel: arch/arm/boot/Image is ready
  Building modules, stage 2.
  Kernel: arch/arm/boot/zImage is ready
  MODPOST 21 modules

Possible solution?

A: PROBLEM SOLVED!
Step-by-step procedure to build kernel from source code is the following:
1) set the environment variable:
source /opt/fslc-x11/2.2.1/environment-setup-armv7at2hf-neon-fslc-linux-gnueabi
2) clean all with:
make mrproper
3) set configuration:
make imx6ul-var-dart_defconfig
4) Customize the kernel configuration (if needed):
make menuconfig
5) Build what you need (in my case dtbs):
make -j4 dtbs
Well, in the previous procedure I forget step 3). Once all was done, Device Tree Blob built perfectly.
Just in case it 'd be useful for someone else.


text:
Q: How to run gatling with scala file name without simulation name? I run the gatling with ./gatling.sh -s className command.
But class name can be different from simulation file name.
For Example The simulation name below is Test,but scala file name can be different.The file name is TestSimulation.scala.
How can I run the simulation with file name?
 import io.gatling.core.Predef._
 import io.gatling.http.Predef._
 import scala.concurrent.duration._

 class Test extends Simulation {
   val httpConf = http.baseURL("url")
   var scn = scenario("Test")
        .exec(
            http("My Other Request")
              .get("/1")
   )

   setUp(scn.inject(rampUsers(2000) over  (200 seconds)).protocols(httpConf))
 }

A: According to Scala documentation

In short, the Java file naming and positioning conventions should be preferred, despite the fact that Scala allows for greater flexibility in this regard.

So your class should be named TestSimulation, not Test
If you want to run your simulation as it is you can provide just test as the simulation name like:
gatling -s test

and it should start executing your simulation given it is under user-files/simulations or Gatling can find it somehow else.
Check out How to Run a Simple Load Test with Gatling for more information if needed.


text:
Q: Javascript forEach swallowing exceptions I am trying to loop over an array using forEach loop with async callback in javascript. The problem is that when I throw an exception it gives
(node:2500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 6)

Although I have a catch block after forEach. Here is my code
async function func() {
    try {
        array.forEach(async (e) => {
            try {
                let bom = await BOMChild.findOne({
                    where: { id: e.id },
                });

                if (bom.BOMProductId || bom.BOMProductId === 0) {
                    throw {
                        name: " error",
                        description: `Description `,
                    };
                }
            } catch (e) {
                throw e;
            }
        });
    } catch (e) {
        //exception caught
    }
}

What I am doing wrong and what is the possible way to solve this.
TIA

A: Unfortunately there's no safe way to use async callbacks with forEach. The simplest solution is to re-implement forEach in an async way as shown below. Note that asyncForEach itself returns a promise, so you'll need to use .then() to continue your program.
const asyncForEach = async (array, callback) => {
  try {
    for (let i = 0; i < array.length; i++) {
      await callback(array[i]);
    }
  }
  catch (ex) {
     // handle exception here.
  }
}

asyncForEach(array, async () => {
  let bom = await BOMChild.findOne({
    where: { id: e.id },
  });

  if (bom.BOMProductId || bom.BOMProductId === 0) {
    throw {
      name: " error",
      description: `Description `,
    };
  }
}).then(() => {
  // continue program.
});

If you want to test your promise chops with a cleaner, but more confusing solution, take a look a Promise.all().


text:
Q: Understanding how spring-data handles @EntityGraph (I made a SSCCE for this question.)
I have 2 simple entities : Employee and Company. Employee has a @ManyToOne relationship with Company with default fetch strategy (eager).
I want to be able to load the Employee without the Companywithout changing the fetch strategy defined in the Employee because I need to do that for only one use case.
JPA's entity graph seems to be intended for this purpose.
So I defined a @NamedEntityGraphon the class Employee:
@Entity
@NamedEntityGraph(name = "employeeOnly")
public class Employee {

  @Id
  private Integer id;
  private String name;
  private String surname;
  @ManyToOne
  private Company company;

  //Getters & Setters

And a EmployeeRepository like this :
public interface EmployeeRepository extends CrudRepository<Employee, Integer> {

  @EntityGraph(value = "employeeOnly", type = EntityGraph.EntityGraphType.FETCH)
  List<Employee> findByCompanyId(Integer companyId);

}

Despite the use of @EntityGraph, I can see in the logs that the Company is still loaded by hibernate :
2016-11-07 23:16:08.738 DEBUG 1029 --- [nio-8080-exec-2] org.hibernate.SQL                        : select employee0_.id as id1_1_, employee0_.company_id as company_4_1_, employee0_.name as name2_1_, employee0_.surname as surname3_1_ from employee employee0_ left outer join company company1_ on employee0_.company_id=company1_.id where company1_.id=?
2016-11-07 23:16:08.744 DEBUG 1029 --- [nio-8080-exec-2] org.hibernate.SQL                        : select company0_.id as id1_0_0_, company0_.name as name2_0_0_ from company company0_ where company0_.id=?

Why? How to avoid that?

A: Modified Answer
per-specification, the fetch type for @ManyToOne is EAGER by default. But even through we set:
@ManyToOne(fetch = FetchType.LAZY)
private Company company;

You will get the same result. The problem because the way spring-data-jpa create HQL/JPQL for you. So adding @ManyToOne(fetch = FetchType.LAZY) won't work is not enough. To solve this, use@ManyToOne(fetch = FetchType.LAZY) and @Query annotation in your repository:
Employee.java :
@ManyToOne(fetch = FetchType.LAZY)
private Company company;

EmployeeRepository.java
@Query("from Employee e where e.company.id = :companyId")
List<Employee> findByCompanyIdUsingQuery(@Param("companyId") Integer companyId);

In the test, this is SQL that generated by your loadByCompanyId() (which is generate left outer join):
select employee0_.id as id1_1_, employee0_.company_id as company_4_1_, employee0_.name as name2_1_, employee0_.surname as surname3_1_ from employee employee0_ left outer join company company1_ on employee0_.company_id=company1_.id where company1_.id=?

And this is SQL generated by method that use @Query annotation:
select employee0_.id as id1_1_, employee0_.company_id as company_4_1_, employee0_.name as name2_1_, employee0_.surname as surname3_1_ from employee employee0_ where employee0_.company_id=?

You could check the latest code in my repository.
HTH.

A: Hibernate did not support handling non-lazy attributes as lazy, even with entity graphs. There was an issue for this: HHH-8776, but it's fixed now.
Previously, the only solution for the time being was to make the association lazy.

A: Seems a bug in Hibernate.
@Dragan Bozanovic you are right. I only see one workaround in this case.
Set fetch = lazy
@Entity
@NamedEntityGraph(name = "Employee.withCompany" , attributeNodes = @NamedAttributeNode("company"))
public class Employee {

  @Id
  private Integer id;
  private String name;
  private String surname;
  @ManyToOne(fetch = FetchType.LAZY)
  private Company company;

Introduce new method for loading company eagerly
public interface EmployeeRepository extends CrudRepository<Employee, Integer> {

  List<Employee> findByCompanyId(Integer companyId);

  @Query("select e from Employee e left join e.company c where c.id = :companyId")
  @EntityGraph(value = "Employee.withCompany", type = EntityGraph.EntityGraphType.FETCH)
  List<Employee> findByCompanyIdFetchingCompany(@Param("companyId") Integer companyId);

}

And use following two interchangeably where required
  @RequestMapping(value = "/by-company/{id}")
  public void loadByCompanyId(@PathVariable Integer id) {
    employeeService.loadByCompanyId(id);
  }

  @RequestMapping(value = "/by-company/eager-company/{id}")
  public void loadByCompanyIdFetchingCompany(@PathVariable Integer id) {
    employeeService.loadByCompanyIdFetchingCompany(id);
  }

First one (for lazy loading) http://localhost:8080/employees/by-company/42
select employee0_.id as id1_1_, employee0_.company_id as company_4_1_, employee0_.name as name2_1_, employee0_.surname as surname3_1_ from employee employee0_ left outer join company company1_ on employee0_.company_id=company1_.id where company1_.id=?

Second (eager loading) http://localhost:8080/employees/by-company/eager-company/42
select employee0_.id as id1_1_0_, company1_.id as id1_0_1_, employee0_.company_id as company_4_1_0_, employee0_.name as name2_1_0_, employee0_.surname as surname3_1_0_, company1_.name as name2_0_1_ from employee employee0_ left outer join company company1_ on employee0_.company_id=company1_.id where company1_.id=?

A: I was under impression you have to specify fields within your Graph definition.
https://docs.oracle.com/javaee/7/tutorial/persistence-entitygraphs001.htm (43.1.2.1 Fetch Graphs)

A fetch graph consists of only the fields explicitly specified in the
  EntityGraph instance, and ignores the default entity graph settings.

A: Maybe not so cool solution is using a native query.
 @Query(value = "select * from employee where company_id= ?1", nativeQuery = true)
  List<Employee> findByCompanyId(Integer companyId);

I tested it and it was giving expected results, without being forced to set  fetch = FetchType.LAZY

A: though the association is lazy by specifying (fetch=FetchType.Lazy) the company is exposed with a separate query call because you are exposing the Entity Employee which has property company. If you don't want the company to be exposed then either use @JsonIgnore, which is not very much recommended. And here comes one of the reasons why we make used of DTO so that we can expose only the required fields. You can create an EmployeeDTO with employee specific fields keep the association lazy which will ensure that separate query is not executed to fetch company details and map the entity to DTO either explicitly or you can make use of MapSturct Api


text:
Q: Scala classes in clojure It's just a stupid question that I had this morning : Can we use Scala classes from clojure ?
Because if the answer is yes, I'll definetly learn Clojure ^^

A: Worth saying that Scala classes which take function parameters, such as:
Option.map(f : A => B)

Are unlikely to be very useable from Clojure, because the Clojure compiler will not turn Clojure lambdas into instances of scala.FunctionN. I'm with Daniel - I think interop will be poor.

A: Scala classes are Java classes and you can use Java classes from Clojure quite conveniently.
Have fun learning Clojure. :-)

A: Scala classes, yes. Scala singleton objects, with the same year signature as from Java. Scala traits, no. Scala implicits, hah, you jest!
So the experience may range from "ok", if it's just your classes, to very disagreeable, in the case of Scala collections, for instance.


text:
Q: Swift and NSUserDefaults - EXC_BAD_INSTRUCTION when user defaults empty I'm converting one of my projects to Swift, file by file. I have a strange behavior with NSUserDefaults. I use an NSString and not a String for compatibility with other code
var selectedMonth : NSString {
get {
    return NSUserDefaults.standardUserDefaults().objectForKey(AppUserDefaults.SelectedMonth.value()) as NSString
}
set {
    NSUserDefaults.standardUserDefaults().setObject(self, forKey: AppUserDefaults.SelectedMonth.value())
    NSUserDefaults.standardUserDefaults().synchronize()
}
}

The method works correctly for getting/setting the property, but when the app is executed the first time and the user defaults are empty, I receive an EXC_BAD_INSTRUCTION error on return NSUserDefaults.standardUserDefaults().objectForKey(AppUserDefaults.SelectedMonth.value()) as NSString
The problem is not in the return, since I can "expand" the statement as this:
    let defaultKey = AppUserDefaults.SelectedMonth.value()
    let defaults = NSUserDefaults.standardUserDefaults()  // defaults is correctly set
    let result : AnyObject = defaults.objectForKey(defaultKey)  // <-- the error is here
    return result as NSString

A similar statement in objective C works correctly, returning nil, but I see that the declaration of objectForKey in swift is
func objectForKey(defaultName: String!) -> AnyObject!

Note the exclamation mark at the end, it seems that an object MUST be returned from the function, but I think that the correct declaration (to make it work like in objc) should end with a ?
So I think that the behavior changed, and it's not written in the documentation.
Do you think it's a bug (so I'll file it) or am I missing something?
Thanks

A: Try this
if let myObject : AnyObject = defaults.objectForKey(defaultKey){
    // grab myObject here
    return myObject;
}else{
    // .. //
    return nil;
}

A: edit
This answer is no longer updated since in the final Swift release Apple changed the method declaration of objectForKey on NSUserDefaults (and many other methods bridged from objective c) to return an optional ( ? ) and no more an Implicitly Unwrapped Optional ( ! )
end edit
Ok, I read better the docs and the meaning of the ! in a declaration, which is different from a ! when using a variable.
! in a declaration means that that variable is implicitly unwrapped (on the Swift book, read "Implicitly Unwrapped Optionals" and "Unowned References and Implicitly Unwrapped Optional Properties" chapters to understand better what it means
In simple words, it means that the return value can still be nil, but since it happens "rarely", the return value / variable is not marked as optional (with the ?).
This is made to avoid the needing for the programmer to unwrap the value every time (checking with an if statement and unwrapping the value) having a cleaner code.
However, the first problem was that the EXC_BAD_INSTRUCTION was given on the wrong line, since with this statement
let defaultKey = AppUserDefaults.SelectedMonth.value()
let defaults = NSUserDefaults.standardUserDefaults()
let result : AnyObject = defaults.objectForKey(defaultKey)
return NSString(UTF8String: "")

no error is given.(the result was not returned but the objectForKey call did not fail)
So this brought me on the right way again and understanding the meaning of Implicitly Unwrapped Optionals
The solutions are simple, since the returned value can be nil the variable selectedMonth should have a ? (to be marked as optional) or a ! (to be marked as implicitly unwrapped optional)
Examples
1) return AnyObject? optinal value as a type for the var selectedMonth
var selectedMonth : AnyObject? {
get {
    return NSUserDefaults.standardUserDefaults().objectForKey(AppUserDefaults.SelectedMonth.value())

}
set {
    NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: AppUserDefaults.SelectedMonth.value())
    NSUserDefaults.standardUserDefaults().synchronize()
}
}

2) return an optional NSString?, cast the return type to AnyObject? and then to NSString?
var selectedMonth : NSString? {
get {
    return NSUserDefaults.standardUserDefaults().objectForKey(AppUserDefaults.SelectedMonth.value()) as AnyObject? as NSString?
}
set {
    NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: AppUserDefaults.SelectedMonth.value())
    NSUserDefaults.standardUserDefaults().synchronize()
}
}

this is like writing
var selectedMonth : NSString? {
get {
    var returnValue : AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey(AppUserDefaults.SelectedMonth.value())
    return returnValue as NSString?
}
set {
    NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: AppUserDefaults.SelectedMonth.value())
    NSUserDefaults.standardUserDefaults().synchronize()
}
}

3) return an implicitly wrapped NSString!
var selectedMonth : NSString! {
get {
    var returnValue : AnyObject! = NSUserDefaults.standardUserDefaults().objectForKey(AppUserDefaults.SelectedMonth.value())
    return returnValue as NSString!
}
set {
    NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: AppUserDefaults.SelectedMonth.value())
    NSUserDefaults.standardUserDefaults().synchronize()
}
}

4) short version
var selectedMonth : NSString! {
get {
    return NSUserDefaults.standardUserDefaults().objectForKey(AppUserDefaults.SelectedMonth.value()) as AnyObject! as NSString!
}
set {
    NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: AppUserDefaults.SelectedMonth.value())
    NSUserDefaults.standardUserDefaults().synchronize()
}
}


text:
Q: Setting up Model Changes for DB Migrations MVC5 I've created a standard MVC app in visual studio 2015, with the few basics automatic steps "New Project --> ASP.NET Web Application --> Individual User Account".  I've created a table Menus directly in the DB. The question is: how to update the model directory to ad the relatice class from the database? there are a lot of tutorials about migrate the db from the models but I can't find the opposite. Thanks
CREATE TABLE [dbo].[Menus](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ParentID] [int] NULL,
    [Title] [varchar](50) NULL,
    [Description] [varchar](250) NULL,
PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

A: In Entity Framework you can choose between three different approaches: Code first, Database first, and Model first. Check the link for more info: http://www.entityframeworktutorial.net/choosing-development-approach-with-entity-framework.aspx
Since you are manually creating the database tables, it looks like you want to use the Database first approach.
In order to create a data model in Visual Studio based on your existing database, you need to:

*

*Add a "ADO.NET Entity Data Model" to your project.

*In the first step of the wizard, select "EF Designer from database".

*Specify the connection details (Server, database and authentication)

*Select what entities should be in your model (you can include tables, views, stored procedures and functions).

After all those steps, an edmx file will be created with your model in it. Once you save this, all the classes will be generated.
If you want to modify an existing model, you can right click on your edmx file, select update model from database and follow the steps specified above.
Check this link for a more detailed explanation:
https://msdn.microsoft.com/en-us/data/jj206878


text:
Q: Android Studio Rendering Error: Missing Styles I'm trying to learn Android through the tutorials at TheNewBoston.com.
In the tutorial, I'm supposed to switch to the material light theme. That's when I get the error. It says:

Missing styles. Is the correct theme chosen for the layout?

Here's a screen shot:

Here's what I've tried:

*

*I've tried switching out of Android API 23, N preview for a lower
API

*I've tried changing code in the styles.xml file from
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
to
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

*I've tried invalidating the cache and restarting.
Nothing seems to be working. I'm very new at Android and just want to get the IDE set up correctly. I also get this message on startup and I think it's related to the error:

A: Change your layout Preview from API N to API 23. also select target and compile sdk version 23.

Change Compile sdk version and Build SDK version

A: Have you added this line to your build.gradle file under dependencies
   compile 'com.android.support:appcompat-v7:23.2.1'

Note that the support version number might be higher for you. Add below line too to your depedencies
    compile 'com.android.support:design:23.2.1'

A: In theme dropdown at the top of the graphical display of layout. change  Theme.
check your theme in style than choose it in the layout too
OR
changed from Holo to Theme and the layout displayed and error disappeared.
check this answer for more detail

A: Reinstalling Android Studio and right-clicking the shortcut to run the program as administrator sorted out the problem.


text:
Q: How to make the chrome browser window move down to show text continuously without user input? This page is for an art project; it should look like a ghost is typing continuously. More "real" text will be added and I need it to loop back at the end. The #1 problem is when the text hits bottom of page it continues, but can't be seen without user scrolling.
My cobbled together code is kind of working in chrome; however, I want the page to automatically move down when the copy continues to appear line by line at the bottom of the page, (without input from user). Also, I'm unable to break the lines with
 or
. Tried using back tics instead of quotes and single quotes instead of double; line breaks don't work.
Below is the code I'm using:
<!DOCTYPE html>

A: All you need is to force the scrolling parent (in this case it will be document.documentElement to scroll by its scrollable height. Technically speaking the scrollable height is scrollHeight - offsetHeight, but the scrollTo function is smart enough that if you provide a value that is too large it will just scroll to the bottom of the element.
Then it is just a matter of calling document.documentElement.scrollTo(0, document.documentElement.scrollHeight). See proof-of-concept below (I have increased the speed by a factor of 10).
A usability warning tho: by constantly updating the scroll position can cause frustration to the user as it will overwrite whatever scroll position they are at: e.g. if a user scrolls up to read the earlier text they will be forcibly scrolled to the bottom every time a new character is inserted.

let i = 0;
const speed = 10;

function typeWriter() {
  if (i < txt.length) {
    document.getElementById("testType").textContent += txt.charAt(i);
    i++;
    setTimeout(typeWriter, speed);
    document.documentElement.scrollTo(0, document.documentElement.scrollHeight);
  }
}

const txt = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sed faucibus turpis in eu mi. Tortor vitae purus faucibus ornare suspendisse sed nisi. Elementum curabitur vitae nunc sed velit. Accumsan in nisl nisi scelerisque eu ultrices vitae auctor. Lectus sit amet est placerat in egestas erat imperdiet sed. In iaculis nunc sed augue lacus. Tristique nulla aliquet enim tortor at. Ac placerat vestibulum lectus mauris ultrices. Fermentum leo vel orci porta non pulvinar neque. Erat imperdiet sed euismod nisi. Vel fringilla est ullamcorper eget nulla facilisi etiam. Eget nullam non nisi est. A diam maecenas sed enim. Pulvinar etiam non quam lacus suspendisse faucibus interdum. Nullam eget felis eget nunc lobortis. Urna cursus eget nunc scelerisque viverra mauris in. Ultrices tincidunt arcu non sodales neque sodales ut etiam sit. Vitae sapien pellentesque habitant morbi tristique senectus et netus et. Purus non enim praesent elementum facilisis leo vel fringilla est. Aliquet sagittis id consectetur purus. Venenatis lectus magna fringilla urna porttitor rhoncus dolor. Arcu odio ut sem nulla pharetra diam sit amet.";

document.addEventListener("DOMContentLoaded", typeWriter);
body {
  font-family: monospace;
  font-size: 30px;
  margin: 10px 50px;
  letter-spacing: 6px;
  font-weight: normal;
}

We can do better with async/await
There is actually no need to keep track of the index i, if we use a for...of loop. Moreover, if we use async/await we can make things a lot more readable without needing to worry about recursion, when used with a for loop:

const speed = 10;

async function sleep(d) {
  return new Promise(r => setTimeout(r, d));
}

const container = document.getElementById('testType');
async function typeWriter() {
  for (const character of txt) {
    container.textContent += character;
    document.documentElement.scrollTo(0, document.documentElement.scrollHeight);
    await sleep(speed);
  }
}

const txt = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sed faucibus turpis in eu mi. Tortor vitae purus faucibus ornare suspendisse sed nisi. Elementum curabitur vitae nunc sed velit. Accumsan in nisl nisi scelerisque eu ultrices vitae auctor. Lectus sit amet est placerat in egestas erat imperdiet sed. In iaculis nunc sed augue lacus. Tristique nulla aliquet enim tortor at. Ac placerat vestibulum lectus mauris ultrices. Fermentum leo vel orci porta non pulvinar neque. Erat imperdiet sed euismod nisi. Vel fringilla est ullamcorper eget nulla facilisi etiam. Eget nullam non nisi est. A diam maecenas sed enim. Pulvinar etiam non quam lacus suspendisse faucibus interdum. Nullam eget felis eget nunc lobortis. Urna cursus eget nunc scelerisque viverra mauris in. Ultrices tincidunt arcu non sodales neque sodales ut etiam sit. Vitae sapien pellentesque habitant morbi tristique senectus et netus et. Purus non enim praesent elementum facilisis leo vel fringilla est. Aliquet sagittis id consectetur purus. Venenatis lectus magna fringilla urna porttitor rhoncus dolor. Arcu odio ut sem nulla pharetra diam sit amet.";

document.addEventListener("DOMContentLoaded", typeWriter);
body {
  font-family: monospace;
  font-size: 30px;
  margin: 10px 50px;
  letter-spacing: 6px;
  font-weight: normal;
}

Want to use line-breaks?
If you want to introduce line breaks, I would suggest you split it up into an array of texts instead. The reason being that you still want to treat your string "as-is", but need to arbitrarily insert HTML
 tags to create spacing.
You can store this info in any way you want, but let's say we run with an array of objects that basically store a string and an optional "breakAfter", which will insert x number of
 tags as you see fit:

const speed = 10;
const container = document.getElementById('testType');

async function sleep(d) {
  return new Promise(r => setTimeout(r, d));
}

async function typeWriter() {
  for (const entry of texts) {
    // Assume we want to start a new line with every entry
    // When `entry.breakAfter` is undefined we fallback to 1
    // NOTE: This is ES6 object destructuring!
    const { text, breakAfter = 1 } = entry;

    for (const character of text) {
      container.innerHTML += character;
      await sleep(speed);
    }

    for (let j = 0; j < breakAfter ; j++) {
      container.innerHTML += '
';
      await sleep(speed);
    }
  }
}

const texts = [{
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
  },
  {
    text: "Foo",
    breakAfter: 3,
  },
  {
    text: "Bar",
    breakAfter: 5,
  }, {
    text: "End"
  }
];

document.addEventListener("DOMContentLoaded", typeWriter);
body {
  font-family: monospace;
  font-size: 30px;
  margin: 10px 50px;
  letter-spacing: 6px;
  font-weight: normal;
}


text:
Q: Can I Import Android Map Extensions in Eclipse Android Map Extensions Library had been containing the gradle for references, There is no bin to add it directly as library in Eclipse, I try to paste those files into the same package name in Eclipse but it does not work and gave many errors.
Is there any way i can Import Android Map Extensions in Eclipse.

A: If you want to use the play-services library you can locate it inside your sdk directory as shown in the figure below

Go to your sdk -> extras -> google -> m2repository -> to play-services -> go inside the version you'd like to use, you'll find an .aar file, copy that and rename the extension to .jar
If you'd like to add other repos you could browse through maven or jcenter (depending on where the project is uploaded) download the .aar file and repeat the same process.
If you were looking for the android map utils, here the link.


text:
Q: WPF WriteableBitmap problems with transparency First of all Ill explain what I try to do, just in the case that someone comes up with a better approach
I need to blend too images using the "color" stile from photoshop (you know, the blending methods: Screen, hard light, color ... )
So, I have my base image (a png) and WriteableBitmap generated on execution time (lets call it color mask). Then I need to blend this two images using the "color" method and show the result in a UI component.
So far what Im trying is just to draw things on the WriteableBitmap but I'm facing unexpected behavior with the alpha channel.
My code so far:
// variables declaration
WriteableBitmap img = new  WriteableBitmap(width, height, 96,96,PixelFormats.Bgra32,null);
pixels = new uint[width * height];

//function for setting the color of one pixel
private void SetPixel(int x, int y, Color c)
    {
        int pixel = width * y + x;

        int red = c.R;
        int green = c.G;
        int blue = c.B;
        int alpha = c.A;

        pixels[pixel] = (uint)((blue << 24) + (green << 16) + (red << 8) + alpha);

    }

//function for paint all the pixels of the image
private void Render()
    {
        Color c = new Color();
        c.R = 255; c.G = 255; c.B = 255; c.A = 50;
        for (int y = 0; y < height; y++)
            for (int x = 0; x < width; x++)
                SetPixel(x, y, c);

        img.WritePixels(new Int32Rect(0, 0, width, height), pixels, width * 4, 0);
        image1.Source = img;  // image1 is a WPF Image in my XAML
    }

Whenever I run the code with the color c.A = 255 I get the expected results. The whole Image is set to the desired color.  But if I set c.A to a different value I get weird things.
If I set the color to BRGA = 0,0,255,50  I get a dark blue almost black. If I set it to BRGA = 255,255,255,50 I get a yellow ...
Any clue !?!?!
Thanks in advance !

A: Change the order of your colour components to
pixels[pixel] = (uint)((alpha << 24) + (red << 16) + (green << 8) + blue);


text:
Q: Qt Installer Framework: conditional action based on whether a component was selected for installation Generally: I need a bool or other hook to determine whether a component has been selected for installation, so that my controlscript.qs (or component-specific installscript.qs) can take the appropriate action.
Specifcally: the Qt installer framework has several default pages for the user to click through. On Windows there is a StartMenuSelection page which allows the user to specify what group (if any) the shortcut to the application should go into in the Windows Start menu.
Start Menu group selection example
One of my components to be installed is an (optional) shortcut in the Start menu. If not selected for install, there will be no shortcut to the installed application in the start menu.
My issue is that the Start Menu group selection page shows up regardless of whether the user has asked for a shortcut in the Start menu. I know how to get rid of it in all cases. But not conditionally on whether a Start menu shortcut is actually being installed.
I have a control script with the following:
function Controller()
{
}

Controller.prototype.StartMenuDirectoryPageCallback = function()
{
  // Get the current wizard page
  var widget = gui.currentPageWidget();
  if (widget != null) {
    var component = installer.componentByName("startmenu"); // startmenu is the component name
    //if (!component.isSelected){
    //if (!component.isSelectedForInstallation){
    if (!component.isInstalled){
      // I only want this hidden if the user didn't want a start menu link
      // Either of the below commands will skip the startMenuSelection page
      installer.setDefaultPageVisible(QInstaller.StartMenuSelection, false);
      //gui.clickButton(buttons.NextButton);
    }
  }
}

But this doesn't work. component.isSelected and component.isSelectedForInstallation always return false, and component.isInstalled always returns true, regardless of if the component was actually selected for installation. Maybe these are the wrong booleans to ask?
Or maybe this is the wrong approach? Essentially, I just need a hook to determine if a component is selected or not.

A: Just found this link:
https://github.com/danimo/qt-creator/blob/master/dist/installer/ifw/packages/org.qtproject.qtcreator.application/meta/installscript.qs
Here they use:
component.installed
The isInstalled is a function (http://doc.qt.io/qtinstallerframework/scripting-component.html#isInstalled-method) that's why probably it always returns true.
So probably component.isInstalled() would have worked as well...
Either, installationRequested() would be another possibility to use. This is probably set before actual installation.


text:
Q: regex that selects lines containing a phone number I did my code for regular expression that selects lines containing a phone number. I have to create an expression for a phone number, but it may have - or . in between the numbers, and it may or may not have an extension. I couldn't figure out and didn't submitted as my homework...I just want to know how its done right because I might have it on the Exam at the end of the semester.
718-951-5000,
718.951.5000,
(718)-951-5000
My code
     "(^(\([2-9]\\d{2}\)|[2-9]\\d{2})[- .]?\d{3}[- .]?\\d{4}$)|(^(\([2-9]\\d{2}\)|[2-9]\\d{2})[- .]?\d{3}[- .]?\\d{4}[xX]\\d{1,4}$)"

My Error
RETest1.java:4: error: illegal escape character
                  "(^(\([2-9]\\d{2}\)|[2-9]\\d{2})[- .]?\\d{3}[- .]?\\d{4}$)|(^(\([2-9]\\d{2}\)|[2-9]\\d{2})[- .]?\\d{3}[- .]?\\d{4}[xX]\\d{1,4}$)"
                       ^

A: It might not be the prettiest, but here is one that works:
"^((\\([2-9]\\d{2}\\)|[2-9]\\d{2})(-\\d{3}-\\d{4}|\\.\\d{3}\\.\\d{4})([Xx] ?\\d{1,4})?)$"

A: [- .]?\d{3}[- .]?
You forgot the second escape \ on the \d
Should be:
"(^(\([2-9]\\d{2}\)|[2-9]\\d{2})[- .]?\\d{3}[- .]?\\d{4}$)|(^(\([2-9]\\d{2}\)|[2-9]\\d{2})[- .]?\\d{3}[- .]?\\d{4}[xX]\\d{1,4}$)"


text:
Q: Given spectral sequence of algebras $E_r$, why for all page, $H(E_r)\otimes_kH(E_r)\cong H(E_r\otimes_k E_r)$? Given spectral sequence of algebras $E_r$ over field $k$, it is clear that there is induced map for $H(E_r)\otimes H(E_r)\to H(E_r\otimes E_r)$ where $H$ is taken against the homology against differential of the page $r$.
$\textbf{Q:}$ Why for all page $r$, $H(E_r)\otimes_kH(E_r)\cong H(E_r\otimes_k E_r)$?
Ref. McCleary, User's guide to spectral sequences, Chpt 1, Def 1.7

A: In McCleary's setting, $k$ is a field, so this is an application of the Künneth isomorphism.


text:
Q: Drawing 4 Circle one button different sizes and colors I'm trying to do this code to output the same result as the picture
it should start with one black circle then when I click the button, a white circle appear with shift the right and get bigger by 20 pixels and so on
after the 4th circle it should clear the window and start from the beginning and I keep getting only one circle color or two circles together
here's the code
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.WindowConstants;

public class CircleList extends JFrame implements ActionListener {
    JButton addCircle;
    int nCircle = 1;
    int step = 0;
    int shift = 0;
    int d = 0;

    public static void main (String [] args){
        new CircleList();
    }

    private class Circle {
        public int x1;
        public int y1;
        public int w;
        public int h;
        public Color color;
    }

    private List<Circle> whiteList = new ArrayList<>();
    private List<Circle> blackList = new ArrayList<>();

    public CircleList() {
        super("CircleList");
        setSize(500,500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setBackground(Color.gray);
        addCircle = new JButton("Add Circle");
        add(addCircle,BorderLayout.SOUTH);
        addCircle.addActionListener(this);
        repaint();

        setVisible(true);
    }

    public void paint(Graphics g){
        super.paint(g);
        g.fillOval(35, 35, 35, 35);
        if (d==1) {
            for (Circle s: whiteList ) {
                paintWhiteCircle(g, s);
            }
            addWhiteCircle();
        }
        else if (d==2) {
            for (Circle s: blackList ) {
                 paintBlackCircle(g, s);

            }
            addBlackCircle();
        }
    }

    public void paintWhiteCircle(Graphics g, Circle circle) {
        g.setColor(circle.color);
        g.fillOval(circle.x1, circle.y1,  circle.w, circle.h);
    }

    public void paintBlackCircle(Graphics g, Circle circle) {
        g.setColor(circle.color);
        g.fillOval(circle.x1, circle.y1, circle.w, circle.h);
    }

    public void addBlackCircle(){

        Circle circle = new Circle();

        circle.x1 = 40 + shift;
        circle.y1 = 30 ;
        circle.w = 30 + step;
        circle.h = 30 + step;
        circle.color = new Color(0,0,0);
        this.blackList.add(circle);
    }
    public void addWhiteCircle() {

        Circle circle = new Circle();
        circle.x1 = 100 + shift;
        circle.y1 = 30 ;
        circle.w = 50 + step;
        circle.h = 50 + step;
        circle.color =  new Color(255*65536+255*256+255);
        this.whiteList.add(circle);
    }

    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        d = 0;
        if (source == addCircle) {
            for (nCircle = 2; nCircle <= 5; nCircle++) {
                if (nCircle == 2) {
                    d = 1;
                    step+=20;
                    shift += 20;
                    nCircle++;
                }
                else if (nCircle == 3) {
                    d = 2;
                    step+=20;
                    shift += 20;
                }
                else if (nCircle == 4) {
                    d=1;
                    step+=20;
                    shift += 20;
                }
                else if (nCircle == 5)
                    repaint(); // it should clear the window and start with one circle like the beginning
                }

                repaint();
           }
      }
}

the output should be like this

A: I've corrected your example. It works now.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class CircleList extends JPanel implements ActionListener, Runnable {

    private static final int INTERVAL = 20;

    private static final int INITIAL_DIAMETR = 20;

    private int actualXPos;

    private final List<Circle> circleList = new ArrayList<>();

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new CircleList());
    }

    @Override
    public void run() {
        JFrame frm = new JFrame(getClass().getSimpleName());
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.getContentPane().add(this);
        frm.pack();
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }

    public CircleList() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(500, 500));
        setBackground(Color.gray);
        JButton addCircle = new JButton("Add Circle");
        add(addCircle, BorderLayout.SOUTH);
        addCircle.addActionListener(this);
        addCircle();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Circle c : circleList) {
            c.paint(g);
        }
    }

    private void addCircle() {

        Circle circle = new Circle();

        int num = circleList.size();
        circle.x1 = 40 + actualXPos;
        circle.y1 = 30;
        circle.w = 30 + INITIAL_DIAMETR * (num + 1);
        circle.h = 30 + INITIAL_DIAMETR * (num + 1);
        circle.color = num % 2 == 0 ? Color.BLACK : Color.WHITE;
        circleList.add(circle);
        actualXPos += circle.w + INTERVAL;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (circleList.size() == 4) {
            circleList.clear();
            actualXPos = 0;
        }
        addCircle();
        repaint();
    }

    private static class Circle {
        private int x1;

        private int y1;

        private int w;

        private int h;

        private Color color;

        public void paint(Graphics g) {
            g.setColor(color);
            g.fillOval(x1, y1, w, h);
        }
    }
}


text:
Q: Strings taken from user in C are being scrambled I have written the following C code to get in a list of strings from the user. But the stored strings are giving out weird values.
#include <stdio.h>
#include <stdlib.h>

#define MAX_STRING_LENGTH 50

void readInStrings(char* arr[],int n)
{
  int i=0;
  char line[MAX_STRING_LENGTH];

  for(i=0;i<n;i++){
    arr[i]=malloc(MAX_STRING_LENGTH);
    printf("Enter another string : ");
    scanf("%s",&arr[i]);
    //fgets(&arr[i],MAX_STRING_LENGTH,stdin);
  }

  printf("Strings read in correctly.... \n");

  printf("Displaying out all the strings:   \n");
  for(i=0;i<n;i++){
    printf("%s\n",&arr[i]);
  }
}

void testStringInputs()
{
  printf("Enter the number of entries : ");
  int n;
  scanf("%d",&n);

  char* strings[n];
  readInStrings(strings,n);
}

Input Sample:

Enter the number of entries : 3
     Enter another string : Alladin
     Enter another string : Barack Obama
     Enter another string : Strings read in correctly....
     Displaying out all the strings:
     AllaBaraObama
     BaraObama
     Obama

Problems:
1) Why is one string not taken in as input at all?
2) Why are the displayed strings scrambled like that?
The problem is the same if I use gets() or fgets() in place of scanf().

A: arr[i] is already a pointer, you don't need the &

A: Its better to use an array of arrays(two dimensional) instead of array of pointers.
I had a tough time correcting your code. So I changed the code to this
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LENGTH 50
void readInStrings(char (*arr)[MAX_STRING_LENGTH],int n)
{
  int i;
  for(i = 0 ; i< n+1; ++i)
   fgets(*(arr+i),MAX_STRING_LENGTH,stdin);
  printf("Strings read in correctly.... \n");
  printf("Displaying out all the strings:   \n");
  for(i=0;i< n+1;i++){
    printf("%s",arr[i]);
  }
}
int main()
{
  printf("Enter the number of entries : ");
  int n;
  scanf("%d",&n);
  char strings[n][MAX_STRING_LENGTH];
  readInStrings(strings,n);
  return 0;
}

A: Removing the & (as the first answerer noted) in scanf("%s",&arr[i]); and in printf("%s\n",&arr[i]); did the trick for me.  Also, note if you compiled with warnings at their highest, your compiler would have told you right away that the & was misplaced.


text:
Q: Can we choose the Coulomb gauge if we're in a gauge where the gradient of the scalar potential is zero? If we start in the gauge
\begin{align*}
     \textbf{E}=-\nabla\phi-\frac{\partial\textbf{A}}{\partial t},
\end{align*}
\begin{align*}
\textbf{B}=\nabla\times\textbf{A}
\end{align*}
We can express everything in terms of the vector potential by performing the gauge transformation
\begin{align*}
\textbf{A}\rightarrow\textbf{A}'=\textbf{A}+\nabla\chi
\end{align*}
\begin{align*}
\phi\rightarrow\phi'=\phi-\frac{\partial\chi}{\partial t}
\end{align*}
Where $\nabla\phi=\nabla\partial_{t}\chi$, then we have a gauge where both the electric and magnetic fields are expressed solely in terms of vector potential:
\begin{align*}
     \textbf{E}=-\frac{\partial\textbf{A}'}{\partial t},
\end{align*}
\begin{align*}
\textbf{B}=\nabla\times\textbf{A}'
\end{align*}
Often, in textbooks on quantum optics, I see them start with this definition for both fields before choosing the Coulomb gauge. To transform to the Coulomb gauge we require $\nabla\cdot\textbf{A}=0$.  Thus repeating the gauge transformation to enforce this
\begin{align*}
\textbf{A}'\rightarrow\textbf{A}''&=\textbf{A}'+\nabla\chi'\\
&=\textbf{A}+\nabla\chi+\nabla\chi'
\end{align*}
\begin{align*}
\phi'\rightarrow\phi''&=\phi'-\frac{\partial\chi'}{\partial t}\\
&=\phi-\frac{\partial\chi}{\partial t}-\frac{\partial\chi'}{\partial t}
\end{align*}
As long as
\begin{align*}
\nabla^{2}\chi'=-\nabla\cdot\textbf{A}'
\end{align*}
we're in the Coulomb gauge. However is it possible to do this without changing the value of $\nabla\phi$? Intuitively, if
\begin{align*}
\nabla\frac{\partial\chi'}{\partial t}=0
\end{align*}
then it's fine, but that implies that $\nabla^{2}\chi'$ has no time dependence, and therefore that $\nabla\cdot\textbf{A}'$ has no time dependence. Feels like theres a loss of generality in doing this, for instance if the fields are functions of time. So my question is, is it okay to take both these gauges in conjunction for a completely general pair of electric and magnetic fields? And if not, what conditions is this okay in?

A: You're asking whether we can impose both $\phi = 0$ and $\nabla \cdot \mathbf{A} = 0$ simultaneously.  This will not be possible in any situation where $\rho \neq 0$, since if both conditions on the potentials hold we necessarily have
$$
\frac{\rho}{\epsilon_0} = \nabla \cdot \mathbf{E} = - \nabla^2 \phi - \frac{\partial (\nabla \cdot \mathbf{A})}{\partial t} = 0.
$$
However, in the absence of any charge (which is usually the case in optics), it is possible to impose both of these conditions simultaneously.  Specifically, we want to construct a $\chi(\mathbf{r},t)$ so that (given our original $\phi$ and $\mathbf{A}$) we simultaneously have
$$
\nabla^2 \chi = - \nabla \cdot \mathbf{A}, \qquad \frac{\partial \chi}{\partial t} = \phi. \tag{1}
$$
The second condition implies that we can write
$$
\chi(\mathbf{r},t) = \int^t_{t_0} \phi(\mathbf{r},t')\,dt' + f(\mathbf{r})
$$
where $t_0$ is an arbitrary initial time and $f(\mathbf{r})$ is an as-yet-undetermined function of $\mathbf{r}$ only. Assuming that there is no charge present, we then have
\begin{align*}
\nabla^2 \chi(\mathbf{r},t) &= \int^t_{t_0} \nabla^2 \phi(\mathbf{r},t')\,dt' + \nabla^2 f(\mathbf{r})\\ &= - \int^t_{t_0} \left[ \underbrace{\nabla \cdot\mathbf{E}}_{{}=\,0} + \nabla \cdot \frac{\partial \mathbf{A}}{\partial t'} \right]_{\mathbf{r},t'}\,dt'  + \nabla^2 f(\mathbf{r})\\
&= - \nabla\cdot \mathbf{A}(\mathbf{r},t) + \nabla\cdot \mathbf{A}(\mathbf{r},t_0)  + \nabla^2 f(\mathbf{r})
\end{align*}
Choosing $f$ to satisfy
$$
\nabla^2 f(\mathbf{r}) = - \nabla \cdot \mathbf{A} (\mathbf{r},t_0)
$$
completes the proof:  the $\chi(\mathbf{r},t)$ that we have constructed satisfies both of the conditions in (1) simultaneously.


text:
Q: How to put the table of contents in Arial I have install the package for a font similar to Arial
\usepackage{helvet}
\renewcommand{\familydefault}{\sfdefault}

However, in the table of contents the name of my sections don't show in this font but the normal latex font. I have put some subsections in my text, in one of the section, and the title of the subsections in the table of contents appear in the font similar to Arial.

A: I don't see the problem. Compiling this MWE:
\documentclass{report}
\usepackage{helvet}
\renewcommand{\familydefault}{\sfdefault}
\usepackage{lipsum}

\begin{document}
\tableofcontents
\chapter{Introduction}
\section{The social interaction}
\subsection{Homophily}
\lipsum[1]
\subsection{Social distance}
\lipsum[2]
\end{document}

I get:

Notice that my TeXLive is regularly updated.


text:
Q: Positioning of \flalign and arrows between the equation I want to have something as following, but I'm not satisfied with the result:
\documentclass[12pt,parskip]{scrartcl}

\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{geometry}
\usepackage[english]{babel}
\selectlanguage{english}

\begin{document}
$\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;
\;\;$\begin{minipage}[r]{8cm}
\begin{flalign*}
\beta_0
&=
\cos\left(\frac{\Phi}{2}\right)\longrightarrow&
\Phi
&=2\arccos\left(\beta_0\right)
=
118.67^\circ\\
\beta_1
&=
e_1\sin\left(\frac{\Phi}{2}\right)\longrightarrow&
e_1
&=
\frac{\beta_1}{\sin\left(\frac{\Phi}{2}\right)}
=
-0.857716\\
\beta_2
&=
e_2\sin\left(\frac{\Phi}{2}\right)\longrightarrow&
e_2
&=
\frac{\beta_2}{\sin\left(\frac{\Phi}{2}\right)}
=
-0.513132\\
\beta_3
&=
e_3\sin\left(\frac{\Phi}{2}\right)\longrightarrow&
e_3
&=
\frac{\beta_3}{\sin\left(\frac{\Phi}{2}\right)}
=
-0.031914
\end{flalign*}
\end{minipage}\\
\end{document}

Sorry for the bad formatting, I am still a beginner in LaTex.
I would like to connect the equations with arrows, but the arrows should also be aligned. And the equations should be close together... I tricked with a minipage, but I think that is also not the best solution.
Thank you!

A: You could use alignat to align at multiple positions:

\documentclass[12pt,parskip]{scrartcl}
\usepackage{amsmath}% http://ctan.org/pkg/amsmath
\begin{document}
\begin{alignat*}{3}
  \beta_0 &= \cos(\tfrac{\Phi}{2}) && \longrightarrow\ & \Phi &=2\arccos(\beta_0)=118.67^\circ \\
  \beta_1 &= e_1\sin(\tfrac{\Phi}{2}) && \longrightarrow\ & e_1 &=\frac{\beta_1}{\sin(\tfrac{\Phi}{2})}=-0.857716 \\
  \beta_2 &= e_2\sin(\tfrac{\Phi}{2}) && \longrightarrow\ & e_2 &=\frac{\beta_2}{\sin(\tfrac{\Phi}{2})}=-0.513132 \\
  \beta_3 &= e_3\sin(\tfrac{\Phi}{2}) && \longrightarrow\ & e_3 &=\frac{\beta_3}{\sin(\frac{\Phi}{2})}=-0.031914
\end{alignat*}
\end{document}

Consider reading Herbert Voss' mathmode document. Specifically section 25 align environments (p 43 onward).
Alignment using a standard array is also possible. Here's one such suggestion:

\documentclass[12pt,parskip]{scrartcl}
\begin{document}
\[
  \begin{array}{r@{{}={}}l@{\quad\longrightarrow\quad}r@{{}={}}l@{{}={}}l}
    \beta_0 & \cos(\frac{\Phi}{2})    & \Phi & 2\arccos(\beta_0) & 118.67^\circ \\
    \beta_1 & e_1\sin(\frac{\Phi}{2}) & e_1 & \frac{\beta_1}{\sin(\frac{\Phi}{2})} & -0.857716 \\
    \beta_2 & e_2\sin(\frac{\Phi}{2}) & e_2 & \frac{\beta_2}{\sin(\frac{\Phi}{2})} & -0.513132 \\
    \beta_3 & e_3\sin(\frac{\Phi}{2}) & e_3 & \frac{\beta_3}{\sin(\frac{\Phi}{2})} & -0.031914
  \end{array}
\]
\end{document}

The use of @{{}={}} inserts = between the array cells as a "column separator", but also makes sure that the spacing matches that of a regular binary relation.


text:
Q: Side Popup Window I was interested in putting a popup window that appeared on the bottom-left side of the page, kind of like the Cloudflare Flashcard app, but in pure JS and HTML.
It would look somewhat like this, on the bottom left of the page, but it would not interfere with the scrolling or be a modal.
Thanks,
Coding

A: For the window you could use this css:
.popup {
   position: fixed;
   left: 20px;
   bottom: 20px;
}

And to show/hide:
document.querySelector(".popup").style.opacity = 1; // show
document.querySelector(".popup").style.opacity = 0; // hide

Working demo: https://jsfiddle.net/bortao/wq12aju5/


text:
Q: Why data is not inserted into the table(this table contains Foreign Key) from these PDO statements? I am writing a simple android app with database in the server using PHP/MYSQL. Previously my register form's data is inserted into the table. However when I made a relation with another table from this table problem started, data isn't inserted anymore. I used some customized volley library for network connectivity and hence it is not a issue. I couldn't find the exact error but I did come to know there is a problem with the php file. I am using PDO and I have inserted data into the foreign key column using SELECT method.
Table 1 StructureTable 2 Strucutre
  The PHP CODE is given below:
    <?php
require 'init.php';
error_reporting(E_ALL);

$category = $_POST['category'];
$ownername = $_POST['ownername'];
$ownerno = $_POST['ownerno'];
$pricing=$_POST['pricing'];
$description=$_POST['description'];
$whatsappno=$_POST['whatsappno'];
$email=$_POST["email"];

$response = array();
$response["SUCCESS"] = 0;

//get database connection
$databse = new Database();

$con = $databse->getConnection();

try
  {

    $STH = $con->prepare("INSERT INTO Profile (Category_type, Full_name, Personal_no, Pricing, Description, Whatsapp_no, userid) value (?,?,?,?,?,?, (SELECT userid FROM users where email=$email)");
    $STH->bindParam(1,$category);
    $STH->bindParam(2,$ownername);
    $STH->bindParam(3,$ownerno);
    $STH->bindParam(4,$pricing);
    $STH->bindParam(5,$description);
    $STH->bindParam(6, $whatsappno);
    $STH->execute();
     if ($STH->rowCount() > 0) {

    $response["SUCCESS"]  = 1;
    $response["message"]="User profile is complete now !!";
     }else{
         $response["SUCCESS"]=2;
     }

}catch(PDOException $e){

    echo $e->getMessage();
}

echo json_encode($response);

?>

The android code is here
public class ProfileComplete extends AppCompatActivity implements Urls {
    EditText Edit_OwnerName,Edit_OwnerNo,edit_Pricing,Edit_Business_Description,Edit_WhatsappNo;
    TextView Category;
    Button Submit;
    String category;
    String value;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_complete);

        Category=  (TextView)findViewById(R.id.categorytype);
        Edit_OwnerName=(EditText)findViewById(R.id.editOwnername);
        Edit_OwnerNo=(EditText)findViewById(R.id.editOwnerNumber);
        edit_Pricing=(EditText)findViewById(R.id.editPricing);
        Edit_Business_Description=(EditText)findViewById(R.id.Description);
        Edit_WhatsappNo=(EditText)findViewById(R.id.editWhatsappNumber);
        Submit=(Button)findViewById(R.id.submitbutton);

        Spinner spinner = (Spinner) findViewById(R.id.service_cat_spinner);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.service_category_array, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
            {
                // An item was selected. You can retrieve the selected item using
                category=parent.getItemAtPosition(pos).toString();
                Category.setText(category);
            }
            public void onNothingSelected(AdapterView<?> parent)
            {

            }
        });

        Submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RegisterNow();
            }
        });

    }

    String ownername,pricing,businessdescription;
    String ownerno,whatsappno;
    private void setValues(){

        ownername= Edit_OwnerName.getText().toString().trim();
        ownerno=Edit_OwnerNo.getText().toString().trim();
        pricing=edit_Pricing.getText().toString().trim();
        businessdescription= Edit_Business_Description.getText().toString().trim();
        whatsappno=Edit_WhatsappNo.getText().toString().trim();

    }

    private boolean checkEmpty(){
        boolean ok = true;

        if (TextUtils.isEmpty(ownername)) {
            Edit_OwnerName.setError("Please enter your Full Name");
            Edit_OwnerName.requestFocus();
            return false;
        }

        if (TextUtils.isEmpty(ownerno)) {
            Edit_OwnerNo.setError("Please enter your personal number");
            Edit_OwnerNo.requestFocus();
            return false;
        }
        if (TextUtils.isEmpty(pricing)) {
            edit_Pricing.setError("Please enter your price range");
            edit_Pricing.requestFocus();
            return false;
        }

        if (TextUtils.isEmpty(businessdescription)) {
            Edit_Business_Description.setError("Please enter your Business Description");
            Edit_Business_Description.requestFocus();
            return false;
        }

        if (TextUtils.isEmpty(whatsappno)) {
            Edit_WhatsappNo.setError("Enter your whatsapp number");
            Edit_WhatsappNo.requestFocus();
            return false;
        }

        return ok;
    }

    private void RegisterNow(){
        setValues();
        if(checkEmpty()==false){return;}

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            value = extras.getString("email");
        }

        Map<String, String> params = new HashMap<>();
        params.put("category", category);
        params.put("ownername", ownername);
        params.put("ownerno", ownerno);
        params.put("pricing",pricing );
        params.put("description",businessdescription );
        params.put("whatsappno",whatsappno );
        params.put("email",value);
        new Post_to_Server(this, params).getJson(URL_PROFILE, new HTTP_Post_Callback() {
            @Override
            public void onSuccess(String string) {
                try {
                    JSONObject job = new JSONObject(string);
                    int SUCCESS = job.getInt("SUCCESS");
                    if (SUCCESS == 1) {
                        Toast.makeText(ProfileComplete.this, "Profile completed !", Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
                    }
                }

                catch (JSONException ex){
                    Toast.makeText(ProfileComplete.this, "Error", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(VolleyError error) {

            }
        });

    }

}

A: You make those changes
Replace :
(SELECT userid FROM users where email=$email)

to
(SELECT userid FROM users where email=?)

And add this line to end of $STH lines
$STH->bindParam(7, $email);


text:
Q: How to color only for points above and below certain amounts in ggplot2? So I have a reproducible code below, I only want to color the points below and above the dotted black lines and nothing in between. The points in between should be grey or whatever default color without aes(color = x)
color_above <- mean(iris$Sepal.Width) + sd(iris$Sepal.Width)
color_below <- mean(iris$Sepal.Width) - sd(iris$Sepal.Width)

ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point(aes(color=Species, shape=Species)) +
  xlab("Sepal Length") +  ylab("Sepal Width")+
  geom_hline(yintercept = color_above, linetype = "dashed", color = "black") +
  geom_hline(yintercept = color_below, linetype = "dashed", color = "black")

A: One option would be to add a column to your dataframe where using an ifelse assigns an NA to obs. between your threshold lines and map this new column on the color aes. These values will automatically be assigned the na.value of scale_color_discrete. To get rid of the NA entry in the legend I use the breaks argument and set the name for the color legend to Species so that it still gets merged with the shape legend.
library(ggplot2)

color_above <- mean(iris$Sepal.Width) + sd(iris$Sepal.Width)
color_below <- mean(iris$Sepal.Width) - sd(iris$Sepal.Width)

iris$color <- ifelse(iris$Sepal.Width > color_above | iris$Sepal.Width < color_below, as.character(iris$Species), NA_character_)

ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width, color = color)) +
  geom_point(aes(shape=Species)) +
  scale_color_discrete(breaks = unique(iris$Species), name = "Species") +
  xlab("Sepal Length") +
  ylab("Sepal Width")+
  geom_hline(yintercept = color_above, linetype = "dashed", color = "black") +
  geom_hline(yintercept = color_below, linetype = "dashed", color = "black")

A: You could add a new layer:
grey <- iris[iris$Sepal.Width < color_above & iris$Sepal.Width > color_below,]

ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point(aes(color=Species, shape=Species)) +
  xlab("Sepal Length") +  ylab("Sepal Width")+
  geom_hline(yintercept = color_above, linetype = "dashed", color = "black") +
  geom_hline(yintercept = color_below, linetype = "dashed", color = "black") +
  geom_point(data=grey,aes(x = Sepal.Length, y = Sepal.Width),color='grey')

A: We could also use gghighlight package: I think this made for such situations:
p +  gghighlight::gghighlight(Sepal.Width > 3.5 | Sepal.Width < 2.6)


text:
Q: Bootstrap toggle chechkbox is not working when using it with html helper chechkboxfor? I am using @Html.CheckBoxFor and trying to apply bootstrap class on this html helper but when I apply bootstrap class on this helper it become read-only. Can you please help me how I can submit 1 or 0 in db using MVC controller in DB.
@Html.CheckBoxFor(m => m.IsStreamProcessing, new { @class = "custom-control-input" } )
 <label class="custom-control-label" for="customSwitch1">Stream Processing</label>

A: Since you are already using Bootstrap, I would suggest to use Bootstrap Toggle instead, it should works as expected:
@Html.CheckBoxFor(x => item.IsStreamProcessing, new { data_toggle = "toggle",
                            data_onstyle = "success" })

However you need to reference the following:
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>


text:
Q: Json Laravel Model How to write model in Laravel without creating Database and with function getData that returns Json? Something like:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Table extends Model
{
    protected $table = 'table';
    protected $fillable = [
        'atribute1',
        'atribute2',
        'atribute3',
        'atribute4'
    ];
}

But without database.
I would be grateful for help

A: You need to extend Model only if you're using Eloquent.
If you just need to get json data from somewhere, create usual class which gets data from somewhere and returns JSON:
class MyModel
{
    public function getJsonData()
    {
        $jsonData = // get json data from somewhere

        return $jsonData;
    }
}

Register this class in composer.json file, run composer dumpauto and use your class:
$model = new MyModel();
$data = $model->getJsonData();


text:
Q: Clion failed and got clang: error: linker command failed with exit code 1, but it work using clang++ I am new to C++ and now I am studying Class. I am using the book "Guide to Scientific Computing in C++" and using Clion(for Mac) to write my code and test them. Yesterday I encountered a weird problem that I couldn't run my code in Clion but it worked by using clang++ file1 file2 file3.
In Clion I got:
Undefined symbols for architecture x86_64:
  "ComplexNumber::ComplexNumber(double)", referenced from:
      _main in main.cpp.o
  "ComplexNumber::GetRealPart() const", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [2] Error 1
make[2]: *** [CMakeFiles/2.dir/all] Error 2
make[1]: *** [CMakeFiles/2.dir/rule] Error 2
make: *** [2] Error 2

Here is my header file:
#ifndef COMPLEXNUMBERHEADERDEF
#define COMPLEXNUMBERHEADERDEF

#include <iostream>

class ComplexNumber
{
    private:
        double mRealPart;
        double mImaginaryPart;
    public:
        ComplexNumber();
        ComplexNumber(double x, double y);
        double CalculateModulus() const;
        double CalculateArgument() const;
        ComplexNumber CalculatePower(double n) const;
        ComplexNumber& operator=(const ComplexNumber& z);
        ComplexNumber operator-() const;
        ComplexNumber operator+(const ComplexNumber& z) const;
        ComplexNumber operator-(const ComplexNumber& z) const;
        friend std::ostream& operator<<(std::ostream& output,const ComplexNumber& z);

        double GetRealPart() const;
        double GetImaginaryPart() const;
        friend double RealPart(const ComplexNumber& z);
        friend double ImaginaryPart(const ComplexNumber& z);
        ComplexNumber(const ComplexNumber& z);
        ComplexNumber(double real);
        ComplexNumber CalculateConjugate() const;
        void SetConjugate();

        //not mandatory, but useful for exercise 6.1.7
        ComplexNumber operator*(const ComplexNumber& z) const;

};

Because till now, I don't need to use all functions so I only defined functions that I would use, like those:
#include "ComplexNumber.hpp"

ComplexNumber::ComplexNumber()
{
    mRealPart = 0.0;
    mImaginaryPart = 0.0;
}
// 6.1.1
double ComplexNumber::GetRealPart() const
{
    return mRealPart;
}

double ComplexNumber::GetImaginaryPart() const
{
    return mImaginaryPart;
}

// 6.1.2
double RealPart(const ComplexNumber& z)
{
    return z.GetRealPart();
}

double ImaginaryPart(const ComplexNumber& z)
{
    return z.GetImaginaryPart();
}

// 6.1.3
ComplexNumber::ComplexNumber(const ComplexNumber &z)
{
    mRealPart = z.mRealPart;
    mImaginaryPart = z.mImaginaryPart;
}

//6.1.4
ComplexNumber::ComplexNumber(double real)
{
    mRealPart = real;
    mImaginaryPart = 0.0;
}

ComplexNumber::ComplexNumber(double x, double y)
{
    mRealPart = x;
    mImaginaryPart = y;
}

//6.1.5
ComplexNumber ComplexNumber::CalculateConjugate () const
{
    double conjugate_real = mRealPart;
    double conjugate_imaginary = -mImaginaryPart;
    ComplexNumber conjugate(conjugate_real, conjugate_imaginary);
    return conjugate;
}

//6.1.6
void ComplexNumber::SetConjugate()
{
    double minus = -mImaginaryPart;
    mImaginaryPart = minus;
}

// overload operator =
ComplexNumber& ComplexNumber::operator=(const ComplexNumber &z)
{
    mRealPart = z.mRealPart;
    mImaginaryPart = z.mImaginaryPart;
    return *this;
}

// overload operator +
ComplexNumber ComplexNumber::operator+(const ComplexNumber &z) const
{
    ComplexNumber w;
    w.mRealPart = mRealPart + z.mRealPart;
    w.mImaginaryPart = mImaginaryPart + z.mImaginaryPart;
    return w;
}

// overload operator *
ComplexNumber ComplexNumber::operator*(const ComplexNumber &z) const
{
    ComplexNumber w;
    w.mRealPart = (mRealPart * z.mRealPart) - (mImaginaryPart * z.mImaginaryPart);
    w.mImaginaryPart = (mRealPart * z.mImaginaryPart) + (z.mRealPart * mImaginaryPart);
    return w;
}

In my main.cpp, I writed like this to test my Class:
#include "ComplexNumber.hpp"
#include <iostream>

using namespace std;

int main()
{
    ComplexNumber test(1.0);
    cout << test.GetRealPart() << endl;
    return 0;
}

and for cmakelist, I wrote this:
cmake_minimum_required(VERSION 3.19)
project(handin2)

set(CMAKE_CXX_STANDARD 14)

add_executable(1 ComplexNumber.cpp)
add_executable(2 main.cpp)
add_executable(4 test.cpp)

Then I got the linker error, but it did work by using clang++ main.cpp  <.cpp>.
How can I solve this problem?

A: I think you misunderstand CMake. Each add_executable command tells CMake to create a new executable which contains the code from the given files. So you have created three executables, each contains the code of one .cpp file.
The CMake command which is equivalent to your commandline is:
add_executable(executeable_name main.cpp <.cpp>)

Or with the concrete names:
add_executable(executeable_name main.cpp ComplexNumber.cpp)


text:
Q: How can I get Chef to error or at least report a missing variable in an .erb template? If I have a line like the below in an .erb:
        TMP_DIR=$(mktemp -d <%= @temp_dir %>/tmp_dir.XXXXXX)

Is there a way I can get Chef to fail, or at least report, if the @temp_dir variable is undefined?
Ideally I'd like to do this with a single call at the top of the recipe, or at the command line with a config option (I'm using chef-client).
Thanks ahead!

A: You can throw an error and exit Chef with:
Chef::Application.fatal!("Temporary directory is undefined") unless defined? temp_dir

It will not cover empty variable, so you might add temp_dir.empty? check or whatever applies to your case


text:
Q: Android Layout Fragment/Activity Confusion I am making my first android application with the ActionBarSherlock.
The application will always have an action bar consisting of 3 tabs (first tab selected by default).
The app could be extended for use with a tablet.
I have been searching the web, and following the android development guides, however I am finding a few things confusing.
The first tab screen will be a list view with a list of items, onitemselected should send the user to a screen which features more details about that item.
When should I use a fragment? Should each tab be a fragment?
Or, should each tab call a new activity, which consists of fragments?
And, if using fragments, should I place them in different classes, or embed them within an activity??
Appreciate any help, thanks.

A: you should probably read these two links first.
http://android-developers.blogspot.com/2011/09/preparing-for-handsets.html
http://android-developers.blogspot.com/2011/02/android-30-fragments-api.html
If you plan to make an app that work on both phone and tablet. It is a good idea to use a fragment, and then use a shell activity to wrap that fragment.

A: My experience with Fragments is mostly on ViewPager, so I am not entirely sure if it applies here.
In Android, you should use Fragments as much as possible. As a general rule of thumb, imagine you are translating the UI from phones to tablets, elements that can stay together in the same configuration should be a Fragment.
There is a Fragment subclass called ListFragment, so you might want to look into that for your first tab. (ListFragment is for Fragment like ListActivity is for Activity)
There is also a tutorial I found to deal with fragments. Did not really look into it but I hope it helps.
http://android.codeandmagic.org/2011/07/android-tabs-with-fragments/
As for ActionBar / ActionBarSherlock, I have absolutely no experience withit so someone might want to add to that.


text:
Q: Notified property not "updated" in the UI I have a model composed of three classes: A, B and C.
A has an ObservableCollection of B, B has an ObservableCollection of C.
C has a reference (not observable.. I don't think is needed) to its parent (B), and B has a reference to A.
Each attribute of A, B and C notifies its changes.
I then have a Model class which "keeps track" of all the objects allocated. So it has an ObservableCollection of A, of B and of C (the only one that is required is for the As; I keep the lists for B and C only for faster reference).
My UI has a custom control: it has a ViewModel. The view has a list. Its ItemSources is bound to its ViewModel to an observablecollection named sensors. This ObservableCollection is of RowViewModel. Each RowViewModel keeps a reference to a C object.
My application loads the Model (creating A, B, C objects) and then sets the list of the view by calling this method (maybe this is the problem?)
public void setSensors(IList<C> list)
        {
            this.sensors.Clear();
            if (list != null)
            {
                foreach (var row in list)
                    this.sensors.Add(new RowViewModel(row));
            }
        }

The problem is that if I modify a property of my C object, this is not reflected on the UI.
Someone can help me?
Thank you
Francesco
EDIT: (SOLVED)
thanks to your answers I checked my code and changed one thing: instead of binding my UI element to its ViewModel (and the viewModel simply "redirect" the call to the model property), I directly bind the UI to the real property, and it works!!
So... in MVVM I cannot use "shortcuts"??.. or if I use them I should register for notification of the property and "propagates" them?

A: I think your UI isn't updated, because it's binded to RowViewModel object, not to C. So, you should subscribe to PropertyChanged event of C in your RowViewModel's constructor, and notify about those changes through RowViewModel.PropertyChanged. By the way, can you provide an example of binding in your UI?
UPDATED:
An example of "proxying" PropertyChanged event:
public class Model: INotifyPropertyChanged
{
  private string _YourProperty;
  public string YourProperty
  {
    get { return _YourProperty; }
    set
    {
      if (_YourProperty == value) return;
      _YourProperty = value;
      RaisePropertyChanged("YourProperty");
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  private void RaisePropertyChanged(string propertyName)
  {
    if (PropertyChanged != null)
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  }
}

public class ViewModel: INotifyPropertyChanged
{
  private Model _Model;

  public ViewModel(Model model)
  {
    _Model = model;
    _Model.PropertyChanged += OnModelPropertyChanged;
  }

  public string YourProperty
  {
    get { return _Model.YourProperty; }
  }

  private void OnModelPropertyChanged(object sender, PropertyChangedEventArgs e)
  {
    if (e.PropertyName == "YourProperty")
      RaisePropertyChanged("YourProperty");
  }

  public event PropertyChangedEventHandler PropertyChanged;

  private void RaisePropertyChanged(string propertyName)
  {
    if (PropertyChanged != null)
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  }
}

You can read also http://george.softumus.com/2011/10/inotifypropertychanged-and-magic.html - how to avoid using "magic strings" (hardcoded constants) as property names.

A: Rules for Model to update UI Automatically :-

*

*Your Property of type Collection must be of type ObservableCollection

*Your Model should implement INotifyPropertyChanged interface

*Every property of your model, unless it is string or value type, must of type that should implement INotifyPropertyChanged

*If your value Property of type Collection changes, it should fire PropertyChanged for name of property even if it is derived from ObservableCollection


text:
Q: Selecting a row in PHP and putting that data into a form/text fields I have page which has a table and for each row a corresponding button. I am trying to select that specific row and place the data into the text fields of a form but, the query doesn't seem to be working. Any help is much appreciated. Thanks. Here's the code so far:
    <?php
    if (isset($_POST['add'])){
    unset($_POST['add']);

    $id =$_POST['bookID'];
    $q = "SELECT * FROM book WHERE book.bookID = $id";
    $query1 = $db->query($q);
    $data = $query1->fetch(PDO::FETCH_BOTH);

    }
      ?>

    <form>

<form action = "basket.php" method="post">

<input type="text" name="title" value="<?php print($data['Title']); ?            >"/>

    </form>

    <input type="submit" name="add" value="Add to Field" />
    </form>

A: Change about i missed something.
 $db->query($q);
 $db->execute(); // this line is missing you have to execute

 $data = $db->fetch(PDO::FETCH_ASSOC); // no point fetching both when you know the names.


text:
Q: using jquery/ajax/webmethod to update a listbox i have a listbox that i want to update by using jquery/ajax to call a webmethod from a code behind page. the listbox displays all the users who are logged in (they're added to a global list on successful login). i can obviously get the listbox to update using full page refreshes, but this isn't aesthetically pleasing. i'm having two problems.

*

*when i run the app in chrome, and check network activity via dev tools, i can't see the webmethod being called. i have other webmethods that (i can see) are being fired/executed as expected.

*i wrote the script based on a example i found, so i'm not entirely sure (i'm relatively new to these areas) if i'm (a) getting the data from list correctly (i just want the username to be displayed) and (b) appending it to the listbox correctly.
here's the webmethod:
[WebMethod()]
    public static string[] getCurrentList()
    {
        int count = 0;
        for(int i = 0; i < Global.ListUsers.Count(); i++)
            count++;

        string[] results = new string[count];

        for (int i = 0; i < count; i++)
        {
            results[i] = Global.ListUsers[i].Username.ToString();**//edited...**
        }

        return results;
    }

and the script:
$(function updateListbox() {
var lBox = $('select[id$=ListBox1]');
setInterval(function () {
    $.ajax({
        beforeSend: function (req) {
            req.setRequestHeader("Accept", "application/json");
        },
        type: "POST",
        url: "Homepage.aspx/getCurrentList",
        data: "json=" + JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var results = data.d;
            if (results.length > 0) {
                var updatedList = [];
                for (var i in results) {
                    updatedList.push(results[i]);
                }
                $(lBox).append(updatedList.join('\n'));
            }
            else alert("No new items to update...");
        }
    });
}, 5000);

});
all help and suggestions welcome and appreciated

A: You don't want anything in the data field unless you are passing parameters into the function. Just leave that field out, and it should work fine.
I've also never needed to use the beforeSend parameter, but your scenario may be slightly different.

A: Actuallly the problem seems to be AJAX call property data. Please modify data property as follows:
data: "{}",

No need to send any parameters ("json=" + JSON.stringify(data). Your web method does not contain any parameters). Also as per servarevitas answer, beforeSend parameter is not required the ajax call already specified the content type as Json.


text:
Q: How can I validate credentials in gmail? I am trying to work in python to make a function that you give two parameters, checks them on gmail, and returns 1 or 0 if you could login with it. For example
validate("realmail@gmail.com","correctPass") -> This is 1
validate("wrong@gmail.com","incorrectPass") -> This is 0

How can I make this? I can't understand even where to begin.

A: Your question is poorly written, but you can use imaplib to connect to imap.gmail.com and check the credentials, something like:
def gmail_checker(username,password):
        import imaplib
        i=imaplib.IMAP4_SSL('imap.gmail.com')
        try:
                i.login(username,password)
                if "OK Gimap" in i.welcome :
                    return True
        except:
                return

if ( gmail_checker('username','password') ) :
    print("Valid Credentials")
else:
    print("Invalid Credentials")

Forked and modified from original checkemail.py into gmail_check_credentials.py

PS: Make sure less secure apps access is enabled on your gmail account.


text:
Q: How do I detect when the sound has finished playing when using PlaySound in Win32 SDK? I am using the PlaySound function from the Win32 SDK to play a wave sound file. Currently, I have the following line of code:
PlaySound(szFile,NULL,SND_FILENAME );

But now I want to know, how I can detect the time when the wave file finished playing? I want to change a button's text when the wave stops playing.

A: PlaySound is very limited in what it can do.  In a product I work on, we built a media playback library on top of DirectSound to do get over the limitations.  Among many things it did, it involved writing a WAV file parser and threading code to maintain a stream of PCM samples into a DirectSound buffer.  Not for the faint of heart.
You could go this route, but here's some simpler suggestions.

*

*If you know the length of the WAV file you are playing, you can call PlaySound with the SND_ASYNC flag.  Schedule a timer to fire at the estimated time the sound is supposed to finish playing.  If you don't know the length of the WAV file, you could write a parser to read the header of the file.  Compares the sampling rate and format from the "fmt" chunk to the number of bytes in the data chunk to compute the time length of the file.

*OR.... Create a dedicated thread for issuing PlaySound calls (without the SND_ASYNC flag).  When the synchronous PlaySound function returns, do a PostMessage to your UI thread to update the button. If you have overlapping calls to PlaySound, you'll likely need to do some multi-threaded synchronization, but it shouldn't be hard.

A: Unless you specify the SND_ASYNC flag, the PlaySound function is synchronous, meaning that after you call it, it does not return control to your program until after it has finished playing the sound file.
Therefore, once the function returns a value (either TRUE if successful, or FALSE otherwise), you know that the sound has finished playing.
You can simply update the text of your button control in the next line of code, immediately after you call the PlaySound function. If you want to ensure that the button gets updated immediately to reflect your changes, you might need to call the UpdateWindow function, as well.