text:
Q: Sorting by Specimen ID using Python script I have a python script to merge data files with the same format, remove duplicate headers only, adds two new blank lines between every every three lines, except first instance is the first four lines to include headers.
import glob

read_files = glob.glob("*.txt")

header_saved = False
linecnt=0
with open("merged_data.txt", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            header = next(infile)
            if not header_saved:
                outfile.write(header)
                header_saved = True
            for line in infile:
                outfile.write(line)
                linecnt=linecnt+1
                if (linecnt%3)==0:
                    outfile.write("\n\n")

Example input file text (infile 1):
Specimen_ID Measured_by_initals Measure_date    Sex Beak_length Pronotal_width  Right_fore_femur_length Right_fore_femur_width  Left_fore_femur_length  Left_fore_femur_width   Right_hind_femur_length Right_hind_femur_width  Left_hind_femur_length  Left_hind_femur_width   Right_hind_femur_area   Left_hind_femur_area    Right_hind_tibia_width  Left_hind_tibia_width   Notes
a   1   30-Dec-16   M   4   4   4   4   4   4   4   4   4   4   4   4   4   4
b   1   30-Dec-16   F   4   4   4   4   4   4   4   4   4   4   4   4   4   4   beak bent
c   1   30-Dec-16   M   4   4   4   4   4   4   4   4   4   4   4   4   4   4
d   1   30-Dec-16   F   4   4   4   4   4   4   4   4   4   4   4   4   4   4
e   1   30-Dec-16   F   4   4   4   4   4   4   4   4   4   4   4   4   4   4   pronotum deformed
f   1   30-Dec-16   F   4   4   4   4   4   4   4   4   4   4   4   4   4   4

Example input file text (infile 2):
Specimen_ID Measured_by_initals Measure_date    Sex Beak_length Pronotal_width  Right_fore_femur_length Right_fore_femur_width  Left_fore_femur_length  Left_fore_femur_width   Right_hind_femur_length Right_hind_femur_width  Left_hind_femur_length  Left_hind_femur_width   Right_hind_femur_area   Left_hind_femur_area    Right_hind_tibia_width  Left_hind_tibia_width   Notes
a   2   30-Dec-16   M   4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1
b   2   30-Dec-16   F   4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1
c   2   30-Dec-16   M   4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1
d   2   30-Dec-16   F   4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1
e   2   30-Dec-16   F   4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1
f   2   30-Dec-16   F   4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1

I would now like to modify the script so that it will sort the output by Specimen_ID, while keeping the two blank lines in between every three lines (i.e., there should be two blank lines after each unique Specimen_ID). Any suggestions on sorting the rows? I see a lot on sorting multidimensional data or python lists, but not much on 2D tables.
Also, I've encountered some odd behavior in that if I export my data from Excel in tab-delimited txt files, this script will only result in output that contains the contents of the first infile, but not the others. Yet, if I copy and paste the example data from this website into a txt file and use these as infiles, I have no problems. Does anyone know why I'm experiencing this issue?

A: I changed your test data to already be in a list by line.  This is roughly equivalent to what would be returned by readlines():
data_1 = """
Specimen_ID Measured_by_initals Measure_date    Sex Beak_length Pronotal_width  Right_fore_femur_length Right_fore_femur_width  Left_fore_femur_length  Left_fore_femur_width   Right_hind_femur_length Right_hind_femur_width  Left_hind_femur_length  Left_hind_femur_width   Right_hind_femur_area   Left_hind_femur_area    Right_hind_tibia_width  Left_hind_tibia_width   Notes
a   1   30-Dec-16   M   4   4   4   4   4   4   4   4   4   4   4   4   4   4
b   1   30-Dec-16   F   4   4   4   4   4   4   4   4   4   4   4   4   4   4   beak bent
c   1   30-Dec-16   M   4   4   4   4   4   4   4   4   4   4   4   4   4   4
d   1   30-Dec-16   F   4   4   4   4   4   4   4   4   4   4   4   4   4   4
e   1   30-Dec-16   F   4   4   4   4   4   4   4   4   4   4   4   4   4   4   pronotum deformed
f   1   30-Dec-16   F   4   4   4   4   4   4   4   4   4   4   4   4   4   4
""".split('\n')[1:-1]

data_2 = """
Specimen_ID Measured_by_initals Measure_date    Sex Beak_length Pronotal_width  Right_fore_femur_length Right_fore_femur_width  Left_fore_femur_length  Left_fore_femur_width   Right_hind_femur_length Right_hind_femur_width  Left_hind_femur_length  Left_hind_femur_width   Right_hind_femur_area   Left_hind_femur_area    Right_hind_tibia_width  Left_hind_tibia_width   Notes
a   2   30-Dec-16   M   4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1
b   2   30-Dec-16   F   4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1
c   2   30-Dec-16   M   4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1
d   2   30-Dec-16   F   4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1
e   2   30-Dec-16   F   4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1
f   2   30-Dec-16   F   4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1 4.1
""".split('\n')[1:-1]

This program removes the need to count lines, by reading in all of the data before writing any data back out:
headers = []
data = {}

# Go through the data for each file and sort by specimen id
for file_data in (data_1, data_2):
    headers.append(file_data[0])
    for line in file_data[1:]:
        # specimen id is first column of space separated data
        specimen_id = line.split(' ', 1)[0].strip()

        # store each line in a list per specimen id
        if specimen_id not in data:
            data[specimen_id] = []
        data[specimen_id].append(line)

# output the merged data
with open("merged_data.txt", "wb") as outfile:
    for specimen_id in sorted(data):
        outfile.write(headers[0] + '\n')
        for line in data[specimen_id]:
            outfile.write(line + '\n')
        outfile.write("\n\n")

A: I would probably recommend using pandas for working with tabular data in general, since you could easily just read in the data using from_csv(), then call sort_values(by='Specimen ID'), and then iterate over the output to print out the newlines.
Assuming these input files are tab-delimited files, here's how you would read them in and sort them, with pandas:
import pandas as pd
import glob
try:
    from io import StringIO
except ImportError:
    from StringIO import StringIO

dfs = []
for infile in glob.glob('*.txt'):
    # Infile can be a file path or an open file object
    df = pd.read_csv(infile, delimiter='\t')
    dfs.append(df)

df = pd.concat(dfs)     # Combine all the dataframes you loaded in.

df.sort_values(by='Specimen_ID')

# Write this to an intermediate StringIO object before the next step.
o_s = StringIO()
df.to_csv(o_s, sep='\t', index=False)
o_s.seek(0)
lines = o_s.readines()   # Get CSV as a list of lines.

At this point, you want to dump them out. Without your requirement that they have a blank line every 3 lines, you would just do df.to_csv('merged_text.csv', sep='\t', index=False) and you'd be good (sep to make it tab-delimited, index because pandas will add a numeric index when you read it in and you don't want that to be written out, since it is meaningless), but instead we read it into a list of lines so we can iterate over them and write extra lines as necessary:
# This will read through o_s 3 lines at a time and then append a blank "line"
# before writing it.
with open('merged_data.txt', 'w') as f:
    f.writelines(lines[0])   # Write the header line
    for ii in range(1, len(lines) // 3):
        # Write three lines at a time after the header, then an extra newline
        f.writelines(lines[(3 * ii + 1):(3 * (ii + 1) + 1)] + ['\n'])

If you don't want to use pandas for this, you can try the csv module:
import csv
from operator import itemgetter

lines_in = []
header_line = None
for infile in glob.glob('*.txt'):
    with open(infile, 'r') as f:
        reader = csv.reader(f, delimiter='\t')
        first_line = next(reader)
        if header_line is None:
            header_line = first_line

        # Append all the lines
        lines_in += list(reader)

# Making the assumption that Specimen_ID is always the first column
lines = sorted(lines, key=itemgetter(0))

# Write this out as a well-formatted CSV
o_s = StringIO()
writer = csv.writer(o_s, delimiter='\t')
writer.writerow(header_line)
writer.writerows(lines)

lines = o_s.readlines()

Once you have lines, you can use the same code I used above to write it to the output file.


text:
Q: return value inside html tag with beautifulsoup I'm trying to get the data from some social networks and put in the mongodb.
This is the information inside the html tag
347K

I was able to recover the 347K as follows
page = requests.get("https://twitter.com/cancaonova")
soup = BeautifulSoup(page.content, 'html.parser')
followers = soup.find_all(class_="ProfileNav-value")
seguidores = followers[2]
print seguidores.get_text()

However I wanted to get the data inside the data-cont tag I'm trying that way, but the result was: none
page = requests.get("https://twitter.com/cancaonova")
soup = BeautifulSoup(page.content, 'html.parser')
followers = soup.find('data-count')
print(followers)

Tks for you

A: Use 'element.attrs' to read attribute:
seguidores = followers[2]
datacount = seguidores.attrs['data-count']

A: rel_soup = BeautifulSoup('347K','html.parser')
rel_soup.span['data-count']

redpajama_set_name: RedPajamaStackExchange


text:
Q: Closed maps with non-compact fibers A geometric example of a non-closed map with compact fibers is obtained by taking a finite covering map and removing a point upstairs. This fragmentation of the fiber destroys closedness but retains compactness of fibers.
What are some geometric examples of a closed map with non-compact fibers? I'm not interested in things like the terminal map of an uncountable discrete space. Hoping for some pictures, the closer to manifolds the better.
My motivation is to justify the intuition for proper (universally closed separated) maps as "complete" families of compact spaces. I want to understand how a "mere" closed map might fail to warrant this description when the fibers aren't compact.

A: This is not a final answer, but it shows that there are serious restrictions for possible examples.
A map $p : Y \to X$ is not a closed map provided
(1) $X$ contains a countable non-closed set $A$ such that for each $x \in A$ the  fiber $F_x = p^{-1}(x)$ is a closed non-compact subset of $Y$. Note that if all one-point subsets of $A$ are closed in $X$, then the $F_x$ are automatically closed.
(2) $Y$ can be written as $Y = \bigcup_{m=1}^\infty C_m$ with relatively compact open $C_m \subset Y$ such that $C_m  \subset C_{m+1}$. Note that we do not assume that compact includes Hausdorff; if you want to assume this, then $Y$ is nothing else than a Hausdorff locally compact and $\sigma$-compact space. Example: $Y$ locally compact, separable and metrizable.
Proof. Write $A = \{ x_n \}$. For each $n$ the fiber $F_{x_n}$ is closed and non-compact, hence it cannot be contained in any $\overline{C}_m$. Define $Y_n = F_{x_n} \setminus C_n$ (which is nonempty and closed in $Y$) and $B = \bigcup_{n=1}^\infty Y_n$. We show that $B$ is closed in $Y$. In fact, for $y \notin B$ there exists $m$ such that $y \in C_m$. For $n \ge m$ we have $Y_n \cap C_m \subset Y_n \cap C_n = \emptyset$. Hence $D = B \cap C_m = \left(\bigcup_{n=1}^{m-1} Y_n \right) \cap C_m$ is closed in $C_m$ and $U = C_m \setminus D = C_m \setminus B$ is an open neigborhood of $y$ not meeting $B$. But by construction $p(B) = A$.
Remark:
(1) implies that the set $N$ of all $x \in X$ with a non-compact fiber $F_x$ has an accumulation point (in fact, each $\xi \in \overline{A} \setminus A$ is an accumulation point). The converse is true if $X$ is $T_1$ and first countable: If $x$ is an accumulation point of $N$, then there exists a countable $A \subset N \setminus \{ x \}$ such that $x \in \overline{A}$, i.e. $A$ is not closed.
The map $p : (\mathbb Z \times \mathbb R) \cup (\mathbb R \times \{ 0 \}) \to \mathbb R, p(x,y) = x,$ is an example of closed map with infinitely many non-compact fibers.


text:
Q: Android Spinner throws an exception I have an activity that contains a TextView, a ListView and a Spinner.
The spinner contains 4 items. onCreate, the spinner is assigned with one of the values that matches the current activity.
When user clicks on another Item a new Intent must be started (a new activity with the same layout).
However, I get an error when I leave uncommented the code regarding the spinner.
My Activity works fine without the "implements OnItemSelectedListener" and the implementation of the event.
So my code for the spinner :
public class ViziteIeri extends Activity implements OnItemSelectedListener{
...

protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.my_new_screen);
                Spinner spinner = (Spinner) findViewById(R.id.spinner1);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.liste_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
                spinner.setOnItemSelectedListener(this);
}

