text:
Q: Pandas Dataframe: Split multiple columns each into two columns I have a pandas dataframe named df like this:
0   2J-AAB1 AA  AA  CC  CC  AA  AA  CC  AA  CC
1   2J-AAB4 AA  TA  TC  TC  GA  AA  CC  AA  CC
2   2J-AAB6 AA  TA  CC  CC  AA  AA  CC  AA  CC
3   2J-AAB8 AA  TT  TT  TT  GG  AA  TC  CC  CC
4   2J-AAB9 AA  TT  TT  TT  GG  AA  TC  CC  CC
5   2J-AABA AA  AA  CC  CC  GA  AG  CC  AA  CG
6   2J-AABE AA  TT  TT  TT  GG  AA  TC  CA  CC
7   2J-AABF AA  AA  CC  CC  AA  AA  CC  AA  CC
8   2J-AABH AA  TT  TT  TT  GG  AA  CC  AA  CC
9   2J-AABI AA  AA  CC  CC  AA  AA  CC  AA  CG

I want to split columns like "AA,AT,CC" etc all into two columns and get new data-frame like:
0   2J-AAB1 A   A   A   A   C   C   C   C   A   A   A   A   C   C   A   A   C   C
1   2J-AAB4 A   A   T   A   T   C   T   C   G   A   A   A   C   C   A   A   C   C
2   2J-AAB6 A   A   T   A   C   C   C   C   A   A   A   A   C   C   A   A   C   C
3   2J-AAB8 A   A   T   T   T   T   T   T   G   G   A   A   T   C   C   C   C   C
4   2J-AAB9 A   A   T   T   T   T   T   T   G   G   A   A   T   C   C   C   C   C
5   2J-AABA A   A   A   A   C   C   C   C   G   A   A   G   C   C   A   A   C   G
6   2J-AABE A   A   T   T   T   T   T   T   G   G   A   A   T   C   C   A   C   C
7   2J-AABF A   A   A   A   C   C   C   C   A   A   A   A   C   C   A   A   C   C
8   2J-AABH A   A   T   T   T   T   T   T   G   G   A   A   C   C   A   A   C   C
9   2J-AABI A   A   A   A   C   C   C   C   A   A   A   A   C   C   A   A   C   G

Is there a pythonic way to make it? Any suggestion are appreciated .. Thanks in advance

A: Try this:
In [60]: x = df.set_index(1).stack().str.extractall('(.)').unstack([-2, -1]).reset_index()

In [61]: x.columns = np.arange(len(x.columns))

In [62]: x
Out[62]:
        0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18
0  2J-AAB1  A  A  A  A  C  C  C  C  A  A  A  A  C  C  A  A  C  C
1  2J-AAB4  A  A  T  A  T  C  T  C  G  A  A  A  C  C  A  A  C  C
2  2J-AAB6  A  A  T  A  C  C  C  C  A  A  A  A  C  C  A  A  C  C
3  2J-AAB8  A  A  T  T  T  T  T  T  G  G  A  A  T  C  C  C  C  C
4  2J-AAB9  A  A  T  T  T  T  T  T  G  G  A  A  T  C  C  C  C  C
5  2J-AABA  A  A  A  A  C  C  C  C  G  A  A  G  C  C  A  A  C  G
6  2J-AABE  A  A  T  T  T  T  T  T  G  G  A  A  T  C  C  A  C  C
7  2J-AABF  A  A  A  A  C  C  C  C  A  A  A  A  C  C  A  A  C  C
8  2J-AABH  A  A  T  T  T  T  T  T  G  G  A  A  C  C  A  A  C  C
9  2J-AABI  A  A  A  A  C  C  C  C  A  A  A  A  C  C  A  A  C  G

A: You have a good answer, but I started typing this so figure I'd leave it up.
You can use apply with split and list to output to multiple columns.
For your dataframe with labels:
            A    B
0   "2J-AAB1" "AA"
1   "2J-AAB4" "AA"
2   "2J-AAB6" "AA"
3   "2J-AAB8" "AA"

df['B1'], df['B2'] = zip(*df['B'].apply(lambda x: list(x)))

This gives you:
         A   B B2 B1
0  2J-AAB1  AA  A  A
1  2J-AAB4  AA  A  A
2  2J-AAB6  AA  A  A
3  2J-AAB8  AA  A  A

For more columns, or with specific columns names, can do:
for i in df.columns[1:]:
    df['{}1'.format(i)], df['{}2'.format(i)] = zip(*df[i].apply(lambda x: list(x)))

This gives:
         0   1   2   3   4   5   6   7   8   9 11 12 21 22 31 32 41 42 51 52 61 62 71 72 81 82 91 92
0  2J-AAB1  AA  AA  CC  CC  AA  AA  CC  AA  CC  A  A  A  A  C  C  C  C  A  A  A  A  C  C  A  A  C  C
1  2J-AAB4  AA  TA  TC  TC  GA  AA  CC  AA  CC  A  A  T  A  T  C  T  C  G  A  A  A  C  C  A  A  C  C
2  2J-AAB6  AA  TA  CC  CC  AA  AA  CC  AA  CC  A  A  T  A  C  C  C  C  A  A  A  A  C  C  A  A  C  C
3  2J-AAB8  AA  TT  TT  TT  GG  AA  TC  CC  CC  A  A  T  T  T  T  T  T  G  G  A  A  T  C  C  C  C  C
4  2J-AAB9  AA  TT  TT  TT  GG  AA  TC  CC  CC  A  A  T  T  T  T  T  T  G  G  A  A  T  C  C  C  C  C
5  2J-AABA  AA  AA  CC  CC  GA  AG  CC  AA  CG  A  A  A  A  C  C  C  C  G  A  A  G  C  C  A  A  C  G
6  2J-AABE  AA  TT  TT  TT  GG  AA  TC  CA  CC  A  A  T  T  T  T  T  T  G  G  A  A  T  C  C  A  C  C
7  2J-AABF  AA  AA  CC  CC  AA  AA  CC  AA  CC  A  A  A  A  C  C  C  C  A  A  A  A  C  C  A  A  C  C
8  2J-AABH  AA  TT  TT  TT  GG  AA  CC  AA  CC  A  A  T  T  T  T  T  T  G  G  A  A  C  C  A  A  C  C
9  2J-AABI  AA  AA  CC  CC  AA  AA  CC  AA  CG  A  A  A  A  C  C  C  C  A  A  A  A  C  C  A  A  C  G

A: Very interesting question. One can solve it stepwise as follows:
dfpart = df.iloc[:,1:]                    # get columns to be split
ll = dfpart.values                        # get values as list of lists
sl = list(map(lambda x: "".join(x), ll))  # join all rows into strings
sl = list(map(list, sl))                  # split strings to lists of characters
newdf = pd.DataFrame(data=sl)             # create dataframe from new lists
newdf = pd.concat([df.iloc[:,0], newdf], axis=1) # restore first column
newdf.columns= range(len(newdf.columns))  # correct column numbers;
print(newdf)

Output:
        0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18
0  2J-AAB1  A  A  A  A  C  C  C  C  A  A  A  A  C  C  A  A  C  C
1  2J-AAB4  A  A  T  A  T  C  T  C  G  A  A  A  C  C  A  A  C  C
2  2J-AAB6  A  A  T  A  C  C  C  C  A  A  A  A  C  C  A  A  C  C
3  2J-AAB8  A  A  T  T  T  T  T  T  G  G  A  A  T  C  C  C  C  C
4  2J-AAB9  A  A  T  T  T  T  T  T  G  G  A  A  T  C  C  C  C  C
5  2J-AABA  A  A  A  A  C  C  C  C  G  A  A  G  C  C  A  A  C  G
6  2J-AABE  A  A  T  T  T  T  T  T  G  G  A  A  T  C  C  A  C  C
7  2J-AABF  A  A  A  A  C  C  C  C  A  A  A  A  C  C  A  A  C  C
8  2J-AABH  A  A  T  T  T  T  T  T  G  G  A  A  C  C  A  A  C  C
9  2J-AABI  A  A  A  A  C  C  C  C  A  A  A  A  C  C  A  A  C  G


text:
Q: If given two arrays with integer data how to move one element to other array and delete that element from where it was or vice versa  let a = [1,2,40,60]
let b = [50, 70, 80]

Suppose I want to move 40 from a to array b and delete it from a so I get
a = [1,2,60]
b=[50, 70, 80, 40]

Please help. Any suggestion is appreciated

A: You can do a simple splice to move the value:
b.push(a.splice(2, 1)[0])

This grabs the element you want from a, adds it to b, and removes it from a all at the same time.
Edit: As @malarres pointed out below, you can also concat the returned array:
b.concat(a.splice(2, 1))

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use optional attributes in Spring Data / Webflux I´m trying to work with joins in Spring-Webflux. I have two tables, comments and votes.
My Comment Entity has an attribute named score, which is the calculated number of votes.
The problem is this score isn´t a field inside the database, but at the moment a transient marked field in the Comment Object which is calculated by my application with bad performance.
My goal is to calculate this with a Join and not in my Application.
My Problem is that Spring doesn´t map the score field because of the transient annotation, which is needed because other Operations (patch or update) doesn´t provide this score field.
My Repository looks like this:
@Repository
public interface CommentRepository extends ReactiveCrudRepository<Comment, UUID> {

    @Query("SELECT C.*, COALESCE(SUM(v.vote), 0) as score FROM comment c LEFT JOIN vote v ON c.id = v.comment_id WHERE c.room_id = $1 GROUP BY c.id")
    Flux<Comment> findByRoomIdWithScore(UUID roomId);

    Flux<Comment> findByRoomId(UUID roomId);
    @Transactional
    Flux<Void> deleteByRoomId(UUID roomId);
}

and my Comment Object is this:
@Table
public class Comment implements Persistable<UUID> {
    @Id
    private UUID id;
    private UUID roomId;
    private UUID creatorId;
    private String body;
    private Timestamp timestamp;
    private boolean read;
    private boolean favorite;
    private int correct;
    private boolean ack;
    @Transient
    private int score;
    private String tag;
    private String answer;

    @Override
    public boolean isNew() {
        return id == null;
    }

    public UUID getId() {
        return id;
    }

    public void setId(UUID id) {
        this.id = id;
    }

    public UUID getRoomId() {
        return roomId;
    }

    public void setRoomId(UUID roomId) {
        this.roomId = roomId;
    }

    public UUID getCreatorId() {
        return creatorId;
    }

    public void setCreatorId(UUID creatorId) {
        this.creatorId = creatorId;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public Timestamp getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Timestamp timestamp) {
        this.timestamp = timestamp;
    }

    public boolean isRead() {
        return read;
    }

    public void setRead(boolean read) {
        this.read = read;
    }

    public boolean isFavorite() {
        return favorite;
    }

