text:
Q: How to pass an array of events to the FullCalendar jQuery plugin I am using the FullCalendar jquery plugin to display a calendar on my page.  I am now trying to figure out how to populate the calendar with my own events.  I have some code which loops through my query results and builds a $json_array of all the events.  This seems to be working because when I output the array to the screen I can see my events and they look properly formatted, like this:
    [eventData] => Array
    (
        [0] => Array
            (
                [title] => 09:30 AM Hearing-950 Boundary Rd, South Glengarry PC540 H#559588-Council Chambers - 6 Oak St, Lancaster
                [start] => 2014-04-29
            )

        [1] => Array
            (
                [title] => 09:30 AM Hearing-6-12 Park St, Brockville PC340 H#559597-Council Chambers - 1 King St W., Brockville
                [start] => 2014-04-30
            )

        [2] => Array
            (
                [title] => 09:30 AM Hearing-1340 Kingston Rd, Pickering PC430 H#558975-Council Chambers, One The Esplanade, Pickering
                [start] => 2014-04-01
            )
     )

In addition to building the $json_array, my sample code also builds a string called $eventString which also looks like it could be used as the event source for the calendar.  Here is the code which builds both the $json_array and $eventString:
<?php
$qryEvents = $this->db->query(" SELECT date(tbldeadlines.Date) AS D,
    time_format(tbldeadlines.HearingStartTime, '%H:%i %p') AS S,
    tbldeadlines.Type AS T,
    tbldeadlines.`Property#` AS P,
    tblproperties.`Property Address` AS A,
    tblmunicipalities.MunicipalityName AS M,
    tblproperties.`Property Owner` AS O,
    tbldeadlines.HearingNotes AS N,
    tbldeadlines.HearingNumber AS H,
    format(tblproperties.PC,0) AS PC,
    tblpropertycodes.`SIMPLE PC NAME` AS PCN
FROM tbldeadlines INNER JOIN tblproperties ON tbldeadlines.`Property#` = tblproperties.`Property#`
     INNER JOIN tblmunicipalities ON tblproperties.County = tblmunicipalities.MunicipalitiesCounty
     INNER JOIN tblpropertycodes ON tblproperties.PC = tblpropertycodes.PC
WHERE 1 {$whereCond}
GROUP BY P, D, T, A, N, H, S");

$evntArray =  $qryEvents->result_array();
$eventString = "";
if(!empty($evntArray)){
    $json_array = array();
    $eventString .= "[" ;
    foreach($evntArray as $row){
        $json_array[] = array("title"=>addslashes($row['S'])." ".addslashes($row['T'])."-".addslashes($row['A']).", ".addslashes($row['M'])." PC".addslashes($row['PC'])." H#".addslashes($row['H'])."-".addslashes($row['N']), "start"=> date('Y-m-d',strtotime($row['D'])));
        $eventString .= "{title:'".addslashes($row['N'])."',start:'".date('Y-m-d',strtotime($row['D']))."'},";
    }
    $eventString .= substr($eventString,0,-1);
    $eventString .= "]";
}

if($_GET['start'] != "" && $_GET['end'] != ""){
    echo json_encode($json_array);
}

$data['eventData'] = $json_array;
$data['calurl'] = 'http://mysite.ca/admin/view';
$this->load->view('pts_template', $data);
?>

My problem is that I don't know how to get my results into the calendar. How can I initialize the calendar and reference the array that is already on the page?  Which should I be using, the $json_array or the $eventString?
Thanks for any ideas you might have.


text:
Q: Override Django Object Serializer to get rid of specified model I need to convert a Django Queryset Object into a Json string. The built in Django Serialization library works great. Although it specifies the name of the Model from where it was created. Since I don't need this, how do I get rid of it? What else do I need to override to be able to use the overridden end_object method below?
class Serializer(PythonSerializer):
    def end_object(self, obj):
        self.objects.append({
            "model"  : smart_unicode(obj._meta), # <-- I want to remove this
            "pk"     : smart_unicode(obj._get_pk_val(), strings_only=True),
            "fields" : fields
        })
        self._current = None

A: Here's a serializer that removes all metadata (pk, models) from the serialized output, and moves the fields up to the top-level of each object. Tested in django 1.5
from django.core.serializers import json

class CleanSerializer(json.Serializer):

    def get_dump_object(self, obj):
        return self._current

Serializer = CleanSerializer

Edit:
In migrating my app to an older version of django (precipitated by a change in hosting provider), the above serializer stopped working. Below is a serializer that handles the referenced versions:
import logging
import django

from django.core.serializers import json
from django.utils.encoding import smart_unicode

class CleanSerializer148(json.Serializer):

    def end_object(self, obj):
        current = self._current
        current.update({'pk': smart_unicode(obj._get_pk_val(),
                                            strings_only=True)})
        self.objects.append(current)
        self._current = None

class CleanSerializer151(json.Serializer):

    def get_dump_object(self, obj):
        self._current['pk'] = obj.pk
        return self._current

if django.get_version() == '1.4.8':
    CleanSerializer = CleanSerializer148

else:
    CleanSerializer = CleanSerializer151

Serializer = CleanSerializer

A: Override JSON serializer class:
from django.core.serializers.json import Serializer, DjangoJSONEncoder
from django.utils import simplejson

class MySerializer(Serializer):
"""
Convert QuerySets to JSONS, overrided to remove "model" from JSON
"""

def end_serialization(self):

    # little hack
    cleaned_objects = []

    for obj in self.objects:
        del obj['model']
        cleaned_objects.append(obj)

    simplejson.dump(cleaned_objects, self.stream, cls=DjangoJSONEncoder, **self.options)

In the view:
    JSONSerializer = MySerializer
    jS = JSONSerializer()

A: Sorry I had totally forgot about this question. This is how I ended up solving it (with thanks to FunkyBob on #django):
from django.core.serializers.python import Serializer

class MySerialiser(Serializer):
    def end_object( self, obj ):
        self._current['id'] = obj._get_pk_val()
        self.objects.append( self._current )

 # views.py
 serializer = MySerialiser()
 data = serializer.serialize(some_qs)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Typing effect for javascript creating new line before typing next span item This part of my java script created a style element that acts like a type writer css effect on my website. For some reason when it changes the span item, the style element goes to the new line before typing again on the original line. See image.

html

Hi, Im Roshni. My skills include

javascript:
  // INJECT CSS
  var css = document.createElement("style");
  css.type = "text/css";
  css.innerHTML += ".txt-rotate > .wrap { border-right: 0.08em solid #666 }";
  document.body.appendChild(css);
};

A: span {
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
  border-radius: 2px;
  padding: 1px 5px 3px 0px;
}

seems to work.


text:
Q: Log4back not logging properly I'm using log4back in a really large progect (lots of class).
In the main class i configure the logger ot get the configuration froma an xml file:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="SIFT" class="ch.qos.logback.classic.sift.SiftingAppender">
       <discriminator>
        <key>filePath</key>
        <defaultValue>C:/</defaultValue>
    </discriminator>

    <sift>
        <appender name="startupDailyRolloverAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${filePath}/application.log</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>${filePath}/application.log.%d{yyyyMMdd}_%d{HHmmss,aux}</fileNamePattern>
                <maxHistory>5</maxHistory>
            </rollingPolicy>
            <encoder>
                <pattern>%d{dd/MM/yyyy_HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
            </encoder>
        </appender>
    </sift>
</appender>

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%d{dd/MM/yyyy_HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>

<root level="info">
    <appender-ref ref="SIFT" />
</root>

<root level="info">
    <appender-ref ref="STDOUT" />
</root>-->

This is the part where i configure the logger:
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    try {
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(context);
        context.reset();
        URL res = Ned.class.getResource("package/resources/logback.xml");
        if (res != null) {
            configurator.doConfigure(res);
        }
        MDC.put("filePath", Main.applicationDir.substring(0, Main.applicationDir.length() - 1));
    } catch (JoranException je) {
    je.printStackTrace();
    }
StatusPrinter.printInCaseOfErrorsOrWarnings(context);

Now, in each class, i define the logger as a static variable like this
 private static final Logger logger = LoggerFactory.getLogger(NomeClasse.class);

This is quite perfect, since i ca log many of the class output into the file i specified.
Unfortunately sometimes some class don't log any kind of out put, for example with this line of code
logger.error("Unexpected failure: " + ret.getStatus());

or even his
logger.error(ex.getMessage(), ex);

have no output into the file i specified. And in each class i define the logger as static variable as stated above.
Can i have some hint to figure out what's wrong?
I Used this as reference but i cannot solve the issue.


text:
Q: hibernate @OneToOne mapping with Principal REST SOLUTION: I solved it, here is the new RestUser.java if it can help anyone in the future
@RequestMapping(value="/rate", method=RequestMethod.POST)
public ResponseEntity rate(@RequestBody Rating rating, Principal principal){

    User user = userService.findByUsername(principal.getName());
    Rating ratingAVG = ratingService.findOne(user.getId());
    ratingAVG.setFood(rating.getFood());
    ratingAVG.setService(rating.getService());
    user.setRating(ratingAVG);
    ratingAVG.setUser(user);
    userService.save(user);

    return new ResponseEntity("Rated!", HttpStatus.OK);
}

QUESTION
I've an issue while inserting/updating object that have a foreigner key. I have a table called Rating that looks like this. I want to add a unique Rating object that take the current user_id with principal.getName(). I'm using Advanced REST client to test it and am already logged in
+------------------------------------------------+
|                     Rating                     |
+------------------------------------------------+
| id |    food     |    service     |   user_id  |
+----+-------------+----------------+------------+
|  1 |     5       |        5       |      1     |
+----+-------------+----------------+------------+

User.java
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="Id", nullable=false, updatable=false)
private long id;

private String username;
private String password;
private String firstName;
private String lastName;

@OneToOne(cascade=CascadeType.ALL, mappedBy="user")
@JoinColumn(name="user_id", unique=true)
private Rating rating;

Rating.java
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

private int food;
private int service;

@OneToOne(cascade = CascadeType.ALL)
@JsonIgnore
private User user;

RatingServiceimpl.java
@Service
public class RatingServiceImpl implements RatingService {

    @Autowired
    private RatingRepository ratingRepository;

    @Override
    public Rating save(Rating rating) {
        return ratingRepository.save(rating);
    }

}

UserRest.java
@RestController
@RequestMapping("/user")
public class UserRest {

    @Autowired
    UserService userService;

    @Autowired
    RatingService ratingService;

    @RequestMapping(value="/rate", method=RequestMethod.POST)
    public ResponseEntity rate(@RequestBody Rating rating, Principal principal){

        User user = userService.findByUsername(principal.getName());
        user.setRating(rating);
        rating.setUser(user);
        userService.save(user);

        return new ResponseEntity("Rated!", HttpStatus.OK);
    }

}

This is what I get, it adds a new object while i just want it to update the existent one.
MySQL Browser Screen
Thanks !

A: It looks like you are saving the rating with our setting the user. I do not see any '@Transaction' annotations so I assume your transactions are inside the 'RatingRepository' meaning that you transaction will be committed before you set the rating to the user.
Try setting the user to the rating before calling save.


text:
Q: Appending to new df if items in rows meet conditions between columns I'm trying to organize a big dataset by "correct" and "incorrect" answers. The condition for correct answer is this:
df['color'] == 'green' and df['correct'] = 'v') or (df['color']=='blue' and df['correct']='a') or (df['color']=='red' and df['correct']=='r')

If the rows meet those conditions, I want to append them to a df_correct:
df_correct = pd.DataFrame(columns=['word','rt'])

If the conditions are not met, I need the rows to be appended to another dataframe.
I thought of looping through the rows of the dataframe but this doesn't seem to be working:
df_correct = pd.DataFrame(columns=['word','rt'])
df_incorrect = pd.DataFrame(columns=['word','rt'])

for i in df:
   if (df['color'] == 'green' and df['correct'] = 'v') or (df['color']=='blue' and df['correct']='a') or (df['color']=='red' and df['correct']=='r'):
       df_correct.append(i)
   else:
       df_incorrect.append(i)

This is how part of the df looks:
,word,color,correct,rt

923,ABUSO,red,r,993
929,CHALECO, blue, a,1825
935,ESTATUA, red, r,951
941,ORQUESTRA, blue, a,1393
1556,METAL, blue, a,1285
1562,ABUSO,red,r,1272
1568,CALLE, green, v,1210
1574,CORTINA, blue, a,872
1580,SILLA, blue, a,530
1586,COBARDE, blue, a,510
1592,TRISTEZA, green, v,786
1598,PÁRPADO, green, v,561
1604,ACCIDENTE, blue, a,1329
1853,VENTANA, red, r,1010
1859,ABUSO,red,r,752
1919,CANASTA, blue, a,628
1925,TERRORISTA, green, v,589
1931,BRAZO, red, r,970
1937,TENEDOR, red, r,784
1943,SILENCIO, red, r,614
1949,TRISTEZA, green, v,564
1955,POSTER, green, v,1314
1961,MORGUE, green, v,703
1967,LLUVIA, blue, a,898
1973,VIOLÍN, green, v,638
1979,POBREZA, red, r,724
1985,TRAICIÓN, green, v,856
1991,UTENSILLO, green, v,942
1997,CÁNCER, red, r,845
2003,BANCO, green, v,927
2009,DESASTRE, green, v,769
2015,SILLA, blue, a,999
2021,SOLEDAD, red, r,647
2027,ESFERA, red, r,637
2033,MISERIA, blue, a,823
2039,ESTATUA, red, r,793
2045,DEDO, red, r,566
2051,VIOLACIÓN, blue, a,840
2057,HEBILLA, blue, a,818
2063,ENOJO, red, r,731
2069,DEMONIO, green, v,858
2075,CABALLO, green, v,767
2081,CORTINA, blue, a,763
2087,ASIENTO, green, v,800
2093,CRUEL, red, r,651
2099,MIEDO, green, v,895
2105,EDIFICIO, blue, a,726
2111,PANFLETO, red, r,713
2117,DEPRESIÓN, red, r,598
2123,MANTEL, green, v,578
2129,PARTE, blue, a,580
2135,CÁRCEL, green, v,791
2141,ORQUESTRA, blue, a,569
2147,INFIERNO, red, r,519
2153,MOMENTO, red, r,506
2159,DIABLO, blue, a,680
2165,CUCARACHA, green, v,627
2171,BOMBA, red, r,483
2177,GANGRENA, red, r,514
2183,MUERTE, blue, a,895
2189,AHOGADO, red, r,630
2195,PARALISIS, blue, a,743
2201,VENENO, green, v,646
2207,CHALECO, blue, a,662
2213,ODIO, green, v,792
2219,FUNERAL, green, v,641
2225,MONJA, green, v,728
2231,LÁPIZ, red, r,676
2237,METAL, blue, a,590
2243,PAPEL, green, v,614
2249,CUADRADO, blue, a,795
2255,ACCIDENTE, blue, a,665
2261,CASA, red, r,662
2267,DOLOR, blue, a,781
2273,CHOQUE, green, v,596
2366,HEBILLA, blue, a,1573
2372,BANCO, green, v,732
2378,VIOLÍN, green, v,608
2384,ACCIDENTE, blue, a,564
2390,ASIENTO, green, v,687
2396,SANGRIENTO, blue, a,820
2402,GANGRENA, red, r,951
2408,ENOJO, red, r,708
2414,AHOGADO, red, r,786
2420,TENEDOR, red, r,643
2426,ESTATUA, red, r,427
2432,DOLOR, blue, a,779
2438,MENTÓN, red, r,670
2444,CHALECO, blue, a,450
2450,NUBES, green, v,418
2456,ÍTEM, red, r,627
2462,DEPRESIÓN, red, r,835
2468,CORDERO, blue, a,770
2474,INFIERNO, red, r,781
2480,DIABLO, blue, a,542
2486,SILENCIO, red, r,486
2492,ORQUESTRA, blue, a,734
2498,POSTER, green, v,902
2504,PARALISIS, blue, a,1055
2510,QUEMADURA, green, v,657
2516,LLUVIA, blue, a,557
2522,COBARDE, blue, a,485
2528,CASA, red, r,550
2534,TERRORISTA, green, v,483
2540,ASALTO, blue, a,725
2546,POBREZA, red, r,580
2552,SILLA, blue, a,601
2558,CORTINA, blue, a,467
2564,FUNERAL, green, v,493
2570,MANTECA, green, v,466
2576,ABUSO,red,r,779
2582,PARTE, blue, a,557
2756,CANASTA, blue, a,477
2762,BRAZO, red, r,567
2768,ODIO, green, v,608
2774,MIEDO, green, v,503
2780,LÁPIZ, red, r,561
2786,EDIFICIO, blue, a,529
2792,MATANZA, red, r,740
2798,BOMBA, red, r,404
2804,METAL, blue, a,601
2810,PÁRPADO, green, v,390
2816,CABALLO, green, v,391
2822,MOMENTO, red, r,1270
2828,PIE, green, v,654
2834,MANTEL, green, v,510
2840,GRANJA, blue, a,477
2846,TRAICIÓN, green, v,544
2852,CALLE, green, v,500
2858,CHOQUE, green, v,510
2864,PARAGUAS, blue, a,574
2957,MISERIA, blue, a,1938
2963,SOLEDAD, red, r,1426
2969,LLUVIA, blue, a,1091
2975,TENEDOR, red, r,1181
2981,CORTINA, blue, a,1012
2987,PESADILLA, red, r,865
2993,PARALISIS, blue, a,793
2999,ACCIDENTE, blue, a,776
3005,DEDO, red, r,1669
3011,MENTÓN, red, r,665
3017,TORTURA, blue, a,622
3023,UTENSILLO, green, v,1353
3029,CUADRADO, blue, a,1693
3143,MANTECA, green, v,1028
3149,PÁRPADO, green, v,1257
3155,CADÁVER, red, r,1192
3161,PANFLETO, red, r,560
3167,EDIFICIO, blue, a,1181
3173,CORDERO, blue, a,485
3179,PIE, green, v,1145
3233,BANCO, green, v,989
3239,BOMBA, red, r,935
3371,ABUSO,red,r,981

Since all of them match the condition, they should go to the df_correct.
What's the correct way to do this?
Thank you.

A: If I've understood correctly, try creating the conditions, then filtering df based on the condition:
c1 = df['color'].eq('green') & df['correct'].eq('v')
c2 = df['color'].eq('blue') & df['correct'].eq('a')
c3 = df['color'].eq('red') & df['correct'].eq('r')
m = c1 | c2 | c3

Then select values based on the full condition m using loc:
correct_df = df.loc[m]
incorrect_df = df.loc[~m]

Optional Select specific columns as well:
correct_df = df.loc[m, ['word', 'rt']]
incorrect_df = df.loc[~m, ['word', 'rt']]

Sample DataFrame:
df = pd.DataFrame({'color': ['green', 'blue', 'red'] * 2,
                   'correct': ['v', 'r', 'v', 'a', 'a', 'r'],
                   'word': list('abcdef'),
                   'rt': range(1, 7)})

   color correct word  rt
0  green       v    a   1
1   blue       r    b   2
2    red       v    c   3
3  green       a    d   4
4   blue       a    e   5
5    red       r    f   6

correct_df:
correct_df = df.loc[m]

   color correct word  rt
0  green       v    a   1
4   blue       a    e   5
5    red       r    f   6

correct_df = df.loc[m, ['word', 'rt']]

  word  rt
0    a   1
4    e   5
5    f   6

incorrect_df:
incorrect_df = df.loc[~m]

   color correct word  rt
1   blue       r    b   2
2    red       v    c   3
3  green       a    d   4

incorrect_df = df.loc[~m, ['word', 'rt']]

  word  rt
1    b   2
2    c   3
3    d   4

A: Assuming df is your entire dataset containing all the records

df = ...

cond = ((df['color'] == 'green' & df['correct'] = 'v') | (df['color']=='blue' & df['correct']='a') | (df['color']=='red' & df['correct']=='r'))

df_correct = df.loc[cond,['word','rt']]
df_incorrect = df.loc[~cond,['word','rt']]

cond will be your boolean indexer of all the rows which matches the condition
~cond will be your boolean indexer of all the rows which do not matche the condition


text:
Q: Unable to read file from server I want to download file from server. File is created successfully in my android device but that file is empty file. it is not writing anything in file.
My filereading code is as follows:
URL url = new URL(urlString);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);

        //connect
        urlConnection.connect();

        File SDCardRoot = Environment.getExternalStorageDirectory();
        //create a new file, to save the downloaded file
        File file = new File(SDCardRoot,pos);

        FileOutputStream fileOutput = new FileOutputStream(file);

        //Stream used for reading the data from the internet
        InputStream inputStream = urlConnection.getInputStream();

        //this is the total size of the file which we are downloading
        totalSize = urlConnection.getContentLength();

        //create a buffer...
        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
        }
        fileOutput.close();

}

