text:
Q: Bitmasking conversion of CPU ids with Go I have a mask that contains a binary counting of cpu_ids (0xA00000800000 for 3 CPUs) which I want to convert into a string of comma separated cpu_ids: "0,2,24".
I did the following Go implementation (I am a Go starter). Is it the best way to do it? Especially the handling of byte buffers seems to be inefficient!
package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main(){
    cpuMap     := "0xA00000800000"
    cpuIds     = getCpuIds(cpuMap)
    fmt.Println(cpuIds)
}

func getCpuIds(cpuMap string) string {
    // getting the cpu ids
    cpu_ids_i, _ := strconv.ParseInt(cpuMap, 0, 64) // int from string
    cpu_ids_b := strconv.FormatInt(cpu_ids_i, 2)    // binary as string

    var buff bytes.Buffer
    for i, runeValue := range cpu_ids_b {
        // take care! go returns code points and not the string
        if runeValue == '1' {
            //fmt.Println(bitString, i)
            buff.WriteString(fmt.Sprintf("%d", i))
        }
        if (i+1 < len(cpu_ids_b)) && (runeValue == '1') {
            //fmt.Println(bitString)
            buff.WriteString(string(","))
        }

    }
    cpuIds := buff.String()
    // remove last comma
    cpuIds = cpuIds[:len(cpuIds)-1]
    //fmt.Println(cpuIds)
    return cpuIds
}

Returns:

"0,2,24"

A: What you're doing is essentially outputting the indices of the "1"'s in the binary representation from left-to-right, and starting index counting from the left (unusal).
You can achieve the same using bitmasks and bitwise operators, without converting it to a binary string. And I would return a slice of indices instead of its formatted string, easier to work with.
To test if the lowest (rightmost) bit is 1, you can do it like x&0x01 == 1, and to shift a whole number bitwise to the right: x >>= 1. After a shift, the rightmost bit "disappears", and the previously 2nd bit becomes the 1st, so you can test again with the same logic. You may loop until the number is greater than 0 (which means it sill has 1-bits).
See this question for more examples of bitwise operations: Difference between some operators "|", "^", "&", "&^". Golang
Of course if we test the rightmost bit and shift right, we get the bits (indices) in reverse order (compared to what you want), and the indices are counted from right, so we have to correct this before returning the result.
So the solution looks like this:
func getCpuIds(cpuMap string) (r []int) {
    ci, err := strconv.ParseInt(cpuMap, 0, 64)
    if err != nil {
        panic(err)
    }

    count := 0
    for ; ci > 0; count, ci = count+1, ci>>1 {
        if ci&0x01 == 1 {
            r = append(r, count)
        }
    }

    // Indices are from the right, correct it:
    for i, v := range r {
        r[i] = count - v - 1
    }
    // Result is in reverse order:
    for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
        r[i], r[j] = r[j], r[i]
    }

    return
}

Output (try it on the Go Playground):
[0 2 24]

If for some reason you need the result as a comma separated string, this is how you can obtain that:
buf := &bytes.Buffer{}
for i, v := range cpuIds {
    if i > 0 {
        buf.WriteString(",")
    }
    buf.WriteString(strconv.Itoa(v))
}
cpuIdsStr := buf.String()
fmt.Println(cpuIdsStr)

Output (try it on the Go Playground):
0,2,24


text:
Q: Issue With Content Security Policy in Chrome Extension This is from my chrome extension.
"permissions": [
"storage",
"https://app.socialschools.nl/*",
"http://*.google.com/", // Refer to http://goo.gl/CPeqK http://goo.gl/U3Vev
"bookmarks", // http://code.google.com/chrome/extensions/bookmarks.html
"chrome://favicon/",
"clipboardRead", // document.execCommand('paste').
"clipboardWrite", // document.execCommand('copy' OR 'cut')
"contextMenus", //http:///code.google.com/chrome/extensions/contextMenus.html
"cookies", // http://code.google.com/chrome/extensions/cookies.html
// "experimental", // http://code.google.com/chrome/extensions/dev/experimental.html
"fileBrowserHandler", // http://goo.gl/GqbrP
"geolocation", // http://dev.w3.org/geo/api/spec-source.html
"history", // http://code.google.com/chrome/extensions/history.html
"idle", // http://code.google.com/chrome/extensions/idle.html
"management", // http://code.google.com/chrome/extensions/management.html
"notifications", // code.google.com/chrome/extensions/notifications.html
"tabs", // http://code.google.com/chrome/extensions/tabs.html +windows.html
"tts", // http://code.google.com/chrome/extensions/tts.html
"ttsEngine", // http://code.google.com/chrome/extensions/ttsEngine.html
"unlimitedStorage"
],

"content_security_policy":"script-src 'unsafe-eval' https://apps.socialschools.nl/;object-src 'self';connect-src https://app.socialschools.nl/",

I have added the API url (https://app.socialschools.nl) in both script-src, permissions and connect-src. Still, I get this error:
Refused to load the script 'https://app.socialschools.nl/apiv1/public/924/post/?callback=jQuery16200253…109_1398087409246&only_descendants=false&number_of_items=5&_=1398087409299' because it violates the following Content Security Policy directive: "script-src 'unsafe-eval' https://apps.socialschools.nl/".

I can't seem to understand what I am missing here? Can someone please help me out in figuring out this issue.
Thanks in advance.

A: I found out that the API doesn't support HTTPS yet and CSP's script-src requires HTTPS for external sources. Hence there were the issues with Content Security Policy.

redpajama_set_name: RedPajamaStackExchange


text:
Q: java.lang.ClassCastException: org.hibernate.hql.internal.ast.tree.SqlNode cannot be cast to org.hibernate.hql.internal.ast.tree.FromReferenceNode I am trying to execute a select statement in JPA which is throwing me the above error. The code is:
TypedQuery<ListPersonsObj> typedQuery = null;
String query = "";
List<ListPersonsObj> list = null;
if (some condition) {
   query = "SELECT NEW in.healthelife.DGS.dao.ListPersonsObj"
                    + "(c.personId, c.givenName, c.middleName, c.address1, "
                    + "c.address2, c.dateOfBirth, "
                    + "c.phoneNumber, c.email) FROM Patients c";
   typedQuery = EntityManagerUtil.getEntityManager()
                   .createQuery(query, ListPersonsObj.class);
   list = typedQuery.getResultList();
}

The ListPersonsObj class:
public class ListPersonsObj {

   private Long personId;
   private String givenName;
   private String middleName;
   private String address1;
   private String address2;
   private String dateOfBirth;
   private String phoneNumber;
   private String email;

   public ListPersonsObj() {
   }

   public ListPersonsObj(Long personId, String givenName, String middleName,
         String address1, String address2,
         String dateOfBirth, String phoneNumber, String email) {
      this.personId = personId;
      this.givenName = givenName;
      this.middleName = middleName;
      this.address1 = address1;
      this.address2 = address2;
      this.dateOfBirth = dateOfBirth;
      this.phoneNumber = phoneNumber;
      this.email = email;
   }

   public ListPersonsObj(ListPersonsObj list) {
      try {
         BeanUtils.copyProperties(this, list);
      } catch (IllegalAccessException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (InvocationTargetException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
   // .. getters & setters
}

Exception caught

java.lang.ClassCastException:
  org.hibernate.hql.internal.ast.tree.SqlNode cannot be cast to
  org.hibernate.hql.internal.ast.tree.FromReferenceNode

Can anyone please shed some light on this.

A: One reason for this happening is that Hibernate finds a reserved word in a wrong place in JPQL.
For this case

The problem is with package name
...
The prefix is 'in' instead of 'com'. While parsing the query the 'in' is treated as reserved world

For reference, see this
Related issue in Stack Overflow here


text:
Q: Points and lines in an infinite projective plane Let $\mathcal{P}$ be a projective plane (not necessarily desarguesian) and $\mathcal{L}$ its set of lines. Then any $d_1,d_2 \in \mathcal{L}$ are in bijection (i.e. they have the same cardinal). When this cardinal is a finite number $q+1$ ($q$ is called the order of $\mathcal{P}$), then it is well known that both $\mathcal{P}$ and $\mathcal{L}$ have $q^2+q+1$ elements. So one has a non canonical bijective map between $\mathcal{P}$ and $\mathcal{L}$.
Now for my question: Is there a more conceptual way to prove this bijection, especially in the case of planes of infinte order?
All the proofs I'm aware of work by computing the cardinal of each set and finding that they are equal, and obviously this works only for finite orders.

A: For any line $l\in\mathcal{L}$ there are distinct points $p_1,p_2\in\mathcal{P}$ such that $l=\overline{p_1p_2}$, so the map
$$\mathcal{P}^2-\Delta(\mathcal{P})\ \longrightarrow\ \mathcal{L}:\ (p_1,p_2)\ \longmapsto\ \overline{p_1p_2},$$
is surjective, where $\Delta(\mathcal{P})\subset\mathcal{P}^2$ denotes the diagonal. Similarly, for any point $p\in\mathcal{P}$ there exist distinct lines $l_1,l_2\in\mathcal{L}$ such that $p=l_1\cap l_2$, so the map
$$\mathcal{L}^2-\Delta(\mathcal{L})\ \longrightarrow\ \mathcal{P}:\ (l_1,l_2)\ \longmapsto\ l_1\cap l_2,$$
is also surjective, where $\Delta(\mathcal{L})\subset\mathcal{L}$ again denotes the diagonal. This shows that
$$|\mathcal{P}|\times(|\mathcal{P}|-1)\geq|\mathcal{L}|\qquad\text{ and }\qquad|\mathcal{L}|\times(|\mathcal{L}|-1)\geq|\mathcal{P}|$$
Of course when $|\mathcal{P}|$ is infinite then
$$|\mathcal{P}|=|\mathcal{P}|\times(|\mathcal{P}|-1)\qquad\text{ and }\qquad|\mathcal{L}|=|\mathcal{L}|\times(|\mathcal{L}|-1),$$
from which it follows that $|\mathcal{P}|\geq|\mathcal{L}|\geq|\mathcal{P}|$, so the two are equal.


text:
Q: Use linq to convert string to 3D array I saw examples, and have implemented linq to convert a delimited string to a 2D array like so:
using System;
using System.Linq;

namespace AACOBusinessModel.Extensions
{
  [Serializable]
  public class TwoDimensionalStringArray
  {
    public TwoDimensionalStringArray(string data)
    {
      // 1;2;3^^4;5;6
      this.Data = (
          from string line
          in data.Split(new string[] { "^^" }, StringSplitOptions.RemoveEmptyEntries)
          select line.Split(';')
        ).ToArray();
    }

    public TwoDimensionalStringArray() { }

    public readonly string[][] Data = { };

    public override string ToString()
    {
      return string.Join("^^",
        from string[] line
        in Data
        select string.Join(";", line)
      );
    }
  }
}

When I tried to make this work in 3D I ran into an issue:
using System;
using System.Linq;

namespace AACOBusinessModel.Extensions
{
  [Serializable]
  public class ThreeDimensionalStringArray
  {
    public ThreeDimensionalStringArray(string data)
    {
      // 1;2;3^^4;5;6@4;4;4^^7;7;7
      this.Data = (
          from string line2D
          in data.Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries)
          from string line
          in line2D.Split(new string[] { "^^" }, StringSplitOptions.RemoveEmptyEntries)
          select line.Split(';')
        );
    }

    public ThreeDimensionalStringArray() { }

    public readonly string[][][] Data = { };

    public override string ToString()
    {
      return string.Join("@",
        from string[][] line2D
        in Data
        select string.Join("^^",
          from string[] line
          in line2D
          select string.Join(";", line)
        )
      );
    }
  }
}

I understand that with 2D the ending select was a collection of splits converted to an array thus making a 2D array.
But with 3D, the ending select needs to select a collection of 2D arrays. I don't know how to do this.
UPDATE
I came up with this but I'd like the query syntax if it's possible.
public ThreeDimensionalStringArray(string data)
{
  this.Data = (
      from string line2D
      in data.Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries)
      select (
        from string line
        in line2D.Split(new string[] { "^^" }, StringSplitOptions.RemoveEmptyEntries)
        select line.Split(';')
      ).ToArray()
    ).ToArray();
}

A: Not sure how this should be done in query syntax, but here is the method syntax version:
this.Data = data
    .Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries)
    .Select(table => table.Split(new[] { "^^" }, StringSplitOptions.RemoveEmptyEntries)
        .Select(row => row.Split(';'))
        .ToArray())
    .ToArray();

In query synax :
this.Data = (
    from table in data.Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries)
    select
    (
        from row in table.Split(new[] { "^^" }, StringSplitOptions.RemoveEmptyEntries)
        select row.Split(';')
    ).ToArray()
).ToArray();