    public void setFavorite(boolean favorite) {
        this.favorite = favorite;
    }

    public int getCorrect() {
        return correct;
    }

    public void setCorrect(int correct) {
        this.correct = correct;
    }

    public boolean isAck() {
        return ack;
    }

    public void setAck(boolean ack) {
        this.ack = ack;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public String getAnswer() {
        return answer;
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }

    @Override
    public String toString() {
        return "Comment{" +
                "id='" + id + '\'' +
                ", roomId='" + roomId + '\'' +
                ", creatorId='" + creatorId + '\'' +
                ", body='" + body + '\'' +
                ", timestamp=" + timestamp +
                ", read=" + read +
                ", favorite=" + favorite +
                ", correct=" + correct +
                ", ack=" + ack +
                ", score=" + score +
                ", tag=" + tag +
                ", answer=" + answer +
                '}';
    }
}

I´ve already tried to make another Comment class without the transient annotation, but that doesn´t work because of the used Repository i guess: reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.IllegalArgumentException: Property must not be null!

A: The solution was to create another Class which extends Comment with the non transient score attribute. This could be casted back into a comment and the score is set


text:
Q: TextView customSelectionActionModeCallback issues in NestScrollView nested RecyclerView I have a NestedScrollView contain a RecyclerView, each adapter item have

*

*TextView one

*ImageView

*TextView two

and I want to custom TextView select action use kt ext
fun TextView.customMenuCallBack() {
    var selectAll = false
    customSelectionActionModeCallback = object : ActionMode.Callback {
        override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
            return true
        }

        override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
            return true
        }

        override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
            item?.let {
                return when (it.itemId) {
                    android.R.id.selectAll -> {
                        selectAll = true
                        false
                    }

                    android.R.id.copy -> {
                        if (selectAll) {
                            //TODO set content
                            try {
                                val clipboard: ClipboardManager = context.getSystemService(AppCompatActivity.CLIPBOARD_SERVICE) as ClipboardManager
                                val clip = ClipData.newPlainText(context.toString(), content)
                                clipboard.setPrimaryClip(clip)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }

                        //make custom action work return true
                        true
                    }
                    else -> {
                        false
                    }
                }
            }
            return false
        }

        override fun onDestroyActionMode(mode: ActionMode?) {

        }

    }
}

I appear some issues:

*

*menu not hide after click menu item

*Affects scrolling, when scrolling forward it suddenly back to nearby selected text position

*Not workinig in MIUI ROM

A: I have fixed part of issues

*

*menu not hide after click menu item

*Affects scrolling, when scrolling forward it suddenly back to nearby selected text position
fun TextView.customMenuCallBack() {
    var selectAll = false
    customSelectionActionModeCallback = object : ActionMode.Callback {
        override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
            return true
        }

        override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
            return true
        }

        override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
            item?.let {
                return when (it.itemId) {
                    android.R.id.selectAll -> {
                        selectAll = true
                        false
                    }

                    android.R.id.copy -> {
                        if (selectAll) {
                            //TODO set content
                            try {
                                val clipboard: ClipboardManager = context.getSystemService(AppCompatActivity.CLIPBOARD_SERVICE) as ClipboardManager
                                val clip = ClipData.newPlainText(context.toString(), content)
                                clipboard.setPrimaryClip(clip)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                        //fixed first issue
                        mode?.finish()
                        //fixed second issue
                        clearFocus()
                        //make custom action work return true
                        true
                    }
                    else -> {
                        false
                    }
                }
            }
            return false
        }

        override fun onDestroyActionMode(mode: ActionMode?) {

        }

    }
}

update: Custom my NestedScrollView2:NestedScrollView and override
  override fun requestChildFocus(child: View?, focused: View?) {
     //do nothing prevent focused issued
  }


text:
Q: How to prevent pdb files from being generated in unit test results "out" folder? When I run unit tests via mstest.exe, the test results folder contains .pdb files. These files are not supposed to be there as they interfere with the automated build system. Is there any way to prevent those files from being generated?

A: Running unit tests doesn't produce .pdb files.  Compiling the tests does.  Check your build settings.  It is the /pdb argument to the compiler, in case you are not using msbuild.
One exception, you could get .pdbs if you are unit-testing code that uses System.CodeDom.  In which case checking that you get the .pdbs ought to be part of the test.


text:
Q: Matplotlib, draw on top I am drawing an errorbar plot of some data points, and alongside these points, I want to draw the average in-between two values a line, I also want the line to be drawn on top of the errorbar.
In my code, I write the pyplot.errorbar(...) to draw the data points first, and then pyplot.plot(...) to draw the lines, and the result is that the errorbar is plotted on top of the lines, such that the line is hardly visible:

I have no idea as to how to draw the line on top, this is likely really easy to do, but I do not know how to do so.

A: This is generally controlled using the zorder https://matplotlib.org/3.1.1/gallery/misc/zorder_demo.html
pyplot.plot([0,1], [0,1], linewidth=10)
pyplot.errorbar([0.5], [0.5], 0.3, 0.3, linewidth=20, zorder=-100)

pyplot.plot([0,1], [0,1], linewidth=10)
pyplot.errorbar([0.5], [0.5], 0.3, 0.3, linewidth=20, zorder=100)

A: You can also play with transparency (or opacity) by setting the parameter alpha in plt.errorbar() and the errorbar linewidth (elinewidth) to get a desirable effect.
Example with Dummy Data
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline
%config InlineBackend.figure_format = 'svg' # 'svg', 'retina'
plt.style.use('seaborn-white')

# dummy data
np.random.seed(0)
x = np.arange(-1,1,0.1)
y, yerr = 2*np.random.randn(x.size) + 5, 1*np.random.randn(x.size)
xerr = 0.2*np.random.randn(x.size)

# make figure
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(16,6))
plt.sca(ax1)
plt.plot(x,y, 'bo', markersize=3)
plt.errorbar(x, y, xerr=xerr,
            ecolor='red', elinewidth=1.2, barsabove=False,
            alpha=0.3, lw=1)
plt.title('elinewidth = 1.2')
plt.sca(ax2)
plt.plot(x,y, 'bo', markersize=3)
plt.errorbar(x, y, xerr=xerr,
            ecolor='red', elinewidth=2.0, barsabove=False,
            alpha=0.3, lw=1)
plt.title('elinewidth = 2.0')
plt.suptitle('Controlling Errorbar Width and Transparency')
plt.show()

Output:


text:
Q: How can I reflectively call a method on a Scala object from Java? I have a scala object defined like the following:
package com.example

object Foo {
  def bar(): String = "Interesting Result"
}

I know that I can call Foo$.MODULE$.bar() from Java if Foo is in the build and runtime classpath, but in my situation Foo is not in the build classpath and may or may not be configured in the runtime classpath.
From my Java code I'd like to use reflection to call bar() if it is available on the runtime classpath, otherwise I'll fall back to a default implementation.
Is it possible to do this?

A: You can do it with code that looks something like this:
package com.example.java;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Example {

  /**
   * Returns null or the result of calling a method on a scala object from java
   */
  public String callScalaFromJava(){
    String result = null;

    try {
      Class<?> clazz = Class.forName("com.example.Foo$"); // Note the trailing '$'
      Method method = clazz.getDeclaredMethod("bar");
      Field field = clazz.getField("MODULE$");
      Object instance = field.get(null);
      Object obj = method.invoke(instance, new Object[] {});

      if (obj instanceof String) {
        result = (String) obj);
      }

    } catch (Exception ex) {
      // SWALLOWING
    }
    return result;
  }
}

A: The object Foo class is com.example.Foo$ so if you can just load that class, everything will go fine without using reflection:
try {
    Class.forName("com.example.Foo$");
    String s = com.example.Foo$.MODULE$.bar();
    // ...
} catch (Exception ex) {
  String s = // fallback solution
  // ...
}

A: Inspired by David Carlson's answer I created this utility class for calling methods on Scala objects reflectively.
The class lets you also call Scala methods that expect parameters.
I put it here in the hope that it's useful to somebody and to get feedback on how to improve the code.
ScalaUtil.java:
package your.stuff.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
// I use SLF4J (http://www.slf4j.org/) for logging. Feel free to change this
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Utilities for Scala/Java integration */
public class ScalaUtil {

    private static final Logger LOG = LoggerFactory.getLogger(ScalaUtil.class);

    /**
     * Calls the parameterless {@code method} on a Scala {@code object}.
     *

     * Returns an object of type {@code ReturnType} if the call succeeded, null
     * otherwise.
     *
     * @param object
     *            the fully qualified path to the object such as
     *            "eu.test.MyScalaObj$". Mind the dollar sign at the end
     * @param method
     *            the name of the method inside {@code object} we want to call
     * @param <ReturnType>
     *            type of the return value of the {@code method}
     * @return the return value of the Scala {@code object}'s {@code method} or
     *         null if the {@code method} couldn't be called
     */
    public static <ReturnType> ReturnType callObj(final String object,
            final String method) {
        final Object noParams[] = {};
        return callObj(object, method, noParams);
    }

    /**
     * Calls a {@code method} on a Scala {@code object} with the given method
     * {@code arguments}.
     *

     * Returns an object of type {@code ReturnType} if the call succeeded, null
     * otherwise.
     *
     * @param object
     *            the fully qualified path to the object such as
     *            "eu.test.MyScalaObj$". Mind the dollar sign at the end
     * @param method
     *            the name of the method inside {@code object} we want to call
     * @param arguments
     *            the arguments that {@code method} expects
     * @param <ReturnType>
     *            type of the return value of the {@code method}
     * @return the return value of the Scala {@code object}'s {@code method} or
     *         null if the {@code method} couldn't be called
     */
    @SuppressWarnings("unchecked")
    public static <ReturnType> ReturnType callObj(final String object,
            final String method, final Object... arguments) {
        ReturnType result = null;
        Class<?> objClass = null;
        try {
            final Class<?>[] methArgTypes = getTypes(arguments);
            objClass = Class.forName(object);
            final Method meth = objClass
                    .getDeclaredMethod(method, methArgTypes);
            final Field field = objClass.getField("MODULE$");
            final Object instance = field.get(null);
            result = (ReturnType) meth.invoke(instance, arguments);
        } catch (ClassNotFoundException | SecurityException
                | NoSuchFieldException | IllegalAccessException
                | IllegalArgumentException | InvocationTargetException e) {
            LOG.warn("Could not call method {} on {} with arguments {}",
                    method, object, arguments, e);
        } catch (final NoSuchMethodException e) {
            if (objClass != null) {
                LOG.info("Declared methods: {}",
                        (Object[]) objClass.getDeclaredMethods());
            }
            LOG.warn("Could not call method {} on {} with arguments {}",
                    method, object, arguments, e);
        }
        return result;
    }