I have debugged the code. There is something wrong in  while ( (bufferLength = inputStream.read(buffer)) > 0 ) condition as the compiler didnt go inside this loop.
My log cat error:
ERROR/ActivityThread(8218): Activity com.sec.android.app.myfiles.DetailsActivity has leaked IntentReceiver com.sec.android.app.myfiles.DetailsActivity$4@42760570 that was originally registered here. Are you missing a call to unregisterReceiver()?
        android.app.IntentReceiverLeaked: Activity com.sec.android.app.myfiles.DetailsActivity has leaked IntentReceiver com.sec.android.app.myfiles.DetailsActivity$4@42760570 that was originally registered here. Are you missing a call to unregisterReceiver()?
        at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:792)
        at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:593)
        at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1254)
        at android.app.ContextImpl.registerReceiver(ContextImpl.java:1241)
        at android.app.ContextImpl.registerReceiver(ContextImpl.java:1235)
        at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:372)
        at

    com.sec.android.app.myfiles.DetailsActivity.setLocaleReceiver(DetailsActivity.java:185)
            at com.sec.android.app.myfiles.DetailsActivity.onCreate(DetailsActivity.java:121)
            at android.app.Activity.performCreate(Activity.java:5206)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
            at android.app.ActivityThread.access$600(ActivityThread.java:140)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4898)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
            at dalvik.system.NativeStart.main(Native Method)