A: You'll need a nested select clause to return a nested collection.
Making a list and then converting to an array will work for you
this.Data = (
    from string line2D
    in data.Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries)
    select new List<string>(
      from string line
      in line2D.Split(new string[] { "^^" }, StringSplitOptions.RemoveEmptyEntries)
      select line.Split(';')).ToArray());

A: I usually end up with mostly the same common general extensions in .NET projects:
public static string[] splitR(this string str, params string[] separators) {
    return str.Split(separators, StringSplitOptions.RemoveEmptyEntries); }

public static O[] convert<I, O>(this I[] array, Converter<I, O> converter) {
    return Array.ConvertAll(array, converter); }

public static string joinT<T>(this T[] values, string separator) {
    return string.Join(separator, values); }

and then just:
string s = "1;2;3^^4;5;6@4;4;4^^7;7;7";

string[][][] s3 = s.splitR("@").convert(x => x.splitR("^^").convert(y => y.splitR(";")));

string s0 = s3.convert(x => x.convert(y => y.joinT(";")).joinT("^^")).joinT("@");


text:
Q: How to navigate text by skipping entire words using the arrow keys on Windows? In Mac OS X, Bash, and Emacs, I can navigate quickly in long text areas by pressing Alt + <arrow key direction>. Is there a Windows equivalent, perhaps a third party hack?

A: Yes, there is. Just Control+Arrow.


text:
Q: And Or stacking conditions in Javascript (if $1 && ($2 || $3)) For example. there are 3 variables, 1 is a must, 2 and 3 are eithers so 3 can be false as long as 1 and 2 are true, 2 can be false as long as 1 and 3 are true.
if(xmlhttp.responseText.indexOf("type:SearchList~")>=0 && (obj == "hDrop" || obj == "iDrop")){
}

Isn't working for me
Can anyone spot the problem?

A: I built a truth table of your conditions:
1 2 3 R
-------
0 X X 0
1 0 0 0
1 1 X 1
1 X 1 1

This resolves to 1 && (2 || 3), so something else is wrong.

A: No problem with your script that I can spot. This very simple test validates it:
var a = "yes";
var b = "no2";
var c = true;
alert(c && (a == "yes" || b == 'no'));

Check the values of 'obj'. Is it a string?

A: You code is written correctly but it may be there are error in data you compare with so please trace the data and then check that it execute the condition correctly
you can trace using alert(data);


text:
Q: unable to run android connected app engine starter project I am trying to debug the app engine connected android starter app but when I select account through on my phone (android 2.3.6 and deployed the app on appengine following the tutorial) it shows these errors and prompt to force close the application.
Here is the logcat:
06-09 13:00:07.781: D/dalvikvm(14321): GC_CONCURRENT freed 76K, 44% free 3311K/5831K, external 518K/1030K, paused 3ms+3ms
06-09 13:00:08.007: I/global(14321): Loaded time zone names for en_US in 1308ms.
06-09 13:00:08.398: W/dalvikvm(14321): threadid=9: thread exiting with uncaught exception (group=0x40018578)
06-09 13:00:08.429: E/AndroidRuntime(14321): FATAL EXCEPTION: IntentService[my_registered_c2dm_id@gmail.com]
06-09 13:00:08.429: E/AndroidRuntime(14321): java.lang.RuntimeException: The RequestFactory ValidationTool must be run for the com.testtasker.client.MyRequestFactory RequestFactory type
06-09 13:00:08.429: E/AndroidRuntime(14321):    at com.google.web.bindery.requestfactory.vm.impl.Deobfuscator$Builder.load(Deobfuscator.java:59)
06-09 13:00:08.429: E/AndroidRuntime(14321):    at com.google.web.bindery.requestfactory.vm.InProcessRequestFactory.<init>(InProcessRequestFactory.java:80)
06-09 13:00:08.429: E/AndroidRuntime(14321):    at com.google.web.bindery.requestfactory.vm.RequestFactorySource.create(RequestFactorySource.java:43)
06-09 13:00:08.429: E/AndroidRuntime(14321):    at com.testtasker.Util.getRequestFactory(Util.java:158)
06-09 13:00:08.429: E/AndroidRuntime(14321):    at com.testtasker.DeviceRegistrar.getRequest(DeviceRegistrar.java:107)
06-09 13:00:08.429: E/AndroidRuntime(14321):    at com.testtasker.DeviceRegistrar.registerOrUnregister(DeviceRegistrar.java:54)
06-09 13:00:08.429: E/AndroidRuntime(14321):    at com.testtasker.C2DMReceiver.onRegistered(C2DMReceiver.java:46)
06-09 13:00:08.429: E/AndroidRuntime(14321):    at com.google.android.c2dm.C2DMBaseReceiver.handleRegistration(C2DMBaseReceiver.java:191)
06-09 13:00:08.429: E/AndroidRuntime(14321):    at com.google.android.c2dm.C2DMBaseReceiver.onHandleIntent(C2DMBaseReceiver.java:110)
06-09 13:00:08.429: E/AndroidRuntime(14321):    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:59)
06-09 13:00:08.429: E/AndroidRuntime(14321):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-09 13:00:08.429: E/AndroidRuntime(14321):    at android.os.Looper.loop(Looper.java:130)
06-09 13:00:08.429: E/AndroidRuntime(14321):    at android.os.HandlerThread.run(HandlerThread.java:60)

I searched a lot on google and stackoverflow, but unable to resolve the error.
I did not change single character in the starter code then why its not running.
When I try through emulator (as described in tutorials) it gives PHONE_REGISTRATION_ERROR.
Used software:
Eclipse Java EE IDE for Web Developers.
eclipse platform 3.7.2
Version: Indigo Service Release 2
Build id: 20120216-1857
ADT 18.0.0
app engine java sdk1.6.6
gwt sdk 2.4.0
This is the debug stack:
DalvikVM[localhost:8600]
Thread [<1> main] (Running)
Thread [<8> Binder Thread #2] (Running)
Thread [<7> Binder Thread #1] (Running)
Thread [<9> IntentService[my_registered_c2dm_id@gmail.com]] (Suspended (exception RuntimeException))
    C2DMReceiver(C2DMBaseReceiver).onHandleIntent(Intent) line: 124
    IntentService$ServiceHandler.handleMessage(Message) line: 59
    IntentService$ServiceHandler(Handler).dispatchMessage(Message) line: 99
    Looper.loop() line: 130
    HandlerThread.run() line: 60

On clicking thread 9 variables it shows this:
com.testtasker.C2DMReceiver@4052c3e8
Intent { act=com.google.android.c2dm.intent.REGISTRATION cat=[com.testtasker]
cmp=com.testtasker/.C2DMReceiver (has extras) }

Please help me, I have to work app engine but before that this sample should run on real device.

A: I don't know which "tutorial" you are using. With the ADT 18 you won't be able to run the one here http://bradabrams.com/2011/05/google-io-session-overview-android-app-engine-a-developers-dream-combination/
Instead follow the instruction here:
https://developers.google.com/eclipse/docs/appeng_android_install_setup
Also, make sure to register for the c2dm service: https://developers.google.com/android/c2dm/signup, which I think is your actual problem. I believe when testing you must sign in with the same account you used in registration on your phone and the local App Engine server.
Have you customized files, or are you trying to test the c2dm service out of the box?


text:
Q: Apply two different model matrices to two vertices to draw a line I would like to draw a line between two vertices. But, I don't know the two points in advance.
What I'm trying to do to achieve this is upload a vertex buffer with two vertices at (0, 0, 0). Then, when before the draw call, i.e. before glDrawArrays(GL_LINES, 0, 1), try to translate the two vertices with separate model matrices. I'm using a single shader program. To explain it more, it's sort of like I know the fromVertex and toVertex and I want to draw a line them. I want to apply model matrix 1, to translate vertice 1 from (0, 0, 0) to fromVertex, and model matrix 2, to translate vertice 2 from (0, 0, 0) to toVertex.
uniform mat4 projection;
uniform mat4 camera;
uniform mat4 model;

in vec3 vert;
in vec2 vertTexCoord;
in vec3 vertColor;

out vec2 fragTexCoord;
out vec3 fragColor;

void main() {
    // Pass the tex coord straight through to the fragment shader
    fragTexCoord = vertTexCoord;
    fragColor = vertColor;

    // Apply all matrix transformations to vert
    gl_Position = projection * camera * model * vec4(vert, 1);
}

I can't translate this into code, because I can't think of a way to set the model matrix uniform variable in the vertex shader to two different values when drawing a line. I'm trying to think of using a scale and/or rotate operation to achieve this. But, I'm guessing there must be an easier way to do this.

A: I was trying to solve this without using glBufferData in the render loop. Just using that and uploading the vertices solves the problem trivially.


text:
Q: How can I create profiles with spring boot + .yaml? I have spring boot server with 2 property files: application-local.properties and application-test.properties
In each file I have configs for dev machine and for test. Start it like this:
-Dspring.profiles.active=local

But in new spring boot project I use .yaml config file. And I do not understand how can I use profiles with .yaml. I tried read documentation but understood nothing. Can you explain what to do,  step by step?
I need have two files?
application-local.yaml and application-test.yaml
Or I need write all in one application.yaml file? If in one file how can I separate configs? It is my config:
server:
  path: ***
  port: ***

cxf:
  path: ***

spring.datasource:
  type: com.zaxxer.hikari.HikariDataSource
  driver-class-name: oracle.jdbc.OracleDriver
  url: ***
  username: ***
  password: ***
  hikari:
    minimumIdle: 5
    maximumPoolSize: 20
    idleTimeout: 30000
    poolName: SpringBootJPAHikariCP
    maxLifetime: 2000000
    connectionTimeout: 30000
    connection-test-query: SELECT 1 FROM DUAL

spring.jpa:
  show-sql: false
  database-platform: org.hibernate.dialect.Oracle10gDialect
  properties.hibernate.jdbc.batch_size: 30
  properties.hibernate.cache.use_second_level_cache: false
  hibernate:
    ddl-auto: validate

spring.cache:
  ehcache:
    config: classpath:ehcache.xml

#app configs
my:
  messages-max-count: 5
  messages-delay: 100
  schedulers-charge-delay: 100
  client:
    first-server-address: ***
    second-server-address: ***
    last-server-address: ***
  enabled-client: FirstClient

I want create test profile and change database url (or change to postgreSql), change maximumPoolSize property

A: Yes,  you can create multiple profiles even with single file
Profile are separated with 3 DASH (---)
logging:
  level:
    .: error
    org.springframework: ERROR

spring:
  profiles:
    active: "dev"
  main:
    banner-mode: "off"

server:
  port: 8085

---

spring:
  profiles: dev

---

spring:
  profiles: prod

A: *

*Create application.yaml and define all default properties there.

*Create application-local.yaml and override properties needed for the local profile.

*Create application-test.yaml and override properties needed for the test profile.

*Set spring.profiles.active by either passing it as a system property (-D for java) or defining it within application.yaml.

When you are running an app with a {PROFILE}, Spring will parse application-{PROFILE}.yaml after application.yaml.


text:
Q: Print list with flush I want to print a list, perform some operations and print again, flushing the list.
a=[1,2,3,4,5,6,7,8,9]

for i in range (0, 10):
    a.append(i)
    a=a[-5:]
    print(*a, sep='\n')

I expect the list to be cleared from the screen and the new one takes its place, buy I don't know how to to that.

A: Try out the colorama package to enable ANSI escape sequences:
import colorama
import time
colorama.init()

a=[1,2,3,4,5,6,7,8,9]

for i in range (0, 10):
    a.append(i)
    a=a[-5:]
    print(*a, end='\r')
    time.sleep(0.5)

The '\r' character places the cursor back at the beginning of the line, so you can "print over it".

A: If I get the point, try this:
import sys
import time

a=[1,2,3,4,5,6,7,8,9]
for i in range (0, 10):
  a.append(i)
  a=a[-5:]
  print(chr(27) + "[2J")
  print(*a, sep='\n', flush=True)
  time.sleep(0.5)


text:
Q: Nancy Self Hosting - Service Unavailable - Win7 I've scrapped what I was working with and went to the simplest of code:
class Program
{
    static void Main(string[] args)
    {
        var nancyHost = new Nancy.Hosting.Self.NancyHost(new   Uri("http://localhost:8080"));
        nancyHost.Start();

        Console.ReadLine();
        nancyHost.Stop();
    }
}
public class MainModule : Nancy.NancyModule
{
    public MainModule()
    {
        Get["/"] = x =>
        {
            return "Hello world!";
        };
    }
}

When I browse to
   http://localhost:8080

I get:

Service Unavailable
HTTP Error 503. The service is unavailable.

I've tried several solutions.  Including several variations on: Remote access to a Nancy Self Host
Any ideas?

A: Make sure you are running Visual Studio as Administrator and that 8080 is not used by something else at the same time. Have a look at the self-hosting demo which sets up a couple of different URIs for a self-hosted application https://github.com/NancyFx/Nancy/blob/master/src/Nancy.Demo.Hosting.Self/Program.cs#L12

A: I don't how much value this answer will have, but I did encounter this same 503 error when I started Nancy with this combination of settings:
_nancyHost = new NancyHost(new HostConfiguration {
        RewriteLocalhost = false
    },
    new Uri(string.Format("http://localhost:{0}", port)));

The error was encountered when using a local browser accessing http://localhost:3684/ to Nancy running in a Windows Service as Local System
The prior revision with RewriteLocalHost on default setting of true had been working. This was one of the things I was trying while attempting to diagnose my question here: How do I remotely access self-hosted Nancy service?


text:
Q: JSF 2 selectOneRadio Dependend Validation i have a pretty simple jsf page with three selectOneRadio components. two of them within a panelGroup.
<t:selectOneRadio id="first" value="#{myBean.first}" required="true" requiredMessage="Please make a choice!">
<f:selectItem itemLabel="yeah" itemValue="true"/>
<f:selectItem itemLabel="no!" itemValue="false"/>
<f:ajax render="myform" execute="myform" />
</t:selectOneRadio>

<h:panelGroup rendered="#{not myBean.first}">
  <t:selectOneRadio id="second" value="#{myBean.second}" required="true" requiredMessage="Please make a choice!">
  <f:selectItem itemLabel="yeah" itemValue="true"/>
  <f:selectItem itemLabel="no!" itemValue="false"/>
  <f:ajax render="myform" execute="myform" />
  </t:selectOneRadio>

  <t:selectOneRadio id="third" value="#{myBean.third}" required="true" requiredMessage="Please make a choice!">
  <f:selectItem itemLabel="yeah" itemValue="true"/>
  <f:selectItem itemLabel="no!" itemValue="false"/>
  <f:ajax render="myform" execute="myform" />
  </t:selectOneRadio>
</h:panelGroup>

My problem is, that dependent on value of the first button, the panel should be shown or not. if it shows up, the two other radio selections shall be validated.
the current behaviour is that if i choose someting in  the first selectOneRadio, the required messages for the other two ones are displayed.
does anyone how to avoid that and validate two and three dependent on value one?
kind regards and thanks in advance :-)

A: found the answer...sometimes i am blind :-)
setting the execute attribute to the current radio buttons solved it:
<t:selectOneRadio id="first" value="#{myBean.first}" required="true" requiredMessage="Please make a choice!">
<f:selectItem itemLabel="yeah" itemValue="true"/>
<f:selectItem itemLabel="no!" itemValue="false"/>