    /**
     * Returns the runtime types of some {@code objects}.
     *
     * @param objects
     *            the objects in whose types we are interested in
     * @return an array of the runtime types of the {@code objects}
     */
    private static Class<?>[] getTypes(final Object... objects) {
        final Class<?>[] types = new Class<?>[objects.length];
        for (int i = 0; i < objects.length; i++) {
            final Object o = objects[i];
            final Class<?> type = o.getClass();
            types[i] = type;
        }
        return types;
    }

    /** This utility class is not meant to be instantiated */
    private ScalaUtil() {
    }
}

In order to call the Scala method with parameters you'll need to add the Scala library to the build path of your Java project.
Assuming this is the Scala object you want to call:
package eu.tests.scala
object ScalaObject {

  // You'll have to use Java's boolean when Java calls this
  def sayHello(param: java.lang.Boolean): String = "param: " + param

  def sayHello: String = "no param"

  def sayHello(param: String): String = "param: " + param
}

This is how you use the ScalaUtil on the above Scala object:
String scalaPackage = "eu.tests.scala";
String scalaObject = "ScalaObject";
String method = "sayHello";
String fullScalaObjName = scalaPackage + "." + scalaObject + "$";

String result1 = ScalaUtil.callObj(fullScalaObjName, method);
String result2 = ScalaUtil.callObj(fullScalaObjName, method, true);
String result3 = ScalaUtil.callObj(fullScalaObjName, method, "abc");


text:
Q: clang run error gcc ok

#ifndef _LIST_H
#define _LIST_H

typedef int element_type;
typedef struct node * p_node;
typedef p_node list;

typedef struct node {
    element_type e;
    p_node next;
}node;
#endif

list list_append(list l, element_type n) {
    p_node t = (p_node)malloc(sizeof(node));
    if (!t) {
        exit(1);
    }
    t->e = n;
    while(l->next) {
        l = l->next;
    }
    l->next = t;
    return l;
}

#include <stdio.h>
#include "list.h"

int main() {
    list l = list_init();
    list_append(l,3);
    return 0;
}

c code above, it can run in gcc, but can't run in clang env.
gcc version :4.4.7 20120313 (Red Hat 4.4.7-18) (GCC)
clang:
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.4.0
Thread model: posix
when it run in clang env, throw Segmentation fault: 11.

A:

list list_init() {
    p_node t = (p_node)malloc(sizeof(node));
    if(!t) {
        exit(1);
    }

    return t;
}


text:
Q: Mirror only a subdirectory from a git repository I've been doing some work for the University in a folder within their git repository.
There are other projects on the same repository divided in different folders and I would like to mirror my folder separately, so that it appears also in github.
Is it possible to do this without mirroring the entire repository and all the other folders?

A: You want to make your folder a git submodule.


text:
Q: Calendar Control Behaving Badly I have a problem with a user control containing a calendar control.
It looks OK in the design view in Visual Studio 2015:

However, in the browser, any browser, it looks like this:

I have tried to set the width to 330px wherever I can think of, but it always seems to get the width 1084 somehow!?
Where is the problem?
Here is the code for the user control:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TimeKalender.ascx.cs" Inherits="Blodbanken.TimeKalender" %>

<link rel="Stylesheet" type="text/css" href="StyleSheet1.css" id="style" runat="server" visible="false" />

    <asp:Calendar ID="Calendar1"  runat="server" BackColor="White" BorderColor="Black" BorderStyle="Solid" CellSpacing="1" Font-Names="Verdana" Font-Size="9pt" ForeColor="Black" Height="250px" NextPrevFormat="ShortMonth" Width="100%">
        <DayHeaderStyle Font-Bold="True" Font-Size="8pt" ForeColor="#333333" Height="8pt" />
        <DayStyle BackColor="#CCCCCC" />
        <NextPrevStyle Font-Bold="True" Font-Size="8pt" ForeColor="White" />
        <OtherMonthDayStyle ForeColor="#999999" />
        <SelectedDayStyle BackColor="#E60000" ForeColor="White" />
        <TitleStyle BackColor="Red" BorderStyle="None" Font-Bold="True" Font-Size="12pt" ForeColor="White" Height="12pt" />
        <TodayDayStyle BackColor="#999999" ForeColor="White" />
    </asp:Calendar>

<asp:Label ID="lblLedigeTimer" runat="server" Text="Available appointments:" Font-Bold="True"></asp:Label>

<asp:CheckBoxList ID="CheckBoxList1" runat="server">
    <asp:ListItem>08:00 </asp:ListItem>
    <asp:ListItem>09:00 </asp:ListItem>
    <asp:ListItem>10:00 </asp:ListItem>
    <asp:ListItem>11:00 </asp:ListItem>
    <asp:ListItem>12:00 </asp:ListItem>
    <asp:ListItem>13:00 </asp:ListItem>
    <asp:ListItem>14:00 </asp:ListItem>
    <asp:ListItem>15:00 </asp:ListItem>
</asp:CheckBoxList>

<asp:Button ID="Button1" runat="server" Text="Book it!" Width="119px" />

A: I'm not sure if this is it since you stated that you set the width to 330px but in the sample HTML you set the width to 100%
<asp:Calendar ... NextPrevFormat="ShortMonth" Width="100%">

Take that out the width definition and let the size be defined by the parent div

A: Mystery solved!
It turned out that the asp:calendar-tag translates into a bunch og table-tags. And deeply nested in there are some a-tags that were affected by the css intended for the nav-menu.

Thanks for your input!


text:
Q: jQuery: how to add parameter to a callback function without losing default parameter I have this code:
var callbackAfterLoad = function(data, ecBlock) {
    ecBlock.html(data);
    ecBlock.slideDown();
}

function bindevents(userInput, ecBlock, callbackAfterLoad) {
    userInput.keyup(function () {
        delay(function () {
            $.post("/preview", {content:userInput.val()}, callbackAfterLoad(data, ecBlock));
        }, 500);
    });
 }

And this error:
Uncaught ReferenceError: data is not defined

But when I check out jQuery examples
$.post("test.php", function(data) {
  alert("Data Loaded: " + data);
});

Why do I got this error ? Why do jQuery example is working and not mine ? (we cannot add parameters ?). Is the default $.post callback defined and his signature cannot be overriden ?

A: The third argument in $.post should be a function, but when you do this:
$.post("/preview", {content:userInput.val()}, callbackAfterLoad(data, ecBlock))

The third argument is not the function, but the return value of the function. Like this:
fn = callbackAfterLoad   // function reference
fn = callbackAfterLoad() // function execution and return value reference

And when executed in your example, data is not available yet. The correct syntax would be:
$.post("/preview", {content:userInput.val()}, callbackAfterLoad)

If you need to pass custom arguments to your callback, you can create a new proxy function like this:
var callback = function(data) {
    callbackAfterLoad.call(this, data, ecBlock);
};
$.post("/preview", {content:userInput.val()}, callback);

A: Try to use .post method in little bit another way:
$.post("/preview", {content:userInput.val()}, function(data){ callbackAfterLoad(data, ecBlock)} );

Your example doesn't work because you're immediately calling to callbackAfterLoad , before the .post actually "happens" and returns data. In jQuery example the callback function is only registered as handler but not firing immediately.


text:
Q: How to access env values for react in mern app deployed on heroku? I have deployed a mern stack application on heroku. Where the directory structure of my app is like this: -
|__client/  ** THIS IS EVERYTHING FROM THE REACT SIDE **
    |__ node_modules/
        |__ tons of stuff...
    |__ public/
        |__ index.html
        |__ favicon.ico
        |__ etc.
    |__ src/
        |__ index.js
        |__ main/
            |__ App.js
            |__ etc.
|__ models/
    |__ user.js
    |__ todo.js
    |__ etc.
|__ node_modules/
    |__ stuff...
|__ routes
    |__ userRoutes.js
    |__ todoRoutes.js
    |__ etc.
|__ .gitignore
|__ package.json
|__ server.js
|__ etc.

I have some environment variables set in heroku for backend that is working absolutely fine. I am serving my react build folder from the express app. My react app is having some env variables that I am not able to access. Is there any way I can access env in heroku from /client directory ?
This is my package.json for backend
{
    "name": "mern-to-heroku",
    "version": "1.0.0",
    "main": "index.js",
    "license": "MIT",
    "dependencies": {
        "body-parser": "^1.18.2",
        "express": "^4.16.2",
        "mongoose": "^4.13.6",
        "morgan": "^1.9.0"
    },
    "scripts": {
        "start": "node server.js",
        "heroku-postbuild": "cd client && npm install --only=dev && npm install && npm run build"
    },
    "engines": {
        "node": "8.9.2"
    }
}

A: Env. are only available at build-time (npm run build) of your react app and will be then replaced with their value. They are not "available" at run-time of your application, so they can not be changed, after your react-app has been build.
That means you will have to build you app on heroku itself if the environment variables are only available on heroku.
Example: If you are using the deploy-to-heroku button, you can add to app.json (of course, needs to be customized for your setup):
 "scripts": {
    "postdeploy": "npm run build"
 },

To build you react-app with the new env. after it has been deployed to heroku


text:
Q: Send a value from a listener interface to onPostExecute in AsyncTask class I'm actually trying to build a WebSocket client application on Android with the nv-websocket-client.
But I'm stuck with interfaces in my doInBackground function.
I'm trying to use a AsyncTask for the WebSocket connetion, but I'm stuck when I have to pass to onPostExecute the message from onTextMessage :/
private class Reseau extends AsyncTask<Void, Void, String> {
    // This is run in a background thread
    @Override
    protected String doInBackground(Void... params) {

        socket.addListener(new WebSocketAdapter() {
            @Override
            public void onTextMessage(WebSocket websocket, String message) throws Exception {
                // Here I want to return the String message to onPostExecute
                // How to do it ? return message do not work because onTextMessage is void
            }
        });

        try { socket = new WebSocketFactory()
                .setConnectionTimeout(5000)
                .createSocket(adresse[0] + adresse[1])
                .connect();
        }
        catch (IOException e) { e.printStackTrace(); } catch (WebSocketException e) { e.printStackTrace(); }

        return "I want to pass message from onTextMessage to onPostExecute";
    }

    // This runs in UI when background thread finishes
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        zone.append(result);
    }
}

I can use a RunOnUIThread or enable StrictMode but this is not the good method to do that job.
Thank you for your help !


text:
Q: JAVA 8 upgrade,only mvn clean install the tests are failing, any Idea? I upgraded my project form java 1.5 to java 1.8 and my tests pass in eclipse junit run and also pass when I run individual tests using "mvn  -Dtest=xxxx clean test" but when I run "mvn clean install" the tests are failing, any Idea ?