A: Use Asynctask to download file from server this is the code to download a file from server with Progress dialog and works fine.. please try it..
 package .....;

    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.URL;
    import java.net.URLConnection;

    import android.app.Activity;
    import android.app.Dialog;
    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.Environment;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;

     public class facebook1 extends Activity {

        Button btnShowProgress;

        private ProgressDialog pDialog;

        public static final int progress_bar_type = 0;

        private static String file_url = "yoururl";

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.layout);

            btnShowProgress = (Button) findViewById(R.id.submit1);

            btnShowProgress.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    new DownloadFileFromURL().execute(file_url);

                }

            });
        }

        @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case progress_bar_type:
                pDialog = new ProgressDialog(this);
                pDialog.setMessage("Please wait.....");
                pDialog.setIndeterminate(false);
                pDialog.setMax(100);
                pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pDialog.setCancelable(true);
                pDialog.show();
                return pDialog;
            default:
                return null;
            }
        }

        class DownloadFileFromURL extends AsyncTask<String, String, String> {

            protected static final int BUFFER_SIZE = 0;

            @SuppressWarnings("deprecation")
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                showDialog(progress_bar_type);
            }

            /**
             * Downloading file in background thread
             * */
            @Override
            protected String doInBackground(String... f_url) {
                int count;
                try {

                    URL url = new URL(f_url[0]);
                    URLConnection conection = url.openConnection();
                    conection.connect();

                    int lenghtOfFile = conection.getContentLength();

                    InputStream input = new BufferedInputStream(url.openStream());

                    File downloadloc = Environment.getExternalStorageDirectory();
                    OutputStream output = new FileOutputStream(downloadloc
                            + "/filenam.ext"); //type the name of file with extension.

                    byte data[] = new byte[1024];

                    long total = 0;

                    while ((count = input.read(data)) != -1) {
                        total += count;

                        publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                        output.write(data, 0, count);
                    }

                    output.flush();

                    output.close();
                    input.close();

                } catch (Exception e) {
                    Log.e("Error: ", e.getMessage());
                }

                return null;
            }

            protected void onProgressUpdate(String... progress) {
                pDialog.setProgress(Integer.parseInt(progress[0]));
            }

            @Override
            protected void onPostExecute(String file_url) {
                dismissDialog(progress_bar_type);

            }}

}

Manifest File:
<uses-permission
         android:name="android.permission.WRITE_EXTERNAL_STORAGE"
         > </uses-permission>

A: You should change
File SDCardRoot = Environment.getExternalStorageDirectory();

to
String SDCardRoot = Environment.getExternalStorageDirectory().getPath();

A: Starting from API 14, Network operations are not supported in the main Thread. Try using AsyncTask if you are doing it in the main Thread and using 14 or higher version of SDK.


text:
Q: Tagging specific data from an .xlsx file when importing a data frame to R excel file with marked data
Referencing the picture linked above, I'm looking to import this excel file into R, but I'd like the data that are red and have the strikethrough to be tagged/marked somehow in R - in order to be able to create vectors from them. Is there a way to do that, without having to rearrange the data frame first?

A: The openxlsx package has the ability to access the workbook style. Among much other information, it reads the following from the worksheets:

*

*Cell formatting

*Font name

*Font size

*Font colour

However, it doesn't have the "strikethrough effect". But you can certainly take advantage of the different font colours.
Suppose you have the following Excel file where I've made two cells red with a strikethrough effect and kept the others as normal:

Load the library and import the data.
library(openxlsx)

wb <- loadWorkbook("filename.xlsx")
data <- read.xlsx(wb, colNames=FALSE)

The styles are contained in the styleObjects object
wb$styleObjects
[[1]]
[[1]]$style
A custom cell style.

 Cell formatting: GENERAL
 Font name: Calibri
 Font size: 11
 Font colour: #FF0000

[[1]]$sheet
[1] "Sheet1"

[[1]]$rows
[1] 3 4

[[1]]$cols
[1] 2 3

There may be many other elements of the list depending on the number of custom styles you applied to the cells in your worksheet. Each custom style will be included in this object. Here I've only got 1 custom style corresponding to the red font colour (#FF0000). The $rows and $cols items give the row and column indices of only the cells that have this font colour. You can then use this information to extract the required data values.
red.rows <- wb$styleObjects[[1]]$rows
red.cols <- wb$styleObjects[[1]]$cols

data[cbind(red.rows, red.cols)]
#[1] 43 12


text:
Q: Simplifying Trigonometric Recursive functions Given that:
 $$p_k=k\sin\left(\frac{\pi}{k}\right)\quad\quad\quad P_k=k\tan\left(\frac{\pi}{k}\right)$$
How can I show that $$P_{2k}=\frac{2p_kP_k}{p_k+P_k}\quad\quad\quad p_{2k}=\sqrt{p_kP_{2k}}$$
I started off by doing this: $$\frac{2p_kP_k}{p_k+P_k}=\frac{2\left[k\sin\left(\frac{\pi}{k}\right)\right]\left[k\tan\left(\frac{\pi}{k}\right)\right]}{\left[k\sin\left(\frac{\pi}{k}\right)\right]+\left[k\tan\left(\frac{\pi}{k}\right)\right]}$$
but this is way to complicated and there must be a shorter approach.


text:
Q: Is it possible to keep a column in excel 2016 in sync between sheets? I am trying to split the columns on my server list over multiple sheets within same file. Is it possible to have a master server list on sheet1 and on sheet2 the same master list can appear? to add to that, if i add a server to the list on Sheet1 i want it to show up on sheet2.
I have only basic Excel skills so would need some references to information so i can read up on what suggestions is being presented :)

A: You can use Indirect() to make sure the formula doesn't change.
Say your master list will be in column A of Sheet1.
On Sheet2, put this in A1 and drag down however far you need:
=INDIRECT("Sheet1!A"&row()).
Then if you move anything, add rows, etc in Sheet1, it won't make the Sheet2 formulas adjust relatively:

You may want to do
=IF(INDIRECT("Sheet1!A"&row())<>"",INDIRECT("Sheet1!A"&row()),"")

to hide any 0 that appear.


text:
Q: Proving the concurrence of the three lines formed by connecting midpoints of opposite sides of a hexagon Let's consider a convex hexagon where we know the midpoints of each side.
I'm currently trying to show that if we connect the midpoints of the opposite sides into lines that the three lines will all intersect at one common point. Now because this was in the area unit of my work, I figured that it would have to relate to area in some way or another. And so far, I've been able to find that if you take any one of those three lines that connect the midpoints on the opposite sides of a hexagon, it will divide the hexagon into two pentagons, and these pentagons have an equal area to each other. But I'm not sure how to relate this information back to the problem. If anyone can help out, that would be create.

A: Honestly, this takes almost no effort to find a counterexample.

And if even this figure is not sufficient proof, we can choose an explicit set of vertices; e.g.,
$$A = (12,0) \\ B = (10, 10) \\ C = (-11, 3) \\ D = (-12, 0) \\ E = (-11, -3) \\ F = (10, -10).$$  Then compute the midpoints, and then show that the lines joining the opposite midpoints do not share a common intersection.

A: Here's a counterexample:

The red dots are the vertices, and the blue lines connect the midpoints of the sides.


text:
Q: Trying to create a collapsable gallery nav I'm trying to create a gallery nav, e.g. something like this but I can't figure how to keep the nav items inlined-blocked and including multiple "content" elements per nav item. Here is what I have thus far:
http://jsfiddle.net/dmabuada/sv638nLv/

Digital

digital digital digital

Logos

logos logos logos

Print

print print print

More

more more more

Thanks!

A: I would highly recommend using Isotope. It's tried and true and should cover most of your implementation needs.


text:
Q: JFrame force EXIT_ON_CLOSE no matter what the program do i have a jframe with frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE).
On this JFrame i'm continuously doing calculations by importing API Data etc with the mothod getBestFlipProfit() (it's  at the bottom).
The result is displayed on the Frame every 3 or 4 minutes ( importing take long time ).
My problem is that i can't close the frame when the program is in getBestFlipProfit()
JFrame method who call the getBestFlipProfit() :
private void containtRefresher(){
    int delay = 100; // in milliseconds
    ActionListener taskPerformer = evt -> {
        Executor.getBestFlipProfit();
        String res = "";
        for (String key: Executor.best_flips.keySet()) {
            res += DataManager.get_item_name(key) + " profit = " +
            Executor.best_flips.get(key).get("profit") + "
";
        }
        bestflips.setText(res + "");
    };
    new Timer(delay, taskPerformer).start();
}

