text:
Q: Shopify app with GraphQL failed to work when developing on Heroku I'm developing a Shopify private app with Node.js and React and using GraphQL api to make requests. Everything works fine when I run it locally and publish it with NGROK, but when I push the codes to Heroku, errors occur. It seems that there's something wrong with ApolloClient, but I can't figure it out.
I set up ApolloClient like this (based on this tutorial https://developers.shopify.com/tutorials/build-a-shopify-app-with-node-and-react/fetch-data-with-apollo):
import ApolloClient from 'apollo-boost';

const client = new ApolloClient({
    fetchOptions: {
        credentials: 'include'
    }
});

When building, an error about fetch occurs so I modified the code (based on Using ApolloClient with node.js. "fetch is not found globally and no fetcher passed"):
import ApolloClient from 'apollo-boost';
import { fetch } from 'node-fetch'

const client = new ApolloClient({
    fetch: fetch,
    fetchOptions: {
        credentials: 'include'
    }
});

The build succeed, but my GraphQL call returns error graphql error only absolute urls are supported, so I tried to modified the code like this:
import ApolloClient from 'apollo-boost';
import { fetch } from 'node-fetch'

const client = new ApolloClient({
    fetch: fetch,
    fetchOptions: {
        credentials: 'include'
    },
    uri: `https://${shopOrigin}/admin/api/2019-10/graphql.json`
});

The error now occurs to be Network Error: Failed to Fetch with a CORS issue.
Could anyone help me resolved the problem? Please let me know if you need more information.

A: The Shopify tutorial suggests using isomorphic-fetch for the server side. I tried including it in the Next.js side and the build went successful.
In my _app.js
require('isomorphic-fetch');
import ApolloClient from 'apollo-boost';

...

const client = new ApolloClient({
  fetchOptions: {
    credentials: 'include'
  },
});


text:
Q: Error loading Jar file with Tomcat 7, Spring 3 and Camel 2.9.1 I'm getting the following exception while running Camel (2.9.1) on Tomcat (apache-tomcat-7.0.26) with Spring (3.0.5.RELEASE).
Any pointers would be appreciated. Thanks.

  Mar 12, 2012 3:03:48 PM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(/Users/XXXX/Documents/apache-tomcat-7.0.26/webapps/myapp/WEB-INF/lib/geronimo-servlet_2.5_spec-1.1.2.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
[          http-bio-8080-exec-1] ContextLoader                  ERROR Context initialization failed
java.lang.NoSuchMethodError: org.springframework.core.BridgeMethodResolver.isVisibilityBridgeMethodPair(Ljava/lang/reflect/Method;Ljava/lang/reflect/Method;)Z
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.buildAutowiringMetadata(AutowiredAnnotationBeanPostProcessor.java:346)[spring-beans-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.findAutowiringMetadata(AutowiredAnnotationBeanPostProcessor.java:317)[spring-beans-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(AutowiredAnnotationBeanPostProcessor.java:216)[spring-beans-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:797)[spring-beans-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:492)[spring-beans-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)[spring-beans-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)[spring-beans-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)[spring-beans-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)[spring-beans-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)[spring-beans-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:722)[spring-context-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:410)[spring-context-3.0.7.RELEASE.jar:3.0.7.RELEASE]
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)[spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)[spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)[spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779)[catalina.jar:7.0.26]
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)[catalina.jar:7.0.26]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)[catalina.jar:7.0.26]
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:895)[catalina.jar:7.0.26]
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:871)[catalina.jar:7.0.26]
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)[catalina.jar:7.0.26]
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:958)[catalina.jar:7.0.26]
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:536)[catalina.jar:7.0.26]
    at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1467)[catalina.jar:7.0.26]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)[:1.6.0_29]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)[:1.6.0_29]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)[:1.6.0_29]
    at java.lang.reflect.Method.invoke(Method.java:597)[:1.6.0_29]
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)[tomcat-coyote.jar:7.0.26]
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:836)[:1.6.0_29]
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:761)[:1.6.0_29]
    at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1436)[catalina.jar:7.0.26]
    at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:673)[catalina.jar:7.0.26]
    at org.apache.catalina.manager.ManagerServlet.doPut(ManagerServlet.java:431)[catalina.jar:7.0.26]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)[servlet-api.jar:]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)[servlet-api.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)[catalina.jar:7.0.26]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)[catalina.jar:7.0.26]
    at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)[catalina.jar:7.0.26]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)[catalina.jar:7.0.26]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)[catalina.jar:7.0.26]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)[catalina.jar:7.0.26]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)[catalina.jar:7.0.26]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)[catalina.jar:7.0.26]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)[catalina.jar:7.0.26]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)[catalina.jar:7.0.26]
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)[catalina.jar:7.0.26]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)[catalina.jar:7.0.26]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)[catalina.jar:7.0.26]
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)[tomcat-coyote.jar:7.0.26]
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)[tomcat-coyote.jar:7.0.26]
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)[tomcat-coyote.jar:7.0.26]
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)[:1.6.0_29]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)[:1.6.0_29]
    at java.lang.Thread.run(Thread.java:680)[:1.6.0_29]
Mar 12, 2012 3:03:50 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart

A: There is a version mismatch between your Spring jar files, you are using spring-web 3.0.5 and spring-beans 3.0.7, spring-context 3.0.7 and .... Use a consistent version of Spring jar files, and your problem shall go.

A: I think the problem is that you should not have the servlet spec jar in the war. Can you try to make the dependency to the servlet spec of scope provided. That will avoid putting it into the war.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I import a CSV file into Mathematica? I have a data.csv file in the Downloads folder in my Macbook. I am trying to import the data into a Mathematica notebook using
gdoubleprime =  Import["data.csv", Path -> "Macintosh HD:\\Users\\gag\\Downloads"]

It gives me an error

Import: File not found during import.

Does anyone know why?

A: This is how I import files when I'm not sure of the path name. Open the terminal by typing command-Space then terminal. Then drag the file into the terminal window. You will see something like:
/Users/yourName/Documents/Papers/fileName.csv

Highlight this and copy paste into Mathematica:
data = Import["/Users/yourName/Documents/Papers/fileName.csv"]

and you will have all the information in the csv in the variable data.

A: I recommend the use of FileNameJoin for dealing with OS full file path names. It is system indecent and you don't have to worry about such things as backslashing or directory name delimiters.
Both of the following work.
gdoubleprime = Import[FileNameJoin[{$HomeDirectory, "Downloads", "data.csv"}]];

gdoubleprime =
  Import["data.csv", Path -> FileNameJoin[{$HomeDirectory, "Downloads"}]];

A: One way is gdoubleprime = Import["/Users/gag/Downloads/data.csv"]. However this will only work for the user gag. A more general way is to use the home directory and downloads with gdoubleprime = Import["~/Downloads/data.csv"].
You should also consider one of a couple of possible general policies for data files. The first is to put them into the same directory as the notebook, so that they move together and can be placed anywhere on your drive (or on any other operating system for that matter). You could then set the directory to the notebook directory and import from there:
SetDirectory[NotebookDirectory[]]
Import["data.csv"]

A variation on this that I use (perhaps overkill) looks like this:
SetDirectory[NotebookDirectory[]]
dataDir =  "../Curated Data";
nameS = "/replace_with_file_name_to_import";
extS = ".csv";
fileNameS = dataDir <> nameS <> extS
data=Import[fileNameS]

This allows you to have multiple MMA project directories all of which look into a single directory at the same level in the directory hierarchy which contains vetted data. The extension string is optional, but I sometimes have xls, csv, etc. files all with the same "left" name and this makes it a little less likely that I will confuse them since the extension string is explicit.


text:
Q: return multiple values in jsp How can i return multiple values in a jsp java file ?
I want to return error1 and error but thats not working
I have tried this so fare:
<%!

String validate(String input) {
        String error = "";
        int receptnr = 0;
        String error1 = "";
        int varenr = 0;
        try {
                    receptnr = Integer.parseInt(input);
                    varenr= Integer.parseInt(input);

        } catch (Exception e) {
                    error = error +"Receptnummeret skal være et tal";
                    error1 = error1 +"Varenummer skal være et tal";
        }
        if (receptnr > 99999999||receptnr<1||varenr > 99999999||varenr<1)
                        error = error + " Receptnummeret skal være mellem 1 og 99999999 år";
                        error1 = error1 + " Varenummeret skal være mellem 1 og 99999999 år";
        return error, error1;

}
%>

Later on i want to return more values

A: include this in your jsp page
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

type below two lines in jsp page wherever you want to print java variable.
Do not forget to include jstl jar into your project library folder.
<c:out value="<%=error%>"/>
<c:out value="<%=error1%>"/>

A: There is no way returning multiple values with java.
What you can do is change your return type to List and  return a List of Strings in your case.
For a start ,take a look at List docs

A: you cannot return multiple value like that. You need to use Collection for returning multiple values for e.g,
code sample :
List<String> validate(String input) {
List<String> list= new ArrayList<String>();
String err="someErr";
list.add(err);

String err2="someErr";
list.add(err2);
return list;
}

A: If you are using java7 or above, you can use the
void java.lang.Throwable.addSuppressed(Throwable exception)

and have an outer exception contain multiple exceptions by throwing the outer exception.
Another way can be to create a class that can contain multiple errors in a List<>, then return an object of this class rather than String.

A: Here what you can do is You can add this errors in the any collection framework like ArrayList or vector as shown below:
        List<String> validate(String input) {
        ArrayList<String> list1 = new ArrayList<String>();

        list1.add(error);
        list1.add(error1);

    return list1;
}

And your written type would be collection.

A: u may try this:
String[] validate(String input) {
    String[] errors = new String[2];
    // ur logic here
    // errors[0] = "some error message";
    // so on
    return errors;
}


text:
Q: jMeter really slow reading large CSV results files I have some performance tests running on some servers and collect metrics (basic enough stuff, CPU and Memory per process)
Anyway CSV file can be large ~20MB (ok not large but large for .csv)
Not a code question here, but jMeter is really slow opening the csv, unusable in fact which is a pity , as it would graph the results for me.
I can open the csv no problem in Excel or other text editors.
Any recommendations for other grapher apps ?
Thanks

A: You can generate charts in non-GUI mode using JMeterPluginsCMD Command Line Tool like:
JMeterPluginsCMD.bat --generate-png CPUandRAM.png --input-jtl yourfile.csv --plugin-type PerfMon --width 1024--height 768

