text:
Q: jar is working fine but exe showing exception I am currently trying to make exe using launch4j to generate reports using the jasper. When I run the runnable jar, it is perfectly showing. But when I run the exe file, I always get an exception related to the jar dependencies. I have shown the jre folder while creating exe by launch4j. Despite this, I add the following jars file into my build path,

*

*jasperreports-5.6.0.jar

*commons-logging-1.1.jar

*commons-beanutils-1.8.2.jar

*commons.digester-2.1.jar

*commons-collections-3.2.1.jar

*groovy-all-2.0.1.jar

*jdt-compiler-3.1.1.jar

*jfreechart-1.0.12.jar

*jcommon-1.0.15.jar

*iText-2.1.7.js2.jar

the program generates me class not found exception either related with collections. My main goal is via using jrxml file to generate a report. I am using iReport 5.6.0 to generate jrxml file. Any help is appreciated. The Stack trace of error is below;
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: net/sf/jasperreports/engine/JRDataSource
at shg.da.com.MainFrame.<init>(MainFrame.java:63)
at shg.da.com.MainFrame$1.run(MainFrame.java:41)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: net.sf.jasperreports.engine.JRDataSource
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 16 more

My coding are as follows:
package shg.da.com;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.swing.JRViewer;

public class MainFrame extends JFrame {

    private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MainFrame frame = new MainFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public MainFrame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);

    JButton vouPrintButton = new JButton("Print");

    vouPrintButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            try {
                List<Map<String,?>> datasource = new ArrayList<Map<String,?>>();

                Map<String, Object> m;

                    m = new HashMap<String, Object>();
                    m.put("zorg",880022);
                    m.put("xvoucher", "JV--005282/2017");
                    m.put("xdate", "2021-07-03");
                    datasource.add(m);

                JRDataSource jrDataSource = new JRBeanCollectionDataSource(datasource);
                String sourceName = "glv.jrxml";
                JasperReport report = JasperCompileManager.compileReport(sourceName);
                JasperPrint filledReport =  JasperFillManager.fillReport(report, null, jrDataSource) ;
                JFrame rptFrame = new JFrame();

                rptFrame.getContentPane().add(new JRViewer(filledReport));
                rptFrame.pack();
                rptFrame.setVisible(true);
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    });
    contentPane.add(vouPrintButton);
}

}


text:
Q: I can't get Deferred DeepLink Recently I tested 'deferred deeplink' function by using facebook SDK.
But there is one problem.
# I did it.
First, I have completed all of setting for apps by using the "App Ads Helper" function from developers.facebook.com.
https://developers.facebook.com/tools/app-ads-helper

Second, so I obtained the good result by using "DeepLink Test" provided by"App Ads Helper".