getBestFlipProfit() method :
You can see Thread.sleep(70); in the try i think the problem come from this but i'm not 100% sure, but i can't remove it because then i will have an error while importing API data 429 Too Many Requests ( = doing requests too fast)
Just saying: there is certainly a way to optimize the code but that is not the purpose of the post
public static void getBestFlipProfit(){
    List<String> item_list = new ArrayList<>(DataManager.items_names.keySet());
    DecimalFormat doubleformat = new DecimalFormat("#.##");
    doubleformat.setRoundingMode(RoundingMode.UP);
    String t; double buy_price; double sell_price; int buy_amount; int sell_amount;
    for( String item_id : item_list) {
        try {
            Thread.sleep(70);
            t = JsonReader.readJsonFromUrl("https://api.hypixel.net/skyblock/
                bazaar/product?key="+ api_key +"&productId="
                + item_id ).toString();
            if(t == null) continue;
            JsonElement root = new JsonParser().parse(t);
            buy_amount = root.getAsJsonObject().get("product_info")
                .getAsJsonObject().get("quick_status")
                .getAsJsonObject().get("buyVolume").getAsInt();
            sell_amount = root.getAsJsonObject().get("product_info")
                .getAsJsonObject().get("quick_status")
                .getAsJsonObject().get("sellVolume").getAsInt();
            if( buy_amount < minimum_amount || sell_amount < minimum_amount ) continue;
            buy_price = root.getAsJsonObject().get("product_info").getAsJsonObject()
                .get("buy_summary").getAsJsonArray().get(0).getAsJsonObject()
                .get("pricePerUnit").getAsJsonPrimitive().getAsDouble();
            sell_price = root.getAsJsonObject().get("product_info").getAsJsonObject()
                .get("sell_summary").getAsJsonArray().get(0).getAsJsonObject()
                .get("pricePerUnit").getAsJsonPrimitive().getAsDouble();
        } catch (Exception e) { continue; }
        double profit = new BigDecimal(sell_price - buy_price)
            .setScale(2, RoundingMode.HALF_UP).doubleValue();
        if( !best_flips.containsKey(item_id) ) {
            LinkedHashMap<String, Double> item_info = new LinkedHashMap<>();
            item_info.put("profit", profit);
            item_info.put("amount", (double) buy_amount);
            best_flips.put(item_id, item_info);
        } else {
            best_flips.get(item_id).replace("profit", profit);
            best_flips.get(item_id).replace("amount", (double)buy_amount);
        }
    }
    LinkedHashMap<String, LinkedHashMap<String, Double>> map = best_flips.entrySet()
        .stream().sorted(Comparator.comparing(e->e.getValue().get("profit")))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
        (a,b)->b, LinkedHashMap::new));
    LinkedHashMap<String, LinkedHashMap<String, Double>> res = new LinkedHashMap<>();
    List<String> listKeys = new ArrayList<>(map.keySet());
    ListIterator<String> iterator = listKeys.listIterator( listKeys.size() );
    int i = 5;
    while(iterator.hasPrevious() && i>=0 ){
        res.put( listKeys.get(iterator.previousIndex()), map.get( iterator.previous()));
        i--;
    }
    best_flips = res;
}

A: You can use a scheduled executor service.
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();

private void containtRefresher(){
    int delay = 100; // in milliseconds
    Runnable taskPerformer = () -> {
        Executor.getBestFlipProfit();
        String res = "";
        for (String key: Executor.best_flips.keySet()) {
            res += DataManager.get_item_name(key) + " profit = " +
            Executor.best_flips.get(key).get("profit") + "
";
        }
        String html = res + "";
        EventQueue.invokeLater( ()-> bestflips.setText(html) );
    };
    ses.scheduleAtFixedRate(taskPerformer, delay, delay, TimeUnit.MILLISECONDS);
}

That should be similar to what you've done, but it won't block the EDT. When you close your JFrame, the application should exit terminating the ExecutorService while at it.

A: I fixed it, i just had to change the getBestFlipProfit method like this :
private void containtRefresher(){
    while(true) {
        Executor.getBestFlipProfit();
        String res = "";
        for (String key: Executor.best_flips.keySet()) {
            res += DataManager.get_item_name(key) + " profit = " + Executor.best_flips.get(key).get("profit") + ", amount = " + Executor.best_flips.get(key).get("amount") + "
";
        }
        bestflips.setText(res + "");
        this.panel.revalidate();
    }
}


text:
Q: Laravel inner join column not found I try to:

*

*select categories

*from those categories search in products subspecifications

*return those subspecifications to select in other input

Logic

*

*Product has category_id column

*product subspecifications will save in 3rd table named
product_subspecification where in there product_id and
subspecification_id are stored

Code
public function create()
{
    //get all categories, so i can select
    $categories = Category::all();

    // find category id of chosen ones
    $categories2 = Category::all();
    foreach($categories2 as $cats){
        $catid = $cats->id;
    }

    //get subspecifications in selected categories
    $subspecifications = DB::table('product_subspecification')
        ->join('products','products.category_id', '=', $catid)
        ->join('subspecifications', 'subspecifications.id', '=', 'product_subspecification.subspecification_id')
        ->get();

    $statuses = Status::all();
    return view('admin.landings.create', compact('categories', 'subspecifications', 'statuses'));
}

Issue
it suppose to work like image below:

I get:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '3' in 'on
  clause' (SQL: select * from product_subspecification inner join
  products on products.category_id = 3 inner join
  subspecifications on subspecifications.id =
  product_subspecification.subspecification_id)

Any idea?
UPDATE
I've made something like:
public function create()
    {
        $categories = Category::all();
        $categories2 = Category::all();
        foreach($categories2 as $cats){
            $catid = $cats->id;
        }
        $subspecifications = DB::table('products')
                    ->where('category_id', $catid)
                    ->join('product_subspecification', 'product_subspecification.product_id', '=', 'products.id')
                    ->join('subspecifications', 'subspecifications.id', '=', 'product_subspecification.subspecification_id')
                    ->groupBy('subspecifications.id')
                    ->get();
        $statuses = Status::all();
        return view('admin.landings.create', compact('categories', 'subspecifications', 'statuses'));
    }

it appears to be working however there is 2 issues:

*

*my data are repeating, for eaxmple if i used core i3 in 2
categories when i select both caregories it shows core i3 2 times

*I need to remove subspecifications if i removed their category from input 1.


text:
Q: I can't use my static JS files in ExpressJS I'm new to NodeJS. I'm calling my static javascript file from within my ejs file. It is not outputting anything onto the console.
My .ejs file:
<head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
    <script type="text/javascript" src="/javascripts/calc.js"></script>

  </head>
  <body>...</body>

My static js (calc.js) file:
console.log("WHY IS THIS NOT WORKING?!");//this is it I have NO MORE CODE HERE

I have added app.use(express.static(path.join(__dirname, 'public'))); in my app.js.
My static JS file is in public --> javascripts --> calc.js
thanks.

A: In app.use() you are joining __dirname and the folder "public", yet in your ejs file the src to your script is at the root, not under "public." This might be the issue.

A: app.use('/public',express.static(path.join(__dirname,'public')));

A: Add this line in your app.js.
app.use(express.static(__dirname + '/public'))
It's working for me.


text:
Q: Select anchors without href I'd like to change the css style of all the anchors without href attribute.
I can use selector to select anchors that start with something using $('a[href^="some_link"]') . But I want it to be vice versa. How can I select anchors without href using jquery?
Also, can I achieve this using a css selector?
Thank you.

A: You'll want this selector (jQuery/CSS compatible):
a:not([href])

If you need IE support (because of that :not()), use it as a jQuery selector. Otherwise, you can use it for a CSS rule.

A: Use $("a").filter(function() { return !this.attributes['href']; }).
It's a little longer, but browsers can optimise the selection of the anchors, and do the filtering faster than Sizzle (or querySelectorAll) can run.
http://jsfiddle.net/9PWQB/


text:
Q: Why does ^D (to exit a user) make Bash think I'm breaking out of a loop? I log into an Ubuntu server as one user, and then su to an app-specific user to manage a Rails app.  When I'm done and want to log out, it is normally convenient to enter controlD, but on this particular machine, I get a very odd error message:
bash: break: only meaningful in a `for', `while', or `until' loop

What would cause Bash to think I'm inside a loop trying to break out?
This only happens with the "inner" (app-specific) user, not the "outer" user.
bind -X does not show any custom key bindings for the app-specific user.
I didn't notice this before, but exit has the same problem.
The app-specific user has a ~/.bash_logout file with
if [ "$SHLVL" = 1 ]; then
    [ -x /usr/bin/clear_console ] && /usr/bin/clear_console -q
fi


text:
Q: Sequelize findOne latest entry I need to find the latest entry in a table. What is the best way to do this? The table has Sequelize's default createdAt field.

A: model.findOne({
    where: { key },
    order: [ [ 'createdAt', 'DESC' ]],
});

A: Method findOne is wrapper for findAll method. Therefore you can simply use findAll with limit 1 and order by id descending.
Example:
YourModel.findAll({
  limit: 1,
  where: {
    //your where conditions, or without them if you need ANY entry
  },
  order: [ [ 'createdAt', 'DESC' ]]
}).then(function(entries){
  //only difference is that you get users list limited to 1
  //entries[0]
});

A: If someone has turned timestamps false, you can do it with id too. This one worked for me.
model.findOne({
order: [ [ 'id', 'DESC' ]],
});


text:
Q: Why, intuitively, does the solution to a general linear recurrence relation make sense? I reasoned through the solution to a differential equation, and $e^{\alpha x}$, for better or worse, seems to make sense. Each derivative sending the function to itself seems to suggest $e^{\alpha x}$. Why does the solution to recurrence relations, $ar_1^n$ make sense?
Edit: To try to fix the misguided question, regardless of the poor analogy I gave to differential equations, my question is Why do we guess the solution that we do for recurrence relations. I know it can be shown to work, but what is the intuition?

A: If $f(z)=\sum_{n=0}^\infty \frac{a_n}{n!}z^n$ is a solution to the differential equation, then $a_i$ is a solution to the related recurrence relation, and visa versa. You can just do the arithmetic.
So if $b_n=a_1r_1^n+a_2r_2^n$ then $$f(z)=\sum_{n=0}^\infty \frac{b_n}{n!}z^n = a_1e^{r_1z} + a_2e^{r_2z}$$

A: The solution $y = ar^n$ is the solution to $y_{n + 1} = r y_n$, and not $\Delta y_n = r y_n$. In discrete calculus, $\Delta$ is the  analogue (or at least one analogue) of $\text D \equiv \dfrac{d}{dx}$. But $y_{n + 1} = \text{E}\,y_n$, where $\text{E}$ is the shift operator, and that is not analogous to $\text D$.
You are asking why we guess this solution. Why do we guess $y = e^{ax}$ for $\text D\, y = ay$? Because we have observed that $\text D\, e^{ax} = ae^{ax}$. Similarly, when playing around with discrete differences, we observe that for $y_n = r^n$, $y_{n + 1} = r^{n + 1} = r \times r^n = ry_n$. So obviously, this is a solution to the difference equation $y_{n + 1} = ry_n$.
But the solutions are not all that different, after all, because $r^n$ is an exponential function too. You may even write it as $e^{n\log r}$, if you wish.