<f:ajax render="myform" execute="first" />

</t:selectOneRadio>


text:
Q: decimal format string is null in controller mvc razor c# I have TextboxFor in partial view,I want to display decimal format example( 3,108,000.00). is work for display but want i call controller by Ajax value is be null. thank for help.
@Html.TextBoxFor(x => x.List_TRNQuotationLeasing.CashBook, new { @class = "numeric form-control right", @Value = Model.List_TRNQuotationLeasing.CashBook != null ? Model.List_TRNQuotationLeasing.CashBook.Value.ToString("#,##0.00") : "" })

A: You cannot post a value like 900,000.00 directly to decimal, if you're trying to do that. You need to reformat the number and get rid of the , before sending, use string in the ViewModel and apply convertion after posting, or use a special ASP.NET MVC Model Binder to do that conversion during the Request.
If you want to go with Option 1 for example, you could do this in JavaScript just before sending (jQuery):
 // ...before send...
 // e.g. apply to all fields marked with "numeric"
 $("input.numeric").each(function() {
    numericWithOutComma = $(this).val().replace(",", "");

    // override text... yes it will lose the format. You could enhance that later
    $(this).val(numericWithOutComma);
 });

 // Execute Ajax send...

Also, there is this interesting discussion about that if you want to go with Option 3, for example.


text:
Q: How do I write a function below the main? I have a teacher/professor that only like writing functions below the main and not above it. How would I rewrite this in order to write the functions below main. Always been taught how to do it below, would I just declare it beforehand? How would it look like if so?
#include <iostream>
using namespace std;
/* Output
Enter 4 test score numbers
80 90 80 90
Average is 86.6667

Enter 4 test score numbers
70 80 -60 90
Bad Data

*/
bool input(double& test1, double& test2, double& test3, double& test4)
{
cout << "Enter 4 test score numbers" << endl;
cin >> test1;
cin >> test2;
cin >> test3;
cin >> test4;

if(test1 < 0 || test2 < 0 || test3 < 0 || test4 < 0)
return false;
else
return true;
}

double average(double test1, double test2, double test3, double test4, bool data)
{
if(data == false)
{
cout << "Bad Data" << endl;
return -1;
}
double low = test1;
if(test2 < low)
{
low = test2;
}
if(test3 < low)
{
low = test3;
}
if(test4 < low)
{
low = test4;
}
return (test1+test2+test3+test4-low)/3;
}

int main()
{
double test1, test2, test3, test4;
bool data;
data = input(test1, test2, test3, test4);
double avg = average(test1, test2, test3, test4, data);
if(avg != -1)
{
cout << "Average is " << avg << endl;
}
return 0;
}

A: Just put the declarations before main:
bool input(double& test1, double& test2, double& test3, double& test4);
double average(double test1, double test2, double test3, double test4, bool data);

and the definitions after main:
bool input(double& test1, double& test2, double& test3, double& test4)
{
    ....
}

double average(double test1, double test2, double test3, double test4, bool data)
{
    ....
}

A: All you need to do is provide a function declaration above main.
bool input(double test1, double test2, double test3, double test4);
And then you can implement the function below main.

A: You could declare function above main and implementation of function after the main function.

A: BEFORE (only function implementation)
#include <iostream>
using namespace std;

int sum(int a, int b){
    return a + b;
}

int main(){
    cout<<sum(3, 5);
}

AFTER (function declaration over main, function implementation under main)
#include <iostream>
using namespace std;

int sum(int a, int b);

int main(){
    cout<<sum(3, 5);
}

int sum(int a, int b){
    return a + b;
}

A: Just cut and paste your main() function on the top. And declare your functions using function prototypes.
#include <iostream>
using namespace std;
/* Output
Enter 4 test score numbers
80 90 80 90
Average is 86.6667

Enter 4 test score numbers
70 80 -60 90
Bad Data

*/

bool input(double& test1, double& test2, double& test3, double& test4);
double average(double test1, double test2, double test3, double test4, bool data);

int main()
{
double test1, test2, test3, test4;
bool data;
data = input(test1, test2, test3, test4);
double avg = average(test1, test2, test3, test4, data);
if(avg != -1)
{
cout << "Average is " << avg << endl;
}
return 0;
}

bool input(double& test1, double& test2, double& test3, double& test4)
{
cout << "Enter 4 test score numbers" << endl;
cin >> test1;
cin >> test2;
cin >> test3;
cin >> test4;

if(test1 < 0 || test2 < 0 || test3 < 0 || test4 < 0)
return false;
else
return true;
}

double average(double test1, double test2, double test3, double test4, bool data)
{
if(data == false)
{
cout << "Bad Data" << endl;
return -1;
}
double low = test1;
if(test2 < low)
{
low = test2;
}
if(test3 < low)
{
low = test3;
}
if(test4 < low)
{
low = test4;
}
return (test1+test2+test3+test4-low)/3;
}

A: You need to declare prototypes or function declarations above main(). A declaration or prototype specifies a unique name which includes information about its type. You also do not have to have an argument name in your prototype or function declaration. However, you do have to define it in the definition. Then you can put your functions below main()
For example, (using your example):
#include <iostream>
using namespace std;
double average(double, double, double, double, bool); //Prototype or function
bool input(double&, double&, double&, double&); //Prototype or function declaration.
int main()
{
  //code.
}

double average(double test1, double test2, double test3, double test4, bool data)
{
 //code.
}
bool input(double& test1, double& test2, double& test3, double& test4)
{
 //code.
}

A: You would create a header file with the function headers, include it in the top of the document, and then you can put it in from there.
#include <iostream>
#include "myheaders.h"
using namespace std;

int main()
{
double test1, test2, test3, test4;
bool data;
data = input(test1, test2, test3, test4);
double avg = average(test1, test2, test3, test4, data);
if(avg != -1)
{
cout << "Average is " << avg << endl;
}
return 0;
}

bool input(double& test1, double& test2, double& test3, double& test4)
{
cout << "Enter 4 test score numbers" << endl;
cin >> test1;
cin >> test2;
cin >> test3;
cin >> test4;

if(test1 < 0 || test2 < 0 || test3 < 0 || test4 < 0)
return false;
else
return true;
}

double average(double test1, double test2, double test3, double test4, bool data)
{
if(data == false)
{
cout << "Bad Data" << endl;
return -1;
}
double low = test1;
if(test2 < low)
{
low = test2;
}
if(test3 < low)
{
low = test3;
}
if(test4 < low)
{
low = test4;
}
return (test1+test2+test3+test4-low)/3;
}

In myheaders.h
bool input(double& test1, double& test2, double& test3, double& test4);
double average(double test1, double test2, double test3, double test4, bool data);

To be honest, it doesn't make sense to have those functions in the main. They should be separated.
You could just declare the function above the main as well, and technically you aren't having the function implemented above main, but that's kind of silly to do.
https://www.learncpp.com/cpp-tutorial/header-files/