@Override
    public void onItemSelected(AdapterView<?> parent, View view,
            int pos, long id) {
        // An item was selected. You can retrieve the selected item using
        // parent.getItemAtPosition(pos)

        Toast toast1 = Toast.makeText(getApplicationContext(),""+parent.getItemAtPosition(pos), Toast.LENGTH_SHORT);
        toast1.show();

        Intent i = null;
        if(parent.getItemIdAtPosition(pos) == 1) {
            i=new Intent(ViziteIeri.this, ViziteAzi.class);
        }
        if(parent.getItemIdAtPosition(pos) == 2) {
            i=new Intent(ViziteIeri.this, ViziteMaine.class);
        }
        if(parent.getItemIdAtPosition(pos) == 3) {
            i=new Intent(ViziteIeri.this, ViziteViitor.class);
        }
        startActivity(i);

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }
}

So what am I doing wrong?
Sorry for the previous code. I changed the name of the activity just for pasting reasons. Now they are fixed. In my real app, of course the activities are properly named, otherwise I could not run the app (right?)
@CodeMonkey - here is the error log:
`07-29 23:56:56.155: D/AndroidRuntime(2474): Shutting down VM
07-29 23:56:56.155: W/dalvikvm(2474): threadid=1: thread exiting with uncaught exception (group=0x40015560)
07-29 23:56:56.174: E/AndroidRuntime(2474): FATAL EXCEPTION: main
07-29 23:56:56.174: E/AndroidRuntime(2474): java.lang.NullPointerException
07-29 23:56:56.174: E/AndroidRuntime(2474):     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1374)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at android.app.Activity.startActivityForResult(Activity.java:2827)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at android.app.Activity.startActivity(Activity.java:2933)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at com.softwarex.mydualscreenpro.ViziteIeri.onItemSelected(ViziteIeri.java:89)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at android.widget.AdapterView.fireOnSelected(AdapterView.java:871)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at android.widget.AdapterView.access$200(AdapterView.java:42)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:837)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at android.os.Handler.handleCallback(Handler.java:587)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at android.os.Handler.dispatchMessage(Handler.java:92)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at android.os.Looper.loop(Looper.java:123)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at android.app.ActivityThread.main(ActivityThread.java:3683)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at java.lang.reflect.Method.invokeNative(Native Method)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at java.lang.reflect.Method.invoke(Method.java:507)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-29 23:56:56.174: E/AndroidRuntime(2474):     at dalvik.system.NativeStart.main(Native Method)`

I changed back the activity name because it became confusing. So the activity name is "ViziteIeri"
And again... if I let the event assignment uncommented, I cannot run the activity without receiving the above error stack

A: Because of your Activity Class name is myActivity so
Use
i=new Intent(myActivity.this, ViziteAzi.class);

intead of
i=new Intent(ViziteIeri.this, ViziteAzi.class);

It will fix your OnItemSelectedListener problem.

A: I found my answer.
The solution is to set the Item in the spinner using:
spinner.setSelection(0,false);

before
spinner.setOnItemSelectedListener(this);

That solved my problem. No more errors.
Thank you for your time.


text:
Q: Too much recursion with GMaps4Rails I'm having a problem what I'm not able to fix right now..
Here is my code:
https://gist.github.com/foncho/0bd5d879221c85774346
The problem I have is too much recursion when trying to render all markers

x too much recursion