A: An alternative of trying to 'guess' a solution is to derive it using the "generating function" approach. (To continue the ODE comparison, it's the equivalent of solving via Laplace transforms.)
Suppose we start with the simple recurrence relation $a_{n}=ra_{n-1}$. Consider the formal power series in $x$ defined by $A(x)=\sum_{n=0} a_n x^n$. (By formal, I mean that I won't worry about issues of convergence and the like.) Then
$$A(x) = \sum_{n=0}^\infty a_n x^n = a_0+\sum_{n=1}^\infty a_{n}x^n =a_0+\sum_{n=1}^\infty r a_{n-1}x^n = a_0+rx A(x)\\ \implies A(x)=\frac{a_0}{1-r x}=\sum_{n=0}^\infty a_0 r^n x^n\implies a_n = a_0 r^n$$
So the solution need not be found by 'guess and check' but can instead be algebraically derived.


text:
Q: Makefile: explicit entry works, wildcard % not working I have this rule in my makefile, but make didn't find it:
$(BUILDDIR)%.o : $(BUILDDIR)%.bin
    @echo
    $(OBJCOPY) -I binary -O elf32-avr --redefine-sym _binary_$*_bin_start=$* --redefine-sym _binary_$*_bin_end=$*_end $< $@

If I make it explicit, make will use them (called for build/rom1.o and build/rom2.o; BUILDDIR=build/)
$(BUILDDIR)rom1.o : $(BUILDDIR)rom1.bin
   @echo
   $(OBJCOPY) -I binary -O elf32-avr --redefine-sym _binary_rom1_bin_start=rom1 --redefine-sym _binary_rom1_bin_end=rom1_end $< $@

$(BUILDDIR)rom2.o : $(BUILDDIR)rom2.bin
   @echo
   $(OBJCOPY) -I binary -O elf32-avr --redefine-sym _binary_rom2_bin_start=rom2 --redefine-sym _binary_rom2_bin_end=rom2_end $< $@

Does anyone has a hint whats wrong with the wildcard in my first try?
Edit:
The version of make is 4.1 running on Ubuntu 16.04.
This is the error message from make when trying to run with the wildcard:
make: *** No rule to make target 'build/rom1.o', needed by 'build/rom1.elf'.  Stop.

A: Let's simplify the problem…
If this is your file structure…
.
├── Makefile
└── build
    ├── rom1.bin
    └── rom2.bin

and this is your Makefile…
BUILDDIR := build/

$(BUILDDIR)%.o: $(BUILDDIR)%.bin
    touch $@

and you run $ make build/rom{1,2}.o, your resulting file structure will be…
.
├── Makefile
└── build
    ├── rom1.bin
    ├── rom1.o
    ├── rom2.bin
    └── rom2.o


text:
Q: Bean creation error on @Repository interface import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface FormRepository extends MongoRepository<Form, Integer> {

    Optional<Form> findById(Integer formId);
}

This is a mongo repository I have created. I am accessing it as follows :
@Service
public class FormServiceImpl implements FormService {

        @Autowired
        FormRepository formRepository;
    @Override
    public List<Question> getQuestions(Integer formId, ){
            List<Question> questionList = new ArrayList<>();
            ..........
            ......................
            ........ initialise questionlist .............
            ......................

            formRepository.save(new Form(questionList, "firstForm"));
            return questionList;
        }
    }

Error I'm getting ->
***************************
APPLICATION FAILED TO START
***************************

Description:

Field formRepository in *.service.impl.FormServiceImpl required a bean of type '*.service.FormRepository' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type '*.service.FormRepository' in your configuration.

Process finished with exit code 1

My thoughts :
The @Repository should be enough to register the FormRepository as a bean. However, that is not the case. I'm not able to register the FormRepository interface as a bean. The two files above lie in the same package.
I have replaced the prefix path with * - but rest assured * has the same meaning everywhere.
Please let me know if any additional logs.
Edit :
I added @EnableMongoRepositories on my main application class. That leads to this error ->
2022-04-24 19:20:29.085 ERROR 2941 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Field formRepository in *.service.impl.FormServiceImpl required a bean named 'mongoTemplate' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean named 'mongoTemplate' in your configuration.

Process finished with exit code 1

I think MongoTemplate and MongoRepository are two very different things. Why does my mongo repo need a dependency to MongoTemplate?

A: since you are using mongo you need to add an additional annotation.
@SpringBootApplication
@EnableMongoRepositories(basePackageClasses = FormRepository .class)
public class MainClass {}

also make sure your folders are structured correctly.
for the other Issue you should add a dependency in your 'POM'
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

It is all about mongo configuration.
Hope this helps.


text:
Q: DNS Round-robin failover and load balancing Having read all of the questions and answers (1 2 3 and so on) on here relating to DNS load balancing, and Round-robin DNS, there's still a number of unanswered questions..
Large companies, and I'm looking at Google, Facebook and Twitter here, do present multiple A records.
1) If DNS loadbalancing/failover is so dodgy, why do large organisations do it?
There seems to be very little mention of "DNS Pinning", despite this (PDF) paper about it.
2) Why is DNS Pinning so seldom mentioned?
3) Are there any concrete examples of which ISPs and so on actually do rewrite DNS TTLs?
That said, I'm not entirely backing the side for using DNS for failover or any form of load balancing.  For most networks, BGP diverse routing still seems to be a better fit.
DNS rears it's ugly head again. :(

A: *

*because it's cheaper and easier than
anycasting (BGP) and because it can be implemented entirely on your own hardware

*from a load-balancing standpoint,
there's very little you can do about
the browser caching DNS results in
contradiction to your TTL settings.

*I'm not sure why ISPs would rewrite
TTLs, Most requests will be from
browsers, so I'm not sure it would
be cost effective for them to invest
in the infrastructure to do so.

I use DNS (GSLB actually) over anycasting for a couple of reasons. We've discussed BGP several times over the years, and I choose DNS over BGP because it's easier to do and, in most cases, just as or more reliable. Multiple facilities, clustered DNS servers, combined with proactively monitored GSLB and a TLD hosting service covers most potential faults.


text:
Q: How to create CAN frame using SocketCAN interface in C using values larger and smaller than 8 bit I need to write three different CAN messages to a CAN bus.
The first message consists of 8 values of 8 bits so no problem there but the second and third message are more irregular
In the third message I have three values all with a size of 16bits and the third message has some values which are smaller than 8 bits.
How can I properly create the data for the CAN frame using values larger or smaller than 8 bits.
This is my code
`
int main(int argc, char **argv)
{
    int s;
    struct sockaddr_can addr;
    struct ifreq ifr;
    struct can_frame frame;
    struct can_frame frame2;

    if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
        perror("Socket");
        return 1;
    }

    strcpy(ifr.ifr_name, "vcan0" );
    ioctl(s, SIOCGIFINDEX, &ifr);

    memset(&addr, 0, sizeof(addr));
    addr.can_family = AF_CAN;
    addr.can_ifindex = ifr.ifr_ifindex;

    if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
        perror("Bind");
        return 1;
    }

    frame.can_id = 0x500;
    frame.can_dlc = 8;
    frame.data[0] = 122;
    frame.data[1] = 150;
    frame.data[2] = -27;
    frame.data[3] = -22;
    frame.data[4] = 160;
    frame.data[5] = 160;
    frame.data[6] = -60;
    frame.data[7] = 90;

    frame2.can_id = 0x501;
    frame.can_dlc = 6;
    frame.data[0] = 32766;
    frame.data[2] = -32765;
    frame.data[4] = 20542;

    if (write(s, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {
        perror("Write");
        return 1;
    }

    if (close(s) < 0) {
        perror("Close");
        return 1;
    }

    return 0;
}

`
Index 0 obviously corresponds to the first 8 bits of the data frame but I don't really know any other way to do this because I have very little experience with C
I would like to be able to make these CAN frames properly with the data on two indexes but have no clue how to do this.
Aswell as a way to use single bits instead of 8 bits using the index of the frame.data object since I need to make a CAN message where multiple values exist in the single 8 bit data frame of the can message. If that makes sense

A: First of all, you cannot do this unless you know the network endianess of the specific CAN bus. Big endian is the most common, but some CAN application layers like CANopen use little endian for the payload.
Assuming network = big endian, assuming 32766, -32765 and 20542 are your 16 bit numbers, then:
const int16_t data16[3] = { 32766, -32765, 20542 };
...
frame.data[0] = ((uint16_t)data16[0] >> 8) & 0xFFu;
frame.data[1] = ((uint16_t)data16[0] >> 0) & 0xFFu;
frame.data[2] = ((uint16_t)data16[1] >> 8) & 0xFFu;
frame.data[3] = ((uint16_t)data16[1] >> 0) & 0xFFu;
frame.data[4] = ((uint16_t)data16[2] >> 8) & 0xFFu;
frame.data[5] = ((uint16_t)data16[2] >> 0) & 0xFFu;

Or if you will:
for(size_t i=0; i<3; i++)
{
  frame.data[i*2]   = ((uint16_t)data16[i] >> 8) & 0xFFu;
  frame.data[i*2+1] = ((uint16_t)data16[i] >> 0) & 0xFFu;
}

Here the bit shifts are the same no matter if CPU is big/little endian, but you have to swap MS and LS bytes in case the network uses little endian.


text:
Q: Self-Study Plan for Becoming Statistical Analyst? Can any one please suggest me a self-study plan for becoming a Statistical Analyst? I need suggestion something similar to Self Study Plan for Quantitative Analyst

A: I am currently in the process of doing this (sort of), and think I have had moderate to great success. I have relied solely on primary literature and experience without any textbooks. Here is what I found most helpful:
1) Learn R. I don't see how anyone can get an intuitive understanding without running many, many simulations. Perhaps with a strong math background this is not as necessary.
2) Learn the history of statistics and the source of various controversies, for example bayesian vs frequentist (Neyman Pearson, Error Statistics) vs fisher (inductivist) vs likelihoodist vs the NHST (Null Hypothesis Significance Testing) hybrid. There may even be more! Especially learn about the history of the NHST hybrid controversy, I had no idea how bad it was and was taught that as "Statistics".
3) Get data of the type you think you will analyze (timeseries, comparing groups, etc) and analyze it in many different ways to learn the strength and weaknesses of different approaches.

A: I'll answer from the perspective of an economist who did lots of econometrics.
If you haven't done any R/Python/Matlab etc. and you want to be able to use statistical techniques, understand when to use which, how to apply them I'd suggest you start with Chris Brooks' Introductory Econometrics for Finance. The book uses EViews for all examples, and it's great for a beginner as it explains both the theory, gives an example, and then shows you how to do it step by step. I loved it!
If you want something more interactive, and with programming head over to coursera.org and check out their Stats 101. I think it uses R, and will have plenty of reference material.

A: I am a college dropout and have done this successfully. So follow the steps i enlist below :

*

*Learn R or Python.

*Try to understand what a probability distribution is.

*Learn about the Normal, the binomial and the uniform distribution. Consider only a single variable.