The Command Line Graph Plotting Tool isn't being shipped with official JMeter distribution, it is an extension, you can install this using JMeter Plugins Manager:

A: JMeter provides OOTB an HTML report that can be generated:

*

*at end of test (-e -o report-folder)

*for an existing CSV (-g csv-file -o report-folder)

It can handle very large CSV files and is very rich.
This is the standard for JMETER reporting.
See:

*

*https://jmeter.apache.org/usermanual/generating-dashboard.html#report


text:
Q: BeautifulSoup parsing issues some div not showing I'm trying to parse this page: https://www.ldlc.com/fr-be/informatique/pieces-informatique/carte-professionnelle/c4685/
The problem is, in this element: https://gyazo.com/e544be64a41a121bdb0c0f71aef50692 ,
I want the div that contains the price. If you inspect the page, you can see the html code for this part, shows like this:

    "thePrice"
    93

BUT, when using page_soup = soup(my_html_page, 'html.parser') or page_soup = soup(my_html_page, 'lxml') or page_soup = soup(my_html_page, 'html5lib') I only get this as the result for that part:

And that's it. I've been searching for hours on the internet to figure out why that inner div doesn't get parsed.
Three different parsers, and none seems to get passed the fact that the inner child shares the same class name than its parent, if this is the issue.

A: Hope its help you.
from bs4 import BeautifulSoup
import requests

url = 'https://www.ldlc.com/fr-be/informatique/pieces-informatique/carte-professionnelle/c4685/'
html = BeautifulSoup(requests.get(url).content, 'html.parser')
prices = html.find_all("div", {"class": "price"})
for price in prices:
    print(price.text)

print output
561€95
 169€94
 165€95
 1 165€94
 7 599€95
 267€95
 259€94
 599€95
 511€94
 1 042€94
 2 572€94
 783€95
 2 479€94
 2 699€95
 499€94
 386€95
 169€94
 2 343€95
 783€95
 499€94
 499€94
 259€94
 267€95
 165€95
 169€94
 2 399€95
 561€95
 2 699€95
 2 699€95
 6 059€95
 7 589€95
 10 991€95
 9 619€94
 2 479€94
 3 135€95
 7 589€95
 511€94
 1 042€94
 386€95
 599€95
 1 165€94
 2 572€94
 783€95
 2 479€94
 2 699€95
 499€94
 169€94
 2 343€95
 2 699€95
 3 135€95
 6 816€95
 7 589€95
 561€95
 267€95

A: To scrape all prices where class="price"> see this example:
import requests
from bs4 import BeautifulSoup

url = 'https://www.ldlc.com/fr-be/informatique/pieces-informatique/carte-professionnelle/c4685/'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
# Select all the 'price' classes
for tag in soup.select('div.price'):
    print(tag.text)


text:
Q: How would you redirect the output of a command into the input of another command What can I do to redirect the output of a command such as ls to the input of another command such as grep.
In other words:
what would be in the blank in the following?
$ ls /etc ____ grep host #

A: This is called piping and you simply use | in that spot.
ls /etc | grep host

Returns:
hosts
hosts.equiv
hosts-orig

Another example:
cat /etc/hosts | grep 127

Returns (for me):
#127.0.0.1  google.ca
127.0.0.1   localhost

A: You can use the pipe | character.
Your command would become: ls /etc | grep host #


text:
Q: Are spherical harmonics harmonic? According to Wikipedia, a harmonic function is one which satisfies:
$$
\nabla^2 f = 0
$$
The spherical harmonics (also according to Wikipedia) satisfy the relation
$$
\nabla^2 Y_l^m(\theta,\phi) = -\frac{l(l+1)}{r^2} Y_l^m(\theta,\phi)
$$
which is 0 only if $l = 0$. So by this definition, are the spherical harmonic functions only harmonic when $l,m = 0$?
As a related question, if I change coordinates to some $\alpha(\theta,\phi), \beta(\theta,\phi)$ and I want to find the orthogonal functions similar to the spherical harmonics in the new $\alpha,\beta$ basis, how would I do that? Would I need to solve Laplace's equation
$$
\nabla^2_{\alpha,\beta} f(\alpha,\beta) = 0
$$
where $\nabla^2_{\alpha,\beta}$ is the Laplacian expressed in the new coordinate system?

A: There is more than one Laplacian $\Delta=\nabla^2$ in play here: the ambient Euclidean one, and the invariant Laplacian on the sphere. The "spherical harmonics" extended in the natural way as polynomials, are harmonic for the ambient Euclidean space. They are eigenfunctions for the Laplacian on the sphere, with (generally) non-zero eigenvalues for that operator.
Yes, there is some connection between the two, which can be found in many places...

A: The spherical harmonics are restrictions to the unit sphere of harmonic functions on $\mathbb R^3$.  There are no non-constant harmonic functions on the sphere itself.


text:
Q: How to fit a LSTM model using tf.keras I have an error while trying to fit a model that i can't identify.
KeyError: 168
keras-2.6.0. tensorflow-2.6.0. My data is after onehotencoding and has been standardized with minmaxscaler. I don't have any NaN or inf values.
My code sample below:
x_train,x_test,y_train,y_test=train_test_split(features,target,test_size=0.2,random_state=123,shuffle=False)

from keras.preprocessing.sequence import TimeseriesGenerator
win_length = 168
batch_size = 32
num_features = 40
train_generator = TimeseriesGenerator(x_train,y_train,length=win_length,sampling_rate=1,batch_size=batch_size)
test_generator = TimeseriesGenerator(x_test,y_test,length=win_length,sampling_rate=1,batch_size=batch_size)

import tensorflow as tf
model = tf.keras.Sequential()
model.add(tf.keras.layers.LSTM(128,input_shape=(win_length,num_features),return_sequences=True))
model.add(tf.keras.layers.LeakyReLU(alpha=0.5))
model.add(tf.keras.layers.LSTM(128,return_sequences=True))
model.add(tf.keras.layers.LeakyReLU(alpha=0.5))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.LSTM(64,return_sequences=False))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Dense(1))

model.summary()

Model: "sequential_2"

Layer (type)                 Output Shape              Param #

lstm_6 (LSTM)                (None, 168, 128)          86528

leaky_re_lu_4 (LeakyReLU)    (None, 168, 128)          0

lstm_7 (LSTM)                (None, 168, 128)          131584

leaky_re_lu_5 (LeakyReLU)    (None, 168, 128)          0

dropout_4 (Dropout)          (None, 168, 128)          0

lstm_8 (LSTM)                (None, 64)                49408

dropout_5 (Dropout)          (None, 64)                0

dense_2 (Dense)              (None, 1)                 65

Total params: 267,585
Trainable params: 267,585
Non-trainable params: 0
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, mode='min')
model.compile(loss=tf.losses.MeanSquaredError(),
              optimizer=tf.optimizers.Adam(),
              metrics=[tf.metrics.MeanAbsoluteError()])
history = model.fit(train_generator,epochs=50,validation_data=test_generator,shuffle=False,callbacks=[early_stopping])

And then I got error:
Epoch 1/50
136/136 [==============================] - ETA: 0s - loss: 0.0014 - mean_absolute_error: 0.0243
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~/anaconda3/envs/python3/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2897             try:
-> 2898                 return self._engine.get_loc(casted_key)
   2899             except KeyError as err:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 168

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
<ipython-input-86-b78994610c64> in <module>
      3               optimizer=tf.optimizers.Adam(),
      4               metrics=[tf.metrics.MeanAbsoluteError()])
----> 5 history = model.fit(train_generator,epochs=50,validation_data=test_generator,shuffle=False,callbacks=[early_stopping])

~/anaconda3/envs/python3/lib/python3.6/site-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1212                 use_multiprocessing=use_multiprocessing,
   1213                 model=self,
-> 1214                 steps_per_execution=self._steps_per_execution)
   1215           val_logs = self.evaluate(
   1216               x=val_x,

~/anaconda3/envs/python3/lib/python3.6/site-packages/keras/engine/data_adapter.py in get_data_handler(*args, **kwargs)
   1381   if getattr(kwargs["model"], "_cluster_coordinator", None):
   1382     return _ClusterCoordinatorDataHandler(*args, **kwargs)
-> 1383   return DataHandler(*args, **kwargs)
   1384
   1385

~/anaconda3/envs/python3/lib/python3.6/site-packages/keras/engine/data_adapter.py in __init__(self, x, y, sample_weight, batch_size, steps_per_epoch, initial_epoch, epochs, shuffle, class_weight, max_queue_size, workers, use_multiprocessing, model, steps_per_execution, distribute)
   1148         use_multiprocessing=use_multiprocessing,
   1149         distribution_strategy=tf.distribute.get_strategy(),
-> 1150         model=model)
   1151
   1152     strategy = tf.distribute.get_strategy()

~/anaconda3/envs/python3/lib/python3.6/site-packages/keras/engine/data_adapter.py in __init__(self, x, y, sample_weights, shuffle, workers, use_multiprocessing, max_queue_size, model, **kwargs)
    922         max_queue_size=max_queue_size,
    923         model=model,
--> 924         **kwargs)
    925
    926   @staticmethod

~/anaconda3/envs/python3/lib/python3.6/site-packages/keras/engine/data_adapter.py in __init__(self, x, y, sample_weights, workers, use_multiprocessing, max_queue_size, model, **kwargs)
    792     # Since we have to know the dtype of the python generator when we build the
    793     # dataset, we have to look at a batch to infer the structure.
--> 794     peek, x = self._peek_and_restore(x)
    795     peek = self._standardize_batch(peek)
    796     peek = _process_tensorlike(peek)

~/anaconda3/envs/python3/lib/python3.6/site-packages/keras/engine/data_adapter.py in _peek_and_restore(x)
    926   @staticmethod
    927   def _peek_and_restore(x):