text:
Q: StringBuilder and Radiobuttonlist I am using stringbuilder to create a radiobuttonlist dynamically for a survey I am working on. The code validates fine but will not render in HTML.
Is this because I am not supposed to use stringbuilder to generate asp web controls?
code here:
sb.Append(string.Format("<asp:RadioButtonList ID='" + qnumber + "' runat='server' RepeatDirection='Horizontal' RepeatLayout='flow' CssClass='answers'>"));
sb.Append(string.Format("<asp:ListItem Text='Strongly Agree' Value='1'></asp:ListItem>"));
sb.Append(string.Format("<asp:ListItem Text='Agree' Value = '2' ></ asp:ListItem>"));
sb.Append(string.Format("<asp:ListItem Text='Disagree' Value='3'></asp:ListItem>"));
sb.Append(string.Format("<asp:ListItem Text='Strongly Disagree' Value='4'></asp:ListItem>"));
sb.Append(string.Format("<asp:ListItem Text='Not Applicable' Value='5'></asp:ListItem></asp:RadioButtonList><asp:RequiredFieldValidator runat='server' ID='" + qnumber + "v"+ "' ControlToValidate='ID='" + qnumber + "' ErrorMessage='please answer the question' CssClass='warning' />"));

A: Problem is, you can't force your code behind to generate asp.Net code, those must be placed inside your aspx page. Asp.Net transform asp tags in html tags and listen to them on code behind, that's why you can't send asp tags to your view, the view is already processed by asp.net when code behind code is running.
Your best bet is to send pure HTML content to your page and use another way to read its contents. If you're in a hurry, I suggest you use Javascript to fill a HiddenField just before postbacking your form.
Here's an example on how your StringBuilder should look like:
sb.Append(string.Format("<input type="radio" name="answer" value="1" />Strongly Agree"));
sb.Append(string.Format("<input type="radio" name="answer" value="2" />Agree"));
sb.Append(string.Format("<input type="radio" name="answer" value="3" />Disagree"));
sb.Append(string.Format("<input type="radio" name="answer" value="4" />Strongly Disagree"));
sb.Append(string.Format("<input type="radio" name="answer" value="5" />Not Applicable"));

Then you just use below code on javascript to set the value to a HiddenField:
$('#<%= youHiddenFieldId.ClientID %>').val($("input:radio[name='answer']:checked").val());

Now you just need to call youHiddenFieldId.Value on code behind to get the value of the selected checkbox.


text:
Q: Facebook App not posting to timeline properly We are coding a facebook app that creates a post on people's Walls when they enter the competition. We're having a problem with the contents of the post that is being created.
The status message and link are functioning as intended however the picture, name, caption and description are instead being grabbed from the page that the post is linking to.
This is the code we're using to post to people's Walls:
$facebook->api("/me/feed", "post", array(
    message => "I've just chosen my kangaroo to win a ticket to the Caravan, Camping and Off-Road Sale at the Adelaide Showgrounds (August 2-5). Be quick, there are only 1000 tickets up for grabs! Just click the link below.",
  picture => "http://gmbo.com.au/hosted/cca/pak/app-icon.png",
   link => "http://www.facebook.com/pages/WEIM-Sandbox-2/241942125896015?sk=app_416990981685156",
    name => "CLICK HERE",
    caption => "If you love caravans, camping or outdoor recreation - you'll love this Show.",
    description => "If you love caravans, camping or outdoor recreation - you'll love this Show."

Any help would be hugely appreciated, this Facebook API stuff can be pretty frustrating.
Thanks

A: You are missing ' ' for each of the properties. Also, you forgot to close brackets.
$facebook->api("/me/feed", "post", array(
    'message' => "I've just chosen my kangaroo to win a ticket to the Caravan, Camping and Off-Road Sale at the Adelaide Showgrounds (August 2-5). Be quick, there are only 1000 tickets up for grabs! Just click the link below.",
    'picture' => "http://gmbo.com.au/hosted/cca/pak/app-icon.png",
    'link' => "http://www.facebook.com/pages/WEIM-Sandbox-2/241942125896015?sk=app_416990981685156",
    'name' => "CLICK HERE",
    'caption' => "If you love caravans, camping or outdoor recreation - you'll love this Show.",
    'description' => "If you love caravans, camping or outdoor recreation - you'll love this Show."
));

If it still doesn't work, check that you have allowed publish_stream permission in your fbmain.php.
You can refer to PHP SDK and JavaScript SDK Feed Dialog for more examples.

A: There was nothing wrong with this code. You don't need the quotes.
This was a Facebook API bug. We tried what you mentioned, but there is a known bug about this. What we were trying to do is too ambitious for poor little Facebook to wrap it's tiny brain around.


text:
Q: Generic Collections to be used as a parameter of invoke command Edited : got it worked.
Generic Collections to be used as a parameter of invoke command
--
Removed the brackets from ... SetListDelegate(SetList) in the invoke command of mine

A: You need to name your method parameter. And you are missing the generic argument.
Something like this will do
public delegate void SetListDelegate<T>(List<T> l );

public void SetList<T> (List<T> l)
{
    if ( lstW.InvokeRequired)
        lstW.Invoke(new SetListDelegate<T>(SetList<T>), l);
    else
        lstW.Items.AddRange(l);
}

Edit:
If this is contained in a class with the generic argument <T> you don't need it on the delegate or the method.


text:
Q: AsyncTask java.lang.RuntimeException: An error occured while executing doInBackground() Помогите разобраться с ошибкой. При нажатии на кнопу должны отправляться данные на сервер.
buttonBy1 = (Button) view.findViewById(R.id.buttonBy1);
    buttonBy1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String str;
            try {
                File file = new File(context.getFilesDir(), MainActivity.FILENAME);
                if (!file.exists()) {
                    file.createNewFile();
                    System.out.println( "Fail sozdan");
                }
                BufferedReader br = new BufferedReader(new FileReader(file));
                str = br.readLine();
                if (str == null) {
                    Intent intent = new Intent(view.getContext(), Telefon.class);
                    startActivity(intent);
                }
                else  {
                    MyTask mt = new MyTask();
                    mt.execute(str);
                }
            }
            catch (FileNotFoundException e){
                System.out.println("FAIL NE SOZDAN");
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

class MyTask extends AsyncTask<String, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        // указываем адрес вашего сервера и путь принимающего скрипта
        HttpPost httppost = new HttpPost("http://aqualine09.ru/send.php");
        try {
            List nameValuePairs = new ArrayList(2);
            for (String x : params) {
                nameValuePairs.add(new BasicNameValuePair("name", x));
            }
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httpclient.execute(httppost); // отправка на сервер

            // отправляемое сообщение

        } catch (ClientProtocolException e) {
            // ...
        } catch (IOException e) {
            // ...
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
    }
}

Вылетает ошибка:
FATAL EXCEPTION: AsyncTask #1
        Process: com.ferisov.aqualive, PID: 9256
        java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:304)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)
                   Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:451)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
        at java.net.InetAddress.getAllByName(InetAddress.java:215)
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:142)
        at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
        at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
       at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365)
       at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
       at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
       at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
       at com.ferisov.aqualive.FirstFragment$MyTask.doInBackground(FirstFragment.java:170)
       at com.ferisov.aqualive.FirstFragment$MyTask.doInBackground(FirstFragment.java:152)
                      at android.os.AsyncTask$2.call(AsyncTask.java:292)

Что ему не нравится?

A: Добавьте в манифест:
<manifest xlmns:android...>
 ...
 <uses-permission android:name="android.permission.INTERNET" />
 <application ...
</manifest>


text:
Q: What is the best way to implement multiple timers in kernel module I am trying to build e kernel module which will be used by userspace program to setup timers. I am implementing it as a character device. What is the best way to implement multiple timers in the kernel module?
Currently I have one 'timer_list*', sat 'timer'. I am assigning memory from the heap everytime I get a new request for timer and then use setup_timer() and mod_timer() to set the timer everytime I assign memory. But I am only using one pointer to the timer_list struct. But my concern here is that how to free the memory assigned to 'timer' once the callback function is called because the current value of 'timer' might not be pointing to the structure whose callback function is called.
So, I thought about passing the address of the structure in as an argument to the callback function and then call kfree() on that address.
struct timer_list *timer;
timer = kmalloc(sizeof(struct timer_list), GFP_KERNEL);
setup_timer(timer, my_callback, (unsigend long)timer);

My callback function looks like this:
void my_callback (unsigned long data)
{
      struct timer_list *timer = (struct timer_list*)data;
      printk("%d\n", timer->data);
      kfree(timer);
}

In this case I am getting a segmentation fault when I try to print timer->data saying there is no page for that particular address. So, is the the memoery allocated to timer_list freed when the callback function is called. In that case I dont need to worry about freeing the memory.
Also, is there a better way to implement this thing. Also, to keep a track of all the timers (like checking like existence of a timer), is it adivasable to maintain something like a linked-list or there is some kernel function to check this?

A: void my_callback (unsigned long data)
{
    struct timer_list *timer = (struct timer_list*)data;
    printk("%d\n", timer->data);
    kfree(timer);
}

I'm not a kernel hacker so I really can't suggest how to do it right, yet this generally looks rather like:

*

*a rather suspicious type conversion from an integral type unsigned long to a pointer struct timer_list *). I assume data is usually something small, so you are trying to access pages around 0. Or it can be anything mostly random and hence most likely unmapped.

*resource management gone wrong - I would also expect timer needing some sort of allocation before you can free it at the end. Even if the assignment and subsequent printk() went well (which I doubt), freeing random, previously not allocated memory should lead to crash.


text:
Q: Sankey Diagram Jupyter Notebook I am doing some twitter analysis and would like to use the pySankey package to visualise my results. But when I try to use this package, I get the following error that originates from the package itself. Does anyone know how to fix this? I am using python 3
UnboundLocalError                         Traceback (most recent call last)
 in ()
      6
      7 sankey.sankey(df['State'], df['Location'], aspect=20, colorDict=colorDict,
----> 8               fontsize=1, figure_name="Twitter Sentiment-Topic Per State"
      9              )
/anaconda3/lib/python3.6/site-packages/pySankey/sankey.py in sankey(left, right, leftWeight, rightWeight, colorDict, leftLabels, rightLabels, aspect, rightColor, fontsize, figure_name, closePlot)
UnboundLocalError: local variable 'topEdge' referenced before assignment

A: You may want to give a try to https://github.com/ricklupton/ipysankeywidget
p.s. it provides interactive jupyter functionality, etc.
https://nbviewer.jupyter.org/github/ricklupton/ipysankeywidget/blob/master/examples/More%20examples.ipynb#Styling
Another nice sankey python lib is: https://github.com/ricklupton/floweaver


text:
Q: How to tweak the MongoDB query to get the output in descending order I am working with a OSM file converted to JSON.In this query, I am trying to  fetch the count of all the amenities in the .json file.I need to know how to get the output reverse.
Query :-
db.char.aggregate([{"$match":{"amenity":{"$exists":1}}}, {"$group":{"_id":"$amenity",
"count":{"$sum":1}}}, {"$sort":{"count":1}}, {"$limit":100}])

Current Output:-
{ "_id" : "bar", "count" : 1 }
{ "_id" : "fitness_center", "count" : 1 }
{ "_id" : "fountain", "count" : 1 }
{ "_id" : "studio", "count" : 1 }
{ "_id" : "telephone", "count" : 1 }
{ "_id" : "nightclub", "count" : 1 }
{ "_id" : "shelter", "count" : 1 }
{ "_id" : "courthouse", "count" : 1 }
{ "_id" : "kindergarten", "count" : 1 }
{ "_id" : "doctors", "count" : 1 }
{ "_id" : "laboratory", "count" : 1 }
{ "_id" : "toilets", "count" : 2 }
{ "_id" : "community_centre", "count" : 2 }
{ "_id" : "embassy", "count" : 2 }
{ "_id" : "fire_station", "count" : 2 }
{ "_id" : "townhall", "count" : 2 }
{ "_id" : "prison", "count" : 2 }
{ "_id" : "clinic", "count" : 2 }
{ "_id" : "pub", "count" : 3 }
{ "_id" : "grave_yard", "count" : 3 }