*Find out as many situation where the above three distributions have been applied and find out as many properties about these as you can.

*Try and visualize two variables, both normally distributed. in one case they are positively correlated and the other case they are negatively correlated.

*Try to plot different variables and try to find differences between them using just what you see in the plots.

*Once you have done this, take up any dataset(s) and start finding things about it using the distributions and the plotting.

*generalize your knowledge to other procedures like regression.

*generalize your knowledge to other distributions.

Some books to help you out :

*

*http://www.amazon.com/Statistics-An-Introduction-using-R/dp/0470022981

*http://www.amazon.com/Using-Introductory-Statistics-Chapman-Series/dp/1584884509/ref=pd_sim_b_5

*http://health.adelaide.edu.au/psychology/ccs/teaching/lsr/
Finally start analyzing something that you like using the techniques that you have learned. Now you are ready to go to the advanced level.

A: Learn R. Absolutely, definitely do so. R is open source and I think will soon become the de facto standard for the statistics & machine learning. You also need to learn a scripting language and I would strongly recommend Perl. It doesn't have the fanciness of other languages but it is super powerful and guaranteed to be a solid return on invested time, not to mention the vast swath of packages that are already created for you on CPAN. Finally, you also need to get your hands on some books to learn statistics. Some of the best books in statistics, can be found here. Linear algebra is also a good to know but not necessary. If interested here is a list of books for learning linear algebra. HTH


text:
Q: What's the difference between index.css and App.css? I usually define global styles in index.css. What is the best practice to define global style? When should I put it in index.css vs App.css when I work on React app?

A: For a React app, the best practice is to put every component in its own directory containing its corresponding JS and CSS files. The App component is the topmost component in a React app for wrapping all components. There aren't any predefined rules for using App.css or index.css for global CSS.
Check out this article for React styling best practices: https://medium.com/the-non-traditional-developer/styling-best-practices-using-react-c37b96b8be9c
Relevant question: index.css vs. App.css in default app created by "create-react-app" -- what's the difference?


text:
Q: Puzzling struggle in Signup to GCP - error [OR-CBAT-09] The very beginnings on GCP turn out as a real struggle. Just on the signup page (all access $300 free) receiving error message: "This payment method can't be used for recurring payments [OR-CBAT-09]" also the bank account shows "unverified".
What's been tried: signing in on Google pay - trying to enter the verification code: doesn't show any place to enter code from the wire transfer. Also contacting various Google supports by chat (hours :) ) Cloud Billing Support apparently is responsible yet available only to registered users - real dilemma.
Thank you very much for any tips here

A: Sign up on the Play store and create a merchant account. During the merchant account setup you can enter the test deposit amount which will verify your Bank account.
Sounce: Tried to create a GCP billing account with a German bank as payment method, got [OR-CBAT-09] for two weeks and was given the runabout with the cloud billing support including multiple second-level support escalations. And no, support never made any useful suggestion (we are registered & paying customer).


text:
Q: Intersection of a circle $x^2+(y-1)^2=1$ and a parabola $ax^2=y$, bounds for a I have a circle $x^2+(y-1)^2=1$ and a parabola $x^2=\frac{y}{a}$ and it is required to find the bounds for $a$ if they intersect at point other than origin.
So I proceeded as follow, substituted $x^2=y/a$ into $x^2+(y-1)^2=1$
which led me to get,
$$\implies y^2+y\bigg(\frac{1}{a}-2\bigg)= 0$$
So for more than one point of intersection, I would necessarily have $D>0$, $D$ being the discriminant of the quadratic in $y$
From there I got the bounds as $a \in \bigg(R-\{0, \frac{1}{2}\}\bigg)$
But if I substitute the value of $y$ other than $0$, ie, $y = 2-\frac{1}{a}$ into $x^2=\frac{y}{a}$, I get $x^2 = \frac{2a-1}{a^2}$, which is always greater than $0$, and as a result from here I get the bound that $a \in \bigg(\frac{1}{2}, \infty\bigg)$

A: We can compute very easily the intersections of the two conics, or:
$$\frac{y}{a}+(y-1)^2=1 \leftrightarrow ay^2+y(1-2a)=0 \leftrightarrow y(ay+1-2a)=0$$
Now, a solution is $y=0$ that holds for evry $a$. The other solution is $y=\frac{2a-1}{a}$ and so $x=\frac{1}{a}\sqrt{2a-1}$. Now, taking from here, it's very simple. In fact we want the square root to be defined, so:
$$2a-1>0 \leftrightarrow a>\frac{1}{2}$$
Note that your error has been committed when stating tehe range of $a$ without considering the fact that $x=\pm\sqrt{\frac{y}{a}}$. In fact, as you stated, if $a\in\left(R-\left\{0,\frac{1}{2}\right)\right)$, then for example $a=-1$ would be OK, but if we plug into the equation for $x$ we have a contraddiction. In fact:
$$y(-y+3)=0 \leftrightarrow y=0\vee y=3$$
But now:
$$x=\pm\sqrt{\frac{y}{a}}=\pm\sqrt{\frac{3}{-1}}=\text{IMPOSSIBLE}$$

A: What if $a=0$?
Any point on the circle is $\cos t,1+\sin t$
$$a(1-\sin^2t)=1+\sin t$$
$$\iff a\sin^2t+\sin t+1-a=0$$
$$\sin t=\dfrac{-1\pm\sqrt{1-4a(1-a)}}{2a}=\dfrac{-1\pm(2a-1)}{2a}=1-\dfrac1a, -1$$
So, for any finite value of $a, (0,0)$ is the first intersection
So for second intersection, $$-1\le1-\dfrac1a\le1\iff-2\le-\dfrac1a\le0$$
$$-\dfrac1a\le0\implies a>0$$
$$-2\le-\dfrac1a\iff2\ge\dfrac1a\implies a\ge\dfrac12\text{ as } a>0$$


text:
Q: To split for-cycle using TPL In order to parallelize and accelerate calculations I"ve splitted one long for-cycle by two short for-cycles using TPL, these parts are called PointGenerator and PointGenerator2 in my class bellow:
class CalcPiTPL
    {
        int n;
        int totalCounter;
        int counter1;
        int counter2;
        double aPi;
        public StringBuilder Msg; // diagonstic message
        Stopwatch stopWatch = new Stopwatch();

        public void Init(int aN)
        {
            stopWatch.Start();
            n = aN; // save total calculate-iterations amount
            aPi = -1; // flag, if no any calculate-iteration has been completed
            Msg = new StringBuilder("No any calculate-iteration has been completed");
        }
        public void Run()
        {
            if (n < 1)
            {
                Msg = new StringBuilder("Invalid N-value");
                return;
            }

            Task[] tasks = new Task[2];
            tasks[0] = Task.Factory.StartNew((obj) => { PointGenerator((int)obj); }, n);
            tasks[1] = Task.Factory.StartNew((obj) => { PointGenerator2((int)obj); }, n);

            Task.WaitAll(tasks[0], tasks[1]);
            totalCounter = counter1 + counter2;
            aPi = 4.0 * ((double)totalCounter / (double)n); // to calculate approximate Pi - value
            Console.WriteLine(aPi);
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
            Console.WriteLine("RunTime " + elapsedTime);
        }
        public double Done()
        {
            if (aPi > 0)
            {
                Msg = new StringBuilder("Calculates has been completed successful");
                return aPi; // return gotten value
            }
            else
            {
                return 0; // no result
            }
        }
        public void PointGenerator(int n)//FIRST PART OF ONE BIG FOR-CYCLE
        {
            double s = 0.125;
            double sP = s / (n / 2);
            double x = Math.Sqrt(sP);
            for (double cX = 0; cX <= 0.25; cX += x)
            {
                for (double cY = 0; cY <= 0.5; cY += x)
                {
                    if (((cX - 0.5) * (cX - 0.5) + (cY - 0.5) * (cY - 0.5)) < 0.25)
                    {
                        counter1++; // coordinate in a circle! mark it by incrementing N_0
                    }
                }
            }
        }

        public void PointGenerator2(int n)//SECOND PART OF ONE BIG FOR-CYCLE
        {
            double s = 0.125;
            double sP = s / (n / 2);
            double x = Math.Sqrt(sP);
            for (double cX = 0.25; cX <= 0.5; cX += x)
            {
                for (double cY = 0; cY <= 0.5; cY += x)
                {
                    if (((cX - 0.5) * (cX - 0.5) + (cY - 0.5) * (cY - 0.5)) < 0.25)
                    {
                        counter2++; // coordinate in a circle! mark it by incrementing N_0
                    }
                }
            }
        }
    }

And this is the same class without Tasks using(TPL), it has one long for-cycle:
class TCalcPi//unparallel calculating method
    {
        int N;
        int n_0;
        double aPi;
        public StringBuilder Msg; // diagnostic message

        Stopwatch stopWatch = new Stopwatch();

        public void Init(int aN)
        {
            stopWatch.Start();
            N = aN; // save total calculate-iterations amount
            aPi = -1; // flag, if no any calculate-iteration has been completed
            Msg = new StringBuilder("No any calculate-iteration has been completed");
        }

        public void Run()
        {
            if (N < 1)
            {
                Msg = new StringBuilder("Invalid N - value");
                return;
            }

            double s = 0.25;
            double sP = s / N;
            double x = Math.Sqrt(sP);
            for (double cX = 0; cX <= 0.5; cX += x)//ONE LONG FOR-CYCLE
            {
                for(double cY = 0; cY <= 0.5; cY += x)
                {
                    if (((cX - 0.5) * (cX - 0.5) + (cY - 0.5) * (cY - 0.5)) < 0.25)
                    {
                        n_0++; // coordinate in a circle! mark it by incrementing N_0
                    }
                }
            }
            aPi = 4.0 * ((double)n_0 / (double)N); // to calculate approximate Pi - value
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
            Console.WriteLine("RunTime " + elapsedTime);
        }
        public double Done()
        {
            if (aPi > 0)
            {
                Msg = new StringBuilder("Calculates has been completed successful");
                return aPi; // return gotten value
            }
            else
            {
                return 0; // no result
            }
        }
    }

But unparallelized-class works faster, than parallelized(using TPL)class. How to fix it?

A: counter1 and counter2 most likely sit on the same cache line because they are adjacent in memory. This causes False Sharing. Probably, you are incrementing those counters very often. This pings the cacheline between the L1's of two cores for every alternation in time between the counters.
Separate them. As a proof of concept, like this:
int counter1;
long padding0, p1, p2, p3, p4, p5, p6, p7; //64 bytes padding
int counter2;

Let's hope the JIT does not reorder the fields. Maybe you need to use StructLayout.
Alternatively, make the counters local variables. Stack variables only have false sharing by extreme coincidence.