A: It is impossible to help answer your specific question without more detail, however here's some general guidance for things to check.
It seems likely that one or more of the individual tests are not properly initializing test fixtures or cleaning up after themselves. The earlier tests are changing the environment for the tests that follow. Tests that run after one of these polluting tests do not start with clean, properly initialized test data and they fail. When run individually, the test data is initialized and the formerly failing tests pass.
"Environment" could mean test class variables, cache, database, environment variables... etc.
When this situation happens, do not immediately assume that the tests are broken without a review of the code under test. Depending on what the code under test is doing, the failing test may be valid, pointing out a problem with initialization or proper cleanup in the code itself. For these cases, the tests have done their job!
Also, keep in mind that different JVMs can run tests in a different order - within classes, and between classes. Your test classes should not assume that tests will run in a specific order, thus each should be properly isolated from one another.


text:
Q: Do Biconditionals Have to be Logically Related? I'm studying real analysis from Terence Tao's book, Analysis 1, and was familiarizing myself with mathematical logic that Tao explains in the appendix. In it, he covers the biconditional, or "if and only if" statements. From what I understand, a biconditional is only true when both side are held to be true, or "logically equivalent". The examples he gives as a biconditional which evaluates to true and one that evaluates to false were:

if $x$ is a real number, then the statement
"$x = 3$ if and only if $2x = 6$" is true: this means that whenever $x = 3$
is true, then $2x = 6$ is true, and whenever $2x = 6$ is true, then $x = 3$ is
true. On the other hand, the statement "$x = 3$ if and only if $x^2 = 9$"
is false; while it is true that whenever $x = 3$ is true, $x^2 = 9$ is also
true, it is not the case that whenever $x^2 = 9$ is true, that $x = 3$ is also
automatically true

From what I see, these biconditional statements contain statements that seem to be logically related, or logically relevant to each other: by being given that $x = 3$, we are then able to assess the truth of the statement $2x = 6$ for example.
My question is: is it necessary for the statements to be logically relevant to each other? For example, if I have the statement "It is sunny today if and only if it is a Tuesday", and I were given that the statements "it is sunny" and "it is a Tuesday" were both true statements, would the biconditional statement hold true, despite the fact that the truth of these statements are determined independently from each other, and have no logical correlation? Is it necessary in a biconditional that each statement be logically related to the other, where each statement holds relevant information which is then utilized to assess the truth of the other statement?

A: The biconditional ($\iff$) is a logical connective that is true when both operands are true, or both are false $(0)$, it is false otherwise.
$$(\color{red}{\lnot A}\land\color{red}{\lnot B})\lor(\color{blue}{A}\land \color{blue}{B})\tag{0}$$
The truth table of the biconditional is the following:
\begin{array}{c|cc}
&\lnot A&A\\\hline
\lnot B&\color{red}{1}&0\\
B&0&\color{blue}{1}
\end{array}

Looking at the truth table alone, it is clear that the biconditional is true whenever both its constituents are true. So given that it is Tuesday, and it is sunny, the statement "It is sunny today if and only if it is a Tuesday", is true by virtue of the biconditionals definition $(0)$.
So to answer your question, it is not necessary for the statements to be relevant to another. A subtle point is that the two statements "It is Tuesday" and "It is sunny" are correlated, because they both have the same truth value (today at 3:37 am UTC in my (and possibly your) location at least).


text:
Q: help running a dos script with a space in it i am running this:
C:\Program Files\Microsoft SQL Server\80\Tools\Binn\osql -E -S Sql server-hl7\timeclockplus timeclockplus.sql -oresults.txt

and it doesnt like that there are spaces in the directory. how do i fix this problem?

A: Does this work?
"C:\Program Files\Microsoft SQL Server\80\Tools\Binn\osql" -E -S "Sql server-hl7\timeclockplus timeclockplus.sql" -oresults.txt

A: Try:
"C:\Program Files\Microsoft SQL Server\80\Tools\Binn\osql" -E -S "Sql server-hl7\timeclockplus timeclockplus.sql" -oresults.txt

You may have to include the ".exe" as well, but generally in DOS this is how spaces are handled.


text:
Q: how to using multi-processor ActionResult asp.net mvc 4.0 The controller has many ActionResult and when I click on View, one of them called and run. While I click on the View, ActionResult called will have to wait before it completes ActionResult then run.
I want to call my 2nd ActionResult both 2 and parallel action.
Is there a way to realize it not ??

A: public ActionResult DownLoad(){
// do somethings
return File ( ... );
}

public ActionResult UpLoad(){
// do somethings
return View ( ... );
}

When I called action Download, it is running.
I want to call UpLoad to run parallel with Download and return somethings.
Or  calling two actions Download and runnning them parallel .


text:
Q: C#: Get object from Combobox populated with Linq I populate a ComboBox in WPF with this query:
CBKunder.ItemsSource =
    from a in Master.getDC().Kundes
    select a.Kundenavn;

In the selectionChanged method I want to get the object that is selected. I want to do something like this:
kunde = (Kunde)CBKunder.SelectedItem;
But I get an error saying that I can't cast a String to a Kunde, which is the object I thought was alredy in the ComboBox.
What I'm missing here?

A: Your select seems to be projecting the a.Kundenavn into the list. Is there a chance that Kundenavn is indeed a string? This would mean your itemsource is a list of Strings, not 'Kunde'
Give
CBKunder.ItemsSource = Master.getDC().Kundes;

a go.


text:
Q: How to add a hover effect with dynamic styles to a component element? I have this Angular component where hover effect is currently applied with pseudo-class :hover in .scss file. But I want to apply the hover effect with dynamic values.
So suppose if I want the element's background to change on hover, the current css looks like this:
.element {
     display: flex;
     justify-content: center;

     &:hover {
          background-color: red;
     }
}

But now I want the hover background color to have dynamic values that is available inside the component provided by the user from the UI so the color could be anything. Another thing which I also want to achieve is to add a class to the element when it is selected. What I mean is when hovered, the background will change to a dynamic value but if the element is selected, that same color will be the background color. And if unselected, it will go back to the original color.
I'm new to Angular so I'm not sure how to achieve this. Anyone can help me?

A: You cannot dynamically set pseudo classes via JavaScript. You would have to either:

*

*Implement your own dynamic styling using the mouseover event in your component

*Swap to a pure CSS solution and let the consumer of your component override the hover pseudo selector with the desired color in their own CSS.

I would favor the second option. Turn off view encapsulation in your component declaration, make sure your component CSS is reasonably contained to just that component via some CSS component methodology like BEM, and just let the consumer override your styles.


text:
Q: Actions that Run on Admin Edit Page Load After Posts Are Queried What actions run on the edit page in the admin section of a post type?
i.e. xyz.com/wp-admin/edit.php or xyz.com/wp-admin/edit.php?post_type=shop_order (custom post type)
I need to run a function when the page loads, after the query has performed to get all of the posts that will be displayed on the edit page.
What action should I use for this?
Thanks!

A:
What actions run on the edit page in the admin section of a post type

Here are the do_action and do_action_ref_array calls, for the edit.php (post) screen, without any plugins and with a default theme activated:
muplugins_loaded - do_action
registered_taxonomy - do_action
registered_taxonomy - do_action
registered_taxonomy - do_action
registered_taxonomy - do_action
registered_taxonomy - do_action
registered_post_type - do_action
registered_post_type - do_action
registered_post_type - do_action
registered_post_type - do_action
registered_post_type - do_action
plugins_loaded - do_action
sanitize_comment_cookies - do_action
setup_theme - do_action
unload_textdomain - do_action
load_textdomain - do_action
load_textdomain - do_action
after_setup_theme - do_action
load_textdomain - do_action
load_textdomain - do_action
auth_cookie_valid - do_action
set_current_user - do_action
init - do_action
registered_post_type - do_action
registered_post_type - do_action
registered_post_type - do_action
registered_post_type - do_action
registered_post_type - do_action
registered_taxonomy - do_action
registered_taxonomy - do_action
registered_taxonomy - do_action
registered_taxonomy - do_action
registered_taxonomy - do_action
widgets_init - do_action
register_sidebar - do_action
register_sidebar - do_action
register_sidebar - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_register_sidebar_widget - do_action
wp_loaded - do_action
auth_cookie_valid - do_action
auth_redirect - do_action
wp_default_scripts - do_action_ref_array
_admin_menu - do_action
admin_menu - do_action
admin_init - do_action
wp_default_styles - do_action_ref_array
admin_bar_init - do_action
add_admin_bar_menus - do_action
current_screen - do_action
load-edit.php - do_action
parse_request - do_action_ref_array
send_headers - do_action_ref_array
parse_tax_query - do_action
parse_query - do_action_ref_array
pre_get_posts - do_action_ref_array
parse_tax_query - do_action
posts_selection - do_action
wp - do_action_ref_array
admin_xml_ns - do_action
admin_xml_ns - do_action
admin_enqueue_scripts - do_action
admin_print_styles-edit.php - do_action
admin_print_styles - do_action
admin_print_scripts-edit.php - do_action
admin_print_scripts - do_action
wp_print_scripts - do_action
admin_head-edit.php - do_action
admin_head - do_action
adminmenu - do_action
in_admin_header - do_action
admin_bar_menu - do_action_ref_array
wp_before_admin_bar_render - do_action
wp_after_admin_bar_render - do_action
admin_notices - do_action
all_admin_notices - do_action
restrict_manage_posts - do_action
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
the_post - do_action_ref_array
pre_get_users - do_action
pre_user_query - do_action_ref_array
pre_get_users - do_action
pre_user_query - do_action_ref_array
in_admin_footer - do_action
admin_footer - do_action
admin_print_footer_scripts - do_action
admin_footer-edit.php - do_action
shutdown - do_action

If we include the filters and even if we exclude the gettext filter, we get over five thousand lines!!. I posted it here on Github instead ;-)

I need to run a function when the page loads, after the query has
  performed to get all of the posts that will be displayed on the edit
  page.

I'm not sure what kind of function you need to run, but hopefully you can find your hook with these lists.
You could try for example the wp hook, that's fired later then the main WP_Query query:
Thanks to @TheDeadMedic for reminding me to target the edit.php screen for the shop_order ;-)
Here's the updated code snippet:
is_admin() && add_action( 'wp', function( \WP $wp )
{
    if( 'edit-shop_order' === get_current_screen()->id )
    {
        // ... your code here
    }
} );

I added the is_admin() check, since the wphook also fires on the front-end.
You can also check my answer here for other methods:
How to check if I'm on a custom post type archive in the admin area


text:
Q: How can I access res/colors.xml from other .xml files in Android? I have the following color under res/values/colors.xml:
 <resources>
  <color name="unpaidwarning">#942626</color>
 </resources>

I have created a style and I am trying to access unpaidwarning from it:
 <item name="android:textColor">???????</item>

My problem is that I don't know how to access colors.xml in that line, where the interrogation marks stand.