A: {"$sort":{"count":-1}}
in the sort part should do you!


text:
Q: ld: symbol(s) not found for architecture x86_64 when including header file I am writing the following code to print the underlying Operative System. It's incomplete and might be wrong (appreciate advices for the wrong, no need for complete as it's for learning purposes).
platform.c
#include <stdio.h>

void platform(int a)
{
    #if __APPLE__
        printf("recognized apple\n");
    #elif __LINUX__
        printf("linux\n");
    #else
        printf("unknown\n");
    #endif

    printf("%i\n",a);
}

If I add main() to platform.c and compile it, it works fine. However, as I am experimenting for learning purposes, including a header file:
platform.h
#ifndef PLATFORM_H_   /* Include guard */
#define PLATFORM_H_

void platform(int);

#endif // PLATFORM_H_

and lastly including the header in a new file:
Try.c
#include "./platform.h"

int main()
{
    platform(4);
}

I compile it as:
gcc try.c and I get:
Undefined symbols for architecture x86_64:
  "_platform", referenced from:
      _main in lala-10eeb5.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Please, go easy on me and thank you for your help!

A: You have to link platform.c to Try.c
Try using this command:
gcc try.c platform.c

You only included the declaration, not the implementation. This leads to a successful compiling, but linking will fail, as there is no implementation for platform.


text:
Q: How to mock UnitOfWork when using transactions (NUnit and NSubstitute) I have created a Web API using ASP.NET Core 3.1 and EF Core 5.0. Data is stored in a MSSQL database.
I have implemented UnitOfWork and repository pattern.
The UnitOfWork class has a method used to create transactions and it look like this:
//UnitOfWork
public async Task ExecuteTransaction(Func<Task> insideTransactionFunction)
{
  var transaction = await _context.Database.BeginTransactionAsync();

  try
  {
    await insideTransactionFunction();
    await transaction.CommitAsync();
  }
  catch (Exception)
  {
    await transaction.RollbackAsync();
    throw;
  }
}