text:
Q: Symfony 3 REST API POST validation What is the "best" way to handle entities validation in a Symfony3 REST application?
I know that I could use Form to do it and use its already existing validators (required, email type, repeat type, ...).
Might I also use the entity repository or another service to validate, serialize, unserialize my entities, thus having all the entity IN/OUT logic at the same place? But then how should I handle validation during both creation and update when data might not all be present?
Any thought?

A: *

*Process the request through a Controller

*Use a Form to process that request

*Build custom validators or leverage existing on the FormClass

*Using your controller (#1) handle PUT and POST and PATCH separately with unique actions.

*Serialize/deserialize your request/response in the controller OR using a handler that the controller (#1, #4) hands the request off to.

A: Thanks for your inputs. I'll use the Doctrine Assert validators to handle the validation and the Symfony\Component\Validator\Validation class.
Regarding the Symfony3 documentation I think this is probably the best option.
https://symfony.com/doc/current/validation.html

A: another way, in my project, i not apply form for entity, maybe you need this way

Helper:
  Base function :
Create action in controller

Update Action in controller


text: Q: jQuery Mobile - loading indicator over specified listview I have a little problem with jQuery mobile. On my mobile page I have 3 areas which are loaded asynchronously and I want to show loading indicator over every of those areas. Of course I can keep global loading indicator until every area is loaded but it's not the point. I want to use jQM built in functionality if possible, if not - it's not a problem to create new one. Is there only global-page loading indicator in jQuery?


text:
Q: Automapper - Map one object to another usingdiffrent properties could you help me. I have one object
class Source{
 public string A {get;set;}
 public string B {get;set;}
 public string C {get;set;}
 public string D {get;set;}
}

And destination object
  class Dest{
     public string A1 {get;set;}
     public string B1 {get;set;}

    }

Is it possible using Automapper to Create Dest object from source object but first instance of Dest with mapping A to A1 and B to B1, in the second instance of Dest mapping C to A1 and D to B1?
In dreaming solution to get Collection?
Something like:
 Mapper.Initialize(cfg =>{
      cfg.CreateMap<Source, Dest>()
        .ForMember(dest => dest.A1, opt => opt.MapFrom(src => src.A))
        .ForMember(dest => dest.B1, opt => opt.MapFrom(src => src.B;))
      cfg.CreateMap<Source, Dest>()
        .ForMember(dest => dest.A1, opt => opt.MapFrom(src => src.C))
        .ForMember(dest => dest.B1, opt => opt.MapFrom(src => src.D))});

Or:
 Mapper.Initialize(cfg =>{
          cfg.CreateMap<Source, ICollection<Dest>>()})

[UPDATE]
Maybe better solution will be to use reflection and write custom mapper, with attribute [Attribute(MapType, Order, propertyName)]. E.g
class Source{
     [Dest(Dest,1,"A1")]
     public string A {get;set;}
     [Dest(Dest,1,"B1")]
     public string B {get;set;}
     [Dest(Dest,2,"A1")]
     public string C {get;set;}
     [Dest(Dest,2,"B1")]
     public string D {get;set;}
    }

New go through properties and create object using type from attributes.

A: You can create two mappers:
var m1 = new MapperConfiguration(
    cfg =>
    {
        cfg.CreateMap<Source, Dest>()
            .ForMember(dest => dest.A1, opt => opt.MapFrom(src => src.A))
            .ForMember(dest => dest.B1, opt => opt.MapFrom(src => src.B));
    })
    .CreateMapper();

var m2 = new MapperConfiguration(
    cfg =>
    {
        cfg.CreateMap<Source, Dest>()
            .ForMember(dest => dest.A1, opt => opt.MapFrom(src => src.C))
            .ForMember(dest => dest.B1, opt => opt.MapFrom(src => src.D));
    })
    .CreateMapper();

And then use them behind another interface (that you define) (e.g. ISourceMapper) which would alternate between the two mappers based on the number of the instance (i.e. instance 1 -> mapper 1, instance 2 -> mapper 2, instance 3 -> mapper 1 ...etc.)
For the collection part, you can then easily call IEnumerable.Select passing ISourceMapper.Map method to the projection Func<,>.


text:
Q: Can't get emulator to work in Android Studio I installed the tools I needed in the SDK manager but when I create a new AVD I can't get it to run.
I'm very new to android. Any ideas on what I need to do to get the emulator to run on my computer?


text: Q: Нахождение зависимости между двумя наборами данных Имеется два набора данных, конкретно векторы a1(x11,y11)...an(x1n,y1n) и зависимые векторы b1(x21,y21)...bn(x2n,y2n). Имеется возможность экспериментально измерить векторы b для какого либо количества a, затем необходимо вывести какую то зависимость b от a. Подскажите, пожалуйста, в какую сторону копать.


text:
Q: Regression Problem: How to solve the problem of highly decimal input features I have the following input data structure:
   X1     |    X2     |    X3     | ... | Output (Label)
118.12341 | 118.12300 | 118.12001 | ... | [a value between 0 & 1] e.g. 0.423645

Where I'm using tensorflow in order to solve the regression problem here of predicting the future value of the Output variable. For that i built a feed forward neural network with three hidden layers having relu activation functions and a final output layer with one node of linear activation. This network is trained with back-propagation using adam optimizer.
My problem is that after training the network for some thousands of epochs, I realized that this highly decimal values in both input features and the output, resulted in predictions near to the second decimal place only, for example:
Real value = 0.456751 | Predicted value = 0.452364

However this is not accepted, where i need a precision to the forth decimal place (at least) to accept the value.
Q: Is there any trustworthy technique to solve this problem properly for getting better results (maybe a transformation algorithm)?
Thanks in advance.

A: Assuming you are using a regular MSE loss, this will probably not suit your purpose of relatively low-tolerance in the error per instance. To elaborate, the MSE is defined as follow the average of the the square of the differences between the predicted and true outputs.
Assuming you have 4 instances, and two trained functions that generates the following error per instance:
F1 error rates : (4,.0004, .0002, .0002)
F2 error rates : (.9, .9, .9, .9)
It's obvious that MSE would go for F2, since the average MSE is .81, while the average MSE for F1 is approx 16.
So to conclude, MSE gives too little weight to small differences in value < 1, while it exaggerates the weight for bigger differences in value > 1 because of the square function applied.
You could try MAE, which stands for MEAN ABSOLUTE ERROR, it's only difference is that it doesn't perform a square function on the individual errors, rather it calculates the absolute. There are many other regression losses that could give significant weight to smaller errors like the HUBER loss with a small delta (< 0), you can read more about those losses here.
Another possible solution would be to transform this into a classification problem, where the prediction is true if it's exactly identical to the outputs to the 4th decimal point for example and else it's false.


text:
Q: JavaFX WebView won't show I am having trouble with JavaFX, I only get an empty window when I try to load a web view. Any ideas?
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

/**
 * Created by poa on 15.04.2014.
 */
public class GUI extends Application{

    private Scene scene;
    @Override public void start(Stage stage) {

        stage.setTitle("Hello World!");
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });
        final WebView browser = new WebView();
        final WebEngine webEngine = browser.getEngine();

        StackPane root = new StackPane();
        root.getChildren().addAll(btn, browser);
        stage.setScene(new Scene(root, 300, 250));
        stage.show();
        stage.setTitle("Web View");
    }

    public static void main(String[] args){
        launch(args);
    }
}

A: You didn't load anything into the WebView, so there is nothing to see in it.
Because you put the web view and the button in a stack pane, which stacks nodes one on top of the other, the empty web view is on top of the button, so you can't see the button.


text:
Q: How to remove extra space under paragraph in HTML/CSS With HTML and CSS I have this vertical space between a p tag and an image. It looks like this:

See that extra vertical space between the hello and the image? How do i remove that? I know I can absolutely position the image closer up to the hello but I would like to know what's causing the space.
My code:
HTML:

 hello

CSS:
.Box                           //this is the parent div
{
    background-color:red;
    width:60px;
    margin:0px;
    margin-bottom: 0px;
    padding:0px;

}
.contextimg                            //this is for the image
{
    position:relative;
    margin:0px;
    padding:0px;
    line-height:0px;

}

Note: I've also tried to set the body's margin and padding to 0 but it didn't work.

A: It's common for browsers to give paragraphs a default margin. So just take it away.
Give the
 a margin of 0:
.Box p{
    margin: 0;
}

Check it here: http://jsfiddle.net/aG27X/

A: That's the default padding/margin of p element, try using
.Box p {
   margin: 0;
   padding: 0;
}

You should reset browser defaults before designing any webpage, if you want a quick solution than using
* {
   margin: 0;
   padding: 0;
}

Will suffice your needs, you can also google out for CSS reset stylsheets, these stylesheets will reset each elements precisely

A: Set the padding and margin top/bottom of the
 tag to 0.
 tags automatically have a default padding/margin set, in case you dont overwrite it by something else.
p {
   margin: 0;
   padding: 0;
}

A: p stands for paragraph. the paragraph automaticly adds space like this: Fiddle
and you can remove it like this: fiddle

A: I can't tell you what your problem is, but from this fiddle: http://jsfiddle.net/u6C9E/
p { margin: 0; padding: 0; }

works.

A: If you have any image above and/or bottom of the paragraphs, make the paragraphs in two class.
HTML:

 class="first">Your 1st Paragraph

 class="second">Your 2nd Paragraph

The CSS :
    p.first {
        text-indent: 2em;
        margin-bottom: -5%;
    }
    p.second {
        margin-top: -5%;
        text-indent: 2em;
    }

Use "%" to let it still looking good in responsive web...


text:
Q: Can't bind a click event on a button with jquery I'm a js newbie.
I have a structure like this:

Test

Test

I add en event
$selectableList = $('.selectable-list a');
$selectableList.click(function(){
  console.log(this)
  script.addItem(this);
});

The result is that this is a text so I can't get data attributes... why?
Edit:
        bindEvents : function bindEvents() {
            $selectableList.click(function(){
                console.log(this.attr("data-type"))
                script.addItem(this);
            });
        }

Uncaught TypeError: this.attr is not a function

A: .attr is a function provided by jQuery which mean you can only apply it to jQuery objects.
Here in the code snippet you are trying to use it on this which belongs to  native javascript and it does not have .attr method associated with it. This this object will be the DOM node object that you clicked on.
What you need to do it to wrap your this around $ or jQuery namespace something like
$(this).attr("data-type")

and you should be good to go
Hope this be of some help.
Happy Learning :)

A: I am not sure where the text you are talking about is coming from. The this will be the DOM node that you clicked on. If you wrap it in $() you should be able to read the data attribute.