A: when you created a project there's a predefined color.xml in res/values/. In the colors.xml there're:
<resources>
    <!--<color name="colorPrimary">#3F51B5</color>-->
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#23DEBF</color>
    <color name="colorAccent">#FF4081</color>
</resources>

It is used in styles.xml, which is in the same directory.
<resources>

<!-- Base application theme. -->
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

You just use @color/you_defined_color. That's OK.


text:
Q: Azure - How to confirm NIC is configured correctly? I have an Azure Load Balancer which health probes 2 NICs, with a VM attached to each NIC.
Azure LB -> NIC1 -> VM1
         -> NIC2 -> VM2

The LB health probes (which hit the NICs on TCP port 443) are failing, and I'm struggling to understand why.
I can successfully connect to both VMs just fine using: Test-NetConnection IP -port 443
Therefore I can only assume the NICs themselves are the problem, since the same test fails for their private IP. How can I go about diagnosing this to confirm that's the case? In the Azure portal my NIC is clearly attached to my VM, what exactly else could go wrong with a NIC?


text:
Q: Polynomial Subspace Constraints Polynomial Subspace Question
Could anyone point me in the right direction for this question. I'm stuck on whether these constraints must allow for the the quadratic to make all quadratics in the subspace or not.
My thoughts are that option C and D are correct but do not know how to confirm this.

A: Hint: Only option C doesn't define a subspace: the constant polynomial $1$ is in the given subset, but $(-1)\cdot1$ is not.

A: $C$ is not correct, since we do not have closure under scalar multiplication.  The other three are correct.


text:
Q: Ruby on Rails: Retrieve id of selection made in f.select I have got a predefined selection list and i want to get the id of the selected item in the list.
My selection list is as  follows:
Type: <%= f.select(:SUB_TYPE, [['Type1', 't1'],
                                   ['Type2', 't2'],
                                   ['Type3', 't3']
                                  ],{ :prompt => "Select the Type"},
                                  {:onChange => "ShowTypeForm(this.value)"}
                                ) %>
What i want to know is how to retrieve the id of the selection made, in ruby on rails
Many many thanks

A: If this is part of a form it will be sent through using the name provided. In this case it looks to be a parameter you've named SUB_TYPE but to be sure check your development logs when submitting. The params hash is listed there for each request.
As you have this operating on a form, the form will have an object that is being updated, so the parameters are grouped around that.
It may be as easy as:
# :example refers to the object the form was built around
selection_id = params[:example][:SUB_TYPE]


text:
Q: Spring web returns invalid response I am using spring-web-4.3.10.RELEASE library.
I call postForEntity() method of RestTemplate (entity returns by getRestOperations()) from this library like this:
getRestOperations().postForEntity(getEndpoint(), new HttpEntity<String>(requestStr, headers), String.class);

But the response is returned incorrect (tested by some tools like SOAP UI)
Json with an array [] that is expected:
{
  "Header": {
    "Security": {
      "Timestamp": {
        "Created": "2019-05-27T13:16:57Z",
        "Expires": "2019-05-27T13:18:27Z"
      }
    }
  },
  "Body": {
    "NResponse": {
      "NoteInqRec": [
        {
          "NoteInfo": {
            "BranchDetails": ""
          }
        },
        {
          "NoteInfo": {
            "BranchDetails": ""
          }
        }
      ]
    }
  }
}

And the response from code using spring-web lib I got (the json returned is not even valid):
{
  "Header": {
    "Security": {
      "Timestamp": {
        "Created": "2019-05-27T13:16:57Z",
        "Expires": "2019-05-27T13:18:27Z"
      }
    }
  },
  "Body": {
    "NResponse": {
      "NoteInqRec":
        {
          "NoteInfo": {
            "BranchDetails": ""
          }
        },
        "NoteInqRec":
        {
          "NoteInfo": {
            "BranchDetails": ""
          }
        }
    }
  }
}

Please, assist


text:
Q: Best way to test views in a Rails App I've been using RSpec for testing my Rails application, but I find that testing views, partials and helpers that it isn't fully optimized for that. Can someone suggest a better approach to testing these things?

A: Many users will pair RSpec with Cucumber. Cucumber provides higher level testing and will allow you to test most aspects of your views efficiently.
Edit:
A few resources:

*

*http://railscasts.com/episodes/155-beginning-with-cucumber

*http://railscasts.com/episodes/159-more-on-cucumber

*http://railscasts.com/episodes/186-pickle-with-cucumber

*http://pragprog.com/book/achbd/the-rspec-book

A: Helpers are really easy to test with RSpec, but views and partials can be tricky since you really are doing an integration test. For these I use Cucumber since it allows you to describe the behavior in plain english and then use a nice DSL like Capybara to interact with the application. Much bigger learning curve for Cucumber than RSpec (IMHO), but the payoff has big rewards.

A: Yeah. Cucumbers all the way. Also see:
http://pragprog.com/book/hwcuc/the-cucumber-book
http://peepcode.com/products/cucumber

A: An alternative to Cucumber is RSpec request specs. The syntax is less natural than Cucumber, but still very readable.