Im trying to write tests, for service classses that uses the UnitOfWork class to modify the data in the SQL database. Fx when adding a user using the UserService:
//UserService
public async Task<User> AddUserAsync(User user)
{
   await _unitOfWork.ExecuteTransaction(async () =>
   {
      //Add user locally to generate the local id
      _unitOfWork.UserRepository.Add(user);
      await _unitOfWork.SaveChangesAsync();

      //...Some logic that uses the generated user id...

      if(string.IsNullOrWhiteSpace(email.User) == false)
      {
        //Inviting the user returns the generated Azure User id
        user.AzureUserId = _azureService.InviteUser(user.Email);
        await _unitOfWork.SaveChangesAsync();
      }
   }

   return user;
}

A test for the above method could look like this:
//UserServiceTests
public async Task AddUserAsync_UserQualifiesForAzureInvite_AzureUserIdSetOnCreatedUser()
{
  //Arrange
  var unitOfWork = Substitute.For<IUnitOfWork>();
  var azureService = Substitute.For<IAzureService>();
  var uut = new UserService(unitOfWork, azureService);

  var newUser = new User { ... some setup ... };
  var azureUserId = Guid.NewGuid();
  azureService.InviteUser(null).ReturnsForAnyArgs(Task.FromResult(azureUserId));

  //Act
  var createdUser = await _uut.AddUserAsync(newUser); //Returns right away

  //Assert
  Assert.That(createdUser.AzureUserId, Is.EqualTo(azureUserId));
}

The problem is that the transaction created with UnitOfWork is ignored and the user is returned straight away.
public async Task<User> AddUserAsync(User user)
{
   //Skipped from here...
   await _unitOfWork.ExecuteTransaction(async () =>
   {
      //
   }
   //...To here

   return user;
}

So my question is: How can i mock the UnitOfWork class and still be able to test code wrapped in the the transaction?

A: My architecture was fundamentally flawed. Check out the comments and links made by Panagiotis Kanavos.
The solution was to get rid of UnitOfWork and the repositories and it seems testable now.


text:
Q: How to toggle sidenav component from header component using a button Hello I am using angular 8 and I want to toggle sidenav component on mobile view. So on mobile media query I am using this CSS to hide the sidenav
@media screen and (max-width: 600px)
.sidenav {
    visibility: hidden;
    clear: both;
    float: left;
    margin: 10px auto 5px 20px;
    width: 28%;
    display: none;
}

So on mobile view I have a hamburger icon on header component . So on clicking how can I toggle sidenav component ?
Header HTML:-

  <fa-icon class="hamburger" [icon]="faBars"></fa-icon>

Header Component:-
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
  searchText: string;

  faBars = faBars;

  constructor(private route: Router) { }

  ngOnInit() {
  }
}

Sidennav HTML :-

                <fa-icon [icon]="faTh"></fa-icon>

                Dashboard

                <fa-icon [icon]="faTachometerAlt"></fa-icon>

                Info

                <fa-icon [icon]="faStar"></fa-icon>

                Storage

Sidenav Component :-
@Component({
  selector: 'app-sidenav',
  templateUrl: './sidenav.component.html',
  styleUrls: ['./sidenav.component.scss']
})
export class SidenavComponent implements OnInit {

  faTachometerAlt = faTachometerAlt;
  faTh = faTh;
  faStar = faStar;
  constructor() { }
  activatemenu = false;
  ngOnInit() {
  }
}

How can I make navbar visible on clicking of header fa-icon  in mobile view ?

A: I will post it as an answer but normally, you have all you need on this link (Thanks @Roman Šimík).
Make a service like :
export class HeaderService {

  isDisplayed = false;
  private showSideNavSubject = new Subject<boolean>();

  constructor() {}

  toggle(): void {
    this.isDisplayed = !this.isDisplayed;
    this.showSideNavSubject.next(this.isDisplayed);
  }

  get(): Observable<boolean> {
    return this.showSideNavSubject.asObservable();
  }
}

Header
<fa-icon class="hamburger" [icon]="faBars" (click)="toggle()"></fa-icon>

constructor(private headerService: HeaderService) {}

toggle() {
  this.headerService.toggle();
}

Sidenav

Show sidenav : {{ showSideNav }}

showSideNav = false;
subscription: Subscription;

constructor(private headerService: HeaderService) {}

ngOnInit() {
  this.subscription = this.headerService.get().subscribe(sideNav => this.showSideNav = sideNav);
}

ngOnDestroy() {
  this.subscription.unsubscribe();
}

I implement it on a Stackblitz but without a router. It's working.
Is this what you need ?


text:
Q: Jade, 3 elements under parent don't produce expected result I have this Jade template:
  .widget
    p
      h1 Title!
      | {#Price}:
      a(href='#{item.href}') Link

which produces:

Title
$174 :
   Link

I expected the logical structure:

What am I doing wrong?

A: That structure is probably what Jade produces as output, but in HTML, it's not valid to nest an
 (a block element) under a
 (which is only allowed to contain inline elements). Since HTML5 is not strictly XML, ending tags for some elements are implicit, including
, so the
 element ends there. The browser then sees an extra
 and creates another
 element, because HTML parsing isn't strict – but that part is invalid HTML.
Consider a
 or something instead.

A: There will be like this as follows::
.widget
    p
        h1
          | Title!
          | {#Price}:
        a(href='#{item.href}') Link

I think this will work and you will get expected results.


text:
Q: click on placemark kml file not the exact position of the placemark I've added an click handler to a kmlLayer which places an marker on the location clicked on one of the lines (placemarkers)
google.maps.event.addListener(kmlLayer, 'click', function (kmlEvent) {
    if (kmlEvent.featureData.description != undefined) {
        var data = kmlEvent.featureData;
        var text = data.description;
        var latlong = kmlEvent.latLng;
        var gId = data.id;
        var roadId = data.name;
        var roadName = roadId.split(",")[0];
        resetMarker(selectedmarker);
        showNewMarker(latlong, gId, roadId, roadName);
     }
});

I place a marker based on the latLng received from the kmlEvent. It looks like the marker is placed on the line, but when I zoom in further the marker stands further from the line.
I think the latLng in the event is the exact location where is clicked on the map, not the coordinates of the placemark itself.
Are there any solutions to get the exact latLng of the placemark?So the position of the marker would be exactly on the placemark, no matter how much is zoomed in.


text:
Q: Viewing source code of a function I'm trying to look at how R calculates the p-values for the chi-square test. How do I view the source code?

A: This is not an answer about how to view and interpret source code.
But it seems to me that you don't need to look into the source code
in order to see how the P-value from chisq.test in R is computed.
The method seems transparent from observable output.
For example: The matrix DTA is a contingency table in which
each of the two categorical variables has three levels. Counts
are consistent with independence of the two categorical variables at the 5% level
because the P-value exceeds 0.05.
DTA = matrix(c(20, 30, 40,
               11, 17, 21,
               31, 32, 29), byrow=T, nrow=3)

chisq.test(DTA)

        Pearson's Chi-squared test

data:  DTA
X-squared = 4.9028, df = 4, p-value = 0.2974

Under the null hypothesis of independence, the the statistic
is approximately distributed as $\mathsf{Chisq}(\nu = (3-1)(3-1 = 4).$
For a compact display and to avoid giving more places of accuracy
that are ordinarily of use, R rounds the observed value of the chi-squared
statistic and the P-value.
In order to display a few more places of accuracy, we can use $-notation:
q = chisq.test(DTA)$stat;  q
X-squared
 4.902782
pv = chisq.test(DTA)$p.val;  pv
[1] 0.2974189

The P-value is the probability under the null distribution to the right of
the observed value of the test statistic:
1 - pchisq(as.numeric(q), 4)
[1] 0.2974189

Notes: (1) If the rounded value of the chi-squared statistic is used, then the
P-value from pchisq may differ from the P-value in the output, but only
within rounding error. (2) In the last R expression, as.numeric strips
an unnecessary label from the test statistic.


text:
Q: Firefox does not run this JQuery script, but Chrome does Firefox does not run this JQuery script, but Chrome does. What could be the reason ?
event.preventDefault();
var id = $(this).attr('adat');

$.ajax({
  type: 'POST',
  url: 'index.php',
  data: 'action=profile&option=refresh&ajax=1&id=' + id,
  success: function(contentHTML) {
    alert(contentHTML);
    $('#refreshdate' + id).html('Még ' + contentHTML + ' óra');
  }
});


text:
Q: tf.nn.sparse_softmax_cross_entropy_with_logits is not working properly and shape/rank error Trying to implement Skip-Thought vectors (Sentence encoder for downstream activities like sentiment classification, similarity match and so on) with below training details.

*

*50,000 Sentence - Training sample (On an average of 10-15 words per sentence size)

*20,000 Unique vocab list

*Base reference source code from Tensor skip-thought from github
But found something strange to me in the process of loss calculations and below is reference snapshot, Target and Logits are in different shape and size. Is it valid or do i need to change the 'num_outputs' to targets.get_shape().as_list()[0]
Error message while executing losses line item-
ValueError: Shape mismatch: The shape of labels (received (1280,)) should equal the shape of logits except for the last dimension (received (128, 20000)).


text:
Q: App store Version number and build number I had an app on app store with version 1.1.1 and build 85
While doing an update of the app using application loader the app I used version 1.2.0 and build 5.
It says that build version has to be higher than 85.
Is it that build number should always be incremental irrespective of version number.
If the version number is incremented as in our case can't we use a lower build number
Please point to some apple documentation on this.

A: Both build version numbers need to increment. They can be different numbers and different formats, but they both have to go up with each successive version you want to submit.

A: For each version number, e.g. (version 1), the build number will need to be incremented.
So the following is acceptable

*

*Version 1; build 1

*Version 1; build 2

*Version 1; build 3

*Version 1; build 4

... now, when you come to increase your version number, to say (version 2), you will be able to reset the build number back to say 1, if you want.

*

*Version 2; build 1

*Version 2; build 2

*Version 2; build 3

*Version 2; build 4

Just note that each new build number must be greater than the previous one.
Hope this helps someone else :-)

A: i had versioning problem for hotfix so I tested few cases.
and it can give you little more information, i think.
1.5.10(150) > 1.5.11(1) Failed.
xcode uploader said upload version should have larger number than 150. maybe my version has 2 period seperated version style.
1.5.10(150) > 1.5.11(180) obviously
1.5.11(180) > 1.5.11(1.5.11.1) Failed
1.5.11(160) > 1.5.11(160.1) has no problem.


text:
Q: C weird string output I tried running this simple code
#include <stdio.h>
#include <string.h>

int main() {
    char first[20];
    char last[20];
    char full[40];

    printf("Your first name?: ");
    fgets(first, sizeof(first), stdin);
    printf("your last name?: ");
    fgets(last, sizeof(last), stdin);
    first[strlen(first) - 1] = '\0';
    strcat(full, first);
    strcat(full, " ");
    strcat(full, last);
    printf("Your full name is: %s", full);
}

and the output returned was..
Your first name?: Daniel
your last name?: Jee
Your full name is: pA▒Daniel Jee

Can anyone tell me what this is?

A: full is not initialized,
strcat(full, first); invokes undefined behavior.
Garbage contents is a mild form of undefined behavior.
You should instead use:
strcpy(full, first);

Or better:
#include <stdio.h>
#include <string.h>

int main(void) {
    char first[20];
    char last[20];
    char full[40];

    printf("Your first name? ");
    if (!fgets(first, sizeof(first), stdin))
        return 1;
    printf("your last name? ");
    if (!fgets(last, sizeof(last), stdin))
        return 1;
    first[strlen(first) - 1] = '\0';
    snprintf(full, sizeof full, "%s %s", first, last);
    printf("Your full name is: %s", full);
    return 0;
}

Note that full most likely contains a trailing linefeed.

A: Stack variables in C are not initialized. You did strcat(full, first); without first setting full[0]=0;.

A: You should probably copy the first string into full instead.
#include <stdio.h>
#include <string.h>

int main()
{
    char first[20];
    char last[20];
    char full[40];

    printf ("Your first name?: ");
    fgets(first, sizeof(first), stdin);
    printf("your last name?: ");
    fgets(last, sizeof(last), stdin);
    first[strlen(first) - 1] = '\0';
    strcpy(full, first);
    strcat(full, " ");
    strcat(full, last);
    printf ("Your full name is: %s", full);
}


text:
Q: Sequentially run ruby scripts in a directory I have a directory of *.rb files that I would like to run, but sequentially and not in parallel.  My thoughts are to have a master file which calls each file, but how can I force it to wait until the process is finished before running the next file?

A: Dir['*.rb'].each{ |f| load(f) }

Each file will be fully run; the code will not continue to the next iteration until the current file is fully loaded and executed.
The only caveat to this would be if you have a file that launches a new Thread and does not .join it; the Ruby file would normally exit before the Thread is finished; in this case the next file will begin being loaded while the Thread continues to run.
Edit: If you need to run arbitrary command line code from Ruby, you can simply do:
Dir['*.rb'].each{ |f| `rails r #{f}` }

Again, the Kernel backtick command will wait until the process is complete before returning.


text:
Q: MySQL exceptions not caught (C#) My C# program works with a MySQL database.
For some reason the program cannot catch exceptions caused my the MySQL connection.
Example:
If I make the credentials in the connection string invalid, the program crashes like this (even when running in the debugger): http://imgur.com/SfzkVdW
The connection code is like this:
using MySQLDriverCS;

namespace XXX
{
    public class Data
    {
        private static MySQLConnection con;

        static Data()
        {
            string connectionString = new MySQLConnectionString("XXX",
                "XXX",
                "XXX",
                "XXX").AsString;

            con = new MySQLConnection(connectionString + ";CharSet=utf8");
            con.Open(); // For testing the connection
            con.Close();
        }
...

Any ideas for how I can improve things and start catching MySQL exceptions?
I have tried wrapping the code in the static constructor in a try-catch. That didn't help. The program still crashed in the same way.
Thanks.

Same code with the try-catch wrapper. It still fails with the same error: http://imgur.com/SfzkVdW
    static Data()
    {
        try
        {
            string connectionString = new MySQLConnectionString("XXX",
                "XXX",
                "XXX",
                "XXX").AsString;

            con = new MySQLConnection(connectionString + ";CharSet=utf8");
            con.Open(); // For testing the connection
            con.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

A: Use the appropriate exception type in the catch block.
Use the appropriate MySQL classes.
using MySql.Data.MySqlClient;

// class level var or whatnot:
string connString = @"server=theHostName;userid=dbuser123;password=OpenSesame7;database=my_db_name";

public void connect()
{
    try
    {
        conn = new MySqlConnection(connString); // read above comments for (conn)
        conn.Open();
    }
    catch (MySqlException ex)
    {
        MessageBoxButtons buttons = MessageBoxButtons.OK;
        string s="MySqlException: "+ex.ToString();
        MessageBox.Show(s,"Error",buttons);
    }
    finally
    {
        if (conn != null)
        {
            //conn.Close();
        }
    }
}

Error Caught No Problem:

Add References screenshot:

A: Catching or handling exceptions in C# generally requires a try-catch statement.
The syntax is essentially as follows:
try
{
    // operation likely to cause error
}
catch (Exception e){
    // handle error
    Console.WriteLine("Exception: " + e);
}

Console.Read();

So wrap your con.Open() logic in a try-catch statement like so:
try
{
    Con.Open();
}
catch (Exception e){
    // handle error
    Console.WriteLine("Possible MySQL Exception: " + e);
}

Additionally, you can add a finally block to the end of a try-catch statement, which executes its code regardless of whether an exception was handled or not:
    try
{
    // attempt to do something here
    con.Open();
}
catch (Exception e){
    // handle error
    Console.Writeline("Exception: " + e);
}
finally
{
    Console.Writeline("This runs no matter if an exception is thrown or not!");
}

Console.Read();


text:
Q: If the system Ax=b is consistent for every n x 1 matrix in b, then A is invertible. I have trouble understanding the proof here. I spent an hour trying to understand it but I give up. Can anyone help me with it?

A: At the beginning, they're saying that since $Ax = b$ is consistent no matter which vector $b$ is, then in particular the system
\begin{equation}
Ax = \begin{bmatrix} 1 \\ 0 \\ 0 \\ \vdots \\ 0 \end{bmatrix}
\end{equation}
is consistent.  In other words, there exists a vector $x_1$ such that
\begin{equation}
Ax_1 = \begin{bmatrix} 1 \\ 0 \\ 0 \\ \vdots \\ 0 \end{bmatrix}.
\end{equation}
And, since $Ax = b$ is consistent no matter what $b$ is, it must be true that the system
\begin{equation}
Ax = \begin{bmatrix} 0 \\ 1 \\ 0 \\ \vdots \\ 0 \end{bmatrix}
\end{equation}
is consistent.  In other words, there exists a vector $x_2$ such that
\begin{equation}
Ax_2 = \begin{bmatrix} 0 \\ 1 \\ 0 \\ \vdots \\ 0 \end{bmatrix}.
\end{equation}
And so on.  Now take these vectors $x_1, x_2,\ldots$ and make them the columns of a matrix $C$:
\begin{equation}
C = \begin{bmatrix} x_1 & x_2 & \cdots & x_n \end{bmatrix}.
\end{equation}
You can check that $AC = I$, the identity matrix.  So $A$ is invertible.


text:
Q: Validate multiple forms in sequence with jquery I am trying to validate various forms in steps. I have 3 forms. I am able to get the first form to show and the rest to hide. When I click on "next" to show next form, the first form disappears, but the next form will not show up. Please advice what I am doing wrong. Here is my code
HTML

Account Basics

Account Details

Final Steps

            <form class="form-horizontal clientRegistration" method="post" action="" id="clientRegistration_AccountBasics" >

<fieldset>

Account Basics

<legend>Client Registration</legend>

  First Name
  <input id="firstName" name="firstName" type="text" data-validation-regexp="^[a-zA-Z]+(([. -][a-zA-Z ])?[a-zA-Z]*)*$"  placeholder="First Name" class="form-control input-md rounded" required value="<?php (isset($_POST['firstName'])) ? $_POST['firstName'] : "" ;
?>">

  Last Name
  <input id="lastName" name="lastName" type="text" data-validation-regexp="^[a-zA-Z]+(([. -][a-zA-Z ])?[a-zA-Z]*)*$" placeholder="Last Name" class="form-control input-md rounded" required value="<?php (!empty($_POST['lastName'])) ? $_POST['lastName'] : "" ;
?>">

  Company
  <input id="company" name="company" type="text" data-validation-regexp="^[ A-Za-z0-9_.-]*$" placeholder="Company" class="form-control input-md rounded" value="<?php (!empty($_POST['company'])) ? $_POST['company'] : "" ;
?>">

  Email
  <input id="email" name="email" type="text" placeholder="Email" class="form-control rounded" required value="<?php (!empty($_POST['email'])) ? $_POST['email'] : "" ; ?>">

  Phone Number
  <input id="phoneNumber" name="phoneNumber" type="text" data-validation-regexp="^[0-9]{3}\.?[0-9]{3}\.?[0-9]{4}$" placeholder="###-###-####" class="form-control input-md rounded" required value="<?php (!empty($_POST['phoneNumber'])) ? $_POST['phoneNumber'] : "" ;
?>">

  Password
  <input name="userPass" id="userPass" type="password" placeholder="password" class="form-control input-md rounded" required>

  Re-Enter Password
  <input name="userPassConfirmation" id="userPassConfirmation" type="password" placeholder="confirm password" class="form-control input-md rounded" required>

    <input type="button" name="next" class="next action-button" value="Next" />
</fieldset></form>

            <form class="form-horizontal clientRegistration" method="post" action="" id="clientRegistration_AccountDetails" >
    <fieldset>

 Account Details

        <legend>Client Registration</legend>

            City
            <input name="city" id="city" type="text" placeholder="city" class="form-control input-md rounded" required>

            State
            <input name="state" id="state" type="text" placeholder="state" class="form-control input-md rounded" required>

            Zip Code
            <input name="zipCode" id="zipCode" type="text" placeholder="zipCode" class="form-control input-md rounded" required>

            How did you hear about us?
            <input name="referral" id="referral" type="text" placeholder="referral" class="form-control input-md rounded" required>

        <input type="button" name="previous" class="previous action-button" value="Previous" />
        <input type="button" name="next" class="next action-button" value="Next" />
    </fieldset></form>

            <form class="form-horizontal clientRegistration" method="post" action="" id="clientRegistration_FinalSteps" >
    <fieldset>

Final Steps

        <legend>Client Registration</legend>

            CC info goes here

        <input type="button" name="previous" class="previous action-button" value="Previous" />

            <input type="submit" class="action-button" name="Submit" id="Submit" value="Submit">

    </fieldset></form>

CSS
    * {margin: 0; padding: 0;}

html {
    height: 100%;
    /*Image only BG fallback*/

    /*background = gradient + image pattern combo*/
    /*background:
            linear-gradient(rgba(196, 102, 0, 0.6), rgba(155, 89, 182, 0.6));*/
}

body {
    /* font-family: montserrat, arial, verdana; */
}
/*form styles*/
form {
    width: 100%;
    margin: 10px auto;
    text-align: left;
    position: relative;
}
form {
    background: white;
    border: 0 none;
    border-radius: 3px;
    box-shadow: 0 0 15px 1px rgba(0, 0, 0, 0.4);
    padding: 20px 30px;
    box-sizing: border-box;
    width: 80%;
    margin: 0 10%;

    /*stacking fieldsets above each other*/
    position: relative;
}
/*Hide all except first form*/
form:not(:first-of-type) {
    display: none;
}
/*inputs*/
input[type="text"], textarea {
    padding: 15px;
    /*background-color: #1779ba;*/
    border: 1px solid #ccc;
    /*border-radius: 3px;*/
    margin-bottom: 10px;
    width: 100%;
    box-sizing: border-box;
    font-family: montserrat;
    color: #2C3E50;
    /*font-size: 13px;*/
}
/*buttons*/
input.action-button {
    width: 100px;
    background: #27AE60;
    font-weight: bold;
    color: white;
    border: 0 none;
    border-radius: 1px;
    cursor: pointer;
    padding: 10px 5px;
    margin: 10px 5px;
}
form.clientRegistration .action-button:hover, form.clientRegistration .action-button:focus {
    box-shadow: 0 0 0 2px white, 0 0 0 3px #27AE60;
}
/*headings*/
.fs-title {
    font-size: 15px;
    text-transform: uppercase;
    color: #2C3E50;
    margin-bottom: 10px;
}
.fs-subtitle {
    font-weight: normal;
    font-size: 13px;
    color: #666;
    margin-bottom: 20px;
}
/*progressbar*/
#progressbar {
    margin-bottom: 30px;
    overflow: hidden;
    /*CSS counters to number the steps*/
    counter-reset: step;
}
#progressbar li {
    list-style-type: none;
    color: white;
    text-transform: uppercase;
    font-size: 9px;
    width: 33.33%;
    float: left;
    position: relative;
}
#progressbar li:before {
    content: counter(step);
    counter-increment: step;
    width: 20px;
    line-height: 20px;
    display: block;
    font-size: 10px;
    color: #333;
    background: white;
    border-radius: 3px;
    margin: 0 auto 5px auto;
}
/*progressbar connectors*/
#progressbar li:after {
    content: '';
    width: 100%;
    height: 2px;
    background: white;
    position: absolute;
    left: -50%;
    top: 9px;
    z-index: -1; /*put it behind the numbers*/
}
#progressbar li:first-child:after {
    /*connector not needed before the first step*/
    content: none;
}
/*marking active/completed steps green*/
/*The number of the step and the connector before it = green*/
#progressbar li.active:before,  #progressbar li.active:after{
    background: #27AE60;
    color: white;
}

Javascript w/ jquery


text:
Q: Let $O$ be an open subset of $X=\prod\limits_{n\in\omega}X_n$, then $O=p_F^{-1}p_F(O)$.
Let $O$ be an open subset in $X=\prod\limits_{n\in\omega}X_n$, then $O=p_F^{-1}p_F(O)$ for some finite set $F\subset\omega$.

Where $p_F$ is the projection of $X$ onto $X_F=\prod\limits_{n\in F}X_n$.
How can we prove this claim? Thanks.

A: You should have a very hard time proving this claim.  Let $X_n = \mathbb{R}$ for all $n < \omega$, and define an open $U \subseteq X = \prod_{n \in \omega} X_n = \mathbb{R}^\omega$ by $$U = \{ x = ( x_n )_{n \in \omega} \in \mathbb{R}^\omega : ( \exists n \in \omega ) ( 0 < x_n < 1 ) \}.$$  For any finite $F \subseteq \omega$ we have that $p_F [ U ] = \mathbb{R}^F$, meaning that $p_F^{-1} p_F [ U ] = \mathbb{R}^\omega$.


text:
Q: How to insert a new row with new values (without copying from another object) in HQL..? I am using Hibernate.
And i want to persistently store a new row with new values (Without copying from another object) into my database with HQL.
My code in struts action class used to insert a new row is :
public String execute() throws Exception {
        Users u = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            u = new Users();
            u.setAge(getAge());
            u.setCity(getCity());
            u.setEmail(getEmail());
            u.setName(getUsername());
            u.setPassword(getPassword());
            u.setSex(getSex());
            session.save(u);
            session.getTransaction().commit();
        } catch (Exception e) {
            this.addActionError("Oops. And Error Encountered...!");
        }
        return SUCCESS;
    }

Code successfully executes without any error. But it is not being persistently stored in my database. I can not see a new row in the database. What can be the error.?
Or if there is any other way to insert a new row with HQL then please tell.
Thanks in advance.

A: You have to close the session at the end by calling:
session.close();

better also to do it at the finally block:
finally {
  session.close();
}


text:
Q: POPUP on Boot Completed Trying to create a popup after every boot is completed to get some confirmation. Able to get the BOOT_COMPLETED Message but while opening Alertdialog its crashing, Below are the code lines i am using. Please suggest
public class BootReceiver extends BroadcastReceiver {

    private static final String TAG = "BootReceiver";

    @Override
    public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();
            Log.d(TAG, "BroadcastReceiver:" + action);
            if (action.equals(Intent.ACTION_BOOT_COMPLETED))
            {

                Log.d(TAG, "ACTION_BOOT_COMPLETETED Receved" );
                CharSequence text = "BOOT COMPLETED!";
                int duration = Toast.LENGTH_SHORT;
                Toast.makeText(context,text,Toast.LENGTH_SHORT).show();

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
                alertDialog.setMessage("Message");
                alertDialog.setTitle("CONSENT");
                alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
                alertDialog.setCancelable(false);
                alertDialog.setPositiveButton("AGREE", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Log.d(TAG, " AGREE CLICKED"  );

                } });
                alertDialog.setNegativeButton("DISAGREE", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Log.d(TAG, " DISAGREE CLICKED"  );

                     } });
                alertDialog.show();

            }
        }
    }