$selectableList = $('.selectable-list a');
$selectableList.click(function(){

  var anchor = $(this);
  console.log(anchor.data("id"), anchor.data("type"));

});

Test

Test


text:
Q: Existence of certain endomorphism of supersingular elliptic curve Let $E$ be a supersingular elliptic curve over an algebraically closed field $K$ of characteristic $p$. Let $R = \operatorname{End}(E)$ be its ring of endomorphisms. Then, it is known $R \otimes_{\mathbb Z} \mathbb Q$ is an order in a quaternion algebra $D$. In particular, $D$ has a multiplicative norm function $N\colon D^* \rightarrow \mathbb Q$, which can be defined as $N(\phi) = \phi \hat \phi$, where $\hat\phi$ denotes the dual of the endomorphism $\phi$, or equivalently, by saying that $N(\phi)$ is the degree of an endomorphism $\phi \in R$.
My question is: Does there exist an element $\phi \in R$ such that $N(\phi)$ is singly divisible by $p$, i.e. such that the $p$-adic valuation of $N(\phi)$ is 1?
If $E$ is defined over $\mathbb F_p$, then Frobenius is an endomorphism, and has degree $p$, so that gives an affirmative answer, but some supersingular elliptic curves are only defined over $\mathbb F_{p^2}$. In that case, Frobenius is not an endomorphism of $E$, but an isogeny $E \rightarrow E^{(p)}$ where $E^{(p)}$ is the Frobenius twist of $E$. The question is equivalent to: Does there exists a separable isogeny $E^{(p)} \rightarrow E$?
Also, I don't know much about quaternion algebras over $\mathbb Q$, but I have read that $D$ is ramified at $p$, and if I understand the consequences of that correctly, that implies that there exists an element $\phi$ of $D$ such that $N(\phi)$ has $p$-adic valuation equal to 1. If that's true, then, the question is whether such an element can be chosen to be in $R$, and not just in $D$. I have also read that $R$ is a maximal order in $D$, which seems like it should help, but I'm not sure how to make use of that fact in a non-commutative setting.

A: $\newcommand{\Z}{\mathbb{Z}}$
First, if you want to learn about quaternion algebras, their orders and their relation to supersingular elliptic curves, I suggest John Voight's book.
The answer to your question is yes. To see this, you can use the fact that (because $R$ is maximal) $R/p^2R$ contains an element $\pi$ such that $\pi^2 = p$, and therefore satisfying $N(\pi)\equiv \pm p\bmod{p^2}$. Let $\phi\in R$ be such that $\phi\equiv \pi \bmod{p^2R}$, then the valuation at $p$ of $N(\phi)$ is $1$.


text:
Q: Calculate speed from network location Iam trying to calculate speed ( using distance/time).  I know there getSpeed method on Location, but I tried it while driving and GPS on and it was not accurate at all My calculations were closer to reality.
Anyways, my question is , is there any way I can get speed using network location within a certain error range? Right now , it is throwing values like 100 km/hr and 5 km/hr for every location  I get in the network and I am not if there is reliable way. I currently just make sure that whatever location I get from network is newer than the previous network location
Thank you

A: Since you already have a list of locations, my suggestion is that, filter your location data received from network.

*

*Speed is one of the factor you can use to filter.

*You may try other ways to filter, like points in the wrong direction or far away from your path.

*Increase the frequency of your location collection.

*"accuracy" value from the network location data. But be careful with this. Big value doesn't always mean bad location, and small value doesn't always mean good location.  After filtered, you may calculate your speed again.


text:
Q: Multiple features developed in parallel and git merging at once Having such a situation in git graph:
dev *
     \_ featureA
      \_ featureB

and I requested merges for each of the features to the dev branch.
Both features are developed in parallel and are going to be merged in the same time.
The merge request of the branch featureA has been accepted and now when my colleague wants to merge featureB he sees merge conflict because in CMakeLists.txt in the root directory both of the features add a line in the file at the same place; in featureA:
CMakelists.txt:10:
    add_subdirectory(featureA)

in featureB:
CMakelists.txt:10:
    add_subdirectory(featureB)

The question is should he resolve this merge conflicts by hand or should I rebase the branch featureB locally and then repush the branch or maybe there is something wrong in the workflow and other approach should be taken when having such a situation?

A: Let me preface by saying that there is no right or wrong solution here — the way you handle a merge conflict like this depends on what kind of branch featureB is.
Option 1: rebase if featureB is a private branch
If featureB is a private branch – meaning you're the only one committing to it – then I'd suggest you rebase it on top of dev after featureA has been merged.
That means going from this:
A--B---M dev
 \    /
  C--D featureA
   \
    E--F featureB

To this:
A--B---M dev
 \    / \
  C--D   E--F featureB

Keep in mind that rebasing is still a kind of merge, the difference being that git-rebase applies one commit at a time on top of the previous one, while git-merge merges two commits with their entire set of changes in a single operation.
Doing a rebase forces you to solve the conflict at the commit that introduced the conflicting change. This has a couple of advantages:

*

*It gives you more context around the change, thus making it easier to find a resolution.

*The resolution will become part of the commit itself – where it belongs – instead of ending up in a merge commit, potentially mixed up with other unrelated conflict resolutions.

Option 2: merge if featureB is a public branch
If, however, featureB is a public branch – that is, multiple people commit to it, then you can't rebase it because that would be rewriting history. In that case, you're better off handling the merge conflict in a regular merge on the dev branch.
The resulting history will then look something like this:
A--B---M------N dev
 \    / \    /
  C--D   E--F featureB

where N is where you resolve the conflict.


text:
Q: Abbreviations for variants of mLL? 1. Context
There are various variants of multiplicative linear logic (mLL). I am wondering how those various relatives of mLL are conventionally abbreviated.
2. Question
What are common abbreviations for the following relatives of mLL:

*

*mLL without units?

*mLL without units and without cut?

*mLL without negation and without exchange (but with units)?


text:
Q: Custom wrapper for containers implementing __iter__ and __getitem__ I'm trying to write a custom wrapper class for containers. To implement the iterator-prototocol I provide __iter__ and __next__ and to access individual items I provide __getitem__:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals, with_statement
from future_builtins import *
import numpy as np

class MyContainer(object):

    def __init__(self, value):
        self._position = 0
        self.value = value

    def __str__(self):
        return str(self.value)

    def __len__(self):
        return len(self.value)

    def __getitem__(self, key):
        return self.value[key]

    def __iter__(self):
        return self

    def next(self):
        if (self._position >= len(self.value)):
            raise StopIteration
        else:
            self._position += 1
            return self.value[self._position - 1]

So far, everything works as expected, e. g. when trying things like:
if __name__ == '__main__':
    a = MyContainer([1,2,3,4,5])
    print(a)
    iter(a) is iter(a)
    for i in a:
        print(i)
    print(a[2])

But I run into problems when trying to use numpy.maximum:
b= MyContainer([2,3,4,5,6])
np.maximum(a,b)

Raises "ValueError: cannot copy sequence with size 5 to array axis with dimension 0".
When commenting out the __iter__ method, I get back a NumPy array with the correct results (while no longer conforming to the iterator protocol):
print(np.maximum(a,b)) # results in [2 3 4 5 6]

And when commenting out __getitem__, I get back an instance of MyContainer
print(np.maximum(a,b)) # results in [2 3 4 5 6]

But I lose the access to individual items.
Is there any way to achieve all three goals together (Iterator-Protocol, __getitem__ and numpy.maximum working)? Is there anything I'm doing fundamentally wrong?
To note: The actual wrapper class has more functionality but this is the minimal example where I could reproduce the behaviour.
(Python 2.7.12, NumPy 1.11.1)

A: Your container is its own iterator, which limits it greatly. You can only iterate each container once, after that, it is considered "empty" as far as the iteration protocol goes.
Try this with your code to see:
c = MyContainer([1,2,3])
l1 = list(c) # the list constructor will call iter on its argument, then consume the iterator
l2 = list(c) # this one will be empty, since the container has no more items to iterate on

When you don't provide an __iter__ method but do implement a __len__ methond and a __getitem__ method that accepts small integer indexes, Python will use __getitem__ to iterate. Such iteration can be done multiple times, since the iterator objects that are created are all distinct from each other.
If you try the above code after taking the __iter__ method out of your class, both lists will be [1, 2, 3], as expected. You could also fix up your own __iter__ method so that it returns independent iterators. For instance, you could return an iterator from your internal sequence:
def __iter__(self):
    return iter(self.value)

Or, as suggested in a comment by Bakuriu:
def __iter__(self):
    return (self[i] for i in range(len(self))

This latter version is essentially what Python will provide for you if you have a __getitem__ method but no __iter__ method.


text:
Q: Callback parameter not working JSONP javascript I'm trying to load the data form cross-domain using JSONP. callback parameters that passed in a script isn't printing any data in the console.
I'll load week-7.js from another server but I try it locally it is not working. I can not change any code in serverside part I don't have access to change it
I put this

this is my week-7.js
const data = {
  "noWeek": 1,
  "fstWeek": 1,
  "week": 1,
  "end": 1591459131848,
  "profiles": {
    "test1": {
      "id": "test1",
      "type": "3",
      "name": "test test",
      "picture": {
        "uri": "/flag.png"
      },
      "country": "IN",
      "ed": 1,
      "gs": 100,
      "ts": 13.0,
      "in": 31,
      "px": 34
    }
  },
  "leaders": [
    "test1"
  ]
}

Is there anything wrong? any suggestions?

A: To get you started you could:
1 - Alter your local data file to jsnop by removing '=' and starting it with 'data({' and put a closing bracket ')' at the end.
2 - Add this to your HTML:

Output

3 - Change your callback function to:
function data(y){
document.getElementById('x').innerHTML=JSON.stringify(y, null, 2)
}

If you manually add your callback function name (data) to the data file you will not need to to put a callback name in the calling script - it will be ignored locally and perhaps by the server. However if you are getting third party remote data from eg Yahoo finance you will probably need to put a callback name in the URL and perhaps use a service such as https://json2jsonp.com
The process works by changing you data file into a function call to your callback function.
A word of warning. Things may stop working if you add further related script outside of the callback function. Get it working inside the function first.
Good luck.


text:
Q: Can Google Script(deployed as web app) url be used as endpoint in alexa skill? [EDIT]: The SSL handshake to endpoint Resource [https://xx.yyy.xxx.yy], Type [HTTP] failed. Please check that your java keystore is correctly configured. This is the error I am getting.
I am trying to build my first alexa skill and I am trying to do it without using lambda. I was wondering if we could use google script url as endpoint for the alexa skill. I tried it but alexa says that the skill is unreachable and the google script is also not executed