...ction V(){}K=V[H];K.get=function(a){var b=hf(this);a=a+"";b=qe(b,a);if(be(b)){if...

{main,g...try}.js (line 21, col 830)

x too much recursion

function qe(a,b){if(aa[H][ec]Zc)return a[b]};function P(a,b,c){a-=0;b-=0;...

{main,g...try}.js (line 13, col 20)

x too much recursion

....toUpperCase()+aVb)}function hf(a){a.gm_accessors_||(a.gm_accessors_={});re...

{main,g...try}.js (line 22, col 382)

Any ideas? Any help is welcome!
Thanks in advance


text:
Q: jstl  tags not working in jsp file, getting error in tomcat 7 I have problem using jstl tag <c:if> in jsp file. Basically I should make this as 2 questions although they are related.
The first question:
In my WEB-INF/lib, I put a jstl 1.2.jar
In my jsp file, I put this <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>.
In my jsp file, I use the <c:if> to do something. If the condition is true, it will shows some special message
Basically the contents inside <c:if> is not working, because the message is not shown even the condition is true.
But if I changed to use the older namespace, <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>. Others are not changed, then the if tag is working, because the message inside the if tag is shown.
My first question is why I have to use /jstl instead of /jsp/jstl in namespace. I am using jstl1.2.jar. so I am supposed to use the newer uri for 1.2. however, older uri works but not newer uir.
The second question:
I ignore the first question I have, and just use /jstl as my namespace just because it makes my web app work the way I want. However, when I deploy my web app into tomcat 7.X, it shows exceptions as the following:

org.apache.jasper.JasperException: /mywebapp.jsp (line: 35, column: 10)
  According to TLD or attribute directive in tag file, attribute test
  does not accept any expressions
  org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:42)

in /mywebapp.jsp line:35, column:10, that is < c:if> tag.
If I change the namespace from  <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%> to  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>, it can deploy in tomcat successfully but the functionality inside of < c:if> tag is not useful. other codes outside of <c:if> tag work though.
So I am very confused and really want to know how to fix this.
By the way, I am using servlet 2.5, jsp 2.0, jstl 1.2. I did try to upgrade the jsp2.0 to jsp2.1 in order to see if I can fix the first problem, but I have no idea how to upgrade jsp version.

A:
But if I changed to use the older namespace, <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>. others are not changed, then the if tag is working, because the message inside the if tag is shown.

That can happen if you have a standard.jar of JSTL 1.0 in the /WEB-INF/lib. Get rid of it. See also our JSTL wiki page. I by the way assume that you've untouched Tomcat's and JRE's own /lib folders and have not dropped any JSTL-related JARs in there, or have extracted the JSTL JAR's contents in a careless attempt to solve the problem.

By the way, I am using servlet 2.5, jsp 2.0, jstl 1.2. I did try to upgrade the jsp2.0 to jsp2.1 in order to see if I can fix the first problem, but I have no idea how to upgrade jsp version. I am very new to programming.

You should absolutely not provide any Servlet or JSP libraries in /WEB-INF/lib yourself. The servlet container (in your case, Tomcat) already ships with it. See also How do I import the javax.servlet API in my Eclipse project?
You only need to make sure that your web.xml root declaration complies whatever your servlet container supports. Tomcat 7 is a Servlet 3.0 compatible container, so your web.xml root declaration should look like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

    <!-- Config here. -->

</web-app>

A: I ran into this problem today and I just got it to work as described below. I do not know if this solution is fitted for everyone, but it did work for me. I am a novice in java, so it might not be the best solution.
STL JSP Error Fix - Jar File location for JSTL
1.
Change
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
TO:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
2.
Download below jar files and
COPY them to …/WEB-INF/lib folder.
https://repo.maven.apache.org/maven2/jakarta/servlet/jsp/jstl/jakarta.servlet.jsp.jstl-api/1.2.7/jakarta.servlet.jsp.jstl-api-1.2.7.jar
https://repo.maven.apache.org/maven2/org/glassfish/web/jakarta.servlet.jsp.jstl/1.2.6/jakarta.servlet.jsp.jstl-1.2.6.jar


text:
Q: Externalize angular configuration file ( config.json ) I have an angular application (war format) that run on a jboss application server. My actual architecture is: Front app ( angular ) and back app ( java ), the front calls back services using the rest api link, that is provided in the src/conf/config.json file.
This is my app config file :
{
"restApiUrl": "https://jboss_host:8443/back/rest/",
"ldapAuthentication" : true
}

So, my needs for now ( the client need) is to externalize this config file to change the rest api link easily, without make a rebuild or redeploiment process.
I can't use any further elements in my architecture ( revers-proxy, conf server ) because it going to be a brain teaser for the client production, or api database ( the DB connection is provided by the back service ).
Please can you advise.

A: If you do not want load config file over http, try to use config.js file.
Rename config.json to config.js and change content to this:
var config = {
  "restApiUrl": "https://jboss_host:8443/back/rest/",
  "ldapAuthentication" : true
}

Then include config file into index.html in your application:
<script type="text/javascript" src="config.js"></script>

In angular application you can access to this config via (<any>window).config.
For more convenient use create ConfigService like:
@Injectable({providedIn: 'root'})
export class ConfigService {
  getConfig(): Config { // You should create some model of your config too or you can use 'any'
    return (<any>window).config;
  }
}

A: @mpstv thank you for your replay.
I was able to solve this, by using the power of java servlet. The solution was adding to the project war the WEB-INF folder ( servlet.class + web.xml ) that will charge the config file from the filesystem and serve it to the angular, while HTTP call.


text:
Q: Separate Frame Buffer and Depth Buffer in OpenGL In DirectX you are able to have separate render targets and depth buffers, so you can bind a render target and a depth buffer, do some rendering, remove the depth buffer and then do more rendering using the old depth buffer as a texture.
How would you go about this in opengl? From my understanding, you have a framebuffer object that contains both the color buffer(s) and an optional depth buffer. I don't think I can bind several framebuffer objects at the same time, would I have to recreate the framebuffer object every time it changes(probably several times a frame)? How do normal opengl programs do this?

A: A Framebuffer Object is nothing more than a series of references to images. These can be images in Textures (such as a mipmap layer of a 2D texture) or Renderbuffers (which can't be used as textures).
There is nothing stopping you from assembling an FBO that uses a texture's image for its color buffer and a texture's image for its depth buffer. Nor is there anything stopping you from later (so long as you're not rendering to that FBO while doing this) sampling from the texture as a depth texture. The FBO does not suddenly own these images exclusively or something.
In all likelihood, what has happened is that you've misunderstood the difference between an FBO and OpenGL's Default Framebuffer. The default framebuffer (ie: the window) is unchangeable. You can't take it's depth buffer and use it as a texture or something. What you do with an FBO is your own business, but OpenGL won't let you play with its default framebuffer in the same way.

A: You can bind multiple render targets to a single FBO, which should to the trick. Also since OpenGL is a state machine you can change the binding and number of targets anytime it is required.


text:
Q: Print only the contents after a certain pattern match I have a string like this:
query:schema:query_result{cell=ab}: <timestamp>

I'd like to just print the ab and assign it to a variable. How can I do this with grep/sed?

A: You may try his,
$ var=$(grep -oP '=\K\w+' <<< "$str")

or
$ sed 's/.*=\(\w\+\).*/\1/' <<<"$var"
ab

A: You can also use awk:
s='query:schema:query_result{cell=ab}: <timestamp>'
awk -F '[=}]' '{print $2}' <<< "$s"
ab

To assign it to a variable:
var="$(awk -F '[=}]' '{print $2}' <<< "$s")"


text:
Q: Java HttpsURLConnection - TwitchAPI - Update Channel Information I tried to create a java Tool to change Twitch Channel Informations (status / game / delay). In the Documentation is an example with curl for working with the API to update channel informations:
curl -H 'Accept: application/vnd.twitchtv.v3+json' -H 'Authorization: OAuth <access_token>' \
-d "channel[status]=Playing+cool+new+game!&channel[game]=Diablo&channel[delay]=0" \
-X PUT https://api.twitch.tv/kraken/channels/test_channel

I tried to recreate this in Java with HttpsURLConnection. But I get the Error Response Code 400 and I dont have any idea what could be wrong with my sourcecode.
The Response:{"error":"Bad Request","message":"Missing required parameter channel","status":400}
My sourcecode: http://pastebin.com/F1QyCULu
I hope anyone can help me with this problem.

A: Okay I found a way how it works.
I removed the URLEncoder and just replaced spaces with plus String sendData = "channel[" + key + "]=" + data.replace(' ', '+');
I set the content-type to application/x-www-form-urlencoded apiConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
and thats it.


text:
Q: Unknown function 'exists' I'm a beginner.
I have two labels in my database; user, film. I have a relationship type called [:WATCHLISTED] between those two nodes. I want to get the usernames and film's names and whether they've added that film to their watchlist or not. Here's what I've written so far:
    MATCH (n),(f)
RETURN n.username AS username,f.name AS name, exists((n)-[:WATCHLISTED]->(f)) AS watchlisted

But I get this error:
     Neo.ClientError.Statement.SyntaxError: Unknown function 'exists' (line 2, column 47 (offset: 68))
"RETURN n.username AS username,f.name AS name, exists((n)-[:WATCHLISTED]->(f)) AS watchlist"
                                                       ^

What am I doing wrong? I can't see it. Thank you for you attention.
EDIT:
I wrote EXISTS() instead of exists() and it worked. I don't know why. Good day.


text:
Q: I want to redirect user to a webpage when a button is clicked with a parameter comes from another function? I'm working on a course project which I'm really struggling. I tracked the clicks of the user on a set of images, this is the n variable of my program and the maximum click number is 3. I want to redirect the user to another webpage when a button is clicked and the webpage that I'll redirect will be determined by the n variable, 1 - 2 or 3. The user will be redirected different pages when a button is clicked in terms of the n variable. I'm attaching my code below, please help. I want to add that the index parameter in the increment function attached to the images in the html code. Increment function is working without a problem also. For example I tried the case when the n = 1 and user clicked the button.
function increment(index) {
        var n = 0;
        if (n < 3) {
            n++;
        }

        if (n == 1) {
            document.getElementById("gameButton").onclick = redirect (increment(index)) {
            location.href = "remaining8.html";
        }
   }

A: Once you redirect to the new page, you lose the value of "n" because you have loaded a whole new page.
You could open the url in a new tab/window in which case, I can suggest some coding. Or you could store the value of "n" in a cookie or localstorage, but yet again, different code.
You could also open these URLs in an iframe and then you would still be on the same page when you click it again.
what are you actually trying to do?

A: Your redirect() has already been declared and inside the second if block you're redeclaring it the wrong way. You don't want to check n==1 inside your increment function, you want to do it on the click event, like this:
document.getElementById("gameButton").onclick = () => {
   switch(n) {
      case 1:
         window.location.href = "remaining8.html";
         break;
      case 2:
         // do something
         break;
      case 3:
         // do something
         break;
}

But as for your Original request, I can't give you the right answer if I don't see your html. Post your html here and I'll post back with a solution.
Also instead of redirecting to another page, you could just open the new web page in a separate tab, that way you never loose n. Also I believe discarding that increment function and incrementing the value of n on the click event, is a better solution, the solution is below:
 var n = 0;

 document.getElementById("gameButton").onclick = function() {
    if(value == 3) {
      value = 1;
    } else if(value < 3) value++;

    switch(n) {
      case 1:
         window.location.href = "remaining8.html";
         break;
      case 2:
         // do something
         break;
      case 3:
         // do something
         break;
   }
}

A: You could pass the n parameter along to the redirected page:
if (n == 1) {
    document.getElementById("gameButton").onclick = redirect (increment(index)) {
        location.href = "remaining8.html";
    }

Change the location.href to just pass the n variable ("remaining8.html?index=n") then on the redirect page it can acquire it and thus continue your increment process.
Here is a post about reading the url paramaters:
How to get the value from the GET parameters?
Of course putting it in a cookie or localstorage would be most likely the best answer to keep your count across those page redirects since javascript can read cookies quite nicely.


text:
Q: Exception automating Excel 2007 with Powershell when calling Workbooks.Add() The following code throws an exception in Powershell V1 (Excel 2007):
$E = New-Object -COM "Excel.Application"
$E.Visible = $True
$wb = $E.Workbooks.Add() #<<<Exception here

The error says that the format might be old or that the type library is not valid (translated from Spanish). A similar script for Word works just fine.

A: Adapted to Powershell from one of the solutions proposed in MS Help and Support Article 320369.
$ci = new-object system.globalization.cultureinfo "en-US"

$e = New-Object -COM "Excel.Application"
$e.Visible = $True
$e.UserControl= $True
$books = $e.Workbooks
$books.PSBase.GetType().InvokeMember( `
       "Add", `
       [system.reflection.bindingflags]::InvokeMethod, `
       $null, $books, $null, $ci)

From the same article:

When you use one of these workarounds for a computer where the regional settings
  do not match the current language version of Office, you should be familiar with
  how Excel behaves and how Excel will interpret data that might be formatted for
  a specific locale.

A: I had this issue when trying to open a workbook. I added this line:
[threading.thread]::CurrentThread.CurrentCulture = 'en-US'

A: Office interop assemblies seem to have this problem when the current culture is not en-US. The obvious workaround is to set the culture.
It's important to run the whole thing as a single command on the interactive console, since PowerShell V1 always creates a new thread for each command invocation.
PS C:\Users\jachymko> $e = new-object -com excel.application
PS C:\Users\jachymko> $e.workbooks.add()
Exception calling "Add" with "0" argument(s): "Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))"
At line:1 char:17
+ $e.workbooks.add <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

PS C:\Users\jachymko> & {
>> [threading.thread]::CurrentThread.CurrentCulture = 'en-US'
>> $e = new-object -com excel.application
>> $e.workbooks.add()
>> $e.visible=1
>> }
>>


text:
Q: Translating SQL Queries to LINQ How do I translate SQL Queries to LINQ?
Can you please help me translate the following SQL query to LINQ?
SELECT  Top 1 @SalesRepID = Part.KUNN2
FROM x Part  with(nolock)
JOIN y UserCustomer with(nolock)
ON Part.KUNN2 = UserCustomer.Customer
LEFT JOIN z[User] with(nolock)
ON UserCustomer.UserId = [User].UserId
AND [User].UserDisabled != 'Y'
WHERE (Part.PARVWxx = 'ZP' or Part.PARVWxx = 'ZR' )
AND Part.KUNNRxx =  @Customer
ORDER BY Part.KUNNRxx, Part.PARVWxx DESC

A: You can play with the following here: https://dotnetfiddle.net/wcqLUx It might not be exactly what you need; it will get you started though. I needed to make some assumptions; you can clear those up in the fiddle. The following is the best that I could do in 20 minutes or so.
void Main()
{
    IEnumerable<User> Users =
        new List<User> { new User { UserId = 0, UserDisabled = "N" } };
    IEnumerable<Part> Parts =
        new List<Part> { new Part { SalesRepId = 0, PARVWxx = "ZP", KUNNRxx = "@Customer" } };
    IEnumerable<UserCustomer> UserCustomers =
        new List<UserCustomer> { new UserCustomer { UserId = 0, Customer = 0 } };

    var query =
        from p in Parts
        join y in UserCustomers
        on p.SalesRepId equals y.Customer
        select new { p, y } into inner
            join z in Users
            on inner.y.UserId equals z.UserId
            where ! z.UserDisabled.Equals("Y") &&
            inner.p.PARVWxx.Equals("ZP") &&
            inner.p.KUNNRxx.Equals("@Customer")
            select inner.p.SalesRepId;

    foreach(var result in query)
    {
        Console.WriteLine(result);
    }
}

// Define other methods and classes here
public class Part
{
    public int SalesRepId { get; set; }
    public string PARVWxx { get; set; }
    public string KUNNRxx { get; set; }
}

public class User
{
    public int UserId { get; set; }
    public string UserDisabled { get; set; }
}

public class UserCustomer
{
    public int UserId { get; set; }
    public int Customer { get; set; }
}


text:
Q: Return all pairs from a list in Python 3.4 This code works in Python 2.7, but not in 3.4.
import numpy as np
import itertools

a = [[3,7,9],[2,7,5],[6,9,5]]

def all_pairs(a, top=None):
    d = collections.Counter()
    for sub in a:
        if len(a)<2:
            continue
        sub.sort()
        for comb in itertools.combinations(sub,2):
            d[comb]+=1
    return sorted(np.array([i[0] for i in d.most_common(top)]).tolist())

This is the result I expect:
[[2, 5], [2, 7], [3, 7], [3, 9], [5, 6], [5, 7], [5, 9], [6, 9], [7, 9]]

But using Python 3.4, I get this traceback:
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    prev_pairs()
  File "", line 102, in all_pairs
    sub.sort()
AttributeError: 'map' object has no attribute 'sort'

Also, when I add just one element, I get nothing:
all_pairs([3,7,9])
[]

# Expected to get:
[[3,7],[3,9],[7,9]]

Is there a better way to write this code to solve both of these issues?

A: In Python 2, map() produces a list, which has the method sort(). In Python 3, map() produces a map object, which acts as a lazy generator and does not have the method sort(). If you want to use sort() on it, you'll have to pass that object to list() first:
sub = list(sub)
sub.sort()

Of course, if you're doing that, you might as well just use sorted(), which works on Python 3 map objects as well as list objects:
sub = sorted(sub)


text:
Q: Matching records that do not contain a substring in a array of nested fields elasticsearch I am working with Elasticsearch 8, lets say we have two documents in our index:
[
    {
        "field1": "value1",
        "field2": [
            {
                "nestedField1": "nested value 1",
                "nestedField2": "rock paper scissors"
            },
            {
                "nestedField1": "nested value 2",
                "nestedField2": "paper scissors"
            }
        ]
    },
    {
        "field1": "value2",
        "field2": [
            {
                "nestedField1": "nested value 1",
                "nestedField2": "rock scissors"
            },
            {
                "nestedField1": "nested value 2",
                "nestedField2": "scissors"
            }
        ]
    }
]

Now I want to write a query such that we can fetch the record in which field2.nestedField2 does not contain the word paper.
Below is what I have so far:
{
    "query": {
        "bool": {
            "must": {
                "match_all": {}
            },
            "filter": {
                "bool": {
                    "must_not": [
                        {
                            "match": {
                                "field2.nestedField2": "paper"
                            }
                        }
                    ]
                }
            }
        }
    }
}

I can't seem to get it to work. Can someone help me point out where I am going wrong?

A: The query block is not correct. Nested fields can not search like this. you can find your answer here https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html.


text:
Q: function st_intersects(bytea, bytea) is not unique When trying to combine two tables and export the result to a csv file, I am getting this error i.e. function st_intersects(bytea, bytea) is not unique.

A: The problem is that you use the wrong data type (bytea) for your geometrical data.
PostgreSQL can convert between bytea and geometry / geography implicitly:
\dC bytea
                         List of casts
   Source type   | Target type |      Function      | Implicit?
-----------------+-------------+--------------------+-----------
 bytea           | geography   | geography          | yes
 bytea           | geometry    | geometry           | yes
 geography       | bytea       | bytea              | yes
 geometry        | bytea       | bytea              | yes
[...]
(7 rows)

Now there are three functions st_intersects:
\df st_intersects
                                  List of functions
 Schema |     Name      | Result data type |       Argument data types        | Type
--------+---------------+------------------+----------------------------------+------
 public | st_intersects | boolean          | geog1 geography, geog2 geography | func
 public | st_intersects | boolean          | geom1 geometry, geom2 geometry   | func
 public | st_intersects | boolean          | text, text                       | func
(3 rows)

Now following its function type resolution rules, PostgreSQL has no way to determine if you want the first or the second of these functions, which causes the error message.
Solutions:

*

*Use the appropriate data type (geometry or geography) in your table definitions.

*Use an explicit cast, like the error message tells you:
st_intersects(CAST (g1 AS geometry), CAST (g2 AS geometry))

I think it was a bad choice of PostGIS to make both casts implicit.


text:
Q: Linking issue in a makefile I am writing a compiler using Bison and Flex and have been working until recently with a make all target (I know its not that good of an idea). I am now remaking my directory structure and remaking the makefile properly. Currently I have:
/Compiler
--- /src
---------- c_parser.y
---------- c_lexer.l
---------- AST.cpp
---------- AST.h
---------- Context.cpp
---------- Context.h
--- /bin
I want to obtain bin/c_codegen which depends on AST, Context and the outputs of bison and flex (c_parser.tab.c c_parser.tab.h c_lexer.yy.c). However c_lexer.yy.c also depends on c_parser.tab.h which is created in the src/ directory. This is throwing errors of undeclared functions (which are declared in c_parser.tab.h), in the rule:
bin/lex.yy.o: src/lex.yy.c src/c_parser.tab.h
    g++ -std=c++11 -w -I ./src -c -o bin/lex.yy.o src/lex.yy.c

Error:
src/lex.yy.c: In function 'void yy_init_buffer(YY_BUFFER_STATE, FILE*)':
src/lex.yy.c:1690:59: error: 'fileno' was not declared in this scope
         b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;

I believe this has to do with searching for the header files and therefore tried using the -I flag but it did not work. The full make file is:
bin/c_codegen: bin/lex.yy.o bin/c_parser.tab.o bin/AST.o bin/context.o
    g++ -std=c++11 -w -I ./src -o bin/c_codegen bin/lex.yy.o bin/c_parser.tab.o bin/AST.o bin/context.o

bin/lex.yy.o: src/lex.yy.c src/c_parser.tab.h
    g++ -std=c++11 -w -I ./src -c -o bin/lex.yy.o src/lex.yy.c

bin/c_parser.tab.o: src/c_parser.tab.c src/c_parser.tab.h
    g++ -std=c++11 -w -c -o bin/c_parser.tab.o src/c_parser.tab.c

bin/AST.o: src/AST.cpp src/AST.h
    g++ -std=c++11 -w -c -o bin/AST.o src/AST.cpp

bin/context.o: src/context.cpp src/context.h
    g++ -std=c++11 -w -c -o bin/context.o src/context.cpp

src/c_parser.tab.c src/c_parser.tab.h: src/c_parser.y
    win_bison -d -o src/c_parser.tab.c -v src/c_parser.y

src/lex.yy.c: src/c_parser.tab.h
    flex  -o src/lex.yy.c src/c_lexer.l

all:
    flex  -o src/lex.yy.c src/c_lexer.l
    win_bison -d -o src/c_parser.tab.c -v src/c_parser.y --warnings=none
    g++ -std=c++11 -w -o bin/c_codegen src/lex.yy.c src/c_parser.tab.c src/AST.cpp src/context.cpp

clean:
    rm -f src/lex.yy.c src/c_parser.tab.h src/c_parser.tab.c bin/*.o bin/c_codegen tmp_*.txt

A: Found the problem for those interested:
Turns out that I hadn't noticed that at the same time I made the new makefile I had also introduced new rules in my lexer that use strdup. I had tried this changes in a linux computer. Then now working in my own computer with minGW it was failing due to the known problem of minGW with string conversion problems, and not with the makefile.


text:
Q: Where is '/host' declared for mount in Wubi (Ubuntu 9.10)? I'm using Wubi (ubuntu 9.10), and I couldn't find where '/host' mountpoint is declared for mounting. There's no entry in fstab, but it's listed in /proc/mount and mounted at boot time. Any ideas?

pedroel@ubuntu:~$ cat /proc/mounts

rootfs / rootfs rw 0 0
none /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0
none /proc proc rw,nosuid,nodev,noexec,relatime 0 0
udev /dev tmpfs rw,relatime,mode=755 0 0
/dev/sda1 /host fuseblk rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other,blksize=4096 0 0
/dev/loop0 / ext4 rw,relatime,errors=remount-ro,barrier=1,data=ordered 0 0
none /sys/kernel/security securityfs rw,relatime 0 0
none /sys/fs/fuse/connections fusectl rw,relatime 0 0
none /sys/kernel/debug debugfs rw,relatime 0 0
none /dev/pts devpts rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000 0 0
none /dev/shm tmpfs rw,nosuid,nodev,relatime 0 0
none /var/run tmpfs rw,nosuid,relatime,mode=755 0 0
none /var/lock tmpfs rw,nosuid,nodev,noexec,relatime 0 0
none /lib/init/rw tmpfs rw,nosuid,relatime,mode=755 0 0
/dev/loop1 /home/pedroel/Downloads ext4 rw,relatime,errors=remount-ro,barrier=1,data=ordered 0 0
binfmt_misc /proc/sys/fs/binfmt_misc binfmt_misc rw,nosuid,nodev,noexec,relatime 0 0
gvfs-fuse-daemon /home/pedroel/.gvfs fuse.gvfs-fuse-daemon rw,nosuid,nodev,relatime,user_id=1000,group_id=1000 0 0
/dev/mapper/isw_efhafcifi_RAID_Volume01 /media/RAID_D fuseblk rw,nosuid,nodev,relatime,user_id=0,group_id=0,default_permissions,allow_other,blksize=4096 0 0

pedroel@ubuntu:~$ cat /etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid -o value -s UUID' to print the universally unique identifier
# for a device; this may be used with UUID= as a more robust way to name
# devices that works even if disks are added and removed. See fstab(5).
#
#
proc            /proc           proc    defaults        0       0
/host/ubuntu/disks/root.disk /               ext4    loop,errors=remount-ro 0       1
/host/ubuntu/disks/pedro.disk /home/pedroel/Downloads               ext4    loop,errors=remount-ro 0       1
/host/ubuntu/disks/swap.disk none            swap    loop,sw         0       0
/dev/fd0        /media/floppy0  auto    rw,user,noauto,exec,utf8 0       0

Thanks in advance,
Pedro

A: It's specified as the "root device" - I'm guessing in GRUB's configuration, /boot/grub/menu.lst, or in the Windows bootloader (C:\boot.ini or bootcfg) - then mounted in the initramfs.


text:
Q: Using awk to find a string in a file So I want to grab a string from a file, file contains data:
----------------------------------------------------
Id   Name      CreationDate         Comment
----------------------------------------------------
1    testing    19.10.11             created by jag

2    develop    19.10.12             created by jag

3    array      19.10.12             created by jaguuuu

4    start123   19.10.12             created by akj

I want to grep both start123 but using only start because following number changes from time to time. So it could be start456, start567. But it will start with start****.
This is what I tried so far:
awk '$0 ~ arr{print NR-1 FS b}{b=$0}' arr="start" /filepath
echo "string found : $arr"

Updating:
Also I want to extract only start123 from second column which could be in any row from 1-4 or 1-whatever number. Once I got the string "start123", want to store it in an variable.
Sorry for not being clear initially.
So if I try to sort it via comment = created by akj and print out start123 still. I think it will be just an && statement.
Will something like this work:
arr=$(awk -v str=start '$2 ~ "^" str "[0-9]*" { print $2 }' /filepath)
 if [ -z "$arr" ]
 then echo "string not found"
 else echo "String found: $arr"
 fi

It is not working for some reason. Any help would be appreciated.
Thanks
Kyle

A: You can use the -o option of grep to print just the part of the file that matches the regular expression. In this case, it's start followed by any number of digits.
str=start
if arr=$(grep -o "$str[0-9]*" /filepath)
then echo "string found: $arr"
else echo "string not found"
fi

If you only want to find it in column 2, you can use awk:
arr=$(awk -v str=start '$2 ~ "^" str "[0-9]*" { print $2; exit; }' /filepath)
if [ -z "$arr" ]
then echo "string not found"
else echo "String found: $arr"
fi

A: If you have GNU awk:
gawk 'match($0, /(start[0-9]+)/, m) {print m[1]; exit}'

documentation: http://www.gnu.org/software/gawk/manual/html_node/String-Functions.html#String-Functions


text:
Q: Refresh Embedded Excel Data in Powerpoint Charts I'm trying to automate the creation of a PowerPoint deck that I create a few times a week. I use a program called Alteryx to update the embedded excel files for all my charts in PowerPoint and that part works great. The problem that I have is that once I open PowerPoint, all the charts look the same as they originally were. It's only when I click edit data, that PowerPoint seems to read the excel changes and updates the chart. I have over 50 charts that I need to update, and clicking edit data on each one is very time consuming.
Is there a macro that can be created that will refresh all charts in my deck?
Thank you in advance for your time!
Update 1
I have tried using the following code from another post, but it results in 50 open workbooks.
Dim pptChart As Chart
Dim pptChartData As ChartData
Dim pptWorkbook As Object
Dim sld As Slide
Dim shp As Shape

For Each sld In ActivePresentation.Slides
    For Each shp In sld.Shapes
        If shp.HasChart Then
            Set pptChart = shp.Chart
            Set pptChartData = pptChart.ChartData
            pptChartData.Activate
            shp.Chart.REFRESH

            On Error Resume Next
            On Error GoTo 0

        End If
    Next
Next

Set pptWorkbook = Nothing
Set pptChartData = Nothing
Set pptChart = Nothing

I tried using the following code to open and close all the embedded workbooks, but it results in an error at this part "ActiveWindow.View.GotoSlide s.Slideindex"
Sub refreshchart()
    Dim ppApp As PowerPoint.Application, sld As Slide
    Dim s As PowerPoint.Shape
    Dim gChart As Chart, i As Integer
    ppApp.Visible = True
    i = 3
     Set sld = ActivePresentation.Slides(i)
    sld.Select

For Each s In ActivePresentation.Slides(i)
    If s.Type = msoEmbeddedOLEObject Then
      s.Select                               'select the object
        s.OLEFormat.Activate                 'Activate it (like 2x click))
        ActiveWindow.Selection.Unselect      'To let it close
        ActiveWindow.View.GotoSlide s.Slideindex  'make current slide active
     End If
Next s

 End Sub

A macro that opens the workbooks to refresh the charts and automatically closes them would be great. Thank you!


text:
Q: Proper indexing for SELECT with OR condition I want to get all the rows where sub string is in the first/last name.
Then I want to order it by the exact match first and limit to 5 (pagination basically)
Query works well until the table is getting huge, so I wonder if I can better tune it.
SELECT id, first_name, last_name, (first_name='nir' OR last_name='nir') exact_match
FROM users
WHERE first_name like '%nir%'
      OR last_name like '%nir%'
Order by exact_match desc, last_name, first_name
limit 5 offset 0;

create table users(
id int ,
first_name varchar(100),
last_name varchar(100),
primary key(id),
key first_name(first_name),
key last_name(last_name));

insert into users values(1,'anir','asd');
insert into users values(2,'ansir','asnird');
insert into users values(3,'nir','asnird');
insert into users values(4,'nixr','nir');
insert into users values(5,'nsixr','nsir');

A: It's difficult to improve this query very much because of the prefix wildcard.
Without any changes, the query execution plan shows it will not make use of your indexes:
EXPLAIN SELECT id, first_name, last_name, (first_name='nir' OR last_name='nir') exact_match
FROM users
WHERE first_name like '%nir%' OR last_name like '%nir%'
ORDER BY exact_match desc, last_name, first_name
LIMIT 5 OFFSET 0\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: users
   partitions: NULL
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 5
     filtered: 36.00
        Extra: Using where; Using filesort

You can improve it a little bit by creating a compound index:
ALTER TABLE users ADD INDEX idx_names (first_name, last_name);

Which gives the following query execution plan:
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: users
   partitions: NULL
         type: index
possible_keys: NULL
          key: idx_names
      key_len: 206
          ref: NULL
         rows: 5
     filtered: 36.00
        Extra: Using where; Using index; Using filesort

As you can see, this will make use of the compound index, However, if I understand correctly, it only does so after first having filtered the table  using the where condition.

A: How about a compromise -- assume that the user is asking about the beginning of either the first or last name.  This will work efficiently for a "huge" table:
( SELECT id, first_name, last_name
    FROM tbl
    WHERE first_name LIKE 'nir%' )
UNION DISTINCT
( SELECT id, first_name, last_name
    FROM tbl
    WHERE last_name LIKE 'nir%' )
ORDER BY (first_name = 'nir' OR last_name = 'nir') DESC,
    last_name,
    first_name
LIMIT 5, 0

And toss the two indexes you have, replacing them by two composite indexes:
INDEX(last_name, first_name, id),
INDEX(first_name, last_name, id)

Another approach -- Do the above; if you don't get 5 names, then go back to your slower query.  This will help the overall performance of the system.  But it will lead to individual searches being either fast (my query) or slow (needing both queries).


text:
Q: Eventually periodic orbit? I am doing a self study on dynamical systems.
I faced the following exercise in this book:
Prove that any point on $f:[0,1]\to [0,1],\ f(x)=3x \mod 1$ is eventually periodic iff its a rational number.
I find the problem really hard comparing to the simple material that the textbook covered so far and consider my answer sophisticated for the question. So here is my solution:
Suppose $a=\frac{m}{n}$ is the assumed point. Eventually we have to prove that there exist $k,k'$ so that $3^k m \overset{n}{\equiv}3^{k'}m$ which then has an answer using Euler's totient function wether $3|n$ or not. The "only if" case is even easier because there should exist integer $n$ such that $n=3^{k-k'}a$ which makes $a$ rational. Does anybody know any simpler answer or a  hint for the simpler answer?

A: Multiplying by $3$ can only make the denominator of a rational number smaller, so if you start with a fraction $x\in[0,1]$, the iterates $f(x)$, $f(f(x))$, etc. are restricted to a finite set of numerators and denominators, hence must eventually return to an earlier value, at which point the process becomes periodic.


text:
Q: Is there a way to interact with other records in the same transaction using record triggered flow? I need to access to all the records that are in the same transaction using a record triggered flow as you can do with triggers using Trigger.New() that returns you all the record in the same transaction and loop over them. Is there a way to achieve that behaviour using record triggered flows?

A: As far as I'm aware, you can't share state between flows in the same transaction directly. From your given example in the comments, there are at least two possible solutions to the "let's build our own rollup feature" scenario.
The first solution is to use a post-save Record-Triggered Flow on the child to update the parent, and then use a pre-save Record-Triggered Flow on the Parent to count the children (see this answer on how to get collection size in Flows). This may have performance problems scaling up, but it could work for most typical use cases (presuming you're avoiding Parent-Child Data Skew). The last I recall, though, you still can't update the parent more than 12 times in a single DML statement, so bulkification would likely be limited to just 12 records in a single DML statement.
The second solution is to write an InvocableMethod; this method is bulkified, so all flows that stop at this element at the same time will be visible to Apex. You can then build out a collection for each interview to have essentially a shared state. Of course, now we're talking about writing some code, but the overall solution would use far less code than a trigger. Because of the aforementioned limit of 12 simultaneous updates to a single parent, I would recommend you set a flag in the return value, such that only one child per parent is allowed to update the parent, and the others would skip to the next step/end.


text:
Q: Swift generic T.Type becomes T.Protocol Swift 5.1
I'm writing a class that has a generic parameter T, and one of its methods accepts a type as an argument, where the type extends from T.Type.  See foo1 below:
public protocol P {
}

public class C: P {
}

public class X<T> {
    public func foo1(_ t: T.Type) { // The function in question
    }

    public func foo2(_ t: P.Type) {  // Note that this works as expected, but is not generic
    }
}

public func test() {
    let x = X<P>()
    x.foo1(C.self) // ERROR Cannot convert value of type 'C.Type' to expected argument type 'P.Protocol'
    x.foo2(C.self) // Works as expected, but is not generic
}

Now, foo1 works fine when T is a class.  However, when T is a protocol (e.g. P), Swift seems to rewrite my function signature from T.Type to T.Protocol.

*

*Why did it do this?

*How do I instead get foo1 to accept a type that inherits from P?

Class X is used in a number of other places - any changes to it must not restrict or remove class parameter T nor reduce X's functionality, nor make explicit reference to C or P.  (It would be acceptable to constrain T to exclude protocols that do not extend AnyObject; I don't know how to do that, though.  It might also be acceptable to e.g. create a subclass of X that adds the ability to handle a protocol in T, but I'm not sure how to do that, either.)
For clarity, this class is used to register classes (t) that conform to some specified parent (T), for more complicated project reasons.  (Note that classes are being registered, not instances thereof.)  The parent is given at the creation of X, via the type parameter.  It works fine for a T of any class, but I'd also like it to work for a T of any protocol - or at least for a T of any protocol P: AnyObject, under which circumstances foo1 should accept any subclass of P...the same way it works when T is a class.

A: Even though C is a P, but C.Type != P.Type, so the error.
But generics works in a bit different way, like in below examples:
public class X {
    public func foo1<T>(_ t: T.Type) { // this way
    }

    public func foo3<T:P>(_ t: T.Type) { // or this way
    }

    public func foo2(_ t: P.Type) {  // Note that this works as expected, but is not generic
    }
}

public func test() {
    let x = X()
    x.foo1(C.self) // << works
    x.foo3(C.self) // << works
    x.foo2(C.self) // Works as expected, but is not generic
}


text:
Q: Найти повторения по полю date в коллекции и объединить повторяющиеся объекты в один Есть коллекция вида
dict = [
  {
    date: '19.10.2018,
    hours: 2,
  },
  {
    date: '19.10.2018,
    hours: 10,
  },
  {
    date: '24.11.2010,
    hours: 4,
  },
]

Я бы хотел совместить поле hours у объектов с повторяющейся датой, то есть:
 [
      {
        date: '19.10.2018,
        hours: 12,
      },
      {
        date: '24.11.2010,
        hours: 4,
      },
    ]

Есть ли какие нибудь идеи как лучше это реализовать?
Спасибо!!!

A:

var dict = [
  {
    date: '19.10.2018',
    hours: 2,
  },
  {
    date: '19.10.2018',
    hours: 10,
  },
  {
    date: '24.11.2010',
    hours: 4,
  },
],
obj = {};

dict.forEach(function(item){

  if(!obj[item.date]){
    obj[item.date] = item;
  } else {
    obj[item.date].hours =  obj[item.date].hours + item.hours;
  }
});

console.log(obj);


text:
Q: How to update multiple columns with a single statement with multiple conditions I want to update a series of columns Country1, Country2... Country 9 based on a comma delimited string of country names in column Country. I have done so with the following statment:
cur.execute("\
            UPDATE t \
            SET Country1 = returnCommaDelimitedValue(Country,0),\
                Country2 = returnCommaDelimitedValue(Country,1),\
                ...
                Country10 = returnCommaDelimitedValue(Country,9),\
            WHERE Country IS NOT NULL\
            ;")

I also have a column named Genre in my tabe. Now I would like to update columns Genre1, Genre2... Genre9 in the same statment. I think the statment would look something like:
cur.execute("\
                UPDATE t \
                SET Country1 = returnCommaDelimitedValue(Country,0), Genre1 = returnCommaDelimitedValue(Genre,0)\
                    Country2 = returnCommaDelimitedValue(Country,1), Genre2 = returnCommaDelimitedValue(Genre,1)\
                    ...
                    Country10 = returnCommaDelimitedValue(Country,9), Genre10 = returnCommaDelimitedValue(Genre,9)\
                WHERE Country IS NOT NULL\
                AND Genre IS NOT NULL
                ;")

Is the statement correct?

A: You should run 2 separate update queries. The problem is that Country can be null independently of Genre. So however you combine the conditions Country IS NOT NULL and Genre IS NOT NULL in the where clause of the query, you will miss some columns that could have been updated, or you will update some columns with null values.
Now, I haven't seen the implementation of returnCommaDelimitedValue. It is possible that it returns null when the string argument is null. In that case, you might consider remove the where clause completely and update the countryN and genreN columns in the same query. In that case, if Country is null, this will also make Country1 null, so this might be something that you want. If almost all rows have a non-null Country and Genre, this approach might be faster.

A: Country1, Country2, Country3... this is an anti-pattern. You're feeling the consequences of very poor table design. Don't feel too put out, this is a very common anti-pattern. Lists are difficult and very non-intuitive to work with in standard SQL. The whole mess is referred to as "normalization".
Lists are represented by join tables in a one-to-many relationship. One t has many countries. This is a very big topic to get into, but here's a sketch.
Instead of having Country1, Country2, Country3, etc... in whatever t is, I'm going to call it Thing, you'd have a table called ThingCountries to represent the list.
create table ThingCountries (
    ThingID integer references Thing(id),
    Country text
);

Each Country belonging to a Thing would be inserted into ThingCountries along with the ID of the thing.
# Do this in a loop
insert into ThingCountries (ThingID, Country) values (?, ?)

They'd be retrieved with a join by linking Thing.ID and ThingCountries.ThingID.
select ThingCountries.Country from Thing
join ThingCountries on Thing.ID = ThingCountries.ThingID
where Thing.ID = ?

By querying ThingCountries you can quickly find out which Things have a certain Country.
select ThingID from ThingCountries
where Country = ?

They can be removed with a simple delete.
delete from ThingCountries where ThingID = ? and Country = ?

There's no need to know how many Country columns there are. There's no gaps to be filled in. There's no limit to how many Countries a Thing can have.

Later on down the road you might want to store information about each country, like its name and abbreviation.  In which case you make a Country table.
create table Country (
    id integer primary key,
    name text not null,
    abbrev text not null
);

And then ThingCountries references Country by is id rather than storing the Country name.
create table ThingCountries (
    ThingID   integer references Thing(id),
    CountryID integer references Country(id)
);

Now you can store whatever information you want about each Country, and it protects against typos (because the Country has to exist in the Country table).
Do the same thing for Genre and your problem goes away.
It's a bit awkward, but that's how SQL does it. Best to get used to it. Alternatively some databases offer array types to make this simpler, like Postgres arrays.
More Reading:

*

*Ten Common Database Design Mistakes particularly "Ignoring Normalization"

*Database normalization


text:
Q: FileSystemResource as ResponseBody in spring rest controller gives ClassCastException I have defined a controller which serves local content like this:
@RequestMapping(value = PATH_CONTENT, method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<FileSystemResource> getContent(
    @PathVariable(URI_PATH_PARAM_CONTAINER_UID) String containerUid,
    @PathVariable(URI_PATH_PARAM_DOC_UID) String docUid) {
    ...
}

In the client side:
I am adding ResourceHttpMessageConverter to RestTemplate messageConverters.
When I finally make the following call:
ResponseEntity<FileSystemResource> response = getMyRestClient()
        .getContent(url, null, FileSystemResource.class);
FileSystemResourcecontent = response.getBody();

This produces a ClassCastException saying it cant cast ByteArrayResource to FileSystemResource.
I can do some modification to my code to return a Resource instead of FileSystemResource and things will work. But I am really wondering why is this exception? I also don't want to take the path of writing to HttpServletResponse directly as I want to use Spring's HttpMessageConverter framework.


text:
Q: ViewState across servers in a SharePoint Farm When a new server is added to a farm will SharePoint automatically synchronise the machine key such that view state will work across the farm, or is a manual operation required?

A: No manual operation is required as long as you are using Out of the box box Sharepoint components.
If you are using some custom code, please clarify what is it you are trying to do.


text:
Q: Certain Japanese Unicode String Breaks File Reading In one of my programs, I regularly write wstrings to a file in c++ and then read them back. These strings are composed of Japanese characters.
I use this code to do it:
#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;

std::wstring readUnicodeFile(const char* filename)
{
    std::ifstream wif(filename);
    std::stringstream wss;
    wss << wif.rdbuf();
    std::string  const& str = wss.str();
    std::wstring wstr;
    wstr.resize(str.size() / sizeof(wchar_t));
    std::memcpy(&wstr[0], str.c_str(), str.size()); // copy data into wstring
    return wstr;
}

void writeUnicodetoFile(const char* myFile, wstring& ws)
{
    std::ofstream outFile(myFile, std::ios::out | std::ios::binary);
    outFile.write((char*)ws.c_str(), ws.length() * sizeof(wchar_t));
    outFile.close();
}

I have used this code without problems for over a year. But today I tried to write and then read a specific unicode string "宴会".  The result is that it can write it but cannot read it. It only reads the first character and then cuts off the string.
You can use this to test it:
int main()
 {
     wstring test1 = L"学校";  //Japanese word for school
     wstring test2 = L"宴会";  //Japanese word for banquet
     writeUnicodetoFile("somefilepath\\test.txt", test1);
     std::wstring s = readUnicodeFile("somefilepath\\test.txt");
 }

"test1" works fine the result appears in "s".  "test2" is broken and only the first character appears.
Why is this happening and how do I fix it?


text:
Q: Slick refresh on resize creating console errors I have a logo carousel which shows different amount of slides based on responsive widths.
I have used the refresh() function to make the carousel work on resize (rather than resizing and then refreshing the page so that slick initiates based on the correct parameters).
However, when I'm resizing the screen, I'm receiving a lot of $(...).refresh is not a function errors.
Is there a way to achieve for slick to re-init on resize, without these errors?
See demo here:

$(function() {

  var $slider = $("#logoCarousel-slick");

  var slickOptions = {
    speed: 3500,
    autoplay: true,
    autoplaySpeed: 0,
    cssEase: 'linear',
    slidesToShow: 3,
    slidesToScroll: 1,
    infinite: true,
    arrows: false,
    mobileFirst: true,
    pauseOnHover: false,
    responsive: [{
        breakpoint: 767,
        settings: {
          slidesToShow: 4,
          slidesToScroll: 1,
        }
      },
      {
        breakpoint: 1023,
        settings: {
          slidesToShow: 5,
          slidesToScroll: 1,
        }
      }
    ]
  };

  $($slider).slick(slickOptions);

  $(window).on('resize orientationchange', function() {
    $($slider).refresh();
  });

});
.slick-track,
.slick-slide {
  display: flex;
  justify-content: center;
  align-items: center;
}

.logoCarousel__logo {
  width: 100px;
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">


text:
Q: Any efficient way to obtain area estimation with pixel counting approach for land cover raster in R? I want to get area estimation for each polygon by using pixel counting method. The original landcover map was raster data that come with a distinctive class assigned to each pixel (landcover map legend). However, to get area estimation by using pixel counting is not intuitive to me. Perhaps, the first things I can do is extract all the pixels for each polygon which present information about the distribution of land cover classes within each polygon. After that, I need to use pixel counting method to get area estimation and aggregate all land/soil coverage for the city, agriculture area for each polygon. For me, using pixel counting to obtain area estimation is not straightforward and don't have a solid idea how to get this done in R.
Note that original landcover map is rather big (about 92mb) and it is difficult to produce reproducible example for landcover raster, so forgive me for such inconveniece. Here is the R script to acquire landcover raster:
library(raster)
library(R.utils)

url = "https://cidportal.jrc.ec.europa.eu/ftp/jrc-opendata/LUISA/PrimaryOutput/Europe/REF-2014/JRC_LUISA_Input_Corine_land_cover_2006_r_ref_2014.zip"
download.file(url, basename(url))
gunzip(basename(url))
rname <- list.files(getwd(), "tif$")
land_cover <- raster::raster("~/LUISA_CLC_land_coverage/clc06_r.tif")

I want to aggregate all land/soil coverage information for each polygon (total 403 polygon that land cover information to be aggregated); Here are polygons I am gonna use for area estimation:  shapefile with polygons are available on the fly:

I cropped original landcover raster as follow:
deu_shp = maptools::readShapePoly("~/adm2.shp",
                                  proj4string=crswgs84,verbose=TRUE)
deu_proj <- spTransform(deu_shp, CRSobj = land_cover@crs)
land_cover_deu <- crop(land_cover, deu_proj )

To understand area estimation with pixel counting, I googled related article and found this :  Using remote sensing for crop area estimation and idea that presented in this article is closely match with my interest, but to implement presented method is purely theoretical and hard for me to do it in R. I am quite okay if there is any quick and dirty way to get area estimation with pixel counting where land/soil coverage information (such as city, forest, agricultural land) must be aggregated to each polygon (shapefile with polygons are available on the fly).
for pixel extraction, I could simply use raster::extract as follow (the code down below is trial):
lapply(deu_proj, function(x) {
    pixel_extract = raster::extract(land_cover_deu, deu_proj[x,])
    pixel_extract= as.data.frame(pixel_extract)
})

and above simple pixel extraction is not very efficient for original land cover raster. I don't know how to make pixel counting for the extracted pixel in each polygon and get corresponding area estimation (such as land coverage of the city, forest, agriculture area and so on).
Any idea to make this happen in R? How can I get area estimation with pixel counting approach for given land cover raster? Is that possible to aggregate land/soil coverage information to each polygon? Thanks in advance

A: Here is a workflow to get the number of pixels of each land cover class by polygons (an operation called tabulate area). The idea is to rasterize the shapefile using the resolution and the extent of the land cover raster. Then, compute the tabulate area using a very efficient function based on data.table that counts the number of pixels of each class, in each polygon.
# add ID field to the shapefile
deu_proj@data$ID <- 1:nrow(deu_proj@data)

# extract extent and resolution of land cover raster
ext <- extent(land_cover_deu)
ext <- paste(ext[1], ext[3], ext[2], ext[4])
res <- paste(res(land_cover_deu)[1], res(land_cover_deu)[2])

# rasterize shapefile using gdal (more efficent than rasterize from raster package)
# you can change GDAL_CACHEMAX according to your RAM
system(paste0("gdal_rasterize --config GDAL_CACHEMAX 8000 -a ID -te ",
               ext," -tr ", res,
               " -ot Int16 /home/deu_proj.shp /home/zones.tif"))

# load raster
zones <- raster("/home/zones.tif")

# zonal stats using myZonal function
Zstat <- myZonal(land_cover_deu, zones)

# reshape output
results <- data.table::dcast(Zstat, z ~ vals)
colnames(results)[1] <- "ID"

# merge data
deu_proj@data <- plyr::join(deu_proj@data, results, by="ID")

# show results
head(deu_proj@data[, c(8, 17:ncol(deu_proj@data))])

           NAME_2  0   1    2    3    4  5   6   7  8   9 10  11    12  15   16    18    20   21 22    23    24    25  26
1 Alb-Donau-Kreis NA 241 4504  781 1317 NA  NA 357 NA  NA NA 133 57460  NA   NA  7212 19899 1627 NA 16403  6628 15248 135
2       Böblingen NA 369 4947 1599 1140 NA  NA 149 87 116 98 438 17845  NA 1712  1717  4742 3079 NA  3988  2286 14557  NA
3     Baden-Baden NA  45  791  150  306 NA  83  33 NA  NA 38  41   695 338  602   721   468   92 NA  1090  2272  4401  NA
4        Biberach NA 201 4681  462 1264 NA 152 312 NA  48 NA 131 46163  NA   29 23780 19126  920 NA  2291 28679  5140  NA
5   Bodenseekreis NA 268 3219  561  814  7 169  81 NA  NA NA  76  9482 418 5403  4750 19105  804 NA    96  9151  8797  NA
6        Bodensee NA  NA   13    1   NA  9  NA  NA NA  NA NA   3    NA  NA   NA     1     2   NA NA    NA    NA     4  NA
  27   29 30 31 32 34   35  36 37 39 40  41 42 43   45 46   128
1 NA  581 NA NA NA NA  104  NA NA NA NA 397 NA NA 2643 40    NA
2 NA  801 NA NA NA NA   NA  NA NA NA NA  NA NA NA 2001 58    NA
3 NA 1117 NA NA NA NA  157  NA NA NA NA  79 NA NA  486  1    NA
4 NA 2063 NA NA NA NA 1105 273 NA NA NA 384 NA NA 3760 25    NA
5 NA  240 NA NA NA NA  299  NA NA NA NA 193 NA NA 2476 66    45
6 NA   NA NA NA NA NA    4  NA NA NA NA 415 NA NA   20  1 27563

Zonal Stats function (adapted from here)
myZonal <- function (x, z, digits = 0, na.rm = TRUE) {
  vals <- raster::getValues(x)
  zones <- round(raster::getValues(z), digits = digits)
  rDT <- data.table::data.table(vals, z = zones)
  plyr::count(rDT) }

Sample data
# I have loaded the shapefile using getData but you can use your own shp.
# The only difference will be in the column numbers of "show results" step.
deu_shp <- getData("GADM", country="DEU", level=2)


text:
Q: My div's are not showing? Hi can you please help me how to fix this? my div's are not showing and when I inspect it is there but it is not showing the whole content of it.
Here is my div code

                            Previous

                            Next

Christmas Clothes

                                         £300.00

                                    Add to cart

Christmas Clothes

                                         £300.00

                                    Add to cart

Christmas Clothes

                                         £300.00

                                    Add to cart

Christmas Clothes

                                         £300.00

                                    Add to cart

Here is the screenshot of my div that I want to show but it's not showing anything

I don't know why my div are not showing? can you please help me!!  I've been stuck with this code for days already huhu

A: You appear to be missing one closing div tag. There are 4 opening divs before class="container", and only 3 closing. I thinking your main wrapping div (id="men_product") isn't being closed so that's why it's not displaying. Or perhaps, the last div just wasn't included when you copied the code?


text:
Q: Compute the stochastic differential for $t\cdot B_t$ using Ito's Lemma Consider $Y_t=B_t^3$, $t \geq 0$ where $(B_t)_{t \geq 0}$ is standard Brownian Motion.
Here, $dB_t = 0+1\cdot dB_t$ and $G(x,t)=x^3$, What is $dY_t$?
Using Ito's Lemma, we can calculate the partial derivatives and get:
$$\begin{align*}
dY_t &= [3B_t^3\cdot 0+0\cdot \frac{1}{2}\cdot 6B_t\cdot 1^2]dt + 3B_t^2\cdot 1\cdot dB_t \\
&= 3B_t^2dt + 3B_t^2dB_t
\end{align*}$$
If $Y_t = t\cdot B_t$, how can I use this same logic to get $d(tB_t)$?

A: You need to use Itô's lemma with $g(x,t) = xt$. Notice that $g_x(x,t) = t, g_t(x,t) = x, g_{xx}(x,t) = 0$, so that
\begin{align*}
dY_t &= dg(B_t, t) \\
&=  g_t(B_t, t) dt + g_x(B_t, t) + \frac{1}{2}g_{xx}(B_t,t)(dB_t)^2 \\
&=  B_t dt +t dB_t
\end{align*}


text:
Q: removing each . after ] appear in a line in complete text file I have a file in which I need to eliminate . after the ] on every line
e.g
xyz[1.2]35.23
xyz[1.2.3]35.234

output should be
xyz[1.2]3523
xyz[1.2.3]35234

A: To remove the dots after the right-most ]:
sed -e :1 -e 's/\(][^]]*\)\.\([^]]*\)$/\1\2/;t1'

Or:
awk -F']' -vOFS=']' 'NF>1 {gsub(/\./,"",$NF)};1'

Or:
perl -pe 's/.*\]\K.*/$&=~s|\.||gr/e'

To remove after ] regardless of whether there are other ] at the right.
sed -e :1 -e 's/\(].*\)\./\1/;t1'

Or:
perl -pe 's/.*?\]\K.*/$&=~s|\.||gr/e'

A: With perl:
$ perl -pe 's/(?<=])\d+\K\.//g' file
xyz[1.2]3523
xyz[1.2.3]35234


text:
Q: Javascript: "Cannot read property "name" of undefined" error at native javascript code I'm working in a Chrome extension. At some point, in a script called CLAWS_Sem_Imagens_Script.js, I send a message from an Iframe inside the page to my background-page with the following line:
chrome.runtime.sendMessage({type:"execution order",sendToContentScript:true, data:"show"});

It works most of the times. However, sometimes, javascript throws the error Cannot read property "name" of undefined, at the line 316 of @extensions::messaging:
if (port.name != kNativeMessageChannel)...

The full call stack is:
sendMessageImpl @ extensions::messaging:316
(anonymous function) @ extensions::runtime:115
target.(anonymous function) @ extensions::SafeBuiltins:19
(anonymous function) @ extensions::binding:57
target.(anonymous function) @ extensions::SafeBuiltins:19
(anonymous function) @ extensions::binding:385
enviaPalavraAoBackgroundPageImagem @ CLAWS_Sem_Imagens_Script.js:66

Do someone has any guess? Please ask me for any additional info you need.
EDIT: My manifest:
{
  "manifest_version": 2,

  "name": "name",
  "description": "description",
  "version": "1.0",

  "permissions": [
    "tabs",
    "activeTab",
    "https://google.com.br/",
    "http://localhost/*",
    "https://localhost/*"
  ],

 "background": {"scripts":["background.js"]},

  "content_scripts": [
    {
      "js": ["CLAWS_Content_Script.js", "jquery.js", "Caixas_De_Texto_Dos_Botoes.js"],
      "css": ["CLAWS_Content_Script_CSS.css"],
      "matches": ["<all_urls>"]

    }
  ],

  "web_accessible_resources": [
        "iframe.html",
        "icon.png",
        "Caixas_De_Texto_Dos_Botoes.js",
        "search.png"
  ]

}

A: This can also occur if you reload the extension but not the page with injected script. Reloading the page solves the problem.

A: Just to clarify, the error was occurring because the extension was disabled (chrome://extensions -> unmark the check box), and then the background page was disabled, even with the extension aparently working. Regards!


text:
Q: Unwanted url is coming with magento2 site url Whenever I open my website it opens with an unwanted URL like

www.mysite.com/?SID=gjc3knlipsmuhsbc73j0is36h2.

It should open like

www.mysite.com/

Why this type of URL is coming. And when I clear cache, then site opens with normal url, but after some time same problem. Please tell me permanent solution of this problem.
Thanks

A: Please follow this link, you can remove that from admin panel on follwing path.

Go to the Store > Configuration > General > Web > Session Validation
  Settings > Use SID on Storefront and set its value to No
The SID is a "session ID". Magento uses this to track a user's
  activity within the same Magento installation. Normally, Magento
  powers one website and one store from one installation (database).
Magento could power multiple websites with multiple stores from one
  installation though. The SID allows users to stay logged in while
  navigating across these websites/stores.
I think if you have the function enabled, the SID is sent when
  accessing catalog URLs so Magento can update the session with the
  user's location/state for the current website/store.
If you're not running a multi-website or multi-store environment, it's
  safe to disable the SID on the frontend.

A: I was facing same issue in Magento-2.1.9 and setting Use SID on Storefront to No doesn't work for me because I have set "Auto-redirect to Base URL" to "Yes".
I have resolved the issue by doing following.
If you are using single store mode, then copy file vendor/magento/framework/Session/SidResolver.php to lib/internal/Magento/Framework/Session/S
idResolver.php and change protected $_useSessionInUrl to false


text:
Q: Ruby " yield row if block_given?"   # Get our data back
  def queryNewsTable
    @conn.exec( "SELECT * FROM newslib" ) do |result|
      result.each do |row|
        yield row if block_given?
      end
    end
  end

For this piece of code. I don't quite understand  yield row if block_given?
can anybody point to any good article teaching about this or you can briefly explain it to me a little bit
thanks so much

A: This yield row if block_given? means that block which could be passed into the #queryNewsTable method(!), is evaluated with yield operator, in other words, if you pass the block into function #queryNewsTable:
queryNewsTable do
   #some code
end

You will get the call to the code, for each of rows in the result variable.
NOTE: That for your case it will be better to optimize the code (if not dbtrigger is used):
# Get our data back
def queryNewsTable
  @conn.exec( "SELECT * FROM newslib" ) do |result|
    result.each do |row|
      yield row
    end
  end if block_given?
end

A: Ask yourself how Hash.new works:
http://www.ruby-doc.org/core-2.1.0/Hash.html#method-c-new
It can take no argument, a single argument, or a block. If there is no argument, fetching the value for a non-existent key gives nil. If there is a block, fetching the value for a non-existent key gives whatever the block says to give. Clearly its implementation needs a way to ask "was there a block?" so that it knows which behavior to use. That is what block_given? does.
http://www.ruby-doc.org/core-2.1.0/Kernel.html#method-i-block_given-3F
As for yield, it is simply the way a method that has taken a block calls the block, passing it parameters as needed.

A: When you use functions like Enumerable#each, you typically pass in a block using {|arg| ... } or do ... end. The line yield row if block_given? checks to see if a block was supplied to this function call, and if it was, calls that block with row as an argument.
One way you might use this function would be:
queryNewsTable {|row| puts row}

This example would print each row of the query to standard output, since the block that does the printing gets called for each row in the query result. If no block were given, then that line would be ignored.


text:
Q: $log_{10} 11$ with an accuracy of at least $0.0001$ I need need to calculate $log_{10} 11$ with an accuracy of at least $0.0001$ with Maclaurin Series.
I thought it was not so difficult, but I can not move forward in reasoning.
I forgot to clarify what should be presented in the form of a sum of rational fractions

A: Hint
Write $$\log_{10}(11)=\log_{10}(10)+\log_{10}\left(1+\frac 1 {10}\right)=1+\log_{10}\left(1+\frac 1 {10}\right)=1+\frac{\log_e\left(1+\frac 1 {10}\right)}{\log_e(10)}$$ Now, use Taylor series in particular the very fast converging $$ \log \left(\frac{1+x}{1-x}\right)=2\left(\frac{x}1+\frac{x^3}3+\frac{x^5}5+\frac{x^7}7+\cdots\right)$$ Setting $$\left(\frac{1+x}{1-x}\right)=\frac{11}{10}\implies x=\frac 1{21}$$


text:
Q: Editing the Form in Django creates new instance I am editing the form , it loads data correctly buy when i hit save it creates new entry in database.
Here is the view functions
def create_account(request):

    if request.method == 'POST': # If the form has been submitted...
        form = AccountForm(request.POST, request.FILES) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
                form.save()
                return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = AccountForm() # An unbound form

    return render_to_response('account_form.html', {
            'form': form,
    })

--
def edit_account(request, acc_id):

    f = Account.objects.get(pk=acc_id)
    if request.method == 'POST': # If the form has been submitted...
        form = AccountForm(request.POST, request.FILES) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
                form.save()
                return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = AccountForm(instance=f) # An unbound form

    return render_to_response('account_form.html', {
            'form': form,
    })

Do i really need to have separate function of editing and separate for deleting. Can i do all in one function
template
    <form action="/account/" method="post" enctype="multipart/form-data" >
    {% csrf_token %}
    {% for field in form %}

            {{ field.errors }}
            {{ field.label_tag }}: {{ field }}

    {% endfor %}

<input type="submit" value="Send message" />

    </form>

A: You are missing the instance argument at the POST section.
Instead of this:
form = AccountForm(request.POST, request.FILES) # A form bound to the POST data

You should use this:
form = AccountForm(request.POST, request.FILES, instance=f) # A form bound to the POST data

Once you add that to the add/edit form you will be able to add/edit at the same time.
It will add if instance=None and update if instance is an actual account.
def edit_account(request, acc_id=None):
    if acc_id:
        f = Account.objects.get(pk=acc_id)
    else:
        f = None

    if request.method == 'POST': # If the form has been submitted...
        form = AccountForm(request.POST, request.FILES, instance=f) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            form.save()
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = AccountForm(instance=f) # An unbound form

    return render_to_response('account_form.html', {
        'form': form,
    })

A: Have you tried something like this?
 # Create a form to edit an existing Object.
     a = Account.objects.get(pk=1)
     f = AccountForm(instance=a)
     f.save()

# Create a form to edit an existing Article, but use
# POST data to populate the form.
    a = Article.objects.get(pk=1)
    f = ArticleForm(request.POST, instance=a)
    f.save()


text:
Q: My partial view does not refresh after AJAX call I am having an issue not able to refresh my Partial view.
my cshtml page page
<script type="text/javascript">
  $(document).ready(function () {
      $('#btncreate').click(function () {
          var projectid = $("#txtprojectid").val();
          $.ajax({
              url: '/Projects/CreateFinanceItems?pid=' + Id,
              datatype: 'json',
              type: "POST",
              success: function (response) {
                  alert("record created successfully");
                  if (response != null) {
                      window.close();
                      refreshpartial();
                  }
              }
          })
      });

      function refreshpartial()
      {
          $.ajax({
              url: '/Projects/PartialItem?id=' + "Test",
              datatype: 'json',
              success: function (response) {
                  $("#displayproContainer").html(response);
              },
              error: function (xhr, ajaxOptions, thrownError) {
              }
          })
      }
    });
    </script>

I can see record created successfully alert message, but when it goes to refreshpartial method my partialview does not refresh with Added data. I put the alert in success function it does not hit.
Partialview DIV ID #displayproContainer
$("#displayproContainer").html(response);

Controller code
  [OutputCache(Duration = 0)]
        public PartialViewResult PartialItem(string id)
        {
            // Logic to Insert data
            return PartialView(viewModel);
        }

Something I am missing here?


text:
Q: Visual studio 2013 database publish do nothing I'm trying to publish a DB project in Visual Studio 2013 Professional and the "Publish" button do nothing.
In project properties I checked "Create script (.sql file)". I right click the project name in solution explorer > Publish... > Load Profile (a profile that works for my colleagues) > Publish
Nothing Happens, not an error, warning or anything (same with "Generate Scripts" button).
Visual studio error logs say nothing and I tried to restart the PC, Visual studio and SQL server.
Thank you!

A: If you have an Azure Cloud Explorer window open in Visual Studio (could be table, blob or queue), that leads to the Publish of an SSDT project hanging.
Close the window and start a new Publish operation. It may take a little longer than usual but eventually that will progress and you'll be able to close Visual Studio as normal.
Thanks to Noel Abrahams for his comment that led to this answer.
EDIT: putting it here as an answer so that it can be more easily found but credit goes to Noel.

A: Found a fix on the MS Connect site.
In my publish profile I had set the connection string as so:
<TargetConnectionString>Data Source=.\sql2008r2;Integrated Security=SSPI;</TargetConnectionString>

According to the comments on Connect, it doesn't like Integrated Security=SSPI. Instead you should use Integrated Security=True;:
<TargetConnectionString>Data Source=.\sql2008r2;Integrated Security=True;</TargetConnectionString>

Then it all works fine.

A: I cloned the solution from VCS to a new directory and only this helped.
Other symptoms that I had with this issue:

*

*While editing a table .sql script, Design pane didn't work.

*Integrated Security=True; was set in my publishing profile. So Rhumborl's answer is not about my case.

*If the solution folder is copied to another machine the issue is reproduced there too.

I tried to Clean Solution before re-cloning, but it didn't work.

A: For me publishing the database project to a new sql server database with a different name allowed the publish to proceed.  Once I'd done that I was then able to publish to the original database again.

A: I found that having an Azure Queue or Blob Storage opened in Visual Studio Professional 2015 meant that clicking Publish did nothing and I couldn't close the application. After closing those windows which I had launched from the Cloud Explorer, I had to click Publish once again to kick it off. A strange bug.


text:
Q: Drupal 7: How to Create a Menu/Route Item That Doesn't Appear in the Site Navigation How can I create a new route/menu in Drupal that doesn't automatically render a navigation link?
I'm trying to create a simple page callback in Drupal that doesn't show up in the Navigation menu.
I have a module named helloworld.
The .module file contains the following
function _helloword_page_callback()
{
    return array('#markup'=>'The quick brown fox says hello, and the lazy dogs thanks you
    for following conventions.');
}

function helloworld_menu()
{
    $items['helloworld'] = array(
      'title'               => 'Hello World',
      'page callback'       => '_helloword_page_callback',
      'access arguments'    => array('content'),
      'type'                => MENU_CALLBACK
    );
    return $items;
}

This successfully exposes a URL on the site of
http://example.drupal.com/helloworld

However, I'm still getting a link in the left hand (Bartik) navigation menu, despite the use of
'type'              => MENU_CALLBACK

So, why isn't this working?  Am I configuring the Menu item correctly?  A more likely question: How am I misinterpreting the use of the menu type constants/system? Are there additional caches to clear that
drush cc all

wouldn't take care of?  What other steps can I take to debug this?

A: There must be something else wrong (perhaps you forgot to clear the caches ?) because even with Bartik, it works as expected. In that example, only "Hello 2" is shown in the navigation:
function helloworld_menu(){
    return array(
        'hello1' => array(
            'title'               => 'Hello 1',
            'page callback'       => 'helloworld_page_callback',
            'access arguments'    => array('content'),
            'type'                => MENU_CALLBACK
        ),
        'hello2' => array(
            'title'               => 'Hello 2',
            'page callback'       => 'helloworld_page_callback',
            'access arguments'    => array('content')
        )
    );
}

function helloworld_page_callback(){
    return array('#markup'=>'The quick brown fox says hello, and the lazy dogs thanks you for following conventions.');
}

By the way, there is a typo in your snipplet (helloroute_menu should be named helloworld_menu), but I assume this is due to code simplification before posting on StackOverflow.

A: Check out that menu link in the menu administration. If you customized it there (weight change for example), it's possible that it remains even though you set to type to callback.
If that's the case, you can just delete there.


text:
Q: Is there hotkey for Show Desktop Icons function in Windows? On my desktop there are a sea of icons and I realy like ability to hide them.
I can do that if do right click on desktop and find arrange icons -> Show Desktop Icons
I am also addicted to many types of keyboards shortcuts and I use mouse just when I have to.
Is there hot-key for function I mentioned already.  My OS is WIN XP and I do not know is this function relater to my Nvidia display adapter drivers.

A: *

*Create a shortcut to the HideDesktopIcons.exe application.

*Edit the properties of the shortcut to give it a hotkey.
— How-To Geek - Create a Shortcut or Hotkey to Turn the Desktop Icons On or Off

A: *

*Download Actual Hide Desktop Icons: Click here

*Extract the zip file & create a shortcut from ActualHideDesktopIcons.exe

*Place the shortcut anywhere for your convenience & use it to toggle hide/show desktop icons.

*

*If you're really interested in creating a keyboard shortcut to show or hide desktop icons with the help of AutoHotKey. => Continue to the source tutorial. (I've tried a simple solution such as assigning a shortcut key to the created app shortcut via its Properties, but it doesn't work well after a few usages.)
Source: How To Create Keyboard Shortcut To Show or Hide Desktop Icons

Why not using HideDesktopIcons.exe from How-To-Geek article?
HideDesktopIcons program works ok but was not perfectly programmed. It can toggle show/hide Desktop icons normally, but it doesn't update the state of Show desktop icons in the context menu. So, sometimes it seems broken due to conflicting the state with our old usage behavior. (Right-click > View > Show desktop icons)


text:
Q: php showing just plain text I have installed php5 but when I tried for
<html>
  <head>
    <title>PHP Test</title>
  </head>
  <body>
    <?php echo "Hello World"; ?>
  </body>
</html>

and I got following output rendered on my browser
Hello World'

; ?>

why am I getting extra output?
(I am working on Linux Mint 17.1 Rebecca)

A: If you look at the source of the rendered document, you'll probably see it's actually the whole source of the PHP file. It's interpreting out the <?php tags as something that might be HTML.
Installing PHP5 isn't enough. Your webserver needs to know what to do with PHP files. That depends on both distribution and your webserver. Given we know neither, and that this is a very common use-case for Linux servers, just look in your distribution's documentation. Here's an example from the Ubuntu documentation that covers a wide array of deployments.
If you're using NGINX or another httpd, you'll want different instructions, but the process is similar.