Back Trace :
I/ActivityManager(  109): Start proc com.android.mms for broadcast com.android.m
ms/.transaction.MmsSystemEventReceiver: pid=311 uid=10015 gids={3003, 1015}
E/AndroidRuntime(  246): FATAL EXCEPTION: main
E/AndroidRuntime(  246): java.lang.RuntimeException: Unable to start receiver co
m.android.settings.BootReceiver: android.view.WindowManager$BadTokenExceptio
n: Unable to add window -- token null is not for an application
E/AndroidRuntime(  246):        at android.app.ActivityThread.handleReceiver(Act
ivityThread.java:1862)
E/AndroidRuntime(  246):        at android.app.ActivityThread.access$2400(Activi
tyThread.java:124)
E/AndroidRuntime(  246):        at android.app.ActivityThread$H.handleMessage(Ac
tivityThread.java:1035)
E/AndroidRuntime(  246):        at android.os.Handler.dispatchMessage(Handler.ja
va:99)
E/AndroidRuntime(  246):        at android.os.Looper.loop(Looper.java:126)
E/AndroidRuntime(  246):        at android.app.ActivityThread.main(ActivityThrea
d.java:3897)
E/AndroidRuntime(  246):        at java.lang.reflect.Method.invokeNative(Native
Method)
E/AndroidRuntime(  246):        at java.lang.reflect.Method.invoke(Method.java:4
91)
E/AndroidRuntime(  246):        at com.android.internal.os.ZygoteInit$MethodAndA
rgsCaller.run(ZygoteInit.java:841)
E/AndroidRuntime(  246):        at com.android.internal.os.ZygoteInit.main(Zygot
eInit.java:599)
E/AndroidRuntime(  246):        at dalvik.system.NativeStart.main(Native Method)

E/AndroidRuntime(  246): Caused by: android.view.WindowManager$BadTokenException
: Unable to add window -- token null is not for an application
E/AndroidRuntime(  246):        at android.view.ViewRoot.setView(ViewRoot.java:4
34)
E/AndroidRuntime(  246):        at android.view.WindowManagerImpl.addView(Window
ManagerImpl.java:181)
E/AndroidRuntime(  246):        at android.view.WindowManagerImpl.addView(Window
ManagerImpl.java:95)
E/AndroidRuntime(  246):        at android.app.Dialog.show(Dialog.java:269)
E/AndroidRuntime(  246):        at android.app.AlertDialog$Builder.show(AlertDia
log.java:853)
E/AndroidRuntime(  246):        at com.android.settings.BootReceiver.onRecei
ve(XtraBootReceiver.java:53)
E/AndroidRuntime(  246):        at android.app.ActivityThread.handleReceiver(Act
ivityThread.java:1855)
E/AndroidRuntime(  246):        ... 10 more

A: A dialog needs an activity context. You have a service. Your options are:

*

*Use a toast.

*Create an activity and give it a Dialog theme.

*There may be a third option to create or obtain a suitable context, but I'm not aware of one.


text:
Q: DataFrame data appearing twice when returned from function I currently have a function that will get data from a list of entries. I have a DataFrame that will have the data repeated. My code is,
import pandas as pd
import numpy as np
import csv
from requests import get
from bs4 import BeautifulSoup

def earnings(ticker):
    url_test = ('https://finance.yahoo.com/calendar/earnings?from=2018-04-08&to=2018-04-14&day=2018-04-12&symbol={}')
    for i in l:
        url = url_test.format(i)
        response = get(url)
        soup = BeautifulSoup(response.text, 'html.parser')
        table = soup.find('table',{'class':'W(100%)'})

        for tr in table:
            tr.find('tr')
            for td in tr:
                td.find('td')
                if len(td.contents) >= 3:
                    tic = td.contents[0].text
                    tic_list.append(tic)
                    tic_df = pd.DataFrame(tic_list)
                    dates = td.contents[2].text
                    dates_list.append(dates)
                    dates_df = pd.DataFrame(dates_list)
                    earnings_df = pd.concat( [dates_df, tic_df], axis=1)
    return(earnings_df)

l = {"AAPL", "KO"}
for ticker in l:
    earnings_df = earnings(ticker)
    earnings_df.to_csv('earnings_df.csv')

When looking at my csv file I will get the same data twice in the form of it repeating under itself. I feel like I messed up somewhere when creating the earnings_df. Any ideas?

A: Well I ran your code, but I added the initialization oftic_list = [] and dates_list = [] since that wasn't included. But when I ran that, the csv file contained earnings dates for AAPL and KO, 100 rows each. I didn't get duplicate data


text:
Q: Using the adverb "not"
The night was so quiet that not a sound could be heard.

Would you possibly tell me if the following, which I have just written, is correct or not? And could you tell me in what topic of grammar I can find such lessons?

The night was so quiet that a sound could not be heard.

A: Both sentences mean more or less the same thing, but, contrary to what Man_From_India says, they are not the same.

The night was so quiet that a sound could not be heard.

This means that if there would be a sound, it could not be heard.
This is difficult to imagine, but let's take a more obvious example.

The music was playing so loudly that a speaking voice could not be heard.

vs.

The people were all sleeping, not a voice could be heard.

In the first case, even if someone tried speaking, it could not be heard over the noise of the music.
In the second case, even though you would be able to hear the voices if people would speak, nobody actually used their voice, so not a voice was heard.
The original sentence:

The night was so quiet that not a sound could be heard.

Now, we could have heard any sound, because the night was so quiet. But there was not a single sound.

The night was so quiet that a sound could not be heard.

This sentence makes little sense, because the quiet night does not make it impossible to hear a sound that is there. Compare it to the music and the voices.
In practice, many people will ignore this distinction and read over it, understanding the second version to mean the same as the first, especially because the second sentence does not really make much logical sense.