--> 928     return x[0], x
    929
    930   def _handle_multiprocessing(self, x, workers, use_multiprocessing,

~/anaconda3/envs/python3/lib/python3.6/site-packages/keras_preprocessing/sequence.py in __getitem__(self, index)
    372         samples = np.array([self.data[row - self.length:row:self.sampling_rate]
    373                             for row in rows])
--> 374         targets = np.array([self.targets[row] for row in rows])
    375
    376         if self.reverse:

~/anaconda3/envs/python3/lib/python3.6/site-packages/keras_preprocessing/sequence.py in <listcomp>(.0)
    372         samples = np.array([self.data[row - self.length:row:self.sampling_rate]
    373                             for row in rows])
--> 374         targets = np.array([self.targets[row] for row in rows])
    375
    376         if self.reverse:

~/anaconda3/envs/python3/lib/python3.6/site-packages/pandas/core/series.py in __getitem__(self, key)
    880
    881         elif key_is_scalar:
--> 882             return self._get_value(key)
    883
    884         if is_hashable(key):

~/anaconda3/envs/python3/lib/python3.6/site-packages/pandas/core/series.py in _get_value(self, label, takeable)
    988
    989         # Similar to Index.get_value, but we do not fall back to positional
--> 990         loc = self.index.get_loc(label)
    991         return self.index._get_values_for_loc(self, loc, label)
    992

~/anaconda3/envs/python3/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2898                 return self._engine.get_loc(casted_key)
   2899             except KeyError as err:
-> 2900                 raise KeyError(key) from err
   2901
   2902         if tolerance is not None:

KeyError: 168

My data is aggregated by the hour and 168 is the whole week. How can I fit my model properly?

A: My best guess without the data is that it is retrieving the target value using the index of the y_test which looks like a pd.Series.  After the split, y_test probably still has the old index values from target because y_test is just a view into a portion of target.  If I'm right, the first/smallest index value in your y_test series is probably ~17,512.  You can test that hypothesis with:
print(y_test.index.min())

When it goes to pick 168, it doesn't find it because the indexes start ~17K higher.  If that's the case, this should fix it:
y_test = y_test.copy().reset_index(drop=True)


text:
Q: Illegal map value with envoy v3 about typed_config http connection manager I am following this tutorial, in order to have a gRPC service transcoded to HTTP.
However, it is not up to date, since it uses envoy API v2, but this is not anymore available (I am getting an error saying this), they are now using the v3. Therefore, the syntax is slightly different.
For the v2, this snippet has no syntax error, however, it raises an error saying that the V2 is not available anymore (so it is not usable in the end):
 - name: envoy.http_connection_manager
        config:
            ...

According to this example, the way of having an HTTP connection manager (which is v3 compliant) would be to do like this, in an envoy.yml configuration file (we are explicitly telling that we are using the v3):
- name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager

However, I am getting an Illegal map value error pointing on the "@type":
error initializing configuration '/etc/envoy/envoy.yaml': yaml-cpp: error at line 15, column 17: illegal map value
I also have tried to force envoy to use the V2, with the flag --bootstrap-version 2, but it keeps saying that the v2 is no longer in use, so the only way of using envoy now is to use the v3.
Do you have experienced the same issue ?
My goal is just to have an rGPC service transcoded to HTTP.
If you need more materials to figure out the problem, I uploaded the whole project on GitHub

A: Yes, its a bit of a pain.
There's an online envoy config checker that helps a bit in determining exactly which versions ditch backwards compatability.
You have correctly switched from the legacy config to typed_config data.
However, it looks like you inadvertently included a tab in your latest config (line 15) which causes illegal map value.
You also need to migrate clusters/hosts section to load_assignments like this:
load_assignment:
  cluster_name: grpc-backend-services
  endpoints:
  - lb_endpoints:
    - endpoint:
        address:
          socket_address:
            address: 127.0.0.1
            port_value: 53000

There's a good example in the current envoy docs: https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/grpc_json_transcoder_filter


text:
Q: Spinlock not working to protect critical section on multi-core system I have a character device driver which is causing a system deadlock on a multicore system. The write call has a critical section  protected by a spin lock (spin_lock_irqsave). The ISR must obtain this lock to finish its task as well. If the ISR is called on one core while the write is executing the critical section on another, a panic occurs due to a watchdog timer detecting a hard lockup on the core for the ISR. The write process never returns to finish executing. Shouldn't the write process continue to execute on its core, release the lock which will allow the other core in its ISR to then run?
The critical section requires about 5us to complete. The hard lock occurs after 5 seconds.
I assume I'm doing something wrong but do not know what.
Appreciate any help!

A: Turns out the critical section was calling wait_for_completion_timeout. Even though the timeout was zero, it still slept and didn't wake up to release the spin lock if the interrupt occurred in the blocking section. Using try_wait_for_completion in this case resolved the issue.
I would have posted source but it spans many modules and has architecture abstractions for portability between operating systems. Would have been a mess.


text:
Q: Retorno de campo em laravel Tenho o seguinte campo guardado em minha base de dados:

Ao tentar retornar ele na view pelo Laravel 5.2 ele está retornando somente o 45 o restante não está.
o campo está definido assim no banco:

Porém outros campos como telefone estão retornando corretamente.
Alguém sabe o que poderia ser?

A: Recomendo que você remova a pontuação antes de armazenar estes valores, vai facilitar as comparações, as buscas e qualquer outra operação que envolva esta coluna.
Para resolver o seu problema, você pode utilizar o attribute casting do eloquent model. Dentro da sua classe modelo, tente definir a propriedade casts como um array, e dentro dela o seu campo como string, por exemplo:
/**
 * The attributes that should be casted to native types.
 *
 * @var array
 */
protected $casts = [
    'cnpj' => 'string',
];

Se mesmo assim não resolver, tente modificar o seu migration para utilizar o método string, dessa forma:
Schema::create('customers', function (Blueprint $table) {

    ....

    $table->string('cnpj', 14)->nullable();

    ....

}

Para mais informações você pode visitar a documentação oficial do Laravel sobre attribute casting.


text:
Q: How to maintain session in swagger editor I am using swagger for building API documentation. I am new to it. What I am doing is logging in first and the giving call to a list API. But as the session, cookies are not maintained, the list call is not getting executed. You need to first login to the application and then give call to the list.
How can I do it in swagger editor http://editor.swagger.io/#/
Thankyou

A: I just spent some time struggling with this same question and as far as I can tell the Swagger Editor will not make API calls with xhr.withCredentials = true, which means that your browser will not send cookies even if the server's CORS policy allows it. There's been some discussion of updating Swagger Editor to allow an option to do this (e.g., https://github.com/swagger-api/swagger-js/issues/251), but it doesn't appear this has been done quite yet.
Your best option is probably to avoid the entire cross-origin security issue by hosting Swagger Editor on your own domain. This is one of the suggestions: https://github.com/swagger-api/swagger-editor/blob/master/docs/cors.md#host-swagger-editor-in-your-own-domain. Just run it as if it was one of your own apps on your dev site.
Another suggestion is to just disable Chrome web security: https://github.com/swagger-api/swagger-editor/blob/master/docs/cors.md#run-swagger-editor-in-a-browser-that-ignores-http-access-control. I haven't tried this but it may not work because Swagger Editor is still not setting the XHR request appropriately.
Finally, if you're familiar with docker, you can run a Swagger Editor docker instance and link everything up. This is complicated but I accomplished this by:

*

*running our backend inside a docker container

*running a Swagger Editor instance inside another docker container on the same network (https://hub.docker.com/r/swaggerapi/swagger-editor/)

*running an nginx reverse proxy server inside a third docker container such that any requests to, e.g., http://localhost/dev/swagger-editor/ are proxy-forwarded to the swagger docker container and any requests to http://localhost/api/ are proxy-forwarded to your backend. This way the browser only sees requests to localhost and everything works just fine.

But you need to be willing to get into docker and nginx reverse proxy configs before having a reasonable expectation you'll be successful with this. Otherwise this could be another rabbit hole. Good luck!


text:
Q: jhipster - how to load data from a database and show data? I'm learning JHipster and a beginner (web developper).
Can someone show me step by step for loading data in a database (h2 or mysql or oracle) within JHipster application and showing to the home page?
Thanks in advance,

A: First, you should look at the jhipster documentation to generate an app : see this 12 minute video tutorial
Jhipster actually does a lot for you, it generates the back-end with your classes, logging, database interfacing ... But also creates a nice-looking front-end for you.
Next you should have a database up and running. In the choices you have mentioned, I think Mysql could be the most interesting for a beginner as you would have a good visibility on your database (h2 is mostly in memory, I use it for testing on my app) and the install should be simple enough.
In order to do that, you could use docker or install it manually.
For docker, you just have to type the following command :
docker run  -p 3306:3306 --name mysql_instance_01 -e MYSQL_ROOT_PASSWORD=pass -d mysql

And then if you want to stop it :
docker stop mysql_instance_01

See the docker documentation for more information about install and usage : this link
To connect and administrate your database graphically, you can use dbeaver, it is free and easy to use.
Once you have generated the app and the database is running, you have different options : either you add your 'entities' and manually populate your database, or you create an SQL script to do it for you (Which is specific to the database you're using).
JHipster is using liquibase which will automatically translate the entities created in Jhipster into your database.
This is a short introduction, I strongly advise you read the jhipster documentation. For example, this video shows what Jhipster can do and how to use it.
Hope this helps.

A: You can read this link, a basic jhipster example


text:
Q: Iterate config array in html template via Angular directives? I've got into AngularJS recently and trying to create a registration form where I would fill country list from my JavaScript config that is widely used elsewhere, thus I keep it as JS object.
I've been trying to use ng-repeat-start and *-end on my select input, but it fails.
The main question is, how do I load countries array and iterate it in my template?
Edit: 30.11.2014 - Better examples
HTML:

                Country
                <select-country ng-model="credentials.country"></select-country>

{{credentials.country}}

File:

/public/directives/countrySelector.directive.js

Directive contents:
'use strict';

angular.module('app', [])
.value('countries', [
    {name: 'Afghanistan', code: 'AF'},
    {name: 'Åland Islands', code: 'AX'}
])
.directive('selectCountry', ['countries', function (countries) {
    function link (scope, element, attrs) {
        scope.countries = countries;
    }

    return {
        template: '<select ng-options="country[1] as country[0] for country in countries"' +
        '        ng-model="credentials.country">' +
        '</select>',
        link: link,
        scope: {
            credentialsCountry: '='
        }
    };
}]);

A: just replace country[0] and country[1] with country.code and country.name
http://plnkr.co/edit/OIGGitze5LLehDes2MQ8?p=preview
or i missed something?

A: I don't think you need to make a new directive for this.  There is already a built in select directive for angular, so you are making more work for yourself than necessary. So what you could do is inject that service into your controller for the page, then bind the service to the scope of the controller like you did for the directive.  It would end up looking something like:
angular.module('app', [])
.value('countries', [
    {name: 'Afghanistan', code: 'AF'},
    {name: 'Åland Islands', code: 'AX'}
]);

and the you have a controller
app.controller('whateverTheControllerIs', ['countries', '$scope', function (countries, $scope) {
    $scope.countries = countries;
});

and then your scope is available to the template

    Country
    <select ng-options="country.name for country in countries" ng-model="credentials.country"></select>

{{credentials.country}}

As a side note: if you would like to find out about best practices for the latest Angular 1.* version.  Read everything Todd Motto says.

A: It's a good idea to create directives for things that could be commonly reused, like a country selector. You want to inject your countries into a directive where you can then iterate over it with ng-options. Plunker: http://plnkr.co/edit/zfkeLNQ0LHxR7FB0nM18?p=preview
.directive('selectCountry', ['countries', function (countries) {
  var directive = {
    template: '<select ng-options="country[1] as country[0] for country in countries"' +
              '        ng-model="ngModel">' +
              '</select>',
    link: link,
    scope: {
      ngModel: '='
    }
  };

  return directive;

  function link (scope, element, attrs) {
    scope.countries = countries;
  }
}]);


text:
Q: Spring boot Multiples bases de datos Soy nuevo en spring boot y me salte mucho del aprendizaje en java.  Con mucho trabajo construí un webservice / websocket que trabaja bastante bien.
También dispongo de una app móvil que se comunica con el webservice. Y estoy trabajando en una aplicación web en Scriptcase (lo escogí por ser muy sencillo).
Ahora necesito que todo, trabaje multi base de datos (con Mysql).
Hay una base de datos que contiene todos los usuarios e incluye la/s base/s de datos de trabajo a la/s que puede acceder (relación de 1 a muchos).
Las bases de datos de trabajo son todas iguales (las mismas tablas con diferente información).  Si tengo la necesidad, puedo crear otra base de datos e incluir la información en la base de datos de usuarios que tiene la configuración.
Mi pregunta es como hago para replicar esto en el webservice y que cada vez que un usuario se logue, consuma la base de datos que a seleccionado o que tiene permisos.
Si cuentan con un ejemplo sería realmente valioso.


text:
Q: Getting data from server regularly even when the app is closed I want to get data from the server and store it in a cache regularly, even when the app is closed. I am not sure what is the correct way to do it. I have listed down the possible ways I can think of. Please let me know the correct or the best way to do it. Really appreciate any help.

*

*Create an Activity and set a repeated alarm to call a service. The service should connect to the server and download the data in cache.

*From a fragment, check the last time the cache was updated and then if the data is out-dated, connect to server in a background thread and update the cache.

A: You can Directly Use IntentService for Frequently Updating Data
IntentService is a subclass of android.app.Service class. A stated intent service allows to handle long running tasks without effecting the application UI thread. This is not bound to any activity so, it is not getting effected for any change in activity lifecycle. Once IntentService is started, it handles each Intent using a worker thread and stops itself when it runs out of work.
IntentService would be an best solution, If you have an work queue to process. For example, if your application using analytics you will likely to send event name and related parameter to your tracking server for each user generated event. Although each event means a tiny piece of data, creating networking request on each click will result an overhead to your application
For implementation :  Updating Data from Server Using Intent Serive

A: Do take a look at Android Sync Adapter Framework.
https://developer.android.com/training/sync-adapters/index.html
Hope this helps.


text:
Q: Is it safe to run hdparm -y on lvm I've got a lvm volume, which is composed of two hard drives enclosed in external enclosure connected through usb.
As it's external and not used too much, I like to spin it down if it is not used.
I'm using Linux Mint 18.3
Disk utility (gnome-disk-utility) doesn't support disk power management on disks containing lvm volumes.
I can do it with command hdparm -y /dev/sde /dev/sdf
I can check beforehand if there is any process accessing mounted volume through fuser -m /dev/lvm/volume
Is it safe to run hdparm command on lvm volume in such a situation?

A: Yes; all the command does is ask the drive to spin down.  As soon as it is accessed again, it will automatically spin up again.


text:
Q: Regex for matching text between two regex-patters I am looking for a way to capture text and its paragraph title from a text document.
Text File:
paraTitle-1
--------
Lines and words
empty....
more lines

still part of paraTitle-1

paraTitle-2
--------
Lines and words
empty....
more lines

still part of paraTitle-2

I want to capture both the titles and the text below them.
 array = [paraTitle-1: <text...below paraTitle-11>,
          paraTitle-2: <text below paraTitle-2>]

I made a few attempts with pattern (?<=(.*))\n----*\n(?=(.*)) to no avail. Any guidance would be awesome.

A: The following regex will do:
(?!--------\R)(.*)\R--------\R((?:\R?(?!.*\R--------\R).*)+)
See regex101.
The title separator line (--------) can also be specified as -{8}, which is easier to adjust to variable length if needed, e.g. instead of exactly 8 dashes, it could be 6 or more: -{6,}
Explanation:

*

*Capture a line of text (paragraph title):
(.*)\R

*

*The . doesn't match line break characters

*\R matches line breaks, including the Windows CRLF pair. If your regex engine doesn't support \R, use \r?\n as a simple alternative.

*Make sure the captured text is not the title separator line:
(?!--------\R)

*Skip the mandatory title separator line:
--------\R

*Capture the paragraph text, as a repeating group of lines:
((?:xxx)+)

*A line has an optional leading line break (first line doesn't have one):
\R?.*

*But make sure the line is not the title of the next paragraph, i.e. it's not a line followed by the title separator line.
(?!.*\R--------\R)


text:
Q: How can I loop a range within find_element_by_xpath? I'm getting this error when trying to loop through the following range.
TypeError: Failed to execute 'evaluate' on 'Document': The result is not a node set, and therefore cannot be converted to the desired type.
for x in range(1, 12):
addressxpath = '"table/tbody/tr[' + str(x) + ']/td/ul[1]/li[1]/div/a"'

address = driver.find_element_by_xpath(addressxpath)


text:
Q: SQL Server - Using spatial data I'm using SQL Server 2008 R2 for real-time location aware service. The service mostly receives location data (lat/lon) from a user and returns locations around the user.
The data is being sent from each user once in a second. For every location being reported there is a query that checks other users around that user and returns data about them.
I'm using Lat/Lon as float fields and run a scalar-function to find the closest users.
I guess that approach is not the best. I know there are spatial data constructs in SQL Server, but don't know if they are good. Should I use them? If so, what is the best approach?
What approach should I take to make this operation as fast and scalable as possible?
Maybe NoSQL is better for spatial data?
P.S - I'm talking about thousands and tens of thousands users at any given time.

A: Yes you should use spatial indexes, but you should also consider there are limitations that simple sargability concerns can resolve.
A spatial index is good for finding locations in a particular area. It's not good for working out which distance is shortest.
So... when trying to find the closest item, start with a small distance and find items in that area. Something like:
select id
from dbo.locations
where location.STIntersects(@point.STBuffer(@somedistance)) = 1;

...and slowly increase the value of @somedistance until you find what you're looking for. This will allow Seeks to be done, quickly eliminating locations that are not of interest.


text:
Q: reCaptcha doesnt appear in comment (manual or plugin) I tried the following:

*

*https://www.quora.com/How-can-I-insert-Captcha-code-in-WordPress-theme-without-using-any-plugin

*https://codeforgeek.com/add-google-recaptcha-wordpress/

*https://pluginsforwp.com/blog/add-recaptcha-to-wordpress-comments/
But I can't get comments with recaptcha. I also tried also "reCaptcha by BestWebSoft" and nothing appears.
I am using News Talk Theme (child theme - active) https://wordpress.org/themes/news-talk/ that is from NewsUp theme (parent theme).
I tried "reCaptcha by BestWebSoft" with other themes (https://themesinfo.com/rehub-vendor-wordpress-magazine-theme-bmke/2/) and it works. But some also don't work for other theme https://themegrill.com/themes/colormag/. So maybe it is a theme issue?
So far, I've only tried with adding the code in the parent theme because the child does not have a single.php file. Is this the right way? Or how should I do it?
Here is a screenshot of my comment, there is no reCaptcha

A: As I see you are using reCaptcha v3 as the examples you try and it will not appear until the user score is under the minimum you added into the configuration but it is still working and checking the user score before he submits your form.
anyway if you configured the plugin correctly you may see the reCaptcha sticky button at the bottom right corner of your website


text:
Q: How to determine all the isomorphisms I am trying to find all the isomorphisms from the representation modulo p(x), where $$p(x) = X^3 + X^2 + X + 2,$$ to the representation modulo q(Y), where $$q(y) =  Y^3 + 2Y^2 + 1,$$ in $$ GF(3^3) $$
I believe there will be 3 of them. Below is what I have done so far:
$$ (a + bX + cX^2)(d + eX + kX^2) = (a,b,c)(d,e,k) = ad + (ae + bd)X + (ak+be+cd)X^2 + (bk+ce)X^3 + ckX^4 $$
After reducing the above to p(x):
$$(a,b,c)(d,e,k) = (ad-2(bk+ce-ck),ac+bd-ck-bk-ce,ak+be+cd-bk-ce)$$
After reducing the same thing but to q(x) now:
$$(a,b,c)(d,e,k) = (ad-(bk+ce-2ck),ae+bd-ck,ak+be+cd-2(bk+ce-2ck))$$
Isomorphism needs to satisfy the following property:
$$f(a,b,c) * f(d,e,k) = f((a,b,c)*(d,e,k))$$
I assume I need to define $$f(x) = u + vX + wX^2$$
and express f(a,b,c) in terms of 'u's,'v's and 'w's but this is where I get confused and don't know what to do.


text:
Q: How can I display-filter the correspondant response to a specific display-filtered request in wireshark? I am just tracing a very sporadic error in responses to HTTP requests to a specific resource on an embedded device's webserver.
So my plan is to run a test over night (or even weekend), capture the traffic with wireshark and then skim the dumpfiles for damaged responses.
With "http.request.uri matches "^/resource/to/be/tested" display filter I get all wanted requests.
But I need all the responses to these requests - how can I archive this?

A: You can do it with tshark follow the below steps:

*

*Filter all HTTP packets with specific pattern in request uri

*Follow TCP stream based on src IP, src port, dst IP, dst port

$ tshark -r x.pcap -R 'http.request.uri matches "^/resource/to/be/tested"' \
-T fields -e ip.src -e tcp.srcport -e ip.dst -e tcp.dstport | \
while read line; do
    tshark -r x.pcap \
    -R "http && ip.addr == `echo $line | awk '{ print $1 }'` && \
    tcp.port == `echo $line | awk '{ print $2 }'` && \
    ip.addr == `echo $line | awk '{ print $3 }'` && \
    tcp.port == `echo $line | awk '{ print $4 }'`" \
    echo
done


text:
Q: Pandas - Column Compare Return False when Nan's are present in both the columns I am comparing two columns row by row.
It Returns false when NaN's are present in both the columns and I want to return True if Nan's are present.
For Example,
This is the code I am using :-
Pre_Out_df[res_name] = Pre_Out_df[plain_col] == Pre_Out_df[b_col]

This Returns False for example, when both Columns have Nan for the comparing rows.

A: Check missing or not missing and then DataFrame.all for check if both values are Trues or
DataFrame.any for check if at least one value is True:
df = pd.DataFrame({'plain_col':['1A12','1C12',np.nan],
                   'b_col':[np.nan,'1B',np.nan]})

df['res_name1'] = df[['plain_col', 'b_col']].isnull().all(axis=1)
df['res_name2'] = df[['plain_col', 'b_col']].isnull().any(axis=1)

df['res_name3'] = df[['plain_col', 'b_col']].notnull().all(axis=1)
df['res_name4'] = df[['plain_col', 'b_col']].notnull().any(axis=1)

print (df)
  plain_col b_col  res_name1  res_name2  res_name3  res_name4
0      1A12   NaN      False       True      False       True
1      1C12    1B      False      False       True       True
2       NaN   NaN       True       True      False      False


text:
Q: Emacs initialization as org file: how can I get the right version of org-mode? I've been experimenting with the org-babel tutorial that describes how to put the bulk of your emacs init.el file into an org file. However, I would like to use org-mode 8 (mainly for the new exporter) and I'm on gnu emacs 24.3.1 (for windows) which comes with org-mode 7.9 built-in, so I have org-mode installed from the elpa package manager instead of using the built-in version.
My problem is that emacs loads the org-mode that comes with emacs rather than the one I have installed in elpa. Is there a way to load the elpa org-mode?
Here is my init.el, modified from the org-babel tutorial to point (I thought) to my org-mode distribution - but my emacs-lisp knowledge is minimal so I don't really know what it is doing.
;;; From http://orgmode.org/worg/org-contrib/babel/intro.html#literate-programming
;;; init.el --- Where all the magic begins
;;
;; This file loads Org-mode and then loads the rest of our Emacs initialization from Emacs lisp
;; embedded in literate Org-mode files.
;; Load up Org Mode and (now included) Org Babel for elisp embedded in Org Mode files
(setq dotfiles-dir (file-name-directory (or (buffer-file-name) load-file-name)))
(let* ((org-dir (expand-file-name
             "elpa" (expand-file-name
                     "org-plus-contrib-20130624" )))
  (org-contrib-dir (expand-file-name
                     "lisp" (expand-file-name
                             "contrib" (expand-file-name
                                        ".." org-dir))))
       (load-path (append (list org-dir org-contrib-dir)
                      (or load-path nil))))
  ;; load up Org-mode and Org-babel
  (require 'org-install)
  (require 'ob-tangle))

;; load up all literate org-mode files in this directory
(mapc #'org-babel-load-file (directory-files dotfiles-dir t "\\.org$"))

;;; init.el ends here

A: Put (package-initialize) before any calls to org-babel-load-file or any other Org function, and you'll get the ELPA version.

A: I use same kind of initialization and recently did two major changes:

*

*Changed to https://github.com/dimitri/el-get based packaging management

*upgraded to org-mode > 8.0

Here's how my init.el looks now,
https://github.com/d4gg4d/my-emacs/blob/master/init.el
Also,

*

*I removed .deb packaged org-mode which came with ubuntu

A: Though already solved and only somewhat related, I thought I would offer this for those who don't use package-based solutions but need to unload things like org and cedet/semantic, etc. without restarting emacs.
In general for unloading a set of features based on a starting name regexp, I would do something like this - which seems more complete than the hardcoded version from Andreas' answer, which doesn't seem to cover all loaded org features (at least in my case).
load-history is a massive assoc list of files -> reqs,provides,defuns,...
(mapc
 #'(lambda (f) (and (featurep f) (unload-feature f t)))
 (loop for file-syms in load-history
       for prov = (assoc 'provide file-syms)
       with features
       if (and prov (string-match "^org" (symbol-name (cdr prov))))
       collect (cdr prov) into features
       finally return features))

Replace the regexp "^org" to suit your needs, or go wild and make it a defun.
This could also be modified to grab all loaded org features from load-history, unload them, add the new load-path, and reload those same features from the new location.

A: I configure package repositories in an org-based configuration file as well, so, to adjust the load path I have this in my init.el prior to loading org:
;; remove org-mode shipped with emacs from the load-path
(setq custom-org-path (car (file-expand-wildcards
                            (concat my-init-dir "elpa/org-plus-contrib-20*"))))
(when custom-org-path
  (setq load-path (remove-if (lambda (x) (string-match-p "org$" x)) load-path))

  (add-to-list 'load-path custom-org-path))

A: Unloaded shipped org-mode and installed development version this way
(defun unload-org-mode ()
  (interactive)
  (and (featurep 'org-agenda)(unload-feature 'org-agenda t ))
  (and (featurep 'org-bbdb)(unload-feature 'org-bbdb t ))
  (and (featurep 'org-bibtex)(unload-feature 'org-bibtex t ))
  (and (featurep 'org-compat)(unload-feature 'org-compat t ))
  (and (featurep 'org-exp)(unload-feature 'org-exp t ))
  (and (featurep 'org-exp-blocks)(unload-feature 'org-exp-blocks t ))
  (and (featurep 'org-faces)(unload-feature 'org-faces t ))
  (and (featurep 'org-footnote)(unload-feature 'org-footnote t ))
  (and (featurep 'org-gnus)(unload-feature 'org-gnus t ))
  (and (featurep 'org-html)(unload-feature 'org-html t ))
  (and (featurep 'org-info)(unload-feature 'org-info t ))
  (and (featurep 'org-infojs)(unload-feature 'org-infojs t ))
  (and (featurep 'org-irc)(unload-feature 'org-irc t ))
  (and (featurep 'org-jsinfo)(unload-feature 'org-jsinfo t ))
  (and (featurep 'org-list)(unload-feature 'org-list t ))
  (and (featurep 'org-macs)(unload-feature 'org-macs t ))
  (and (featurep 'org-mew)(unload-feature 'org-mew t ))
  (and (featurep 'org-mhe)(unload-feature 'org-mhe t ))
  (and (featurep 'org-rmail)(unload-feature 'org-rmail t ))
  (and (featurep 'org-src)(unload-feature 'org-src t ))
  (and (featurep 'org-vm)(unload-feature 'org-vm t))
  (and (featurep 'org-w3m)(unload-feature 'org-w3m t))
  (and (featurep 'org-wl)(unload-feature 'org-wl t )))

(defun ar-load-PATH-TO-NEW-org-mode ()
  (interactive)
  (unload-org-mode)
  (find-file "~/PATH-TO-NEW-org-mode/lisp/ob-python.el")
  (add-to-list 'load-path "~/PATH-TO-NEW-org-mode")
  (add-to-list 'load-path "~/PATH-TO-NEW-org-mode/lisp")
  (load "~/PATH-TO-NEW-org-mode/lisp/ob-comint.el" nil t)
  (load "~/PATH-TO-NEW-org-mode/lisp/ob-emacs-lisp.el" nil t)
  (load "~/PATH-TO-NEW-org-mode/lisp/org.el" nil t)
  (load "~/PATH-TO-NEW-org-mode/lisp/ob-eval.el" nil t)
  (load "~/PATH-TO-NEW-org-mode/lisp/ob.el" nil t)
  (load "~/PATH-TO-NEW-org-mode/lisp/ob-python.el")
  ;; (load "~/PATH-TO-NEW-org-mode/testing/org-test-ob-consts.el" nil t)
  ;; (load "~/PATH-TO-NEW-org-mode/testing/org-test.el" nil t)
  (load-this-directory "~/PATH-TO-NEW-org-mode/lisp")
    (org-babel-do-load-languages
   'org-babel-load-languages
   '(
     (sh . t)
     (python . t)
     (emacs-lisp . t)
     (perl . t)
     (R . t)
     ))
)

(ar-load-PATH-TO-NEW-org-mode)

Replace PATH-TO-NEW-org-mode with the directory your version whished resides.


text:
Q: Queue access to the database to avoid multiple cache items I have a music related ASP.NET web site which caches a lot of static information from the database on the first request.
Sometimes, the application is reset and cache is cleared while the application is on heavy load and then all http requests go to the database to retrieve that static data and cache it for other requests.
How can I ensure that only one request go to the database and cache the results, so that other request simply read that info from cache and not needlessly retrieve the same info over and over again.
Can I use thread locking? For example, can I do something like lock(this) { db access here }?

A: Yes, in your caching code, you'll want to put your database-accessing code inside a lock block. However, don't lock on this. Typically you'd do something like
private static readonly object staticObjectToLockOn = new object();

...

if (cache[cacheKey] == null)
{
   lock(staticObjectToLockOn)
   {
      // double-check the cache is still null inside the lock
      if (cache[cacheKey] == null)
      {
         // get data from the database, add to cache
      }
   }
}

A: Point is with using a generic lock, is that you are getting in serious trouble with alot of users, as the thread can be blocked for every cache item when your app starts. Furthermore will every thread still create it's own lock and query (and with 10 machines and 32 threads each, that's 320 requests!)
We us an approach like this (> 10 mio pageviews / day, and memcached):
When grabbing data from the database, we store an 'in progress' message in a similar cachekey (f.e. adding in-progress to the cachekey or something). When another thread cannot find the current item, it will check the in progress key. If the item is in progress, wait a couple of ms. and try to fetch again. If after a couple of moments (500 ms. ?) do the database action again from the current thread, to protect yourself from killing the app when an item keeps on 'in progress'.
This way you can create some sort of lock, but over multiple machines etc.
Without doing this, our CMS server will get like 200 of the same requests within the first second, so we really need cluster-wide locks.


text:
Q: Why thread_id creates not in order? I tried to create 10 threads, and output each tread index. My code is shown as below, I am wondering why   they are repeating instead of arranging in order?
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "util.h"
#include <errno.h>
#include <unistd.h>

#include <signal.h>
#include <time.h>
pthread_mutex_t request_buf_lock = PTHREAD_MUTEX_INITIALIZER;
void * worker(void *arg)
{
    int thread_id = *(int*)arg;
    //  int requests_handled = 0;
    //requests_handled = requests_handled + 1;
printf("%d\n",thread_id);
}
int main(int argc, char** argv)
{

    pthread_t dispatchers[100];
    pthread_t workers[100];

    int i;
    int * thread_id = malloc(sizeof(int));

    for (i = 0; i < 10; i++) {
            *thread_id = i;
            pthread_create(&workers[i], NULL, worker, (void*)thread_id);
    }

    for (i = 0; i < 10; i++) {
            pthread_join(workers[i], NULL);
    }

    return 0;
}

And the output result is:
4
5
5
6
6
6
7
8
9
9
But I expected it as:
0
1
2
3
4
5
6
7
8
9
Anyone has any idea or advice?

A: All 10 threads execute in parallel, and they all share a single int object, the one created by the call to malloc.
By the time your first thread executes its printf call, the value of *thread_id has been set to 4. Your second and third threads execute their printf calls when *thread_id has been set to 5. And so on.
If you allocate a separate int object for each thread (either by moving the malloc call inside the loop or just by declaring an array of ints), you'll get a unique thread id in each thread. But they're still likely to be printed in arbitrary order, since there's no synchronization among the threads.


text:
Q: Wait for forEach with a promise inside to finish I have a problem with waiting for my forEach loop, which has a promise inside, to finish. I can't find any real solution, that would make the script wait till the end, before continuing with the execution. I cannot make the someFunction synchronous.
makeTree: function (arr) {
    arr.forEach(function (resource) {
        someModule.someFunction(resource).then(function () { //a Promise
            //do something with the resource that has been modified with someFunction
        });
    });
    // do something after the loop finishes
}

A: Instead of forEach() use map() to create an array of promises and then use Promise.all()
let promiseArr = arr.map(function (resource) {
    // return the promise to array
    return someModule.someFunction(resource).then(function (res) { //a Promise
        //do something with the resource that has been modified with someFunction
        return res;
    })
});

Promise.all(promiseArr).then(function(resultsArray){
   // do something after the loop finishes
}).catch(function(err){
   // do something when any of the promises in array are rejected
})

A: Try this,
makeTree: function (arr) {
   var promises = [];
   arr.forEach(function(resource) {
      promises.push(someModule.someFunction(resource));
   });
   Promise.all(promises).then(function(responses) {
      // responses will come as array of them
      // do something after everything finishes
   }).catch(function(reason) {
      // catch all the errors
      console.log(reason);
   });
}

You can refer this link for more on Promise.all with simple examples.


text:
Q: Pagination not working for ACF Query on front-page.php I'm using the following query based on the ACF documentation. For some reason, the pagination isn't working. Can anyone tell me what I'm missing? The pagination code is working fine on an archive.php page.
front-page.php
<?php
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$args = array(
    'paged' => $paged,
    'posts_per_page'    => 6,
    'post_type'     => 'airdrop',

    'meta_query'    => array(
        'relation'      => 'AND',
        array(
            'key'       => 'airdrop_type',
            'value'     => array('Airdrop'),
            'compare'   => 'IN',
        )
    )
);
$the_query = new WP_Query( $args ); ?>
<?php if( $the_query->have_posts() ): ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

    <?php get_template_part('airdrops/full-width'); ?>

<?php endwhile; ?>

    <div class="col-md-12">
        <?php html5wp_pagination(); ?>
    </div>

<?php endif; ?>
<?php wp_reset_query(); ?>

pagination code in functions.php
add_action('init', 'html5wp_pagination');

function html5wp_pagination()
{
    global $wp_query;
    $big = 999999999;
    echo paginate_links(array(
        'base' => str_replace($big, '%#%', get_pagenum_link($big)),
        'format' => '?paged=%#%',
        'current' => max(1, get_query_var('paged')),
        'total' => $wp_query->max_num_pages
    ));
}

A: check this
Pagination_Parameters
And  http://prntscr.com/kt47rs
You don't need use add_action('init','...') function for pagination.
and use calling function like : html5wp_pagination($the_query );

A: Please check, replace with this
 function html5wp_pagination()
    {
        global $the_query;
        $big = 999999999;
        echo paginate_links(array(
            'base' => str_replace($big, '%#%', get_pagenum_link($big)),
            'format' => '?paged=%#%',
            'current' => max(1, get_query_var('paged')),
            'total' => $the_query->max_num_pages
        ));
    }

A: Using a plugin may not be the best solution but I ended up using WP-PageNavi which allows wp_query. This worked for me and solved the problem.
Documentation can be found here: http://scribu.net/wordpress/wp-pagenavi/wpn-2-74.html


text:
Q: What are maximum dimensions of Three.js render canvas? When I set render canvas size to ~4000x4000px it's ok, however starting from around 4000 (tested 5k, 6k, 8k) it seems that scene is "cut off" in some way. See image below:

So up to ~4k content is properly rendered in the center of canvas and for higher canvas sizes it cuts the content.

*

*Is it a Three.js/WebGL limitation?

*If yes then what are actual maximum canvas dimensions that don't cause any "deformations"?

*Is there anything I can do about it? I need to get canvas snapshot in high resolution (8k).

A:
Is there anything I can do about it? I need to get canvas snapshot in high resolution (8k).

You can render portions of the scene using Camera.setViewOffset and then assemble the parts into a large image. You can look at this sample where it renders the image in 4 separate parts. In that example it makes 4 renderers but for your case you'd only need one and just render->capture canvas->render->capture canvas-> repeat until you get all parts. Then you need a way to stitch those parts together. You could use gIMP or Photoshop for example.
Here's library that does this
https://greggman.github.io/dekapng/
I know there is an answer here I wrote that shows how to do this in three.js since I wrote that library because of my answer. Unfortunately 10 minutes of searching didn't bring up >:(

A: This is not a limitation of three.js but a limitation of the maximum size of the drawing buffer. It's defined by the browser vendor and can't be exceeded by an application. More information in this github issue:
https://github.com/mrdoob/three.js/issues/5194


text:
Q: Robo cup 2d rcssserver 15 ready to use parser I have installed robocup 2d rcssserver 15.x.x and a client team in my machine, I am trying to understand how server-client communication works in robocup 2d simulation.I need to know which parser(ready to use) is available for "Robocup 2d simulator" ?

A: Some base codes have been already released. All of them of-course contain the connection and parser part, which is what you're looking for.
Agent2D is one of the base codes written by Hidehisa AKIYAMA who is also the developer of rcssserver2d. You can get it from here.
Beside that, WrightEagle team also releases their base code. You can download it from here.
Those two mentioned above are the most up-to-date base codes in this field. You can also get more stuff like that from here and here.

A: read server-manual (can be found in sourceforge.org )
or use a base code such as agent2d or WEBase or UVA_Trilearn base


text:
Q: nothing provides libcrypto.so.1.0.0(OPENSSL_1.0.0)(64bit) I ran over a sles 12 server and i got this issue when I try to install php7-openssl-7.2.13-155.1.x86_64.rpm :
zypper in ./php7-openssl-7.2.13-155.1.x86_64.rpm
Loading repository data...
Reading installed packages...
Resolving package dependencies...

Problem: nothing provides libcrypto.so.1.0.0(OPENSSL_1.0.0)(64bit) needed by php7-openssl-7.2.13-155.1.x86_64
 Solution 1: do not install php7-openssl-7.2.13-155.1.x86_64
 Solution 2: break php7-openssl-7.2.13-155.1.x86_64 by ignoring some of its dependencies

But when I check i got the lib:
ls /lib64/*crypto*
/lib64/libcrypto.so.1.0.0

But I don't know if it's well declared :
ldconfig -p | grep libcrypto.so
        libcrypto.so.1.0.0 (libc6,x86-64) => /lib64/libcrypto.so.1.0.0
        libcrypto.so.1.0.0 (libc6) => /lib/libcrypto.so.1.0.0

Thanks for your help.

A: Thanks to dratenik, I've installed the package ignoring the warning and it works !


text:
Q: How to print a triangle using for loops I need some help trying to solve this, right now it keeps printing vertically only

height = int(input("Height of triangle: "))
for x in range(height):
   for y in range(height):
     print("#",end = '')
     print()

A: Here's my solution, it involves the use an of accumulator:
height = int(input("Height of triangle: "))
count = 0

for i in range(height-1):
    print('#' + ' '*count + '#')
    count += 1

print('#'*height)

A: height = 6

for rowIndex in xrange(height-1):
    row = [' ']*height            # yields array of size height
    row[0] = row[rowIndex+1] = '#'
    print (''.join(row))    # This makes string from array
print ('#'*height)          # Print lower side of triangle

You can also remove "+1" on line 5 to get more "edgy" triangles.


text:
Q: Adding images from an external gallery to a SilverStripe site via a BuildTask I'm making a Silverstripe build task to get many images from an external gallery, and create/upload them into the /assets/images/gallery folder with the necessary database links to the GalleryPage.
So I load the list of Urls, display the images to the browser, now how do I save an image into the assets folder with the necessary GalleryPage database links?
class ImportGalleryTask extends BuildTask {
    public function writeImage($data) {
        //$data->Title
        //$data->Filename
        //$data->Url
        //this is the external url that I can output as an image to the browser
        //
        // folder to save image is 'assets/images/gallery'
        //
        // ? save into folder and database and associate to PageImageBelongsToID  ?
    }
}

A: You can use copy to copy a remote file to your local filesystem. PHP must be configured to support allow_url_fopen though.
So, your resulting function might look like this:
/**
 * @param $data
 * @return null|Image return written Image object or `null` if failed
 */
public function writeImage($data)
{
    // The target folder for the image
    $folder = Folder::find_or_make('images/gallery');

    // assuming that $data->Filename contains just the file-name without path
    $targetPath = $folder->getFullPath() . $data->Filename;

    // Check if an image with this name already exists
    // ATTENTION: This will overwrite existing images!
    // If you don't want this, you need to implement this differently
    if(
        file_exists($targetPath) &&
        $image = Image::get()->where(array(
            '"Name" = ?' => $data->Filename,
            '"ParentID" = ?' => $folder->ID
        ))->first()
    ){
        // just copy the new file over…
        copy($data->Url, $targetPath);
        // … and delete all cached images
        $image->deleteFormattedImages();
        // and we're done
        return $image;
    }

    // Try to copy the file
    if (!copy($data->Url, $targetPath)) {
        return null;
    }

    // Write the file to the DB
    $image = Image::create(array(
        'Name' => $data->Filename,
        'ParentID' => $folder->ID,
        'Filename' => $folder->getRelativePath() . $data->Filename
    ));

    $image->write();
    return $image;
}


text:
Q: Angular what's the parent component for Material2 Dialog I use code like const dialogRef = this.dialog.open(...); in component MyComponent, which has provider MyService, and in the constructor of the  dialog, I have public myService: MyService, however, it comes the error no provider for the service, so what's the parent component that the dialog can succeed service from?

A: Material Dialog doesn't have a parent component. You can inject your service inside a component which calls dialog.open and pass it to the dialog configuration.

A: You need to import the service in app.module.ts file.
import { MyService } from './myservice.service';

@NgModule({
  providers: [
     MyService
]
})

A: There are two ways of doing that.

*

*As yer has told provide the service in module level. (app.module.ts or any other)

*As marko has told pass it (code below)
const dialogRef = this.dialog.open(AbcComponent, { myService: MyService });
export class AbcComponent {
        constructor(@Inject(MAT_DIALOG_DATA) public myService: MyService, ...) {}
}


text:
Q: Valgrind malloc leaks I'm writing a program to search though directories for a requested file. The output on command line will be the path of the directory to the file, for each file found with the same name. For some reason it is giving memory leaks when I run it with valgrind.
I am running on a linux virtual machine on a windows box.
I updated my valgrind output. I have no leaks free leaks but still errors.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <string.h>

struct tree_t {

  char *name;
  int  nchildren;
  struct tree_t **children;
};

char *make_path(const char *dirname, const char *filename) {
  char *fullpath = (char *) malloc((strlen(dirname) + strlen(filename) + 1 + 1) * sizeof(char));
  strcat(fullpath, dirname);
  strcat(fullpath, "/");
  strcat(fullpath, filename);
  return fullpath;
}

struct tree_t *get_tree(const char *name) {
  struct tree_t *tree = (struct tree_t *) malloc(sizeof(struct tree_t));
  char *namecp = (char *) malloc((strlen(name) + 1) * sizeof(char));
  strcpy(namecp, name);
  tree->name = namecp;

  DIR *dir = opendir(name);
  if (dir == NULL) {
    tree->nchildren = 0;
  } else {
    tree->nchildren = 0;
    int numsubdirs = 0;

    struct dirent *entry;

    while((entry = readdir(dir))) {
      if (strcmp(entry->d_name,".") != 0 && strcmp(entry->d_name,"..") != 0) {
        tree->nchildren++;
        DIR *subdir = opendir(entry->d_name);
        if (subdir != NULL) {
          numsubdirs++;
        }
        closedir(subdir);
      }
    }

    tree->children = (struct tree_t **) malloc(numsubdirs * sizeof(struct tree_t **));
  }
  closedir(dir);
  return tree;
}

void find_in_tree(const struct tree_t *root, const char *filename) {
  int i = 0;

  DIR *dir = opendir(root->name);

  if (dir != NULL) {

    struct dirent *entry;

    while((entry = readdir(dir))) {
      if (strcmp(entry->d_name,".") != 0 && strcmp(entry->d_name,"..") != 0) {
        char *fullpath = make_path(root->name, entry->d_name);
        DIR *subdir = opendir(fullpath);
        if (subdir != NULL) {
          root->children[i] = get_tree(fullpath);
          find_in_tree(root->children[i], filename);
          free(root->children[i]);
          i++;
        } else if (strcmp(entry->d_name, filename) == 0) {
          printf("%s\n", fullpath);
        }
        free(fullpath);
      }
    }
  }

  free(root->name);
  free(root->children);

}

int main(int argc, char **args) {
  printf("What root directory do you want to start from?\n");
  char rootdir[256];
  scanf("%s",rootdir);

  char searchfile[256];
  printf("What file do you want to search for?\n");
  int result = scanf("%s",searchfile);

  if (result == EOF) {
    printf("\n");
    exit(1);
  }

  struct tree_t *root = get_tree(rootdir);
  find_in_tree(root, searchfile);
  free(root);

  return 0;
}

This is what my memcheck looks like after being run.
[vosterjl@clark ~]$ valgrind --tool=memcheck --leak-check=yes -v --track-origins=yes ./dirch
==1464== Memcheck, a memory error detector
==1464== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==1464== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==1464== Command: ./dirch
==1464==
--1464-- Valgrind options:
--1464--    --tool=memcheck
--1464--    --leak-check=yes
--1464--    -v
--1464--    --track-origins=yes
--1464-- Contents of /proc/version:
--1464--   Linux version 2.6.18-274.17.1.el5 (mockbuild@hs20-bc2-5.build.redhat.com) (gcc version 4.1.2 20080704 (Red Hat 4.1.2-51)) #1 SMP Wed Jan 4 22:45:44 EST 2012
--1464-- Arch and hwcaps: AMD64, amd64-sse3-cx16
--1464-- Page sizes: currently 4096, max supported 4096
--1464-- Valgrind library directory: /usr/lib64/valgrind
--1464-- Reading syms from /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch (0x400000)
--1464-- Reading syms from /usr/lib64/valgrind/memcheck-amd64-linux (0x38000000)
--1464--    object doesn't have a dynamic symbol table
--1464-- Reading syms from /lib64/ld-2.5.so (0x3ca2e00000)
--1464-- Reading suppressions file: /usr/lib64/valgrind/default.supp
--1464-- REDIR: 0x3ca2e14730 (strlen) redirected to 0x3803e767 (vgPlain_amd64_linux_REDIR_FOR_strlen)
--1464-- Reading syms from /usr/lib64/valgrind/vgpreload_core-amd64-linux.so (0x4802000)
--1464-- Reading syms from /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so (0x4a03000)
==1464== WARNING: new redirection conflicts with existing -- ignoring it
--1464--     new: 0x3ca2e14730 (strlen              ) R-> 0x04a070b0 strlen
--1464-- REDIR: 0x3ca2e14550 (index) redirected to 0x4a06f20 (index)
--1464-- REDIR: 0x3ca2e14700 (strcmp) redirected to 0x4a07180 (strcmp)
--1464-- Reading syms from /lib64/libc-2.5.so (0x3ca3200000)
--1464-- REDIR: 0x3ca3279f60 (rindex) redirected to 0x4a06dd0 (rindex)
--1464-- REDIR: 0x3ca3279b70 (strlen) redirected to 0x4a07070 (strlen)
Directory?
dir1
Search file?
test.txt
--1464-- REDIR: 0x3ca3274de0 (malloc) redirected to 0x4a0608a (malloc)
--1464-- REDIR: 0x3ca3279630 (strcpy) redirected to 0x4a08a70 (strcpy)
--1464-- REDIR: 0x3ca327ac80 (memmove) redirected to 0x4a07370 (memmove)
--1464-- REDIR: 0x3ca3272890 (free) redirected to 0x4a05c9a (free)
--1464-- REDIR: 0x3ca3279280 (strcat) redirected to 0x4a07d40 (strcat)
==1464== Invalid write of size 8
==1464==    at 0x400AF3: find_in_tree (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==    by 0x400C1F: main (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==  Address 0x4c2c170 is 0 bytes after a block of size 0 alloc'd
==1464==    at 0x4A0610C: malloc (vg_replace_malloc.c:195)
==1464==    by 0x4009D2: get_tree (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==    by 0x400C0B: main (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==
==1464== Invalid read of size 8
==1464==    at 0x400B0B: find_in_tree (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==    by 0x400C1F: main (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==  Address 0x4c2c170 is 0 bytes after a block of size 0 alloc'd
==1464==    at 0x4A0610C: malloc (vg_replace_malloc.c:195)
==1464==    by 0x4009D2: get_tree (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==    by 0x400C0B: main (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==
--1464-- REDIR: 0x3ca32795f0 (strcmp) redirected to 0x4a07140 (strcmp)
dir1/dir2/test.txt
==1464== Invalid read of size 8
==1464==    at 0x400B2C: find_in_tree (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==    by 0x400C1F: main (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==  Address 0x4c2c170 is 0 bytes after a block of size 0 alloc'd
==1464==    at 0x4A0610C: malloc (vg_replace_malloc.c:195)
==1464==    by 0x4009D2: get_tree (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==    by 0x400C0B: main (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==
dir1/test.txt
Search file?

--1464-- REDIR: 0x3ca327ae20 (memset) redirected to 0x4a07320 (memset)
==1464==
==1464== HEAP SUMMARY:
==1464==     in use at exit: 0 bytes in 0 blocks
==1464==   total heap usage: 22 allocs, 22 frees, 262,763 bytes allocated
==1464==
==1464== All heap blocks were freed -- no leaks are possible
==1464==
==1464== ERROR SUMMARY: 6 errors from 3 contexts (suppressed: 4 from 4)
==1464==
==1464== 2 errors in context 1 of 3:
==1464== Invalid read of size 8
==1464==    at 0x400B2C: find_in_tree (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==    by 0x400C1F: main (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==  Address 0x4c2c170 is 0 bytes after a block of size 0 alloc'd
==1464==    at 0x4A0610C: malloc (vg_replace_malloc.c:195)
==1464==    by 0x4009D2: get_tree (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==    by 0x400C0B: main (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==
==1464==
==1464== 2 errors in context 2 of 3:
==1464== Invalid read of size 8
==1464==    at 0x400B0B: find_in_tree (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==    by 0x400C1F: main (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==  Address 0x4c2c170 is 0 bytes after a block of size 0 alloc'd
==1464==    at 0x4A0610C: malloc (vg_replace_malloc.c:195)
==1464==    by 0x4009D2: get_tree (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==    by 0x400C0B: main (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==
==1464==
==1464== 2 errors in context 3 of 3:
==1464== Invalid write of size 8
==1464==    at 0x400AF3: find_in_tree (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==    by 0x400C1F: main (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==  Address 0x4c2c170 is 0 bytes after a block of size 0 alloc'd
==1464==    at 0x4A0610C: malloc (vg_replace_malloc.c:195)
==1464==    by 0x4009D2: get_tree (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==    by 0x400C0B: main (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==1464==
--1464--
--1464-- used_suppression:      4 dl-hack3
==1464==
==1464== ERROR SUMMARY: 6 errors from 3 contexts (suppressed: 4 from 4)

Anything will help, thanks!

A: Trust valgrind and not your code.
For instance:
char *make_path(const char *dirname, const char *filename) {
    char *fullpath = (char *) malloc((strlen(dirname) + strlen(filename) + 1 + 1) * sizeof(char));
    strcat(fullpath, dirname);

The memory returned by malloc() is not initialized.  You can't use strcat() yet.
There will be other problems of a similar ilk, no doubt.

A: For each opendir you do, you should close with a closedir Please check. This can be source of your leaks.
Valgrind is also pointing this out to you
==468== 65,648 bytes in 2 blocks are definitely lost in loss record 3 of 3
==468==    at 0x4A0610C: malloc (vg_replace_malloc.c:195)
==468==    by 0x3CA3296822: __alloc_dir (in /lib64/libc-2.5.so)
==468==    by 0x400A09: find_in_tree (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==468==    by 0x400B0F: find_in_tree (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)
==468==    by 0x400C06: main (in /USERS/STUDENTS/S-Z/V/VOSTERJL/dirch)


text:
Q: Projective cubic curves? I'm trying to find out some reasonable classification of cubic curves in various geometries.
From what I understand, in case of conics, you can start with projective geometry which basically has just an ellipse. Then you can take a line, pronounce it the line at infinity, and you have Euclidean geometry. And since there are three different relationships between line and a conic (nonsecant, tangent, secant), the one projective conic will naturally split in three Euclidean cases (parabola is tangent to the line at infinity, hyperbola is cut by it, ellipse has no contact with it). Similarly, though it's a bit harder, you can put a special conic in the projective geometry and use it to establish hyperbolic geometry where relationship between this "absolute" conic and your original projective ellipse will lead to one of many kinds of hyperbolic conics.
Is such an approach possible for cubic curves or higher? First, I think that cubic curves, unlike conics, exist in topologically distinct forms even in projective geometry. But once those forms are found, could I simply derive Euclidean cubics by making one line special and hyperbolic cubics by making one conic special?
(As an aside, if Euclidean geometry can be obtained through special line and hyperbolic geometry through a special conic, is there a geometry that would be based on claiming a cubic as special?)

A:
you can start with projective geometry which basically has just an ellipse.

In general I'd classify quadrics in projective geometry into several classes, too. See this answer for an overview. What you call "basically […] just an ellipse" I'd call a real non-degenerate conic, which is one of several classes. Cubics would have more classes.

First, I think that cubic curves, unlike conics, exist in topologically distinct forms even in projective geometry.

You are right. See this answer for a discussion of why a single representative is enough for quadrics; that idea would not apply to cubics.
A quadric has 5 real degrees of freedom. You can pick 6 coefficients or matrix entries or whatever, but scalar multiples describe the same quadric. A projective transformation has 8 real degrees of freedom, since it maps any 4 points in general position to any other 4, and each such point represents two degrees of freedom. A cubic has 9 degrees of freedom (10 coefficients to choose), so there has to be an infinite number of equivalence classes of cubics modulo projective transformations.

But once those forms are found, could I simply derive Euclidean cubics by making one line special and hyperbolic cubics by making one conic special?

Sure. A quadric or cubic is a first class citizen in projective geometry. The distinction into ellipse, parabola and hyperbola requires a bit of Euclidean geometry, namely the line at infinity. The classification of some ellipses as circles requires even more Euclidean geometry, but more on that in a moment. You could count intersections between a cubic an the fundamental conic, and then invent names based on that. Not sure anyone would be interested, unless you could come up with applications where those distinctions became relevant.

if Euclidean geometry can be obtained through special line and hyperbolic geometry through a special conic

Not quite. You need a conic in both cases. In Euclidean geometry, that conic is degenerate. As a set of points, it represents the line at infinity, with algebraic multiplicity two, i.e. the conic $z^2=0$. But that's just part of the picture. You can also describe a conic in terms of its tangents. Usually the matrix for the tangent description is the inverse of that for points, but in the case of degenerate conics inversion leads to division by zero, so it's better to represent this so called dual conic separately. For Euclidean geometry, the dual conic is $x^2+y^2=0$, which factors into the two circle points $[1:\pm i:0]$ (or more precisely the set of all the lines through these points) since $x^2+y^2=(x+iy)(x-iy)$. Every circle passes through these two points, and since circles are the basis for length comparisons, and you can also compute angles from these points using the Laguerre formula, the dual fundamental conic is crucial for metric aspects of Euclidean geometry.
The great unifying concept here is Cayley-Klein metrics. The idea is roughy as follows: to compute a distance between two points, draw the line connecting them, intersect it with the fundamental conic, compute the cross ratio of these four points. Dual to that, to compute an angle between two lines, find their point of intersection, draw tangents from that to the fundamental conic, compute the cross ratio of these four lines. In both cases you need to finish the computation by taking a logarithm and applying some constant and possibly complex factor, but that's just consmetic. And for Euclidean geometry all distances will turn out as zero, because that geometry has no absolute distance measure, just relative distance comparisons, but I'll not go into more detail.
Note that for other classes of conics you get other metrics. Richter-Gebert's Perspectives on Projective Geometry has a nice overview of the 7 possible situations here, plus more details on working with Cayley-Klein geometries for various applications. Elliptic geometry resulting from a non-degenerate fully complex conic like $x^2+y^2+z^2=0$ is one interesting class, the geometry of space-time relativity resulting from fully degenerate conics is another. Disclaimer: I've worked closely with the author.

is there a geometry that would be based on claiming a cubic as special

Based on the above, you'd need to replace the cross ratio of four points with something where you use five points as input: the two points on the line and the three points of intersection with the cubic. The formula would need to be sufficiently symmetric that changing the order of points does not change too much (although it does change the sign of the distance for e.g. hyperbolic geometry). Off the top of my head I can't think of a reasonable candidate to fit this bill. If you do find one, it might be interesting to see whether a definition based on this actually satisfies the axioms required for a metric.


text:
Q: Porting from Rails 3.2 to Rails 4.2 - Devise - registration controller bypasses validations I have mostly ported my application from Rails 3.2 to Rails 4.2. (about 2 out of 700 tests are still failing).
In the previous Rails stack, I used:

*

*Rails 3.2.18

*Ruby 2.1.5

*Devise 3.2.2

*RSpec 2.13.1

Now I'm using

*

*Rails 4.2.5

*Ruby 2.2.4

*Devise 3.5.3

*RSpec 2.14.1

My user class looks like this:
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :confirmable , :validatable

  attr_accessible :name, :email, :password, :password_confirmation, :identity_url,
                  :remember_me, :terms

  validates :terms, acceptance: { accept: 'yes' }
end

My registrations controller looks like this:
class RegistrationsController < Devise::RegistrationsController
  def new
    @title = "Sign up"
    super
  end
end

I have an RSpec test for the registrations controller which looks like this:
describe "failure to accept terms" do
  before(:each) do
    @attr = { :name => "New User", :email => "user@example.com",
              :password => "foobar", :password_confirmation => "foobar", :terms => "no" }
  end

  it "should not create a user" do
    lambda do
      @request.env["devise.mapping"] = Devise.mappings[:user]

      post :create, :user => @attr
    end.should_not change(User, :count)
    #raise Exception,  User.last.inspect
  end
end

With the previous application stack, the test passed. With the new application stack it fails.
1) RegistrationsController POST 'create' failure to accept terms should not create a user
  Failure/Error: lambda do
     count should not have changed, but did change from 0 to 1

With the old stack or the new stack, if I try the following in the Rails console,
irb(main) > User.all.count
=> 0
irb(main) > @attr = { :name => "New User", :email => "user@example.com",                  :password => "foobar", :password_confirmation => "foobar", :terms => "no" }
irb(main) > u = User.create(@attr)
irb(main) User.all.count
=> 0
irb(main) u.errors.messages
=> {:terms=>["must be accepted"]}

......the user is not created, and u.errors yields the validation error for the terms. This is what should happen.
When I uncomment the "raise Exception" line in the test, I get the following:
#<User id: 2, name: nil, email: "user@eexample.com", created_at: "2016-01-22 18:13:35", updated_at: "2016-01-22 18:13:35", encrypted_password: "$2a$04$oySRVGtQQrbKkp9hmvHlIuA8kdpEASMkhnQ4rDuDC9L...", salt: nil, admin: false, reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, confirmation_token: "_deYRJswq4yLLNrNNRAz", confirmed_at: nil, confirmation_sent_at: "2016-01-22 18:13:36", authentication_token: nil, unconfirmed_email: nil, terms: nil, identity_url: nil >

It looks like the user gets created, but key data such as the name, and terms are not assigned.
The long and the short? With Devise, user validations all ran with the Rails 3.2 stack, and did not run with the Rails 4.2 stack.
Is there a way to ensure that validations are run when using the Devise-based registrations controller?

A: This issue is due to the switch to strong parameters in Rails 4.
Here's another good thread that shows an example of this same concept.
In the original post the code samples show that the attributes are still being declared in the model via attr_accessible.
In order for the terms validation to be triggered that parameter must be specified in a controller. In this case since you are using an overridden Devise controller you can override the sign_up_params method there in.
So in app/controllers/registrations_controller.rb do try the following:
class RegistrationsController < Devise::RegistrationsController

  def new
    @title = "Sign up"
    super
  end

  private

    def sign_up_params
      params.require(:user).permit(:email, :password, :password_confirmation, :terms)
    end
end

That will allow the "terms" checkbox to make through correctly the model causing the validation of the check box to happen correctly.