And I could see what i want (AppLinkData)
06-04 12:58:25.598  11903-11925/? I/DEBUG_FACEBOOK_SDK﹕ Bundle[{com.facebook.platform.APPLINK_NATIVE_CLASS=, target_url=myapp://myapp.co.kr?test=1111, com.facebook.platform.APPLINK_NATIVE_URL=myapp://myapp.co.kr?test=1111}]
Third, here is the code what I used.
protected void onCreate(){
    ....
    FacebookSdk.sdkInitialize(getApplicationContext());
    AppLinkData.fetchDeferredAppLinkData(getApplicationContext(),
        BSTracker.getInstance().getFacebookIdMeta() ,
        new AppLinkData.CompletionHandler() {
            @Override
            public void onDeferredAppLinkDataFetched(AppLinkData appLinkData) {
            if (appLinkData != null) {
                Bundle bundle = appLinkData.getArgumentBundle();
                Log.i("DEBUG_FACEBOOK_SDK", bundle.toString());
            } else {
                Log.i("DEBUG_FACEBOOK_SDK", "AppLinkData is Null");
            }
         }
    });
}

Finally. This is My App Setting

Ad Setting
It is My Ad setting.
i did input the DeepLink in "Get install of your App" Ad Product.

# Problem
When I created commercial ad at Facebook and released for the audience but I can't get Deferred DeepLink.
Please let me know, anything is wrong with it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problems with the home directory All the files that are in the home directory are showing up on my Ubuntu iterface. I created a directory called problems (last directory in the image) to put the directories that are in the home directory, that way they won't be shown on my interface. This is a image from my interface:
files out of home directory
About the image: The home directory is the first directory and the problems directory is the last.
Is there a way to solve this problem?

A: The files displayed on your desktop are controlled by the value of the
XDG_DESKTOP_DIR

variable, which is usually set int the config file
~/.config/user-dirs.dirs

On my system is set as follows:
XDG_DESKTOP_DIR="$HOME/Desktop"

I suggest you edit the file indicated, and set the value to be the place where you want the environment to show all the folders, shortcuts and files on your desktop.


text:
Q: How to convert text node into object node to add a child node I am using Javascript and JSON files. I am trying to create a child node and insert a value into that node
The base setup is:
    declareUpdate();
xdmp.documentInsert("/example.json",
{"a":"aa","b":"bb"});

What I would like to see is a child node in either a or b with some data.
declareUpdate(); var doc = cts.doc("/example.json"); var docObj = doc.toObject(); docObj. = "this is a much different value"; xdmp.nodeInsertChild(cts.doc("/example.json").xpath("/a"), docObj);

[javascript] XDMP-CHILDNODEKIND: xdmp.nodeInsertChild(Sequence(xdmp.unpath("fn:doc('/foo.json')/text('foo')")), Text("this is a child node value")) -- text nodes cannot have text node children

A: The error suggests your attempt of adding a JSON property as immediate child of the document node. MarkLogic object node can't have document node children.
One effective way of updating JSON document node is to update/replace the JavaScript object node with your construct. (Note: You can't insert a text expression directly into MarkLogic JSON node, insert a named node instead.)
If the desired result is something like
{
  "a": {
    "a1": "aa",
    "a2": "new child node"
  },
  "b": "bb"
}

, then simply apply a node replace:
declareUpdate();
const doc = cts.doc("/example.json");
const newNode = { "a1":"aa", "a2":"new child node" };
xdmp.nodeReplace(doc.xpath("/a"), newNode);


text:
Q: How to calculate modulo of negative integers in JavaScript? I'm trying to iterate over an array of jQuery objects, by incrementing or decrementing by 1. So, for the decrementing part, I use this code:
var splitted_id = currentDiv.attr('id').split('_');
var indexOfDivToGo = parseInt(splitted_id[1]);
indexOfDivToGo = (indexOfDivToGo-1) % allDivs.length;
var divToGo = allDivs[indexOfDivToGo];

so I have 4 elements with id's:
div_0
div_1
div_2
div_3

I was expecting it to iterate as
3 - 2 - 1 - 0 - 3 - 2 - etc..
but it returns -1 after the zero, therefore it's stuck. So it iterates as:
3 - 2 - 1 - 0 - -1 - stuck
I know I can probably fix it by changing the second line of my code to
indexOfDivToGo = (indexOfDivToGo-1 + allDivs.length) % allDivs.length;

but I wonder why JavaScript is not calculating negative mods. Maybe this will help another coder fellow too.

A: You can try this :p-
Number.prototype.mod = function(n) {
    return ((this % n) + n) % n;
}

Check out this

A: Most languages which inherit from C will return a negative result if the first operand of a modulo operation is negative and the second is positive. I'm not sure why this decision was made originally. Probably closest to what processors at that time did in assembly. In any case, since then the answer to "why" is most likely "because that's what programmers who know C expect".
The MDC Reference contains a pointer to a proposal to introduce a proper mod operator. But even that would keep the existing % operator (which they call "remainder" to better distinguish between them) and introduce a new infix word notation a mod b. The proposal dates from 2011, and I know no more recent developments in this direction.


text:
Q: Paperclip dont save image with custom path I try to save picture through paperclip with custom path, but it doesn't work.
The image record was created in the database, but in system/web/message_attachments/images/000/000 there is nothing.
In my message_attachment model:
has_attached_file :image, styles: { original: ['1920x1920>', :jpg],
                                    medium:   ['640x640>',   :jpg]
}, path: "web/message_attachments/images/:id/:timestamp_to_i.:style.:extension"

Paperclip.interpolates :timestamp_to_i do |attachment, _|
  attachment.instance_read(:updated_at).to_i
end

In my rails log:
Command :: file -b --mime '/var/folders/jv/628j4sf51rxgvr52tqq1mhgh0000gq/T/00656d7de02cbc853a6b31bc26138d2520150805-76566-1n7ihtp.jpg'
Command :: identify -format '%wx%h,%[exif:orientation]' '/var/folders/jv/628j4sf51rxgvr52tqq1mhgh0000gq/T/30c2024f8e4df03935003d02f161c2af20150805-76566-5s2k5x.jpg[0]' 2>/dev/null
Command :: convert '/var/folders/jv/628j4sf51rxgvr52tqq1mhgh0000gq/T/30c2024f8e4df03935003d02f161c2af20150805-76566-5s2k5x.jpg[0]' -auto-orient -resize "1920x1920>" '/var/folders/jv/628j4sf51rxgvr52tqq1mhgh0000gq/T/2ffbeb355951900901500392a0001abe20150805-76566-g5q9k0.jpg'
Command :: identify -format '%wx%h,%[exif:orientation]' '/var/folders/jv/628j4sf51rxgvr52tqq1mhgh0000gq/T/0890e9a741bebcf51f3e48d8c19ec49220150805-76566-1yw3t2t.jpg[0]' 2>/dev/null
Command :: convert '/var/folders/jv/628j4sf51rxgvr52tqq1mhgh0000gq/T/0890e9a741bebcf51f3e48d8c19ec49220150805-76566-1yw3t2t.jpg[0]' -auto-orient -resize "640x640>" '/var/folders/jv/628j4sf51rxgvr52tqq1mhgh0000gq/T/b32faf21545a8b32b20d58e5bd912ae120150805-76566-17wzc0l.jpg'
   (0.2ms)  BEGIN
Command :: file -b --mime '/var/folders/jv/628j4sf51rxgvr52tqq1mhgh0000gq/T/00656d7de02cbc853a6b31bc26138d2520150805-76566-1idvdge.jpg'
Command :: identify -format '%wx%h,%[exif:orientation]' '/var/folders/jv/628j4sf51rxgvr52tqq1mhgh0000gq/T/0890e9a741bebcf51f3e48d8c19ec49220150805-76566-1yw3t2t.jpg[0]' 2>/dev/null
  SQL (0.5ms)  INSERT INTO "message_attachments" ("image_file_name", "image_content_type", "image_file_size", "image_updated_at", "width", "height") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"  [["image_file_name", "Wallpaper_3.jpg"], ["image_content_type", "image/jpeg"], ["image_file_size", 502036], ["image_updated_at", "2015-08-05 09:04:34.764154"], ["width", 1920], ["height", 1200]]
   (6.2ms)  COMMIT

A: User :default_url => "/images/:style/missing.png" instead of :path to specify storage location path. You can check paperclip documentation


text:
Q: force chef to reload packages list/versions OS: debian 7. It has nginx 1.2.1-2.2+wheezy4 preinstalled.
I'm writing a cookbook that should upgrade nginx to latest version:
# Remove old versions if found
['nginx', 'nginx-common', 'nginx-full'].each do |pkg|
  package pkg do
    version '1.2.1-2.2+wheezy4'
    action :nothing
  end.run_action(:remove)
end

# Install nginx repository
include_recipe 'chef_nginx::repo'

# Forces nginx installations from nginx repo
apt_preference 'dotdeb' do
  glob 'nginx*'
  pin 'release o=nginx'
  pin_priority '1000'
end

# This should install latest nginx ! But it installs 1.2.1!
package 'nginx'

why chef installs old version of nginx? :( How to force it to reload packages version.
# apt-cache policy
...
Pinned packages:
...
nginx -> 1.10.3-1~wheezy

A: Chef does not track apt/deb versions in memory so the issue is with apt itself. You might have read some confusing guides elsewhere since we do have some internal caching for yum, but that is only for yum installs.


text:
Q: Keeping an AsyncTask alive in low memory conditions? I have written a home screen widget as an ImageView, ie. the code generates the whole widget and writes it to RemoteViews as a bitmap. On slower devices with low memory, such as my G1, it can take a couple of seconds to generate the bitmap, and to avoid the dreaded force-close, I moved all the graphics code into an AsyncTask. So far so good.
However, in very low memory conditions, the AsyncTask can easily be killed by the OS before it has finished generating the bitmap, resulting in an empty square on the homescreen. So before creating the AsyncTask, it sets an alarm for now + 5 seconds, and after the graphics are complete, it resets the alarm. The assumption here is that if the alarm is triggered, more than likely the process was killed, and we have to set another now+5 alarm and start again.
This does work, but in extreme low memory conditions it can take several attempts (20+ seconds) to draw the widget, so I added a placeholder hourglass image, as a static resource, which is displayed on the homescreen until the real image is ready.
My question is this: is this the best way? Is there some way to (politely) ask the OS not to kill the AsyncTask until it's finished (on the grounds that killing it will actually result in more waste of system resources)?
I understand that if a process is categorised as "visible" then Android won't kill it except as a last resort. But I don't know how to tag an AsyncTask as "visible". I'm very happy for the process to be killed just as soon as it's done drawing the widget. Would just like it to stay alive long enough to complete.

A: Use an EmptyService by binding to it and unbinding once the work is done, see https://github.com/android/platform_packages_providers_calendarprovider/blob/master/src/com/android/providers/calendar/EmptyService.java.  I'm not sure if this guarantees that you're process won't be killed or if simply reduces the chances of it being killed.
You can also use a foreground service but you'll have to supply it with a status bar notification, see http://developer.android.com/guide/components/services.html#Foreground.
Or you can use IntentService as @Mike suggested; although I can't see in the documentation that "it gets the same kill priority as a foreground task".

A: Have you considered using an IntentService for this?  While your service code is executing it gets the same kill priority as a foreground task.  It won't have quite the tight coupling to the widget that an AsyncTask would, but I think it would increase the odds of your code finishing.

A: try to use Service class, you can set service as "Foreground". There are probably near to zero chances getting Foreground service closed.
Also,Service does same as Async.
As soon as you are done with the work,then close the service.


text:
Q: Force on a current-carrying loop due to a uniform electric field Why does a closed current carrying coil experience no force when placed in a uniform electric field, whereas a charge moving with constant velocity through a uniform electric field does?

A: A current carrying coil experiences no net force in a uniform electric field because it is electrically neutral. For each positive charge in the coil with a force $\vec F = q \vec E$ there is a corresponding negative charge with force $-\vec F =-q \vec E$. The isolated charge is not electrically neutral.
The motion of the isolated charge is irrelevant as is the motion of the charges in the current.

A: Answer: a current carrying loop is Net neutral, although there are negative charges causing a current. there are also an equal amount of positive charges that aren't moving. thus there's a net zero charge on the wire.
And for a UNIFORM magnetic field, A current carrying loop will experience a net zero force aswell, however WILL experience a net TORQUE
$$\int I dl × B $$
B is independent of the integral as its uniform
$$(\int I dl )×B $$
For a constant current I is also independent of the integral thus
$I (\int dl) × B$
For a closed loop $\int dl$ is zero, remember this is the VECTOR element dl
so I*0×B = 0


text:
Q: Is it possible to query Elastic Search with a feature vector? I'd like to store an n-dimensional feature vector, e.g. <1.00, 0.34, 0.22, ..., 0>, with each document, and then provide another feature vector as a query, with the results sorted in order of cosine similarity. Is this possible with Elastic Search?

A: Version 7.4 of elasticsearch actually has built-in vector comparison functions, including cosine similarity. See: https://www.elastic.co/guide/en/elasticsearch/reference/7.4/query-dsl-script-score-query.html#vector-functions.

A: I don't have an answer particular to Elastic Search because I've never used it (I use Lucene on which Elastic search is built). However, I'm trying to give a generic answer to your question.
There are two standard ways to obtain the nearest vectors given a query vector, described as follows.
K-d tree
The first approach is to store the vectors in memory with the help of a data structure that supports nearest neighbour queries, e.g. k-d trees. A k-d tree is a generalization of the binary search tree in the sense that every level of the binary search tree partitions one of the k dimensions into two parts. If you have enough space to load all the points in memory, it is possible to apply the nearest neighbour search algorithm on k-d trees to obtain a list of retrieved vectors sorted by the cosine similarity values. The obvious disadvantage of this method is that it does not scale to huge sets of points, as often encountered in information retrieval.
Inverted Quantized Vectors
The second approach is to use inverted quantized vectors. A simple range-based quantization assigns pseudo-terms or labels to the real numbers of a vector so that these can then later be indexed by Lucene (or for that matter Elastic search).
For example, we may assign the label A to the range [0, 0.1), B to the range [0.1, 0.2) and so on... The sample vector in your question is then encoded as (J,D,C,..A). (because [.9,1] is J, [0.3,0.4) is D and so on).
Consequently, a vector of real numbers is thus transformed into a string (which can be treated as a document) and hence indexed with a standard information retrieval (IR) tool. A query vector is also transformed into a bag of pseudo-terms and thus one can compute a set of other similar vectors in the collection most similar (in terms of cosine similarity or other measure) to the current one.
The main advantage of this method is that it scales well for massive collection of real numbered vectors. The key disadvantage is that the computed similarity values are mere approximations to the true cosine similarities (due to the loss encountered in quantization). A smaller quantization range achieves better performance at the cost of increased index size.


text:
Q: DataBinding: 'System.Char' does not contain a property with the name 'xxxxx' DataBinding: 'System.Char' does not contain a property with the name 'City'.
I retrieve data from xml file and i want to put this fields in repeater with JavaScript  for Google map this what happened when data binding .

<body>
    <form id="form1" runat="server">
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?      sensor=false"></script>
    <script type="text/javascript">
        var markers = [
        <asp:Repeater ID="rptMarkers" runat="server">
        <ItemTemplate>
                 {
                "title": '<%# Eval("City") %>',
                 "lat": '<%# Eval("Latitude") %>',
                 "lng": '<%# Eval("Longitude") %>',

             }
    </ItemTemplate>
    <SeparatorTemplate>
        ,
    </SeparatorTemplate>
    </asp:Repeater>
    ];
    </script>
    <script type="text/javascript">

        window.onload = function () {
            var mapOptions = {
                center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
                zoom: 8,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var infoWindow = new google.maps.InfoWindow();
            var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
            for (i = 0; i < markers.length; i++) {
                var data = markers[i]
                var myLatlng = new google.maps.LatLng(data.lat, data.lng);
                var marker = new google.maps.Marker({
                    position: myLatlng,
                    map: map,
                    title: data.title
                });
                (function (marker, data) {
                    google.maps.event.addListener(marker, "click", function (e) {
                        infoWindow.open(map, marker);
                    });
                })(marker, data);
            }
        }
    </script>

    <div id="dvMap" style="width: 500px; height: 500px">
    </div>
      </form>

Here the code behind,`
string xx = string.Empty;
void GetData(string strRsult)
{
    XmlDataDocument xmlDataDoc = new XmlDataDocument();
    xmlDataDoc.LoadXml(strRsult);
    foreach (XmlNode n in xmlDataDoc.DocumentElement.GetElementsByTagName("Property"))
    {
        if (n.HasChildNodes)
        {
            foreach (XmlNode childNode in n)
            {
                switch (childNode.Name)
                {
                    case "GEOData":
                        {

                            xx = childNode.Attributes["City"].Value + ", " + childNode.Attributes["Longitude"].Value + ", " + childNode.Attributes["Latitude"].Value;
                            rptMarkers.DataSource = xx.ToCharArray();
                            rptMarkers.DataBind();

                            break;
                        }

                    default: break;
                }
            }
        }

    }
}`

A: Currently you are setting the data source to an array of characters and the Repeater is trying to get at the City property of each char and of course char does not have a City property.  To fix this first you need to create a class that contains the properties that you are interested in.
public class Markers
{
    public string City {get; set;}
    public string Latitude {get; set;}
    public string Longitude {get; set;}
}

Then create a collection of Markers from your xml and set the data source to that.
List<Markers> markers = new List<Markers>();
foreach (XmlNode n in xmlDataDoc.DocumentElement.GetElementsByTagName("Property"))
{
    foreach (XmlNode childNode in n)
    {
        if(childNode.Name == "GEOData")
        {
            markers.Add(new Markers
                {
                    City = childNode.Attributes["City"].Value,
                    Longitude= childNode.Attributes["Longitude"].Value,
                    Latitude= childNode.Attributes["Latitude"].Value
                });
        }
    }
}

rptMarkers.DataSource = markers;
rptMarkers.DataBind();


text:
Q: R-Kernel keeps dying after install "easyGgplot2" package. I installed the eachGgplot2 package for my project which is causing my R-kernel to keep dying on Jupyter Notebook. I tried uninstalling and installing Anaconda (both the simple remove and clean remove methods) but did not solve the problem.  Below are the codes that I used before my R-kernel committed suicide:

install.packages("devtools")
library(devtools)
install_github("easyGgplot2", "kassambara")

The log shows the errors in a package called "digest"

 KernelRestarter: restarting kernel (3/5), new random ports
Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) :
  there is no package called 'digest'
Calls: :: ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>

I do not really need this easyGgplot2 library - what should I do to get my R-kernel back up running?
Any help and tip is most appreciated!

A: I fixed the R-Kernel on Jupyter Notebook.  I want to post the solution in case anyone else runs into similar problem in the future.   @MrFlick you were right that the problem is at the Devtool even thought in R console it says the packages "digest and "devtools" are installed successfully.  I remove the devtool package from the R-console using remove.packages('Devtools') and that revive my R-kernel on Jupyter Notebook.  Thanks.


text:
Q: Induction: $n + 3 < n!$ for all $n>3$ I have a proof that I am trying to prove and I am getting stuck at the inductive hypothesis. This is my theorem:

For all real numbers $n>3$, the following is true: $n + 3 < n!$.

I have proven true for $n = 4$, and will assume true for some arbitrary value $k$, i.e.,
$$k + 3 < n!,$$
and I want to prove for $k+1$, i.e.,
$$(k+1) + 3 < (k+1)!.$$
Consider the $k+1$ term:
$$(k+1)+3 = ?$$
I am confused on how to approach the next step.
Ok here is how I am proceeding. It seems really long so if anyone has a better way let me know:
$$
=(k+3)+1
$$
$$
<(k!)+1
$$
$$
<k!+k!
$$
$$
=2k!
$$
$$
<(k+1)k!
$$
$$
=(k+1)!
$$
Therefore both sides are equivalent.

A: Induction is overkill here.
For $n \gt 3$ we have that $n+3 \lt n + n = 2\cdot n \lt 1\cdot 2 \cdot3\cdots (n-1) \cdot n =n!$

A: As you are trying to solve this problem, I'll only give you a hint.
Inductive Step: we want to show $(n+1)+3 < (n+1)!$
That's equivalent to $n+4 < (n+1)\cdot n!$ by the property of the factorial.
We can distribute: $n+4 < (n\cdot n!) + (1\cdot n!)$
Can you take it from here?

A: Since by induction hypothesis,
$$k+3< k!$$
for $k>4$, multiply both sides by $(k+1)$ to get
$$(k+3)(k+1) < k! (k+1)$$
or
$$(k+3)(k+1) < (k+1)!$$
I'll leave the rest for you to think about, as a hint, remember that's an inequality.

A: Suppose $k! \gt k+3$ is true:

\begin{align*}
\ (k+1)! &=k!\cdot(k+1)
\\ &\gt(k+3)(k+1)
\\ &=k^2+4k+3
\\ &\gt k^2+k+3
\\ &\gt (k+1)+3\ldots(\text{where}\space k\gt 3)
\end{align*}

A: Suppose $n+3< n!$ and $(n+1)!\leq n+1+3$ , we see the following:
$$(n+1)!\leq n+1+3 \Rightarrow (n+1)n!\leq n+1+3 $$
$$\Rightarrow (n+1)(n+3)\leq(n+1)n!\leq n+1+3 $$
$$(n+1)(n+3)\leq (n+1)+3 \Rightarrow (n+1)(n+3)-(n+1) \leq 3$$
$$ \Rightarrow (n+1)(n+3-1)\leq 3$$
$$(n+1)(n+2)\leq 3$$
This should strike some thing s wrong... what is that?


text:
Q: Intermittent Microsoft Azure Web Site access failure I have a number of small MVC apps deployed as Microsoft Windows Azure websites.  This has been working for several months.
Yesterday I rolled out a new one, and the deployment was unremarkable, everything worked fine.  But a couple of hours later, access to the site was unavailable.  The symptoms were that when the browser tried to navigate to the URL for that site, it would try to load for several minutes and then just give up with a completely blank page.
I attempted to stop and restart the site, and it worked once, but the symptoms came back several minutes later.  Then I tried to stop and restart, and it didn't work.
I deployed the identical app to three additional URLs.  Again, immediately on deployment, they all work fine, however, they fail at some interval in the future.  They seem to not all fail at once.  Sometimes restarting the site will fix the problem, and sometimes not.
IMPORTANT:  If I wait for some period of time, the site may start to work again on its own.
However, deploying four versions of the app so that our users can go to a backup one if the primary one is not working is not optimal.
Any words of wisdom as to how I might go about debugging this?
ADDITIONAL INFO NOV 25, 2013:
When sites are failing, the IIS logs show either 500 or 502 Internal Service Errors.  Our own MVC code is never hit, not even app_start.

A: You can start by checking the logs and remote debugging
http://www.drdobbs.com/windows/azure-sdk-22-supports-visual-studio-2013/240163499
Are the apps working locally?

A: Might not be the same problem, but from time to time our Azure instances will get the blue question mark of death as a status.
The reason we found out was that Microsoft will do upgrades on instances from time to time. If you have just one instance in a cloud service/role, then from time to time they will do maintenance and during that time it will be dead.
I have confirmed this with their support.
The only way to get around this that I know of is to create two instances. Then Microsoft guarantees ~99% availability.
Of course I also confirmed with them that this means twice the cost. =/
If that's not the issue I would enable RDP and get onto the machine to see what the problem is. Microsoft has these tools to help debug problems: http://blogs.msdn.com/b/kwill/archive/2013/08/26/azuretools-the-diagnostic-utility-used-by-the-windows-azure-developer-support-team.aspx

A: First, you should always run multiple instances of your web role with more than 1 upgrade domain.  This is configurable in the service definition (CSDEF).  Without this, you don't get an SLA from Microsoft, so you can't really complain that the VMs go down.
Second, to figure out what might be going on with these boxes, you should have both logs (my preference is to roll my own with page blobs or table storage), AND you should always have RDP access to a pre-production environment (production as well if you're not too fussed about security).  Once on the box, look through the event viewer for errors.
Third, when an outage occurs check out the azure service dashboard (http://www.windowsazure.com/en-us/support/service-dashboard/) for outages.
Lastly, contact Microsoft support.  It may take a few hours, but they are pretty good.
That it is happening repeatedly and for extended periods of time (more than 5 minutes), I would be there's something wrong with your hosted service.  Again, RDP in and poke around.  Good luck.

A: To debug your sites try to enable diagnostic logs:
http://www.windowsazure.com/en-us/develop/net/common-tasks/diagnostics-logging-and-instrumentation/
Another nice way to look around your site is using the debug console:
https://github.com/projectkudu/kudu/wiki/Kudu-console


text:
Q: Compare two char variable using strcmp in c++ shows invalid conversion from 'char' to 'const char*' This my code.
if(strcmp(s[0][i],s[rock][j])==0)
{
     count[i]+=1;
     rock++;
}

A: The strcmp function compares two strings. If you want to compare two char variables, just use == or !=.

A: It is obvious that objects s[0][i] and s[rock][j] have type char. That is they are not strings but two characters. You can compare them using operator ==
For example
if ( s[0][i] == s[rock][j] )

Also I would advice to substitute these two expression statements
 count[i]+=1;
 rock++;

for
 count[i]++;
 rock++;

or
 ++count[i];
 ++rock;

In this case the code looks more readable.

A: I will assume for this answer that s was declared as:
char s[100][100]; // or any arbitrary numeric limits

In this case, you cannot compare s[0][i] and s[rock][j] using strcmp, because they are characters, not character pointers.
Instead, you can just write:
if(s[0][i] == s[rock][j])

A: char is primitive datatype - you can compare chars directly:
...
if (s[0][i] == s[rock][j])
{
...

strcmp function expects strings, i.e. char *, hence the error message. You could compare whole strings in s variable:
...
if (strcmp(s[0], s[rock]) == 0)
{
...

A: For comparing to char don't use string compare function! The prototype of strcmp function is-
int strcmp(const char *s1, const char *s2); // where s1 and s2 are strings

So for comparing to characters just use == or !=
if(s[0][i]==s[rock][j])
{
 count[i]++;
 rock++;
}


text:
Q: How can I bucket/bin a dataframe in python based on the year? Let's say I have a very simple dataframe with one column, year.
There would be 14 distinct years, from 2010 to 2023.
I would need to bin/bucket these years into three categories, 'old', 'medium', and 'new'
where new would be the 3 most recent years (2023,2022,2021), medium would be 2015-2020, and old would be 2010-2014.
How would I do this?

A: You're looking for pandas.cut.
Assuming (df) if your dataframe, you can use :
bins = [2010, 2014, 2020, 2023]
labels = ["old", "medium", "new"]

df["cat"] = pd.cut(df["year"], bins=bins, labels=labels, include_lowest=True, right=True)

And here is an example to show you the output :
(
    pd.DataFrame(pd.date_range("2010", periods=14, freq="Y").year, columns=["year"])
        .assign(cat = lambda df_: pd.cut(df_["year"],
                                         bins=[2010, 2014, 2020, 2023],
                                         labels=["old", "medium", "new"],
                                         include_lowest=True, right=True))
)

Output :
    year     cat
0   2010     old
1   2011     old
2   2012     old
3   2013     old
4   2014     old
5   2015  medium
6   2016  medium
7   2017  medium
8   2018  medium
9   2019  medium
10  2020  medium
11  2021     new
12  2022     new
13  2023     new

A: You may just create a hash like the following and use the year as the key to get its bin.
bins = {'2023' : 'new',
        '2022' : 'new',
        '2021' : 'new',
        '2020' : 'medium',
        '2019' : 'medium',
        '2018' : 'medium',
        '2017' : 'medium',
        '2016' : 'medium',
        '2015' : 'medium',
        '2014' : 'old',
        '2013' : 'old',
        '2012' : 'old',
        '2011' : 'old',
        '2010' : 'old'
        }


text:
Q: Limit Read and Write Access to branches of a plain git repository based on user name We are building an assessment process and want to limit the read and write access to specific branches for special users.
there are "normal" users that have read and write access to everything (these users will rate the answers) and there will be a given number of assessment users that should only have read access to master and read/write access to branches that contain their names (e.g. assessment-john.doe). Our assessment center will have a list with 500 users and passwords and will give each candidate a set of credentials from this list.
Short version: I'd like to configure git, that:

*

*Normal Users (e.g. tobi, chris) have:

*

*read & write access to master

*(ideally only) read access to branches starting with assessment-

*Assessment Users (e.g. assessment-1, assessment-2) have:

*

*read access to master

*read/write access to branches that have the same
name as the user (e.g. assessment-1)

*no access to other branches.

We want to use plain git (and ssh) without any version control gui server like gitlab or github as the task doesnt require this.
EDIT: To make it clear: Read control is way more important that write control. (except for master).

A: You cannot meet those requirements with built-in functionality of git.  Access control is left to the hosting environment.
You could fake some level of write permission (by using signed commits and hooks to reject pushes that violate the authorization rules), but probably not exactly what you're asking for; and the limited read permission is right out; you'd basically have to use separate repos.
You can write your own server to perform access control, or you can use an existing one; but your characterization of existing host software (implying that its main function is to provide a gui) is mistaken; and your assertion that your task doesn't require one is incorrect in light of access control being part of the task.

A: What I've done now:

*

*clone a central repository

*strip any branches except master

*rename master with the branch name for the user

*copy some hooks in the repository

*give the correct user read access to the repository

*add the user to a group that is allowed to run a specific script via sudo as another user

*write a hook that pushes the branch to the central repository on a push of the user to its repository


text:
Q: How can I get the corresponding Update_ID for windows patch installation file? I am writing a script in Power-shell that does basically the same thing that WSUS servers do,
Following the steps below:

*

*WSUS server Downloads and installs the required patches on the client systems.

*The PS script if patch is not successfully installed retries the installation on the client systems, by getting & executing the patch installation file (.cab,.msu,.exe) from the client systems.

*The patches are selected by a independent process and send to a 3rd party location from where the PS script gets it.

The issue I am facing is the data in the 3rd party location for the patches contains UPDATE_ID as a patch identifier and I need a way to recognise whats is the UPDATE_ID for the existing patch installation file is.
NOTE: I can work through Hotfix_ID as the directory patches are stored in naming standards similar to "$Hotfix_ID". But single Hotfix_ID can have multiple patches.
The affected code is as follows:
param(
    $KbFailed
)
foreach($KbNumber IN $KbFailed){
    [array]$files_att=Get-ChildItem "C:\Windows\SoftwareDistribution\Download\*\*$KbNumber*"
    Write-Host "Installing $KbNumber ..."
    if ($null -eq $files_att){
        Write-Error "Required file not found for $KbNumber"
    }else{
        foreach($file_att IN $files_att){
            $file_extension=($file_att |Select-Object Extension).Extension
            if ($file_extension -eq ".cab"){
                dism.exe /online /add-package /PackagePath:$file_att  /NoRestart
            }
            elseif($file_extension -eq ".exe"){
                Start-Process "$file_att" -ArgumentList "/q" -Wait
            }
            elseif($file_extension -eq ".msu"){
                Start-Process -FilePath "wusa.exe" -ArgumentList "$file_att /quiet /norestart" -Wait
            }
            else{
                Write-Error "File type $file_extension not supported"
            }
        }
    }
}

As mentioned I am managing it right now with HotFix_ID(Kb_number), but would like to replace it with UPDATE_ID


text:
Q: source .sh file for vscode launch I have a .sh file which sets several environment variables which I need for a software to run. I am trying to debug that software with vscode, and I need to source that file so the debugger can start the software.
I can't source the file and then launch vscode, as the software is running inside a docker container, and the envvars point to locations inside the docker container.
I would like to know if there is a way to source the .sh file as part of the launch.json configuration.


text:
Q: Keep StreamSocketListener running in background on Windows Phone 8 I want to run a server on Windows Phone 8. It is important that the server keeps running even if the user opens another app or the screen lock turns on. Relying on an internet connection is not an option. It should work in a local network.
UseCase: The server is needed for a multiplayer game. The idea is that one player starts a local server. After that, all players (including the player who starts the local server) can connect to this server using a webbrowser. The server delivers html and responds to ajax calls.
It seems that PeriodicTask and ResourceIntensiveTask do not fit my needs. Is that correct? How can I run an app in the background that is always listening for incoming tcp connections?

A: No way to do this on Windows Phone.

A: I don't know a clean way. But if you're happy with a hack: You could use the Geolocator. This blog gives a step by step guidance: How to create application which executes in the background on Windows Phone 8?
As most of the hacks, this brings some problems and questions (probably more than I mention here):

*

*If the user turns off the GPS, your server won't be reachable anymore.

*I don't know how strict Microsoft is with what you can publish on their store.


text:
Q: Checking for individual matching elements in two different array I have these two arrays
arr1 = ["dog", "cat", "bird"]
arr2 = ["fish", "bear", "bird"]
Notice how the only matching element is "bird" from the two arrays. I want to find a check that will say if any elements are matching return true.
For example this does not work arr1.include?(arr2) but looking for method that will.

A: I have found a good way to do this:
(arr1 & arr2).any?

& is a logic operator, if some elements exist in both arrays, this will return these elements.
any? checks if any elements exist in the array. If there exists at least one, then it return true.

A: arr1.any? { |item| arr2.include?(item) }

This will check if any item from first array is included in the second array.

A: You do this with intersection between two arrays and after this we can check if there are any matching elements in result.
(arr1 & arr2).present?

In your case we have
arr1 = ["dog", "cat", "bird"]

arr2 = ["fish", "bear", "bird"]

Result can be like this:
(arr1 & arr2).present?

It will return ['bird'], so its not empty and the present? will return true.


text:
Q: How to create if statements using strings in python 3.x So I decided to make some silly simple code to practice on my own, and I have trouble finding what it is im doing wrong. Python displays 'syntax error' but im not sure what im doing wrong.
>>> x= str(input("Select a colour: Red, Blue or Green"))
Select a colour: Red, Blue or Green:
>>>if x==str(Red):
...    print("Charmander")
...elif x==str(Blue):
...    print("Squirtle")
...elif x==str(Green):
...    print("Bulbasaur")
... else:
...    exit()

A: Couple things here..

*

*This isn't necessarily wrong (the code will still work) but there's no reason to convert input to a str, it already is a string

*Strings need to be in quotes, not inside str(). Use "Red" instead

*Maybe use better variable names, x is unclear

*The last exit is useless

Your code fixed would look something like:
selected_color = input("Select a colour: Red, Blue or Green ")
if selected_color == "Red":
    print("Charmander")
elif selected_color == "Blue":
    print("Squirtle")
elif selected_color == "Green":
    print("Bulbasaur")

Improvements
Since you are just converting a colour to a pokemon you could use a dict here
pokemonColors = {"Red" : "Charmander", "Blue" : "Squirtle", "Green" : "Bulbasaur"}
print(pokemonColors[input("Select a colour: Red, Blue or Green ")])

Notice that this will give a KeyError for a color not in the dict, you could use .get() with a default to fix this if you want though.


text:
Q: Dub somebody something In the sentence

the DRDO-developed anti-satellite system A-SAT successfully destroyed a live satellite in the Low Earth Orbit. With this test, dubbed as Mission Shakti, India is only the fourth country after the U.S., Russia and China to have the technology.

Dub in this context is generally used as Dub somebody something
 He has been dubbed pig.
 But in the sentence above they are using dub as. Isn't it wrong?

A: I can't seem to find any source with an official rule on this matter, but I believe either version is grammatically correct. That said, looking at native speaker usage, it seems like "dub" without "as" is much more common. The vast majority of example sentences I've found have the subject coming directly after the verb, sometimes with an article between them, but rarely a preposition. Not to mention it just sounds a little bit off.
"With this test, dubbed Mission Shakti..." sounds more natural (though again, "dubbed as"  is still not wrong).


text:
Q: Jquery datatables min.js preventing to send response back to Flask server I am using standard bootstrap5 datatable from this link:
Datatables.net/examples/styling/bootstrap5.html
My code involves selecting a row id from table on user-interface and sending row id back to the server. Strange behavior I noticed is the piece of code (from the above hyperlink) is actually preventing to send a response back to the server. jquery.datatables.min.js

However, when I comment out this code the response back to server starts working again perfectly, but then obliviously I don't get the table formatting I need. I have Python/Flask server.
Has anyone come across problem and knows how to solve?


text:
Q: WebGL 1D texture - shader value catch So I'm working on computation using GPU shaders in WebGL-
In the javascript portion of the code, I put precalculated values onto an array to send as a texture to be read up in the fragment shader-
        var count=0;
        var table = [];
        for (var y = 0.1; y<1; y+=.01) {

            for (var x = 0.1; x<1; x+=.01) {

                var u = x;
                var u2 = y;
                u += u2 * 0.003921568627451;
                u *= 4.0;
                var sig = 1/(Math.exp(2.0 *(u-3)) + 1);

                table.push(Math.floor(sig*255));
                //table.push(255);
                table.push(0);
                table.push(0);
                table.push(0);
                count+=4;

                console.log(Math.floor(sig*255)+"");
                console.log(0+"");
                console.log(0+"");
                console.log(0+"");

            }

        }

        //alert(count);
          //alert(table[101]);

        texturetab = gl.createTexture();

        gl.bindTexture(gl.TEXTURE_2D, texturetab);

        gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);

        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 100, 100, 0,

                      gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(table));

        //

        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);

        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);

        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

        gl.uniform1i(gl.getUniformLocation(prog, "uTabSamp"), 2);

but when I "catch" the values of the texture on the shader, the computation acts as if it is only reading values of 0- it's not changing as it should-
(Snippet of where the value is caught on the fragment shader) :
        sigmoid =  (texture2D(uTabSamp, vec2(floor(u*100.+.5), floor(u2*100.+.5))).r)/255.;

        float hfunc   = sigmoid * u * u;
        float ffunc   = -u +(a - pow(v*nb,m))*hfunc ;

Seeing as how WebGL is difficult to read, how do I go about fixing this?

A:
texture2D(uTabSamp, vec2(floor(u*100.+.5), floor(u2*100.+.5))

Texture sample coordinates must range from 0.0 to 1.0. So scale your lookup for the texture size you built.
Your texture-making code isn't shown, but, be sure to set the interpolation to NEAREST (assuming you want exact access to the values), and sample from the "middle" of each pixel. For example, the bottom-left pixel from a 128 x 32 texture will be found at vec2(0.5 / 128.0, 0.5 / 32.0).


text:
Q: Google maps route not getting displayed properly I am trying to build a GPS app which can show directions between 2 places. For decoding the polylines I am using code from here: Decoding Polylines from Google Maps Direction API with Java. I want to show my route more accurately than this, I am able to do that through kml but it works for very small distances only after which file size reaches limit. Here is screenshot for Boston-Seattle where lines on the map do not follow road but intersect roads

Here is how I am using directions API
public void drawRoute(String source, String destination)
{
    String strURL = "http://maps.google.com/maps/api/directions/xml?origin=" + source +
            "&destination=" + destination + "&sensor=false&mode=driving";

    String url = strURL.replace(" ", "%20");
    HttpGet get = new HttpGet(url);
    String strResult = "";
    try {
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
        HttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpResponse httpResponse = null;
        httpResponse = httpClient.execute(get);
        if (httpResponse.getStatusLine().getStatusCode() == 200){
            strResult = EntityUtils.toString(httpResponse.getEntity());
        }
    }
    catch (Exception e){ }

    if (-1 == strResult.indexOf("<status>OK</status>")){
        this.finish();
        return;
    }

    int pos = strResult.indexOf("<overview_polyline>");
    pos = strResult.indexOf("<points>", pos + 1);
    int pos2 = strResult.indexOf("</points>", pos);
    strResult = strResult.substring(pos + 8, pos2);

    List<GeoPoint> points = decodePoly(strResult);

    RouteOverlay mOverlay = new RouteOverlay(points);
    overlayList.add(mOverlay);

    if (points.size() >= 2){
        controller.animateTo(points.get(0));
    }
    map.invalidate();
}

Here is my RouteOverlay class:
public class RouteOverlay extends Overlay{
private List<GeoPoint> points;
private Paint paint;

public RouteOverlay(List<GeoPoint> points) {
    this.points = points;
    paint = new Paint();
    paint.setColor(Color.BLUE);
    paint.setAlpha(150);
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.FILL_AND_STROKE);
    paint.setStrokeWidth(4);
}

@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow)
{
    if (!shadow)
    {
        Projection projection = mapView.getProjection();
        if (points != null && points.size() >= 2)
        {
            Point start = new Point();
            projection.toPixels(points.get(0), start);
            for (int i = 1; i < points.size(); i++)
            {
                Point end = new Point();
                projection.toPixels(points.get(i), end);
                canvas.drawLine(start.x, start.y, end.x, end.y, paint);
                start = end;
            }
        }
    }
}
}

A: Refer this link to draw driving path in your application. You just need to add the four classes present in the link in your project and call the below lines when you need to display the route.
SharedData data = SharedData.getInstance();
data.setAPIKEY("0RUTLH7cqd6yrZ0FdS0NfQMO3lioiCbnH-BpNQQ");//set your map key here
data.setSrc_lat(17);//set your src lat
data.setSrc_lng(78);//set your src lng
data.setDest_lat(18);//set your dest lat
data.setDest_lng(77);//set your dest lng
startActivity(new Intent(YourActivity.this,RoutePath.class));//add RoutePath in your manifeast file

//Also add the permission to your manifeast file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<uses-permission android:name="android.permission.INTERNET"></uses-permission>


text:
Q: Как грамотно интегрировать чужой проект из гитхаба в свой? На эту тему написано уже много всего, да и я сам уже добавлял в свой код сторонние гитхаб-проекты, но в этот раз я столкнулся с проблемой.
Что имею:
Понадобилась такая штука, как libpcap, вернее часть ее исходного кода. Клонировал репозиторий, добавил папку в проект с помощью Cmake.
Содержимое CmakeLists.txt:
cmake_minimum_required(VERSION 3.12)
project(Imap)

set(CMAKE_CXX_STANDARD 11)

add_executable(Imap main.cpp Headers.h glib.h ImapReader.cpp ImapReader.h)

include_directories(/home/alex/libpcap)
target_link_libraries(Imap "/home/alex/libpcap")

Суть проблемы:
Программа падает на этапе компиляции с сообщением:
CMakeFiles/Imap.dir/main.cpp.o: In function `main':
/home/alex/CLionProjects/Imap/main.cpp:39: undefined reference to `pcap_open_offline'
/home/alex/CLionProjects/Imap/main.cpp:59: undefined reference to `pcap_next_ex'
collect2: error: ld returned 1 exit status
CMakeFiles/Imap.dir/build.make:98: recipe for target 'Imap' failed
make[3]: *** [Imap] Error 1
CMakeFiles/Makefile2:72: recipe for target 'CMakeFiles/Imap.dir/all' failed
make[2]: *** [CMakeFiles/Imap.dir/all] Error 2
CMakeFiles/Makefile2:84: recipe for target 'CMakeFiles/Imap.dir/rule' failed
make[1]: *** [CMakeFiles/Imap.dir/rule] Error 2
Makefile:118: recipe for target 'Imap' failed
make: *** [Imap] Error 2

Т.е. компилятор не видит файл, в котором содержатся тела данных функций, хотя он находится в подключенной папке.
Структура папки:
libpcap:

*

*Файлы исходного кода вперемешку со всякой всячиной

*Несколько незначащих(для меня) папок

*Папка с заголовочными файлами (/pcap)

Подскажите, как грамотно сконфигурировать Cmake?

A: target_link_libraries(Imap "/home/alex/libpcap") не занимается сборкой проекта, в лучшем случае компилятор узнает где хедеры искать. Поэтому компилятор справедливо замечает, что от него хотят странного.

Как грамотно интегрировать чужой проект из гитхаба в свой?

*

*озадачится скриптом/использовать менеджер пакетов (vcpkg, conan и пр.), которые соберут и установят зависимости.

Поскольку pcap это CMake проект, собрать его не составит проблем - всё как обычно:
cmake "<source path>" <CMAKE GENERATOR> -DCMAKE_INSTALL_PREFIX=<install path>
cmake --build . --target install

тогда CMakeList.txt мог бы содержать следующее:
find_package(pcap)
add_executable(Imap <sources>)
target_link_libraries(Imap pcap::pcap)

"Мог бы", потому что pcap не экспортирует файл конфигурации как положено, вместо этого куча кода на генерацию libpcap.pc. Поэтому, либо писать свой FindPcap.cmake, либо использовать pkg-config

*

*включить в свой проект как модуль.

Не для всякого проекта такое возможно, но если получится, тогда CMakeList.txt будет содержать следующее:
add_subdirectory(3rdparty/pcap)
add_executable(Imap <sources>)
target_link_libraries(Imap pcap)

Для pcap я бы рекомендовал добавить в начале set(BUILD_SHARED_LIBS OFF) - меньше шансов, что у цели pcap будут пропущены ссылки на зависимости.
Как не надо делать:
Mожно, но не стоит, включать исходники чужого проекта в сборку своего. Это редко, но бывает, что сторонняя либа хорошо разбита на независимые блоки кода и тогда можно попытаться добавить нужные
add_executable(Imap <sources> <list of 3rdparty/pcap/*.c>)

Если есть желание помучиться, то добавьте одну единицу компиляции к Imap а затем на каждый undefined reference to ищите в каком файле лежит реализация и добавляйте его. И, кстати, когда добавите весь набор 3rdparty/pcap/*.c, не удивляйтесь, что не соберётся или будет падать - ещё придётся угадать правильные дефайны и сделать правильные хедеры, которые обычно генерируются.

A: Если пользуетесь cmake и git, то лучшее что можно сделать, это отвести для включаемого проекта (или проектов) отдельную папку (обычно она называется third-party) в которой добавите включаемый проект как СУБМОДУЛЬ git. Это позволит без проблем обновлять включаемый проект. Что касается cmake, то у вас сдесь ошибка: target_link_libraries принимает библеотеку, которую нужно прилинковать, а вы указываете папку. Если libpcap поддерживает cmake, то, скорее всего, достаточно будет просто включить его как subdirectory  в CMakeLists.txt, а в target_link_libraries указать цель из cmake включаемого проекта.
PS не используйте include_directories, вместо этого используйте target_include_directories. Не забывайте о спецификаторах PUBLIC PRIVATE, а стандард указывайте с помощью target_compile_features


text:
Q: NullReferenceException for button array class Puzzle
      {
        private int PUZZLESIZE = 3;
        private int col, row;
        private Button[,] buttons;

        public Puzzle()
        {
        }

        public Puzzle(Form1 form1)
        {
            buttons = new Button[3, 3]
            { { form1.button1, form1.button2, form1.button3 },
            { form1.button4, form1.button5, form1.button6 },
            { form1.button7, form1.button8, form1.button9 } };
        }

        public void reset()
        {
            for (int i = 0; i < 3; i++)
                for (int j = 0; j < 3; j++)
                {
                    buttons[i, j].BackColor = Color.Lime;
                }
        }

buttons[i, j].BackColor = Color.Lime;
this line causes NullReferenceException when I call the reset method in Form1.cs. Any advice is appreciated!!!

A: Two problems:

*

*It's possible that form1.button1 (etc) are null. You should validate this in the constructor.

*If you call the parameterless constructor instead of the Puzzle(Form1) constructor, buttons will still be null. I suggest you get rid of the parameterless constructor.

I'd also advise that you use braces for all loops, i.e.
for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 3; j++)
    {
        buttons[i, j].BackColor = Color.Lime;
    }
}

Yes, it takes more space - but it's clearer and less error-prone in my experience.

A: Are you sure you're calling the default constructor? It looks like your class requires a Form1 instance to function, so try removing the default constructor. If it fails to build you've got your answer!


text:
Q: Hard-coding HTML element names I know that when the name of an HTML form element changes, in order for the Servlet that is processing the form to retrieve the parameter, it has to be aware of the updated element name. In trying to reduce the amount of changes that have to be made (from 2 places to 1) I have created a static field in the Servlet that is referenced in the doPost() method at the time the parameter is retrieved, and also in the JSP, instead of hard-coding the element name. Can anyone think of a reason that this would be a bad idea, other than the use of a scriptlet? Should the name of the element need to change, I would now only have to change it in 1 place (the Servlet constant).
Servlet Code:
package com.example.servlets;

public class ServletDemo extends HttpServlet {
    public static final String FIRST_NAME_FIELD = "firstName";

    public void doPost(HttpServletRequest request, HttpServletResponse response){
        String firstName = request.getParameter(FIRST_NAME_FIELD);
        //do something with the first name
    }
}

JSP:
<%@ page import="com.example.servlets.ServletDemo" %>

    <title>Example Page</title>

    <form method="POST">

FirstName:

      <input name="<%=ServletDemo.FIRST_NAME_FIELD%>"/>
      <input type="submit" value="Submit"/>
    </form>

A: If i understood your question correctly you are currently using the scriptlets like below ,
<input name='<%= Attribute in request %>' , so that you can change it in the server side.

Would this be a bad idea to implement something like that? Thoughts?

It is not the problem with scriptlets as it can be replaced through EL or JSTL.If you are making all the input parameters in jsp name to be dyanamic. You need to pass the request to the servlet .
Consider even if the user deosn't submit the form to jsp , may be just viewing you need to send the data from the server (for the input parameter names)
So all your request should be intercepted by the servlet , though it is not required . So it may again create an overhead in the performance .
So i suggest you to add your idea in the pages where the URL is intercepted by the servlet in case you have many static pages.

A: Going by your Solution:
To set a variable and then to use it anywhere in the code using jstl and basic scriptlet.
<%@page import="com.foo.Constant"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="FOO_NAME" value="<%=Constant.FOO_FORM_FIRST_NAME_PARAMETER %>"/>

To access it through EL
<input name ="${FOO_NAME}" />

If you do not want to use the scriptlets there are other solutions as well.
How to reference constants in EL?
Other solutions
As I see it since it would anyways be a large application with many form and multiple inputs the more ideal solution is some form of binding input fields to.. say Pojo, that way the servlet does not have to keep track of the input names used in the form. That would probably lead to using a filter to capture the request parameters and save in some pojo and make it available in the request scope.
OR
To other web frameworks, like Spring mvc, Struts, JSF etc. If you think that using any of these frameworks is an overkill since you end up rewriting significant portions of the code, you may give the following a shot if you think Struts or Spring MVC is heavy:
https://code.google.com/p/microservlet/

A: If the same form is used by several classes and you have a different name in each class of the same form type then you might need to bind the form dynamically to all those classes. It means that you can create a dynamic binding where the actual binding is determined at runtime. But this usecase is rarely used in practice because it's more complex than static binding. And it's not the same like in your case where you create a constant for field name because you didn't use any javabean and its properties to get the actual field name that you want to bind with the parameter. And you don't like to use fields associated to the servlet class but instantiate some bean and populate that properties. For this case you might want to create some factory for bean instantiation and you need some constants to build a bean. But it seems far away from the topic of your question. If you used these constants as a keys to map some objects and can reuse that key on the view layer using some expression engine that's what you can achieve using that keys. The actual values might change at runtime and it gives you a level of abstraction because the flow also change dynamically. Make sure you have the flow that is properly configured. You should know how it's difficult to construct complex features using raw servlets instead of framework that make a life easier.


text:
Q: how does the ReadableMap interface in React-native convert JS to JAVA? I'm trying to understand how to properly pass options from the js side of react-native to the java side.
The react-native bridge uses ReadableMap to convert but as a Java noob I'm failing to understand how this works.
More specifically I don't understand:

*

*how the actual conversion works?

*how to tell what type/format the downstream Java code wants?

*how to properly use ReadableMap to do this?

Generally I would like to know how this works but I'll give the specific example I'm looking at to give some context.

A react-native package exposes a datetime picker.
The JS side has a showTimePicker method:
showTimePicker(date, callback) {
    date = date || new Date();
    console.log(this.props);
    debugger
    var options = {
        ...this.props,
        hour:date.getHours(),
        minute:date.getMinutes()
    };
    RCTDateTimePicker.showTimePicker(options, function (hour, minute) {
        date.setHours(hour);
        date.setMinutes(minute);
        callback(date);
    });
}

RCTDateTimePicker.showTimePicker is bridged to a Java method on the native side:
@ReactMethod
public void showTimePicker(ReadableMap options, Callback callback) {
    DialogFragment timePicker = new TimePicker(options, callback);
    timePicker.show(activity.getFragmentManager(), "timePicker");
}

which calls
public TimePicker(ReadableMap options, Callback callback) {
    final Calendar c = Calendar.getInstance();
    this.callback = callback;
    hour = options.hasKey("hour") ? options.getInt("hour") : c.get(Calendar.HOUR_OF_DAY);
    minute = options.hasKey("minute") ? options.getInt("minute") : c.get(Calendar.MINUTE);
}

which creates and instance of an Android TimePicker. My goal is to change the style of the Timepicker from watch to spinner.
There is a settable XML attribute android:timePickerMode="spinner" but I don't think I can pass an XML attribute through react-native can I?
I also found a suggestion in comments to pass defStyleAttr to do this, but I don't understand how.

A: First, see the list of Argument Types from the React Native document for Android Native Modules.

Argument Types
The following argument types are supported for methods
  annotated with @ReactMethod and they directly map to their JavaScript
  equivalents

*

*Boolean -> Bool

*Integer -> Number

*Double -> Number

*Float -> Number

*String -> String

*Callback -> function

*ReadableMap -> Object

*ReadableArray -> Array

So, you can pass the extra field for timePickerMode as a String by updating the options that the JS side passes to include it.
var options = {
    ...this.props,
    hour:date.getHours(),
    minute:date.getMinutes(),
    timePickerMode:"spinner"
};

And then get that value from the ReadableMap in your custom TimePicker constructor.
String timePickerMode = options.hasKey("timePickerMode") ?
        options.getString("timePickerMode") : defaultTimePickerMode;

Now you have the value you wish to set. Unfortunately it does not appear that timePickerMode can be set programmatically. This SO question asks how to do it and @alanv (whose profile indicates they are a Software Engineer at Google) indicates that it is not possible at runtime.


text:
Q: Using ArcMap Field Calculator to count number of identical values? I have a file with an attribute table with data in 3 columns, and would like to use field calculator to populate a 4th column. The data is integer numbers between 0 and 56. I want the new column to tell if the numbers in the 3 previous columns are identical or not. I would like the 4th column to state "3" if all 3 columns have the same number, "2" if 2 are the same, and "0" if none of the columns contain the same number.
Does anyone know how to do this calculation?
I tried the following in VB script, but I still get an error message:

A: VBScript does not support syntax such as a=b=c to compare three values. Instead, you should write something like a=b AND a=c.
The complete pre-logic block could be
If [Grunntype] = [Grunntyp_1] And [Grunntype] = [Grunntyp_2] Then
    Lik_grtyp = 3
ElseIf [Grunntype] <> [Grunntyp_1] And [Grunntype] <> [Grunntyp_2] And [Grunntyp_1] <> [Grunntyp_2] Then
    Lik_grtyp = 0
Else
    Lik_grtyp = 2
End If


text:
Q: django/python: to access defined constant by equivelent string I have defined constant in django settings file like
LABEL_NAME = 'xyz'

And now I am having string 'LABEL_NAME' with me and want to have its equivalent constant defined value i.e
'xyz'
I can able to access 'xyz' value by LABEL_NAME. But I don't know how it can be accessed by string equivalent to defined constant.
I came from PHP background and worked with codeIgniter framework which provides the ability like this @CONSTANT('LABEL_NAME') to access equivalent defined constant value. Please let me know if we already have such kind of facility available in django/python. I could not get any help even after spending hour searching this problem.
I really appreciate your help of any kind.

A: You need getattr().
from django.conf import settings

setting_name = "LABEL_NAME"
print(getattr(settings, setting_name))

A: from project import settings
print settings.LABEL_NAME

or
from project.settings import *
print LABEL_NAME


text:
Q: PHP - Sorting a table record in ascending order with respect to one of the columns screenshot attached
The following code displays a 3-column table with alternating row columns. The columns are company name, file and deadline date (closeDate) from the recruitment table. This is for the front end and admins enter the data in the back-end.
The rows currently show in descending order i.e. the date record with the latest recruitment date is at the top.
I want to modify the code so that the records with the soonest recruitment closeDate show first i.e. in ascending order.
The application is written in cakePHP and I don't want to change the controller.
How can I do it?
Thank you.

                             Company
                             File
                             Closing Date

                        <?php foreach ($recruitments as $key=>$recruitment): ?>
                        <tr class="gradeX <?= $key % 2 == 1 ? 'even' : 'odd' ?>" role="row">

                      <?= !empty($recruitment->Companies['name']) ? $recruitment->Companies['name']:$recruitment->othercompany ?>

                      <?php if($recruitment->pdf): ?>
                        <a href="<?= $this->request->webroot.'uploads/recruitmentfile/'.h($recruitment->pdf); ?>" title="Open File" target="_blank">
                          <?php $file=explode('_',$recruitment->pdf); echo $file[1]?$file[1]:$recruitment->pdf; ?>

                        <?php endif; ?>

                    <?= $recruitment= date("d F Y", strtotime($recruitment->closeDate)); ?>

                        <?php endforeach; ?>


text:
Q: tensorflow Asymmetric loss function I want to implement an asymmetric loss function such as referenced here
https://stats.stackexchange.com/questions/37955/how-to-design-and-implement-an-asymmetric-loss-function-for-regression
in TensorFlow.
I currently am using the mean square error loss function:
mse = tf.reduce_mean(tf.squared_difference(out,Y))
Which I want to replace with
mse = tf.reduce_mean(asymetric_squared_difference(out,Y,alpha))
I Looked to see where tf.squared_difference is defined, and found https://www.tensorflow.org/api_docs/python/tf/squared_difference
Which says that tensorflow/python/ops/gen_math_ops.py
edit:
After much digging SquaredDifference is called from ops.math_grad line 999 to 1012.  But it has a lot of extra gradiant functionality that I am not sure how to replicate.
How would I best go about adding this functionality?

A: Are you wanting to implement your own, or would you rather just use any of the asymmetric functions (which should be able to be used as loss functions, as a 'loss' function is just a label for a function used to control loss)
Most of the functions on here that are asymmetric, should be compatible.
Off the top, you could just use
tf.zeta(x,q)

in place of
tf.squared_difference(x,y)

to replace your symmetric loss function (tf.squared_difference) with an asymmetric one (tf.zeta).
If you still want to implement a loss function, then you'd have to define the operation over two Tensors (while also observing the unlisted name function parameter I've left out) and return the result, just like tf.zeta does.
Also, you should check out the "Forecasting unemployment rate. . ." paper that speaks to your needs, as highlighted in your link to the "Cross validated" stack exchange post that sent you on your journey :)  It contains the equation for the basic expression an asymmetric loss function needs, which is what I used to search for tf.zeta in the TensorFlow docs for "Basic Math Functions".
But I could be totally wrong. I don't know.  I don't use TensorFlow. . .yet.


text:
Q: How does the result of this basic arithmetic calculation turns out like this? Pardon my newbie level question, but i've been wondering and also recounting to see why the result turns out to be like that?
I understand why the first row results in like that but the rest remain a mystery to me. I've been using calculator to help and also review some basics on hexadecimal arithmetic but i'm still lost. If anyone could please explain why the result became like that it'll be appreciated.
Thanks.
Question


text:
Q: Cassandra Detected unreadable sstables(data not caches)
ERROR [main] 2017-08-04 13:24:21,949 CassandraDaemon.java:638 - Detected unreadable sstables /opt/cassandra/data/some_key_space/ep_lc_events-adc44160dbe611e6953689bcd3ed73aa/mc-547-big-Summary.db, and many others...

That has happened after I upgraded Cassandra to 3 version and after a while downgraded it to 2nd version.
When I run this command: sudo service cassandra status
I have got such message:

could not access pidfile for Cassandra

In /var/log/cassandra/system.log I have logs which I wrote at the beginning.
PS: let me pay your attention that everything is happening on EC2 Amazon instance.

A: Well, I have just upgraded back to 3rd version, used cassandra-unloader  to export all data, then downgraded back to 2nd version and used cassandra-loader to import all data. But if you were lucky and had backups and snapshots it would not be an obstacle for you.
PS. Afterwards, I had to run this command nodetool resetlocalschema to reset local schema and resynchronize.
PPS. This you can find how to do that.
https://github.com/brianmhess/cassandra-loader

A: I also got the same error, but it was due to switching between cassandra 4.0.0 and version 3.11 and back again while using docker.
Update the version to the right one for the ssltable, or delete the data volume:
docker-compose logs cassandra
docker volumes ls
docker ps
docker-compose down
docker volume rm testapp_cassandra
docker volume ls

docker-compose up


text:
Q: Python lamda function to sort list of tuples based on relationship to previous tuple Is it possible to use sorted(list, lambda x:..) to sort a list of tuples such that the first value of the next tuple equals the second value of the previous tuple?
list_of_tuples = [("JFK", "DEN"), ("LAX", "ORD"), ("DEN", "SFO"), ("LAS", "LAX"), ("ORD", "ATL"), ("ATL", "JFK"), ("SFO", "LAS")]
Desired_output = [('JFK', 'DEN'), ('DEN', 'SFO'), ('SFO', 'LAS'), ('LAS', 'LAX'), ('LAX', 'ORD'), ('ORD', 'ATL'), ('ATL', 'JFK')]

I know how to sort by either value in the tuple (sorted(list_of_tuples, key = lambda x: x[0])), but what is the best way to sort using lambda and somehow reference the previous value in the list?

A: It's not possible with sorted(). But you can solve it using for loop.
d = dict(list_of_tuples)
res = [list_of_tuples[0]]
prev = res[0]

for idx in range(len(list_of_tuples) - 1):
    prev = (prev[1], d[prev[1]])
    res.append(prev)
print(res)

Output:
[('JFK', 'DEN'), ('DEN', 'SFO'), ('SFO', 'LAS'), ('LAS', 'LAX'), ('LAX', 'ORD'), ('ORD', 'ATL'), ('ATL', 'JFK')]

A: You can't do this with sorted(). What you are looking for is a eulerian path in a graph.
Here the vertices of the graph are your tuples, and there is a directed edge from one tuple to another if the last value of the one matches the first value of the other.
Simple solution with a dict
However, if there is always only one possible candidate for the next tuple, and you know that you can start with the first element in the list, then the problem is much simpler and you don't need any complex eulerian-path algorithm.
First, put the elements of the list in an efficient data structures that allows searching for the next tuple easily. You can use a python dict. Then, add the elements one by one.
list_of_tuples = [("JFK", "DEN"), ("LAX", "ORD"), ("DEN", "SFO"), ("LAS", "LAX"), ("ORD", "ATL"), ("ATL", "JFK"), ("SFO", "LAS")]

dict_first = {}
for pair in list_of_tuples:
  dict_first[pair[0]] = pair

result = [list_of_tuples[0]]
key = list_of_tuples[0][-1]
result = []
while key in dict_first and len(result) < len(list_of_tuples):
  result.append(dict_first[key])
  key = result[-1][-1]

print(result)

Output:
[('JFK', 'DEN'), ('DEN', 'SFO'), ('SFO', 'LAS'), ('LAS', 'LAX'), ('LAX', 'ORD'), ('ORD', 'ATL'), ('ATL', 'JFK')]

Using networkx.eulerian_path
In the general case where you really do need an algorithm for the eulerian path problem, there is one in module networkx:

*

*networkx.algorithms.euler.eulerian_path
from networkx import Graph, eulerian_path

list_of_tuples = [("JFK", "DEN"), ("LAX", "ORD"), ("DEN", "SFO"), ("LAS", "LAX"), ("ORD", "ATL"), ("ATL", "JFK"), ("SFO", "LAS")]

G = Graph()
G.add_edges_from(list_of_tuples)
result = list(eulerian_path(G))

print(result)

Output:
[('JFK', 'DEN'), ('DEN', 'SFO'), ('SFO', 'LAS'), ('LAS', 'LAX'), ('LAX', 'ORD'), ('ORD', 'ATL'), ('ATL', 'JFK')]

A: Try this code,
list_of_tuples = [("JFK", "DEN"), ("LAX", "ORD"), ("DEN", "SFO"),
                  ("LAS", "LAX"), ("ORD", "ATL"), ("ATL", "JFK"),
                  ("SFO", "LAS")]
Desired_output=[list_of_tuples[0]]
for i in range (len(list_of_tuples)):
    for j in  list_of_tuples:
        if Desired_output[i][1]==j[0]:
            Desired_output.append(j)
print(Desired_output)


text:
Q: Modify threshold in ReLU in Caffe framework I am new to Caffe, and now I need to modify the threshold values in ReLU layers in a convolution neural network. The way I am using now to modify thresholds is to edit the C++ source code in caffe/src/caffe/layers/relu_layer.cpp, and recompile it. However, this will change the threshold value to a specified value every time when ReLU is called. Is there any way to use different value as threshold in each ReLU layers in a network? By the way, I am using the pycaffe interface and I cannot find such a way to do so.
Finally, sorry for my poor English, if there are something unclear, just let me know, I'll try to describe it in detail.

A: Yes, you can. In src/caffe/proto, add a line:
message ReLUParameter {
  ...
  optional float threshold = 3 [default = 0]; #add this line
  ...
}

and in src/caffe/layers/relu_layer.cpp, make some small modifications as:
template <typename Dtype>
void ReLULayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
    const vector<Blob<Dtype>*>& top) {
  ...
  Dtype threshold = this->layer_param_.relu_param().threshold(); //add this line
  for (int i = 0; i < count; ++i) {
    top_data[i] = (bottom_data[i] > threshold) ? (bottom_data[i] - threshold) :
                  (negative_slope * (bottom_data[i] - threshold));
  }
}

template <typename Dtype>
void ReLULayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
    const vector<bool>& propagate_down,
    const vector<Blob<Dtype>*>& bottom) {
  if (propagate_down[0]) {
    ...
    Dtype threshold = this->layer_param_.relu_param().threshold(); //this line
    for (int i = 0; i < count; ++i) {
      bottom_diff[i] = top_diff[i] * ((bottom_data[i] > threshold)
          + negative_slope * (bottom_data[i] <= threshold));
    }
  }
}

and similarly in src/caffe/layers/relu_layer.cu the code should be like this.
And after compiling your caffe and pycaffe, in your net.prototxt, you can write a relu layer like:
layer {
  name: "threshold_relu"
  type: "ReLU"
  relu_param: {threshold: 1 #e.g. you want this relu layer to have a threshold 1}
  bottom: "input"
  top: "output"
}

A: If I understand correctly your "ReLU with threshold" is basically
f(x) = x-threshold if x>threshold, 0 otherwise

You can easily implement it by adding a "Bias" layer which subtract threshold from the input just prior to a regular "ReLU" layer


text:
Q: How can I use lodash to filter value between two date? created_at is the value I Want to compare with the beginDate and the endDate.

var newARRA = chain(this.props.transferts.transfertAccount)
.filter({ 'officeSender':
      this.props.users.user.office,officeReceiver:this.state.selectedOffice,
  'created_at':(this.state.beginDate,this.state.endDate)})

.groupBy("currency")
.map((v, k) => ({
     currency: k,
  amount: sumBy(v, 'fee')
 }))
.value();

A: You'll need to use the filter's predicate function. Example (not tested):
var newARRA = chain(this.props.transferts.transfertAccount)
  .filter(({ officeSender, officeReceiver, created_at }) => {
    return _.eq(officeSender, this.props.users.user.office) &&
           _.eq(officeReceiver, this.state.selectedOffice) &&
           _.gte(created_at, this.state.beginDate) &&
           _.lte(created_at, this.state.endDate) &&
  })
  .groupBy("currency")
  .map((v, k) => ({
    currency: k,
    amount: sumBy(v, 'fee')
  }))
  .value();

A: You could use the moment library to achieve this for you, assuming that the two values are moment like dates:
'created_at': moment().isBetween(this.state.beginDate, this.state.endDate)

This does assume that the dates are moment-like and don't require any pre-processing by the moment library.

A: I would prefer using a date library.
>
date-fns could do this for you
var isWithinRange = require('date-fns/is_within_range')
isWithinRange(
   new Date(2014, 0, 3), new Date(2014, 0, 1), new Date(2014, 0, 7)
)//=> true


text:
Q: Alternative to Date.to_time_in_current_zone as Rails 4.1 removed it In order to get the beginning of today in the current time zone, I had the following code:
Time.zone.today.to_time_in_current_zone

However, upgrading to Rails 4.1 caused an error as the to_time_in_current_zone method was removed. What should I use as an alternative? Time.zone.today.to_time gives me the beginning of the day in UTC time zone.

A: You should use in_time_zone instead.
Time.zone.today.in_time_zone

Till 4.0.2 to_time_in_current_zone was supported. See this link for more info.


text:
Q: How to get the mouse/keyboard raw events? I want to intercept the raw events from the keyboard (or the mouse, eventually). I tried to use the /dev/input/[...] files, they are very practical and I can read the events of any key even caps lock or Super. But I see that the keyboard input is subject to the key repeat system, and I don't want.
Is this the lowest level of information we can read from the kernel (this means that the key repeat behaviour is implemented in the keyboard??) or does it exists an API with more granularity (that logs as events as possible)? Also, is it possible to read events like this without root privileges ?


text:
Q: How to set rabbitmq connection properties using JNDI variables in Spring xml config? I have an application in Spring with is using RabbitMQ. I'm using xml based context configuration and rabbit namespace in this xml.
So far it looked as this:
<rabbit:connection-factory id="rabbitConnectionFactory" host="localhost" port="5672"/>

but now I want to use JNDI variables for host and port properties.
I know how to use JNDI when I have "classic" bean definitions but I have know idea how to use JNDI and rabbit namespace at the same time.
I wasn't able to define any child elements of rabbit:connection element. I get an error saying that it can't have any child nodes.
Any help appreciated :)
EDIT
This is how I use JNDI lookup in "standard" beans (with no special namespace)
<bean id="connector" class="com.foo.ConnectionProvider">
   <constructor-arg name="url">
        <jee:jndi-lookup expected-type="java.lang.String" jndi-name="java:comp/env/service/url"/>
   </constructor-arg>
</bean>

And in META-INF/context.xml:
<ResourceLink name="service/url" global="service/url" type="java.lang.String"/>

But as I said I don't know how to accomplish it using rabbit namespace. Have tried googling with no success..

A: I figured out I can use "standard" bean definition. I'm not completely happy with the solution, but at least, it works.
    <bean id="rabbitConnectionFactory"               class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
        <constructor-arg name="hostname" >
            <jee:jndi-lookup expected-type="java.lang.String"
                              jndi-name="java:comp/env/rabbit/host"/>
        </constructor-arg>
        <constructor-arg name="port" >
            <jee:jndi-lookup expected-type="java.lang.Integer"
                              jndi-name="java:comp/env/rabbit/port"/>
        </constructor-arg>
        <property name="username" value="guest"/>
        <property name="password" value="guest"/>
    </bean>

    <rabbit:template id="amqpTemplate" connection-factory="rabbitConnectionFactory" exchange="mcs-notifications.topic"/>
    <rabbit:admin connection-factory="rabbitConnectionFactory"/>

A: Another option is to use RMQConnectionFactory
<Resource name="jms/rabbitConnectionFactory" type="com.rabbitmq.jms.admin.RMQConnectionFactory"
        factory="org.apache.naming.factory.BeanFactory" username="guest"
        password="guest" />


text:
Q: How do I update a DocumentDb document? I have a Category->Question relationship in my DocumentDb. The Category documents contain a string-reference to the Questions id. When I add a question, I want to update the list of strings referenced in a Category. This is my code:
    public async Task<string> CreateQuestion(Question question, string categoryId)
    {
        var res = await client.CreateDocumentAsync(collectionLink, question);
        var category = GetCategory(categoryId);
        if (category.Questions == null) {
            category.Questions = new List<string>();
        }
        category.Questions.Add(categoryId);
        await client.ReplaceDocumentAsync(category.SelfLink, category);
        return res.Resource.Id;
    }

Everything returns without error, but the category-document is not updated with the list of questions.
What am I missing?

A: I found an answer - sort of - in this old GitHub issue: https://github.com/Azure/azure-documentdb-dotnet/issues/7
I made my classes inherit from Resource instead of Document and now it works as expected.


text:
Q: Error while attempting to add packages in Meteor So I am very new to Meteor, and I was sifting through some example apps and open source projects when I came across this simple chat application:
(https://github.com/BenderV/simplechat)
I wanted to download the project, run it on my local server, and mess around with the code to learn more about what does what, and how to use the Meteor framework. I simply downloaded the .zip file from github and tried to run it (using the meteor in my terminal. However I got the following error when I ran the application locally in my browser:
Your app is crashing. Here's the latest log.

=> Errors prevented startup:

While building the application:
error: no such package: 'accounts-guest'
error: no such package: 'user-status'
error: no such package: 'accounts-testing'
error: no such package: 'fontawesome4'
error: no such package: 'iron-router'
error: no such package: 'bootstrap-3'
error: no such package: 'fast-render'
error: no such package: 'jquery-titlealert'
error: no such package: 'related'

=> Your application has errors. Waiting for file change.

I can (obviously) infer from the nature of the log that the error that I am experiencing is because I don't have the correct packages installed (the one that are listed, obviously).
So keeping this in mind, I researched how to add packages to meteor (using instructions I found on Atmosphere JS pages of the respective packages). However, when I entered the command that was provided by Atmosphere into my terminal (for example for, 'accounts-guest' package I entered: meteor add artwells:accounts-guest). Unfortunately doing this did not work, and I was given something like the following error in the terminal: artwells:accounts-guest: no such package
I have no idea what to do, the packages will not install so I can not try this code. I come from experience with Rails, and in Rails if you needed to install "gems" (pretty much the same thing as packages in Meteor) you could just enter bundle install into the terminal to download and install undefined packages. Is there something like this in Meteor? I have heard of something called Meteorite, but am unsure what it is and how to use it.
Anyways I really would appreciate any help in getting me past this minor roadblock on my way to learning Meteor!
Thank you

A: That's an older project which use the old packaging system 'meteorite' = 'mrt' on the command line.
I suggest you try a newer example, Meteor ships with a few.  Once you have Meteor installed you can create an example app by typing one of the following commands :
meteor create --example leaderboard
meteor create --example todos
meteor create --example localmarket

And yes, there is a very similar mechanism to the gems commands you are accustomed to.  Simply running a project 'meteor' should download its dependencies.  Also you can run 'meteor update' if you want to update to the latest versions for your project.
Last August there was a major update to the meteor package management system, you can read more about it here : https://www.meteor.com/blog/2014/08/26/meteor-090-new-packaging-system
So, for any examples you'd like to check out, try and get a recent one, from meteor 1.0.   In newer versions of meteor those instructions on Atmosphere should work out fine for you.
You can see what version of meteor a project is running by looking at this file ".meteor/release"  inside a meteor project :
https://github.com/BenderV/simplechat/blob/master/.meteor/release
so you can see that one is old.
good luck!


text:
Q: Getting error in Multilingual Dropdows Jquery Code I am working on Multilingual Dropdowns and I am getting an error in my jQuery Code.
Getting This error on (e.target)
TS2345: Argument of type 'Document' is not assignable to parameter of type 'string | Element | JQuery | Element[] | ((this: HTMLElement, index: number, element: HTMLElement) => boolean)'.
  Type 'Document' is missing the following properties from type 'Element': assignedSlot, attributes, classList, className, and 58 more.
$(document).mouseup(function (e) {
    var container = $("#innerDiv");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) {
        container.hide();
    }
});

A: Try to attach the event to the body.
$('body').mouseup(...);

A: by doing some change in code. My problem solved.

 $(document).on("mouseup", (e: JQueryEventObject) => {
      var container = $("#innerDiv");
      // if the target of the click isn't the container nor a descendant of the container
      if (!container.is(e.target) && container.has(e.target).length === 0) {
        container.hide();
      }
    });


text:
Q: How to reset @class folder to native state I have inadvertently messed around with my matlabroot folder and now some functionality is broken. How do I reset the state of the folder so that everything works again?
While trying to solve this question, I added a new method (nansubset.m) to the @table folder ([matlabroot,'\toolbox\matlab\datatypes\@table\*']). That did not work so I deleted it and moved it to my Matlab path as suggested by @TroyHaskin's answer. Everything worked fine until I restarted Matlab. Now I am getting the error message:
Error using table/nansubset
Previously accessible file "C:\Program
Files\MATLAB\R2015b\toolbox\matlab\datatypes\@table\nansubset.m" is now inaccessible.

I have tried clear classes and clear java and restarting Matlab, to no avail.
EDIT:
I also found this link on the Mathworks site, which led me to doc toolbox_path_cache that in turn suggests using rehash toolboxcache. I did this and now there is a new error message:
Error using table/nansubset
Method 'nansubset' is not defined for class 'table' or is removed from MATLAB's search path.

However, which nansubset returns the right file from a directory on my Matlab path.

A: I have fixed my problem. Essentially, following the instructions from here, we are led to the helpfile for toolbox_path_cache, which states:

When you add or remove files in matlabroot/toolbox folders by some
  other means, MATLAB might not recognize those changes.
...
Update the cache so MATLAB recognizes
  the changes you made in matlabroot/toolbox folders.

To update the cache, type rehash toolbox and rehash toolboxcache. After this, it was necessary to restart Matlab to fix the problem


text:
Q: Finish method of batch class is not invoked when error occurs I have a batch class that http callout in the start method. Also, wrote an some block of codes to send notification when something went wrong in the finish method.
However, when api return unsuccessful response, batch class doesn't invoke the finished method. So, I don't get exception notification email. Also, I tried to add try-catch structure to inside of start method to get notification, instead of this, I don't get email still. In the debug log, I can see email subject etc. but it doesn't send. How should I proceed?
Btw, email deliverability is open.
public class LibringGetDailySpentBatchable implements Database.Batchable<LibringIntegrationJsonParser.Connections>, Database.allowscallouts, Database.Stateful{

public String nextPage;
public Decimal cPage;
public Decimal tPage;
public String network;

public LibringGetDailySpentBatchable(String nextBatchUrl, String network){
    nextPage = nextBatchUrl;
    this.network = network;
}

public LibringGetDailySpentBatchable(String network){
    this.network = network;
}

public Iterable<LibringIntegrationJsonParser.Connections> start(Database.BatchableContext BC){

    LibringIntegration.Result r = new LibringIntegration.Result();

    //Callout
    if(nextPage == null){
        r = LibringIntegration.getAllThisMonth(null,network);
    }
    else{
        r = LibringIntegration.getAllThisMonth(nextPage,null);
    }

    //Parsing
    LibringIntegrationJsonParser rs = LibringIntegrationJsonParser.parse(r.body);

    nextPage = rs.next_page_url;
    cPage = rs.current_page;
    tPage = rs.total_pages;

    return rs.connections;
}

public void execute(Database.BatchableContext info, List<LibringIntegrationJsonParser.Connections> allData){

    Some codes
}

public void finish(Database.BatchableContext info) {

    AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, ExtendedStatus
                      FROM AsyncApexJob WHERE Id =
                      :info.getJobId()];

    if(a.NumberOfErrors > 0 ||test.isRunningTest()){

        Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
        String[] sendingTo = Label.Error_Message_Contacts.split(',');
        semail.setToAddresses(sendingTo);
        semail.setSubject('Libring Integration Failed');
        semail.setPlainTextBody('Libring integration failed. It is called again'+ a.ExtendedStatus);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail});

    }

}

}

A: With your goal being error handling in batch jobs, let me introduce you to the Winter '19 BatchApexErrorEvent!
It slices, it dices... It provides a mechanism to raise platform events from a batch job. More importantly, it is specifically designed for your error handling scenario.
The majority of details you need are covered in Building a Batch Retry Framework With BatchApexErrorEvent.
The short version is that you mark you batch job as implementing the Database.RaisesPlatformEvents interface. Then it will start sending out Platform events as the Batch Job runs. Then you subscribe to the BatchApexErrorEvent events and handle them as required.


text:
Q: Send data from main html page controller to a directive controller I was trying to communicate between controllers and directive. I have studied few blogs and searched stackoverflow, there are some wonderful concepts about these topics. But they all are case specific problems. I tried to solve my problem in their style but I found no luck.
My problem is.. I need to send some array to a directive. The array is defined in the controller of the main html file. And the html page has a directive too. Also the directive has his own controller to do some job. I need to send an array to that directive controller for processing and that array has to be two way binded so that any changes in one side can be reflected in another side.

A: I was dealing with this kind of situation lately and figured out a way to deal with it.
You can use this procedure to send data and process it in a directive from a controller.
First make a controller in the main page and define some array like you want...
app.controller("ctrl", function($scope) {
    $scope.scope = $scope; //this is to transfer the current scope to the directive
    $scope.array = [{
        "a": "vfdxvf",
        "b": "sdc"
    }, {
        "a": "vfdxvf",
        "b": "sdc"
    }, {
        "a": "vfdxvf",
        "b": "sdc"
    }, {
        "a": "vfdxvf",
        "b": "sdc"
    }];
});

above in the code,  $scope.scope = $scope is to create reference of the controller scope.
And then define the directive like this. It will bind all the values you want. And Any change in the array on any side, will reflect on the other side as well.
Here is a dummy code..
app.directive("someDirective", function() {
    return {
        restrict: "EA",
        scope {
            array: "=", // two way binding of array..
            scope: '=' // collecting the scope of the controller it came from
        },
        templateUrl: "./templates/test.html",
        controller: function($scope) {
            $scope.newArray = $scope.scope.array;
            //do useful coding with the array...
        }
    }
});

And for the html main page just write like this..
<some-directive scope="scope" array="array"></some-directive>

A: use = in directive scope for bind controller variable
app.directive("myDir", function(){
  return{
    scope : {
      myArr : "="
    },
    controller : function($scope){

    },
    link : function(scope, ele, attr){
      scope.myArr.push("C");
    }
  }
});

see  https://plnkr.co/edit/pkkaEKBZVEajm5LBf9QD?p=preview