A: Actually you have pretty much figured out yourself.

The night was so quiet that not a sound could be heard = The night was
  so quiet that a sound could not be heard.

Though the second sentence is really a bad one, yet for understanding and grammatical analysis you can arrange it like this. First sentence give a stress on "sound", using the word "not a", whereas in the second sentence "a sound" represents a particular sound, but that is not the case.
If you want to write this sentence correctly, you have to keep in mind the usage of "so...that" and "not a"
So...that - In your example sentence there is an adjective after "so". Here in your case the adjective is "quiet". It means "it's to such extent quiet that the the clause after "that" is true".
Not a/an thing - It's a modifier. It means nothing at all. Here in your sentence it's "not a sound" means "not at all any sound".

A:
The night was so quiet that a sound could not be heard

Well, I see this in a different way. If the night is so quiet, you should be (in fact) able to hear the sound of a pin-drop. Shouldn't you?

The night was so quiet that you could hear a pin-drop - sounds better to me.

I think if you want to refer to the quietest place or surrounding, you emphasize on hearing even a minute sound rather than giving the reason that there was no sound and thus the place/surrounding was quiet.
My answer is valid only in case if you want to emphasize that the night was as silent as the dead.

A: The difference is not in the meaning, the two sentences mean the same, but sentence  2 has no dynamic and is forceless because the main idea is not stressed or emphasized.
 But in sentence 2 the main idea "not a sound" is forcefully stressed and emphasized. You get this effect by placing "not" in an unusual position. A stylistic device.


text:
Q: how to extend a python dictionary while there are list inside I have tried to fetch data from a dictionary like mongodb do.
while there is a document like
{'a': 'b', 'c': ['d', {'e': ['i', {'j': 'h'}]}]}

that I want to get the value 'h' from the search string like 'c.e.j' as mongodb will do
> db.cc.findOne({'c.e.j':'h'})
{
    "_id" : ObjectId("551e5047342b12656b4edecc"),
    "a" : "b",
    "c" : [
        "d",
        {
            "e" : [
                "i",
                {
                    "j" : "h"
                }
            ]
        }
    ]
}

so the first time I think is I will need to extend the dictionary for each list inside, and I have been coding for 4 hours, buy I think it is hard for me.
The final version of my code looks like this:
import types

def extdic(cc):
    lst = []
    for key in cc:
        value = cc[key]
        if type(value) == types.DictType:
            for _ in extdic(value):
                cc[key] = _
                lst.append(eval(repr(cc)))
            return lst
        if type(value) == types.ListType:
            #print cc
            for _ in value:
                cc[key] = _
                lst.append(eval(repr(cc)))
            #print lst
            return lst
        else:
            return [cc]

def mkdic(cc):
    lst = []
    if type(cc) == types.ListType:
        lst = cc
    else:
        lst = [cc]

    reslst = []
    while True:
        for _ in lst:
            #print _
            ext = extdic(_)
            #print ext
            reslst = reslst + ext
        if len(reslst) == len(lst):
            break
        else:
            lst = reslst
            reslst = []
    return lst

if __name__ == '__main__':
    cc = [
        {'a': 'b', 'c': ['d', {'e': ['i', 'j']}]},
        {'f':['g','h']}
    ]

    cd = {'a': 'b', 'c': {'e': ['i', 'j']}}

    ce = {'a': {'b': {'c':{'d':{'e':['f','g']}}}}}
    for _ in mkdic(cc):
        print _

It is sad that I still cannot get what I want
I only get the 'ce' dictionary work like
MBA:code cc$ python todic3.py
{'a': {'b': {'c': {'d': {'e': 'f'}}}}}
{'a': {'b': {'c': {'d': {'e': 'g'}}}}}
MBA:code cc$

other dictionary struct still not the thing I want..
MBA:code cc$ python todic3.py
{'a': 'b', 'c': ['d', {'e': ['i', {'j': 'h'}]}]}
{'f': 'g'}
{'f': 'h'}
MBA:code cc$

I want to use the tools like
MBA:code cc$ echo "{'a': 'b', 'c': ['d', {'e': ['i', {'j': 'h'}]}]}" | python todic3.py c.e.j
c.e.j: h
MBA:code cc$

help please..
thank you very much

A: This should return the specified value. The 'yield from' statements require that you use Python 3.
Unfortunately I cannot test it ATM.
EDIT: I tested it just now, turns out there where some significant bugs. I fixed them and it works as intended now.
def iter_flattened(data):
    '''returns a generator that allows iteration over key,value pairs, even if the dictionaries are nested in lists'''
    if isinstance(data, dict):
        yield from data.items()
    elif isinstance(data, list):
        for item in data:
            yield from iter_flattened(item)

def _find(data, keys):
    '''This function searches the given (sub-)tree for the given keys'''
    if len(keys) == 0:
        return data

    for key, value in iter_flattened(data):
        if key == keys[0]:
            result = _find(value, keys[1:])
        else:
            result = _find(value, keys)
        if result is not None:
            return result
    return None

def find(data, path):
    '''Interface function, that accepts the keys as a string seperated with dots.'''
    keys = path.split('.')
    return _find(data, keys)

To be used like this:
data = {'a': 'b', 'c': ['d', {'e': ['i', {'j': 'h'}]}]}
value = find(data, 'c.e.j')
print(value) # --> h


text:
Q: How to remove Chrome proposals on my websites search bar? When a user clicks on my website, chrome will suggest former searches, the user have searched for on other websites. How can I disable that for all users?
It looks like this:

Thank You!

A: This happens because of the name of your input field. Chrome save these suggestions by a fieldname. Change the name of this input and the suggestions are gone.


text:
Q: How do I troubleshoot this CLR error in SQL Server spatial I have the following query:
Insert into PropertyTractsTemp
    Select
        P.field1 as field1 ,
        P.field2 as field2,
        P.field3 as field3,
        P.field4 as field4,
        G.GEOID,
        P.field5 as field5
    from PROPERTY_PARAMETERS P
    join BH_EDW.dbo.REF_GEOID_GEOG G WITH(INDEX([geog_sidx]))on G.geom.STIntersects(P.GeoLocation) =1
    where P.GEOID is null

This may have 1,000 to 100Mil records to match up.
Either way, the query stops and I receive this error:
Msg 10316, Level 16, State 1, Line 3
The app domain with specified version id (4) was unloaded due to memory pressure and could not be found.
The statement has been terminated.

I'm told it's a CLR error, and it has something to do with the spatial index but no explanation on how to troubleshoot it.
Any wisdom would be greatly appreciated.

A: i had same problem using a custom Clr type in a column.
i solved adding "-g1024" (or you can choose an other value) on SqlServer service.


text:
Q: Setting up a matrix from a recurrence relation to find diagonal matrix? Considering the recurrence $F_n= F_{n−1}+3F_{n−2}−2F_{n−3}$ where $F_0=0$, $F_1=1$ and $F_2=2$, use diagonalization to find a closed form of the expression.
If the sequence is continued the numbers are $F_3=5,F_4=9,F_5=20,F_6=37...$
When putting into a sequence matrix would the matrix be in the format of
\begin{align*}
\begin{pmatrix}
F_4 & F_3 & F_2 \\
F_3 & F_2 & F_1 \\
F_2 & F_1 & F_0
\end{pmatrix}
=
\begin{pmatrix}
8 & 5 & 2 \\
5 & 2 & 1 \\
2 & 1 & 0
\end{pmatrix} ?
\end{align*}

A: you want to set up a $3 \times 3$ transition matrix $A = \pmatrix{0 & 1 & 0\\0 & 0 & 1\\-2 & 3 & 1}$ that takes $\pmatrix{f_{n-3} \\ f_{n-2} \\f_{n-1}}$ to $\pmatrix{f_{n-2}\\f_{n-1} \\f_n}.$
once you find the three eigenvalues(hopefully distinct), you form $f_n = A \lambda_1^n + B\lambda_2^n + C\lambda_3^n$ the three initial conditions will fix the constants $A, B$ and $C.$


text:
Q: Error 440 in Visual Basic Application There is an old VB application running at one of my clients.
An exception is throws in this peice of code:
cn=GetIndexDatabaseConnectionString()
sSql="SELECT * FROM Arh_Naroc WHERE StNarocila = '" & isci & "'"
rs=CreateObject("ADODB.Recordset")
Call rs.Open(sSql,cn)

The exception happens in rs.Open() function. "Error number 440 occured."
This are SBL scripts for KOFAX engine and it's many years old.
The whole SW was transferred from old XP computer to Windows 7 and looks like there are problems everywhere.
Can some one help me determine what is the problem here. At least if I could get a proper error message back in msgbox would be most helpful.
EDIT:
This is the connection string function.
Function GetIndexDatabaseConnectionString
 Dim objXmlDocument As Object
 Dim objXmlGlobalSettingsFileParh As Object
 Dim objXmlIndexDatabaseConnectionString As Object
 Dim strGlobalSettingsFilePath As String
 Dim strTemp As String
 Const strSettingsFilePath = "C:\Data\LocalDocsDistibutingSystem\Settings.xml"
 Set objXmlDocument = CreateObject("MSXML2.DOMDocument")
 objXmlDocument.Load strSettingsFilePath
 Set objXmlGlobalSettingsFileParh = objXmlDocument.selectSingleNode("DocsDistributingSystem/GlobalSettingsFilePath")
 strGlobalSettingsFilePath = objXmlGlobalSettingsFileParh.childNodes(0).Text
 Set objXmlGlobalSettingsFileParh = Nothing
 Set objXmlDocument = Nothing
 Set objXmlDocument = CreateObject("MSXML2.DOMDocument")
 objXmlDocument.Load strGlobalSettingsFilePath
 Set objXmlIndexDatabaseConnectionString = objXmlDocument.selectSingleNode("DocsDistibutingSystem/AscentCapture/IndexDatabase/ConnectionString")
 strTemp = objXmlIndexDatabaseConnectionString.childNodes(0).Text
 Set objXmlIndexDatabaseConnectionString = Nothing
 Set objXmlDocument = Nothing
 GetIndexDatabaseConnectionString = strTemp
End Function

This is the relevant line from Settings.xml:
<ConnectionString> Provider=OraOLEDB.Oracle;Data Source=LINO2;User Id=****;Password=****;OLEDB.NET=True; </ConnectionString>

The real data is masked with *. The connection to Oracle appears to be ok. I created ODBC and linked server to sql using the provider and connection data. It works. It must be something missing installed on the computer for ADODB to work...
The connection appears to be working OK. There is no error when its initialized.
The error happens in Call rs.Open(sSql, cn). All i want is the detailed error message when the error happens...
Many thanks.

A: As it states on MS Knowledge Base

An error occurred while executing a method or getting or setting a
  property of an object variable. The error was reported by the
  application that created the object. Check the properties of the Err
  object to determine the source and nature of the error. Also try using
  the On Error Resume Next statement immediately before the accessing
  statement, and then check for errors immediately following the
  accessing statement.

So as they suggest check the Err object, in a similar fashion to:
If Err.Number <> 0 Then
  Msg = "Error: " & Str(Err.Number) & ", generated by " _
      & Err.Source & ControlChars.CrLf & Err.Description
  MsgBox(Msg, MsgBoxStyle.Information, "Error")
End If

So this will bring back the error in a MsgBox, however you can just use Response.Write if you want it easier to copy & paste etc..

A: to get the error description you can do as follows :
Function GetIndexDatabaseConnectionString()
  On Error GoTo Errorfound
  'your
  'function
  'body
Exit Function
Errorfound:
  With Err
    MsgBox "Source: " & .Source & vbCrLf & "Desc: " & .Description, vbCritical, "Error " & CStr(.Number)
  End With 'Err
End Function