text:
Q: Automating font color selection of specifc text in spreadsheets? I have extracted data from a website and formatted it into a CSV, all with Python. My job requires me to check this data and to make it easier I'd like to have the string in column A be used as a conditional to format the font color of the equivalent text in the string in column B in the same row.
For example, if "P90374" is in column A row 1, then "P90374" from the string "C801273 A12313 P90374 J1823132 B12313" contained in column B row 1 should have the font color set to red.
I was originally planning on processing the data in Google Sheets but am open to any possible solutions (though I don't currently have access to Excel).
Hope that makes sense. Many thanks.

A: You can do it using with "xlsxwriter" library.
You can format parts of a string with XlsxWriter using write_rich_string().
I am assuming you have already converted csv to dict. And you have a problem with how to compare and fill color to partially fill red color to text.
Here is the code:
import xlsxwriter

workbook = xlsxwriter.Workbook('sample_sezer_scraped_data.xlsx')
worksheet = workbook.add_worksheet()
red_color = workbook.add_format({'bold': True, 'color': 'red'})

sample_a_row_1 = "P90374"
sample_b_row_1 = "C801273 A12313 P90374 J1823132 B12313 C801273 A12313 P90374 J1823132 B12313"

if sample_a_row_1 in sample_b_row_1:
    parts_of_row = sample_b_row_1.split(sample_a_row_1)
    colored_row = []
    for order, part in enumerate(parts_of_row):
        if order != len(parts_of_row) - 1:
            colored_row.append(part)
            colored_row.append(red_color)
            colored_row.append(sample_a_row_1)
        else:
            colored_row.append(part)

    worksheet.write_rich_string("A1", *colored_row)

workbook.close()


text:
Q: Let $L_1$ be the language over alphabet $\{0, 1\}$ defined by $L_1 = \{x : \#_{01}(x) \bmod 3 = 0\}$. Give a regular expression that denotes $L_1$ Let $L_1$ be the language over alphabet $\{0, 1\}$ defined by $L_1 = \{x : \#_{01}(x) \bmod 3 = 0\}$.
Give a regular expression that denotes $L_1$, and justify its correctness

attempt
Need 010101 such that mod 3 = 0
How would I make a regex for this?
$R_1 = (01)^*$. How would I do the mod condition?

A: Our regular expression must include every string that has a multiple of $3$ occurences of the string $(01)$. This includes $$
(01)(01)(01)\\
10(01)(01)(01)10\\
1100(01)1100(01)1100(01)1100\\
10(01)(01)(01)(01)(01)(01)10\\
1()00
$$
Notice that we can regroup some of the above expressions as$$
(01)(01)(01)\\
1(001)(01)(011)0\\
11(000111)(000111)(000111)00\\
1(001)(01)(01)(01)(01)(011)0\\
1()00
$$
so that each set of parentheses includes as many $0$'s as it can on the left and as many  $1$'s as it can on the right. We will denote $aa^*$ as $a^+$. We can rewrite the strings as $$
(0^+1^+)(0^+1^+)(0^+1^+)\\
1(0^+1^+)(0^+1^+)(0^+1^+)0\\
11(0^+1^+)(0^+1^+)(0^+1^+)00\\
1(0^+1^+)(0^+1^+)(0^+1^+)(0^+1^+)(0^+1^+)(0^+1^+)0\\
1()00
$$
The regular expression that captures exactly these strings is $$
1^*((0^+1^+)(0^+1^+)(0^+1^+))^*0^* \\
= 1^*(((0^+1^+)^3)^*)0^*
$$


text:
Q: Azure: Can't ping SMTP Server, currently using Gmail SMTP Server for an app deployed using Azure Classic VM Can't ping smtp.gmail.com. I've been using google smtp for email notification and it was working until this moment. The app is deployed using azure vm classic deployment - Windows Server 2012 r2. Firewall is disabled.
I've tried to diagnose using telnet on port 587 but the result is
"220 smtp.gmail.com ESMTP f125sm12740457pfc.91 - gsmtp
Connection to host lost."
telnet smtp.gmail.com 587
220 smtp.gmail.com ESMTP f125sm12740457pfc.91 - gsmtp
Connection to host lost.

A: App might have been spamming host and IP banned. You can check IP against blacklist and see.
https://mxtoolbox.com/blacklists.aspx
But Microsoft does not recommend using Azure VM (Service) as SMTP outgoing Mail server, recommendation is to use a mail relay service like sendgrid, smtpgo, etc...
https://learn.microsoft.com/en-us/azure/virtual-network/troubleshoot-outbound-smtp-connectivity#recommended-method-of-sending-email
Dead Link: https://blogs.msdn.microsoft.com/mast/2017/11/15/enhanced-azure-security-for-sending-emails-november-2017-update/


text:
Q: Help with proving $f : X \rightarrow \mathbb{R}$ Let $X$ be a metric space with distance $d$ and let $p \in X$ be fixed. Define $f(x) = d(x,p)$. Prove that $f: X \rightarrow \mathbb{R}$ is a continuous function.

A: Let $x\in X$ and let $N$ be a neighborhhood of $d(x,A)$ on the real line.  Choose $\epsilon>0$ small enough so that  the interval $(d(x,A)-\epsilon,d(x,A)+\epsilon)$ lies inside $N$.  Let $U$ denote the open ball centered at $x$, radius $\epsilon/2$ and choose a point $a\in A$ such that $d(x,a)<d(x,A)+\epsilon/2$.  If $z\in U$ we have
$$d(z,A)\leq d(z,a)\leq d(z,x)+d(x,a)<d(x,A)+\epsilon$$
By reversing the roles of $x$ and $z$ we also have $d(x,A)<d(z,A)+\epsilon$.  Therefore $U$ is mapped inside $(d(x,A)-\epsilon,d(x,A)+\epsilon)$ and hence inside $N$, by our function, showing that the inverse image of $N$ is a neighborhood of $x$ in $X$ as required.

A: Let $0 \leq a,b\in\Bbb R$, so that $I = (a,b)$ is an open interval in $\Bbb R$. Then $$f^{-1}(I) = \{x\in X : a < d(x,p) < b\} = (X\setminus \overline B(p,a))\cap B(p,b)$$
which is open in $X.$ Now note that the image of $f$ is actually $\Bbb R_{\geq 0}$.$\,\blacksquare $


text:
Q: How can I prevent having just one hanging word on a new line in an HTML element? I'm building a simple webpage with some marketing content. One thing I don't like is that if a line of text is too long, it will wrap onto the next line, which is fine, but it often wraps in such a way that there is only one word on the new line, which is just bad news from a design standpoint.
Such and such doesn't have to be difficult. Such and such product makes it
easy
What can I do to dynamically ensure at least two words on each hanging line?
Such and such doesn't have to be difficult. Such and such product makes it
easy

A: I would use a <nobr>last two words.</nobr> tag.
This also gives the benefit of not cutting off any HTML flourishes you may be doing, eg:
“Here's a big statement I don't want <nobr>cutting off”.</nobr>

A: The simple solution is to use a non-breaking space between the last two words at the end of a paragraph.

Such and such doesn't have to be difficult. Such and such product makes it easy

This could get tedious if you have a lot of content and especially if it is business controlled. In that case you may be able to find a library or write a solution that automatically inserts the non-breaking space between the last two words of every paragraph for you.
Try this:
https://matthewlein.com/tools/widowfix

A: EDIT: The best answer is much cleaner -- you should probably use that instead. I'm leaving my answer up because it does work and it has some value for weird cases (e.g. if you're using a dash instead of a space, if you don't want to use  , etc).

Here's a neat little solution. Create a CSS class like this:
.nobr { white-space:nowrap; }

Any element with the class "nobr" will not be allowed to wrap white-space (spaces, tabs, etc) onto new lines. So just surround the last two words of your text with a span.nobr.

Such and such doesn't have to be difficult. Such and such product makes it easy

A: You can use the   HTML entity or one of the non-breaking-space ASCII character.
Here is one :


text:
Q: Как с помощью PDFBox-а (Java) сохранить картинку из PDF файла? Есть pdf файлы в которых есть отсканированный документ + распознанный в нём текст.
pdfRenderer.renderImage  и pdfRenderer.renderImageWithDPI дают на выходе картинку из распознанного текста, а нужна именно отсканированная картинка (сам растр).

A: Вопрос решён путём добавления levigo-jbig2-imageio. После этого pdfRenderer.renderImage начал возвращать саму картинку, а не рендер текста.


text:
Q: Mustache conditional statement (if/else) not working Trying to come to grips with Mustache... the problem here is that the conditional 'if/else' is not working as expected. I am checking in the data if a user is french... if they are then show true, else show false.
Problem
Mustache is completely ignoring the conditional and displaying both true and false for each table row.

My code
My markup

Looping through people

            Name
            Age
            Language

    <template id="template2">
        {{#users}}

                {{name}}
                {{age}}
                {{language}}
                {{#is_french}}
                    True
                {{/is_french}}
                {{^is_french}}
                    False
                {{/is_french}}

        {{/users}}
    </template>

My jQuery
$(function(){

    /**
     * conditional data
     */
    template = $('#template2').html();
    data = {
        'users': [{
                name: 'John',
                age: 22,
                language: 'French',
                is_french: true,
            },
            {
                name: 'Billy',
                age: 33,
                language: 'Anglaise',
                is_french: false,
            },
            {
                name: 'Michael',
                age: 77,
                language: 'Cambodian',
                is_french: false,
        }]
    };
    $('#table2').html(Mustache.render(template, data));

});

Question
Why is the if/else not working here?
EDIT: Here is my entire document:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title></title>
        <link rel="stylesheet" href="style.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Mustache Examples

Looping through people

                        Name
                        Age
                        Language

                <template id="template2">
                    {{#users}}

                            {{name}}
                            {{age}}
                            {{language}}
                            {{#is_french}}
                                True
                            {{/is_french}}
                            {{^is_french}}
                                False
                            {{/is_french}}

                    {{/users}}
                </template>

A: This is a problem of using template tag, which is actually HTML5 template tag. Using hashes in it makes browser think that this is document fragment. Seems like nested document fragments corrupt Mustache template.
Just change it to script tag, as in mustache manual.


text:
Q: How to use the MSDN This might seem like a stupid question, but the documentation is either bad or I'm missing something i didn't read. Everytime i refer to the MSDN for c++ related questions I'm always confused. Like the SetComputerName function. I looked up the MSDN and didn't know how to use it because i was completely clueless. Can anyone teach me how to read something like this, also if you could explain it in laymens terms im not very good at c++ thanks!
BOOL WINAPI SetComputerName(
_In_ LPCTSTR lpComputerName
);

A: There are a few macros here which are there for mainly historic reasons, and the type and name of the parameter
BOOL WINAPI SetComputerName(
_In_ LPCTSTR lpComputerName
);

BOOL is used for booleans as C didn't have a bool type standardised before 1999 and the Windows API is older than that, see Why does microsoft use so many macros in their C++ code?
WINAPI is used to mark Windows API functions with a calling convention, see What does "WINAPI" in main function mean? . Usually this doesn't matter to you, only to your compiler.
LPTCSTR means 'long pointer to a const TCHAR string'. See LPCSTR, LPCTSTR and LPTSTR . TCHAR is another macro which is either a single byte or wide character depending on compile time options. This one you need to pay attention to, as it is the type of the parameter.
_In_ marks the parameter as an input to the function, rather than pointing to storage for a result. This is sometimes useful documentation, and also a hint to code analysis. See What is _In_ in C++?
lpComputerName the 'lp' is Microsoft Hungarian notation for 'long pointer' containing the new value of the computer name.
'long pointer' is a reference to the old memory model where you had 16 bit pointers and 32 bit 'long pointers', now-a-days all the pointers are either 32 or 64 bit depending on compiler options.

Historically, P stands for "pointer" and LP stands for "long pointer".
  Long pointers (also called far pointers) are a holdover from 16-bit
  Windows, when they were needed to address memory ranges outside the
  current segment. The LP prefix was preserved to make it easier to port
  16-bit code to 32-bit Windows. Today there is no distinction — a
  pointer is a pointer. - Windows Coding Conventions


text:
Q: AddListener in foreach Suddenly problem with lambda in foreach statement:
IEnumerator RefreshNextFrame( Part Current )
{
    yield return null;
    if( Current.Nodes == null )
        yield break;
    Current.Nodes.ForEach( n => Debug.Log( n.name ) );//outputs node0, node1
    for( int i = 0; i < Current.Nodes.Count; i++ )
    {
        Node node = Current.Nodes[i];
        Button button = Instantiate( Resources.Load<GameObject>( "Prefabs/Button" ) ).GetComponent<Button>();
        button.transform.SetParent( content );
        button.GetComponentInChildren<Text>().text = node.name;
        button.onClick.AddListener( delegate
        {
            Debug.Log( button.GetComponentInChildren<Text>().text );
        } );
    }
}

Clicking on buttons always output node1

A: Just assign to a new local variable on each iteration and use that local variable for the AddListener.
EDIT
Quick example:
MyFunction will always receive 100 as the value of i on this:
for (int i=0; i<100; i++) {
    button.onClick.AddListener(() => MyFunction(i));
}

But if you do this it will work correctly:
for (int i=0; i<100; i++) {
    int iLocal = i;
    button.onClick.AddListener(() => MyFunction(iLocal));
}

A: Everything because of this code is in couroutine. Here is the answer http://answers.unity3d.com/answers/974195/view.html


text:
Q: Worker for Background Process in lwc javascript Im implementing a stopwatch in salesforce. It runs fine if Im in the same time where the stopwatch is ticking(lets say tab a) but if I switch to another tab(lets say tab b ) for a while the time is not accurate when I return to the TAB A.
I think that if i implement a worker function as a static resource I might achieve what Im hoping for i.e the clock to work accurately even Im working in TAB B.
I tried to implement worker class but the code fails when entered into the worker resource.
Here is the code
stopwatch.js
    start(event) {
            var worker = new Worker("/resource/webworker");
            worker.onmessage = function(e) {
            timeVal = e.data;
            console.log(e.data);
            };
    }

webworker.js
onmessage = function(e) {

    totalMilliseconds = 0;
    timeIntervalInstance;

        // Run timer code in every 1000 milliseconds
        this.timeIntervalInstance = setInterval(function() {

            // Time calculations for hours, minutes, seconds and milliseconds
            var hours = ( Array(2).join('0') + Math.floor((this.totalMilliseconds % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) ).slice( -2 );
            var minutes = ( Array(2).join('0') + Math.floor((this.totalMilliseconds % (1000 * 60 * 60)) / (1000 * 60)) ).slice( -2 );
            var seconds = ( Array(2).join('0') + Math.floor((this.totalMilliseconds % (1000 * 60)) / 1000) ).slice( -2 );

            // Output the result in the timeVal variable
            timeVal = hours + ":" + minutes + ":" + seconds;
            this.totalMilliseconds += 1000;
            postMessage(timeVal);
        }, 1000);
  }

Im not good with javascript can anyone guide me what Im doing wrong here?
Thank you.

A: Per the Locker API Viewer, you can't use any kind of worker. This feature is blocked because it cannot be regulated by Locker Service, and could pose a security risk. Instead, you might want to just record a time stamp of when the timer started, and again when it stops, so that you will have an accurate measurement of time. Alternatively, you'd have to use Visualforce in order to use a service worker.


text:
Q: What does returning a value really mean? return 0 is a convention that it will execute when there is no error and it will return 0.
There is also a difference in writing return  0 inside main() func and outside main() func.
But what does it actually mean to return a value?
It might be copy of some question. But I have read all the answers and then only making a new thread.
Geeks for Geeks says:

A: The August 4, 2022 working draft of the C standard, section 5.1.2.2.3 says:

If the return type of the main function is a type compatible with int, a return from the initial call
to the main function is equivalent to calling the exit function with the value returned by the main
function as its argument; reaching the } that terminates the main function returns a value of 0. If
the return type is not compatible with int, the termination status returned to the host environment
is unspecified.

The return value for any other function is user-defined.


text:
Q: How to convert a string into a float when reading from a text file Hey guys so I have a text file that I am trying to read from and receive every number string
and convert it into a float. But every time I try it, it says "cannont convert string to float". Why is this happening? Thanks!
try:
    input_file = open("Dic9812.TFITF.encoded.txt","r")
    output_fileDec = open("Dic9812.TFITF.decoded.txt","w")
    output_fileLog = open("Dic9812.TFITF.log.txt","w")
except IOError:
    print("File not found!")

coefficientInt = input("Enter a coefficient: ")
coefficientFl = float(coefficientInt)
constInt = input("Enter a constant: ")
constFl = float(constInt)

try:
    for line in input_file:
        for numstr in line.split(","):
            numFl = float(numstr)
            print(numFl)
except Exception as e:
    print(e)

The file looks like this:
135.0,201.0,301.0
152.0,253.0,36.0,52.0
53.0,25.0,369.0,25.0

It ends up printing the numbers but at the end it says:
cannot convert string to float:

A: At the end of the second line, you have a comma, so you have an empty string in the list. float('') raise an exception, hence your error:
for line in input_file:
    for numstr in line.split(","):
        if numstr:
            try:
                numFl = float(numstr)
                print(numFl)
            except ValueError as e:
                print(e)

As said in comments, avoid to catch Exception and try to have the minimum lines of code in a try/except to avoid silent errors.

A: Input f
135.0,201.0,301.0
152.0,253.0,36.0,52.0
53.0,25.0,369.0,25.0

Python f.py
import sys

for line in sys.stdin.readlines():
    fs = [float(f) for f in line.split(",")]
    print fs

Usage
$ python f.py < f

Output
[135.0, 201.0, 301.0]
[152.0, 253.0, 36.0, 52.0]
[53.0, 25.0, 369.0, 25.0]


text:
Q: Why is the map method (with division) returning NaN? The first function (codeScript) is used to "encrypt a number". The second (descrypter) is for "decrypting", as the name suggests:

const num1 = [1, 2, 3, 4];

const num2 = [4, 3, 2, 1];

const codeScript = (code1, code2, mult) => {

  console.log(code1)

  const map1 = code1.map(x => x * mult)
  code1 = []
  code1.push(map1)

  console.log(code1)

  console.log(code2)

  const map2 = code2.map(x => x * mult)
  code2 = []
  code2.push(map2)

  console.log(code2)

  descrypter(code1, code2, mult)
}

descrypter = (code1, code2, mult) => {

  const map3 = code1.map(function(item) {
    return item / mult;
  });
  code1 = []
  code1.push(map3)

  console.log(code1)

  const map4 = code2.map(function(item) {
    return item / mult;
  });
  code2 = []
  code2.push(map4)

  console.log(code2)
};

codeScript(num1, num2, 2);

However, the second function is returning me the NaN when dividing the items in the num1 and num2 array (code1, code2) by the "mult".

descrypter = (code1, code2, mult) => {

  const map3 = code1.map(function(item) {
    return item / mult;
  });
  code1 = []
  code1.push(map3)

  console.log(code1)

  const map4 = code2.map(function(item) {
    return item / mult;
  });
  code2 = []
  code2.push(map4)

  console.log(code2)
};

I thought the error was in the way it was performing the map, but now I don't know.

A: Currently you are adding a new list to a list (code1.push(map2)), making a list of lists. Instead you could either set code1 = map1 or use map1 as parameter to pass to descrypter

const num1 = [1, 2, 3, 4];

const num2 = [4, 3, 2, 1];

const codeScript = (code1, code2, mult) => {

  console.log(code1)

  const map1 = code1.map(x => x * mult)
  code1 = map1

  console.log(code1)

  console.log(code2)

  const map2 = code2.map(x => x * mult)
  code2 = map2

  console.log(code2)

  descrypter(code1, code2, mult)
}

descrypter = (code1, code2, mult) => {

  const map3 = code1.map(function(item) {
    return item / mult;
  });
  code1 = map3

  console.log(code1)

  const map4 = code2.map(function(item) {
    return item / mult;
  });
  code2 = map4

  console.log(code2)
};

codeScript(num1, num2, 2);

A: When you do this:
  const map2 = code2.map(x => x * mult)
  code1 = []
  code1.push(map2)

You're creating an array containing the "encrypted" array. You should change this to:
  const map1 = code1.map(x => x * mult)
  code1 = map1

in order to have an array of numbers. You should to the same with the rest of the "encryption" and "decryption" code.


text:
Q: Android:: Blocking main thread for worker thread to finish before executing other tasks in main thread I am executing some task in the UI thread and created a worker thread that does the networking stuff for me. However, I have something important that needs to be executed once the worker thread finishes. Could anybody please suggest me a solution?
{
    Main thread...
    worker thread created..and executed..
    //I need to wait here for the worker thread to finish//
    some useful task to be done
}

Thanks in advance!

A: You need to do things on the UI thread after worker has finished? Use runOnUiThread at the end of your worker or use AsyncTask with onPostExecute(). Blocking the UI thread while worker is running doesn't make any sense.

A: You don't. Blocking the UI thread violates the key rule of threading in Android.
Doing so can cause those annoying "Application not responding" dialogs, along with other problems.
From the Processes and Threads page of the developer docs:

So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread. Thus, there are simply two rules to Android's single thread model:
Do not block the UI thread
Do not access the Android UI toolkit from outside the UI thread

You should explore other solutions to what you need to accomplish. You need not give specifics on your problem, but ekholm's solution could work, as could simply calling a method in your Activity from the worker thread.


text:
Q: How to call multiple views in a single controller function I want to call other views in single controller function and want to change one view on clicking the link.
For example when I click the about_us link it should be open the about_us and when I click on contact_us link it should be replaced with about_us view but whole views remain same using jQuery and ajax.I don't know about jQuery and ajax. How it possible to do this?
My view code is

<a href="<?php echo site_url() ?>/about_us">About Us

<a href="<?php echo site_url() ?>/contact_us">Company Profile

<a href="<?php echo site_url() ?>/faq">Why Choose Jan Japan

my controller is
class Home extends CI_Controller
{
    $this->load->view('include/header');
    $this->load->view('top_strip');
    $this->load->view('top_menue);
    $this->load->view('about_us');
    $this->load->view('footer');
}

A: View(Header.php):

<a href="<?php echo site_url() ?>/about_us" onclick="loadaboutus()">About Us

<a href="<?php echo site_url() ?>/contact_us">Company Profile

<a href="<?php echo site_url() ?>/faq">Why Choose Jan Japan

in this view i have written inline JavaScript

onclick="loadaboutus()"

within  tag. so when user click on About Us link, loadaboutus() function of javascript will be call a controller's  loadaboutus() function.
Javascript-Ajax:
function loadaboutus()
{
$.ajax({
                type: "POST",
                url: "<?php echo base_url(); ?>home/loadaboutus",
                success: function (data) {
                   $('#divDynamic').html(data);
                }
            });
}

Controller:
function loadaboutus()
{
  $this->load->view('about_us');
}

A: You have three links:

*

*/home

*/contact_us

*/faq

These are three separate controllers. When the links are clicked, the page is reloaded.
So you need three controllers.
class Home extends CI_Controller
{
    public function index()
    {
        $this->load->view('include/header');
        $this->load->view('top_strip');
        $this->load->view('top_menu');
        $this->load->view('home_page');
        $this->load->view('footer');
    }
}

class About_us extends CI_Controller
{
    public function index()
    {
        $this->load->view('include/header');
        $this->load->view('top_strip');
        $this->load->view('top_menu');
        $this->load->view('about_us');
        $this->load->view('footer');
    }
}

class Contact_us extends CI_Controller
{
    public function index()
    {
        $this->load->view('include/header');
        $this->load->view('top_strip');
        $this->load->view('top_menu');
        $this->load->view('contact_us');
        $this->load->view('footer');
    }
}

This is probably not the ideal way of doing it however as you are a new it is a good learning step.

A: for this you have to make a common file template.php with the following code:
   foreach ($views as $view) {
      $this->load->view($view);
   }

now to called it from controller :
just do the following :
public function index()
    {
        $data=array('view1'=>"include/header",
                    'view2'=>"top_strip",
                    'view3'=>"top_menu",
                    'view4'=>"contact_us",
                    'view5'=>"footer"
          );
        $this->load->view('template',$data);
    }


text:
Q: Infix To postfix Evaluation using stack and array i am trying to convert infix to postfix but unable to get any output although program is free of error and logically correct. its just showing the value of m. I tried to print hello inside loop , but its unable to print that.I can't understand why its not going inside loop. Can't figure out the exact reason behind it.
#include <bits/stdc++.h>
#define m 21
using namespace std;
int isitoperattor(char c) //to find precdenec of operator
{
if(c=='+'||c=='-')
    return 1;
if(c=='*' || c=='/')
    return 2;
if(c=='('||c==')')
    return 3;
 }
  void infixtopostfix(char str[m]){
   char out[m];

  cout<<m<<endl;
  stack <char> s;
static int k;
for(int i=0;i<m;i++)

{

    cout<<"hello";
   if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z')){
    out[k]=str[i];
     k++;}

    else if (str[i]=='(')
        s.push(str[i]);

    else if (str[i]==')'){
        //int j=i-1;
        while(s.top()!='('){

            out[k]=s.top();
            s.pop();
            k++;
            //-;
        }
        s.pop();
    }
    else
    {

            if(isitoperattor(str[i]) && (isitoperattor(str[i])<isitoperattor(s.top()))){
                while(isitoperattor(s.top())>=isitoperattor(str[i])){
                      out[k]=s.top();
                      s.pop();
                      k++;
                      }
                     }

        }
            s.push(str[i]);

    }
}
while(!s.empty())
{
    out[k]=s.top();
    s.pop();
    k++;
}

//string out;

    for(int j=0;j<k;j++)
        cout<<out[j];
}
 int main()
{

  char str[m]="a+b*(c^d-e)^(f+g*h)-i";

   infixtopostfix(str);
   return 0;
}


text:
Q: How to stop PAM messages in auth.log for a specific script run with sudo? I've set up a bash script to run automatically (from crontab) with sudo privileges using this visudo solution.
Since the script requires multiple runs, it pollutes my /var/log/auth.log, so I disabled the TTY output (only for the specific script I designated in visudo) by following this solution successfully. By TTY, I mean this kind of log entry: [user] : TTY=unknown ; PWD=... ; USER=root ; COMMAND=....
But I'm left with the following 2 lines in /var/log/auth.log each time the script is run (it being run with sudo privileges). Since it runs many times, I have this output many many times, which is annoying:
Nov 01 00:00:00 1234567 sudo: pam_unix(sudo:session): session opened for user root by (uid=0)
Nov 01 00:00:00 1234567 sudo: pam_unix(sudo:session): session closed for user root

I'm aware of this question: How to stop sudo PAM messages in auth.log for a specific user?, which seems to allow the disabling of PAM messages per user.
But I couldn't find a solution to disable the above PAM message in /var/log/auth.log for a specific script only. Basically I'm looking for the equivalent of what I did for the TTY output with visudo, which carves-out from logging only  the specific script I've designated.
Any ideas?
(The system is running Ubuntu 18.04 LTS)

A: If the script is being run from crontab one option would be to run it from root's crontab (or the system one) so that sudo is no longer required.


text:
Q: How to obtain with PHP the last ID inserted if my primary key does not autoincrement I have a table in MySQL that for compatibility issues we assigned specific Primary Keys, therefore they can not be auto incremented.
Every time we insert a new topple (in PHP) we need to get back the latest ID inserted. It might sound stupid. but we do not generate the ID from PHP, it comes from an generic AJAX function, therefore we don't know the name of the variable containing the Primary Key, it always changes.
Is there a way, using PHP or MYSQL, to obtain the latest ID inserted for a primary key that does not auto-increment?
Unfortunately mysql_insert_id() and last_insert_id() do not work without auto_increment.
Thanks!

A: Head down to the comments section on this page.
http://php.net/manual/en/function.mysql-insert-id.php
And you should see some methods that might work for you.
I would try inserting the specific time_stamp and then calling that time_stamp insert again.
Dave does a good job of explaining it in this comment. Quoting him..

There is a lot of incorrect info here on "don't use AI" and "using max
  is equivalent".  Then you have people improperly advising you to use
  psuedo-random numbers
If you're really worried about the AI field not returning because of
  the inherent race conditions, just do a select statement based on the
  vars you just input.  If your vars are not unique, DON'T use these
  psuedo-random numbers.  When you have enough iterations, the
  probability that the one of these randoms becomes a duplicate gets
  pretty high.
Instead, just use the unix timestamp.  However, don't use
  UNIX_TIMESTAMP() in your query, because if you do, when you run your
  select statement right after, there's a possibility that you'll end up
  with a different timestamp.
Since date() continues to count up during the execution of the script,
  simply store date(U) into a variable or definition.  Then insert and
  select based on that.  Assuming you're not using mysql procedures:

<?php

define(UNIX_TIMESTAMP, date('U'));

$db->query("insert into table values('', 'a', 'b', 'c', 'd', '".UNIX_TIMESTAMP."'");
$res = $db->query("select id from table where a_col = 'a' and b_col = 'b' and c_col = 'c' and d_col = 'd' and temp_id = 'UNIX_TIMESTAMP'");

//...

?>

A: Following SQL statement will get last inserted id of PK.
Do it after your insert statement...
SELECT LAST_INSERT_ID() FROM tblName;

True, I forgot that you mentioned that your PK is not auto incremented. Then see the answer with timestamp solution. It's the only way I know that you can do this. But it is preferable to have auto increment field. Maybe you need to review your database scheme.


text:
Q: iPhone and Ipad crashes:reason: '*** setObjectForKey: object cannot be nil (key: objectid)' I am getting the following error
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: object cannot be nil (key: objectid)'

is it a dictionary or core data?I could not figure out where the crash is happening.Any idea?
2015-03-18 12:47:23.239 OneChannelApp[3039:6403] INFO: GoogleAnalytics 3.10 -[GAIBatchingDispatcher didSendHits:] (GAIBatchingDispatcher.m:219): 2 hit(s) sent
2015-03-18 12:47:27.804 OneChannelApp[3039:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: object cannot be nil (key: objectid)'
*** First throw call stack:
(0x30668f83 0x3ae19ccf 0x305a48f3 0xbf357 0x32ea06df 0x3301643f 0x32f33d63 0x32f33b6d 0x32f33b05 0x32e85d59 0x32b0362b 0x32afee3b 0x32afeccd 0x32afe6df 0x32afe4ef 0x32af821d 0x30634255 0x30631bf9 0x30631f3b 0x3059cebf 0x3059cca3 0x354a2663 0x32ee914d 0x20555d 0x3b326ab7)
libc++abi.dylib: terminating with uncaught exception of type NSException

A: This is more likely an NSDictionary error. And as it says, you are setting an object as nil.
Also, aren't you getting a line number or trace for the error?

A: Its a NSDictionay crash because the code data can save value nil value..
its a error of trying to save nil value in NSDictionay...


text:
Q: Proving every free action faithful. I can see this as clearly true because - assuming the action free - if $g_1 \not=g_2$, then $g_1 \cdot x \not= g_2 \cdot x$ for all $x \in X$ implies it holds true for some $x \in X$, so the actions is faithful.
However, our teacher defined faithful actions interms of the action induced homomorphism $ \phi : G \to S(X)$ and called the action faithful whenever $\phi$ is injective.
To prove the map injective, how should I proceed? If I define $\phi(g)=g \cdot x$, then $$g_1 \not= g_2 \implies \phi(g_1)\not= \phi(g_2)$$
proves $\phi$ is injective. I'm not sure if the mapping is defined correctly, however.
Also can someone show via an example how a faithful action isn't always free?

A: Note that a free action is precisely one with no fixed points, i.e. if $gx=x$ for some $x$, then $g=1$. A faithful action is just one where no $g$ acts trivially. I.e. if $gx=x$ for all $x$, then $g=1$.
Suppose $\phi$ is not injective, then for some $g_1\ne g_2$, $\phi(g_1)=\phi(g_2)$. Take an element $x\in X$.
Then $g_1x=\phi(g_1)x=\phi(g_2)x=g_2x$, so since the action is free, $g_1=g_2$. Contradiction. $\phi$ is injective.
The action by $D_3$ on the vertices of a triangle is faithful, but the reflections all fix one vertex, so it is not free. Alternatively $S(X)$ acting on $X$ is clearly faithful, but if $X$ has more than two elements, a transposition will fix the other elements of $X$, so that the action is not free.


text:
Q: iphone uidatepicker localization I facing a problem with localization in iphone date picker.I want the date picker to show dates only in English, but now it takes the language which is set to the region in iphone settings.I tried various things which was not useful like the below.

*

*setting the locale setting in the nib file of the uidatepicker.

*setting the locale through code
NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
[datePicker setLocale:locale];
[datePicker setCalendar:[locale objectForKey:NSLocaleCalendar]];

This did not work.If any one has good ideas to resolve the issue please help

A: I think this is a known issue. The date picker seems to rely on the current user's country settings which you cannot change from code. In fact, I don't know what the locale property is there for. It simply does nothing.


text:
Q: Unity is returning a null object when deployed to server but not on local machine Issue
The below code runs fine on my local machine, but once I've deployed it DependencyResolver.Current.GetService<ApplicationUserManager>() returns null, leading to this:
[NullReferenceException: Object reference not set to an instance of an object.]
   xxxx.API.Providers.<GrantResourceOwnerCredentials>d__2.MoveNext() in
   D:\xxxx\xxxx.API\Providers\ApplicationOAuthProvider.cs:36

when userManager.FindAsync(context.UserName, context.Password) is called. Please advise what my next steps should be? I'm not even sure where to start looking beyond server logs.
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = DependencyResolver.Current.GetService<ApplicationUserManager>();
        var roleManager = DependencyResolver.Current.GetService<ApplicationRoleManager>();

        ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }
        var userRoles = user.Roles.Select(r => r.RoleId);

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
           OAuthDefaults.AuthenticationType);
        ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
            CookieAuthenticationDefaults.AuthenticationType);

        oAuthIdentity.AddClaims(roleManager.Roles.Where(r => userRoles.Any(ur => ur == r.Id))
            .Select(r => r.Claims).ToList()
            .Select(c => new Claim("RoleClaims", c.ToString())));

        AuthenticationProperties properties = CreateProperties(user.UserName);
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        context.Validated(ticket);
        context.Request.Context.Authentication.SignIn(cookiesIdentity);
    }

Update
Had a play around with my deploy and have discovered the issue does not arise when I deploy the API to a separate folder from the matching website I'm hosting (My API and website are two separate projects).
So when I deploy the website to xxxx and API to xxxx/API the above issue occurs.
When I deploy the website to xxxx and API to xxxxAPI the above issue does not occur.
The hosting paths on my local machine mirror that of the remote so I presume this is a configuration issue. Does this indicate further to anybody what the problem might be?


text:
Q: Expressing $\forall$ in linear programing I'm doing a linear program to a game and I don't know how to express $\forall$ in linear programing (or if I had the right intuition to do it).
Here is the problem:
I have several vessels that are going to attack several rocket launchers:
I want to minimize the fuel consumption but still have enough weaponry capacity to destroy the rocket launchers.
\begin{array}
& & \mbox{Light Fighter} & \mbox{Heavy Fighter} & \mbox{Cruiser} & \mbox{Battleship}\\
\mbox{Weaponry} & 65 & 195 & 520 & 1300\\
\mbox{Defence} & 6015& 15037,5 & 40575 & 90300\\
\mbox{Consumption} & 20 & 75 & 300 & 500\\
\end{array}
$d_i$ being the number of rocket launchers.

*

*I want that for each rocket launcher it exists a vessel (or set of
vessels) that have individually more weaponry than the sum of hull
and the shield of the rocket launcher.

That is to say:
$$\forall y\in RL,\exists x_i\in V, \underbrace {\sum\alpha_i x_i}_\mbox{One or several vessels} >(H+S),\alpha_i\in W$$
$S=30, H=3000$

*

*I also want that for each vessel or set of vessels, the sum of hull
and the shield be greater or equal than the sum of the weaponry of
the worst case: each rocket launchers attacks the set of vessels (in
reality the worst case would have been that each rocket launcher
attacks one vessel alone, I think).

Therefore would the linear program be:
\begin{cases}
\min & 20x_1 &+ 75x_2 & +300x_3&+500x_4\\
&65x_1&+195x_2&+520x_3&+1300x_4&>3030\\
& 6015 x_1 &+ 15037,5x_2 &+ 40575 x_3 &+ 90300x_4 &> 104*d_i
\end{cases}
Therefore, I think I'm not quite sure of my gait, I'm trying to find a set of vessels minimizing their fuel conumption, able to destroy at least one rocket launcher but also able to support concentrated fire on it in order to be able to find an optimal set for all rocket launcher I would had to face.
Am I not missing something when trying to generalize with the last line of the linear program?


text:
Q: Python Pandas: add value if same date, then drop row I have this df:
c1        c2       c3
A     2017-03-17    1
B     2017-03-17    2
C     2017-05-27    8
D     2017-09-02    4

I want to add the values in c3 if the dates in c2 are the same and then remove the duplicate date row keeping the first.
Output should look like the following:
c1        c2       c3
A     2017-03-17    3
C     2017-05-27    8
D     2017-09-02    4

I am using df.drop_duplicates with keep=first to drop duplicates based on the date, but of course that also removes the value in c3 which I would like to keep.

A: Use groupby() with first on c1 and sum on c3
df.groupby('c2').agg({'c1': 'first', 'c3': 'sum'}).reset_index()

           c2 c1  c3
0  2017-03-17  A   3
1  2017-05-27  C   8
2  2017-09-02  D   4