text:
Q: Android: call a method from calling activity In my activity, on user's request for preferences screen, I call:
startActivity(new Intent(this, Preferences.class));

Preferences class is defined like this:
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
    ...
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
        ...
    }

}

I need to implement OnSharedPreferenceChangeListener in my Preferences class becase I want to be able to - for example - disable a preferences item based on a specific selection.
But I would need to implement it in my main Activity, to react to the preference changes.
Unfortunately onSharedPreferenceChanged() fires only in my Preferences class, and not in my main activity: how can I force it to be fired in bot activities?
Or - how can I manually call onSharedPreferenceChanged() in my main activity from onSharedPreferenceChanged() in Preferences activity?

A: in your main activity, you can register a listener for prefs changes:
SharedPreferences prefs = PreferenceManager
    .getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);

and then you would implement SharedPreferences.OnSharedPreferenceChangeListener in your activity, with your own onSharedPreferenceChanged method.

A: Well, there's little sense in watching for preferences change in an activity that's not currently 'active'. You should handle your main activity's lifecycle events instead such as onResume, onRestart etc.

A: If you want to make some functionality accessible from both activities, you best do this by including this code into a static method which can be called from anywhere. In Android activities are decoupled, you don't really have the access from one activity to the instance of some other activity.


text:
Q: How to add an empty line at the end of these commands? I am in a situation where I have so many fastq files that I want to convert to fasta.
Since they belong to the same sample, I would like to merge the fasta files to get a single file.
I tried running these two commands:
sed -n '1~4s/^@/>/p;2~4p' INFILE.fastq > OUTFILE.fasta

cat infile.fq | awk '{if(NR%4==1) {printf(">%s\n",substr($0,2));} else if(NR%4==2) print;}' > file.fa

And the output files is correctly a fasta file.
However I get a problem in the next step. When I merge files with this command:
cat $1 >> final.fasta

The final file apparently looks correct. But when I run makeblastdb it gives me the following error:
FASTA-Reader: Ignoring invalid residues at position(s): On line 512: 1040-1043, 1046-1048, 1050-1051, 1053, 1055-1058, 1060-1061, 1063, 1066-1069, 1071-1076

Looking at what's on that line I found that a file header was put at the end of the previous file sequence. And it turns out like this:
GGCTTAAACAGCATT>e45dcf63-78cf-4769-96b7-bf645c130323

So how can I add a blank line to the end of the file within the scripts that convert fastq to fasta?
So that when I merge they are placed on top of each other correctly and not at the end of the sequence of the previous file.

A:
So how can I add a blank line to the end of the file within the
scripts that convert fastq to fasta?

I would use GNU sed following replace
cat $1 >> final.fasta

using
sed '$a\\n' $1 >> final.fasta

Explanation: meaning of expression for sed is at last line ($) append newline (\n) - this action is undertaken before default one of printing. If you prefer GNU AWK then you might same behavior following way
awk '{print}END{print ""}' $1 >> final.fasta

Note: I was unable to test any of solution as you doesnot provide enough information to this. I assume above line is somewhere inside loop and $1 is always name of file existing in current working directory.

A: if the only thing you need is extra blank line, and the input files are within 1.5 GB in size, then just directly do :
awk NF=NF RS='^$' FS='\n' OFS='\n'

Should work for mawk 1/2, gawk, and nawk, maybe others as well. This works despite appearing not to do anything special is that the extra \n comes from ORS.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Minecraft: Items scrolling though inventory I am making kind of like a CS:GO Cases plugin for a Minecraft and if you don't know what CS:GO cases are here is an explanation: So you will do a command(/common) and then it opens a common case; there is also going to be rare and legendary. But when you execute the command, a inventory should open and items should start spinning and then slow down and eventually stop and the item in the middle is the item you win I have created a inventory I just have to figure out how to make the items spin. I tried to do:
for(int x = 0; 0 < 18; x++)`
{
   inv.setItem(x, diamondSword);
   inv.setItem(x, diamondShovel);
   inv.setItem(x, Chest);
   inv.setItem(x, Compass);
   inv.setItem(x, stick);
   inv.setItem(x, stonePickaxe);
   inv.setItem(x, diamond);
   inv.setItem(x, emerald);
}

And what happens is that the inventory opens and it is full of emeralds (The last item).
So I tested and printed x in the server chat and when I do the command it makes all of the numbers appear instantly like:
1
2
3
4
5
... until it hits 17.
So I just want a little explanation on how I could make the items cycle through the GUI that appears when executing the command.

A: Add a delay with a scheduler. runTaskTimer runs a set of functions forever with a delay between run. Last argument is amount of time inbetween in ticks. 20 ticks = 1 second
Example code:
List<ItemStack> list = {item1, item2, item3, item4};
int x = 0;
plugin.getServer().getScheduler().runTaskTimer(plugin, new Runnable()
{
  @Override
  public void run()
  {
    inv.setItem(slot, list.get(x);
    x++
  }
}, 40);


text:
Q: Postgis calculate the distance between points I have a table that has more than 15k rows.
The table has locationID, isEmpty, longitude and latitude fields.
I want to calculate the distance between each point has isEmpty field = 1 and the others and insert the result into new table using Postgis.
Please advise what is the best practice for writing sql statement executing this requirement

A: Ok, thanks for explanations - now it's clearer.
In Postgis you don't have to count all distances to find how many other points are within some distance.

*

*Add extension to database
CREATE EXTENSION postgis;

*Now add a column of type geometry
ALTER TABLE mytable ADD COLUMN geom geometry;

*You'll need some index to
CREATE INDEX mytable_geom_idx ON mytable USING gist(geom);

*Now populate new column
UPDATE mytable SET geom = ST_SetSRID(ST_MakePoint(lon, lat),4326);

*And now the query:
Select a.locationID, count(*)
from mytable a
join mytable b on a.locationID!=b.locationID
  and ST_Dwithin(a.geom::geography,b.geom::geography,152)
where a.isEmpty=1
group by 1;

ST_DWithin with geography type is taking distance in meters and 152m~500ft
I didn't test it, so if something will not work please write me a comment


text:
Q: Working with C# generic method and making it strongly typed I have two profile types which are:
TeamPlayerPage.cs & TeamStaffMemberPage

In my code (which is an Umbraco solution) I have created two methods that get and build up a collection of profiles e.g.
GetPlayerProfiles(TeamPlayersLandingPage teamPlayersPage)
GetStaffProfiles(TeamStaffLandingPage staffMembersPage)

Within each of the above methods i create a SponsorListItem to associate a sponsor with the profile. Example below
private SponsorListItem GetPlayerSponsor(TeamPlayerPage teamPlayerPage)
{
    if (teamPlayerPage.Sponsor == null)
        return null;

    var sponsorPage = teamPlayerPage.Sponsor as SponsorPage;

    var sponsor = new SponsorListItem()
    {
        Heading = sponsorPage.Heading,
        Url = sponsorPage.Url,
        ListingImgUrl = sponsorPage.Image != null ? sponsorPage.GetCropUrl("image", "360x152(listing)") : Global.PlaceholderImage.GenericListingItem,
        KeySponsor = sponsorPage.KeySponsor
    };

    return sponsor;
}

The sponsor logic is exactly the same for each type so i would like to create one generic method e.g GetProfileSponsor(T profilePage) as opposed to two (see below) The goal is to be able to pass either aa TeamPlayerPage or TeamStaffMemberPage to a generic method and have it be strongly typed so i can access the properties on it.
private SponsorListItem GetPlayerSponsor(TeamPlayerPage teamPlayerPage)
private SponsorListItem GetStaffSponsor(TeamStaffMemberPage staffMembersPage)

I created the following but i'm not quite sure how to make the T profilePage parameter strongly typed against what is passed in (if that is possible)

I have done some searching around but struggling to understand the concept a little. Can someone please point me into the right direction ?

*

*https://app.pluralsight.com/library/courses/csharp-best-practices-collections-generics/table-of-contents

*https://app.pluralsight.com/library/courses/csharp-generics/table-of-contents
Thank you
Paul

A: To do this, both of your classes need to implement a common interface so you can constrain the method to that. For example:
public interface ISponsor
{
    SponsorPage Sponsor { get; }
}

And then make your class implement that interface:
public class TeamPlayersLandingPage : ISponsor
{
}

Now you can constrain your generic method:
private SponsorListItem GetProfileSponsor<T>(T profilePage)
    where T : ISponsor
{
    var sponsor = profilePage.Sponsor;
}


text:
Q: No Device drivers were found while installing windows Here is the situation, I was trying to install Windows 10 on my PC. I have cleaned the hard disk (including the C drive which contained my Windows OS) and started installation with my bootable usb. I was getting an error called "No device drivers were found. Make sure that the installation media contains the correct drivers, and then click OK.". I tried changing usb stick to different ports but the problem still exists. I have tried the same usb stick for my laptop to check whether the Windows installation is corrupted or not, and it was working perfectly fine. After that I searched and found that by installing intel rapid storage drivers might fix the issue but I was not able to install it because my bootable usb is not visible in the browse section. It only shows C drive (which is empty), a disk drive and a boot drive (but it does not contain those files). Later, I thought of using DVD for the device drivers and tried installing but it gave an error that either files are not correct or they are not present in installation media. I can even burn Windows iso on DVD as the size of iso file is larger than my DVD. I tried
diskpart
list disk # But this shows only my harddrive and not my usb stick, even if I connect multiple usb stick. I have 6 different ports available but none of them worked in detecting it.
clean
create partition primary
format fs=ntfs
exit

I also tried installing Windows 7 but the same issue persist. In short, I am not able to install any of the Windows OS. Can anyone please help. THANK YOU!


text:
Q: Having trouble when requesting with mustache and Javascript What I'm trying to do:
I made an alert function by spring which gives alert to user when the predetermined condition is fullfilled. This functions works well on Spring.
User can set several alerts on their own.
So when User presses "start alert" button in html, javascript sends get request using ajax depending on "idx" of alert on html.
Problem :
Seems like function is not working well on browser.
I did debug by using F12, I found out that Javascript is not getting any "idx" value..
So Nothing happens when I try to get alert.
All I wanna do is request by Alert id when button is pressed.
Here are my full code.
Controller
@GetMapping("/alerts/{id}")
@ResponseBody
public void AlertUser(@PathVariable Long id) {
    alertService.AlertUser(id);
}

Service
public void AlertUser(Long id) {

        Alert alert = alertRepository.findById(id).orElseThrow(() -> new NoSuchElementException());

        double SetPrice = alert.getPrice();
         String ticker = alert.getTicker();

        JSONParser jsonParser = new JSONParser();

        final NotificationRequest build = NotificationRequest.builder()
                .title(ticker + " alert")
                .message(SetPrice + "broke down")
                .token(notificationService.getToken(userDetailService.returnUser().getEmail()))
                .build();

        try {
            final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint();

            Session session = clientEndPoint.connect(new URI("wss://ws.coincap.io/prices?assets=" + ticker));

            WebsocketClientEndpoint.MessageHandler handler = new WebsocketClientEndpoint.MessageHandler() {
                public void handleMessage(String message) throws ParseException, IOException {
                    Object obj = jsonParser.parse(message);

                    JSONObject jsonObject = (JSONObject) obj;

                    double price = Double.parseDouble(jsonObject.get(ticker).toString());

                    System.out.println("가격 : " + price);

                    if (price < SetPrice) {
                        System.out.println("끝");
                        notificationService.sendNotification(build);
                        session.close();
                    }

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        System.err.println("InterruptedException exception: " + ex.getMessage());
                    }
                }
            };
            clientEndPoint.addMessageHandler(handler);

        } catch (URISyntaxException ex) {
            System.err.println("URISyntaxException exception: " + ex.getMessage());
        }
    }

**alert.mustache : {{#alerts}} ~ {{/alerts}} part is where problem occurs **
{{>layout/header}}

<form method="post" action="submitform" id="tickerSubmit">
    <select name="contact" id="contact">
        {{#tickers}}
            <option value="{{.}}">{{.}}</option>
        {{/tickers}}
    </select>

</form>

    <input type="number" id = "price" placeholder="하한 금액을 입력하세요">
    <input type="number" id = "percentage" placeholder="하한 퍼센트를 입력하세요">
    <button type="button" class="btn btn-primary" id="alert-save-btn">알림 등록</button>

{{#alerts}}

{{id}}

    <input type="submit" value="알림시작" id="alert-start"/>
    티커 : {{ticker}}
    가격 : {{price}}

{{/alerts}}

{{>layout/footer}}

part of index.js encrypted in layout/footer
$('#alert-start').on('click', function() {
                _this.alertStart();
            });
    },

    alertStart : function() {
        var idx = $('#idx').val();

         $.ajax({
                            type: 'GET',
                            url: '/alerts/'+idx,
                        }).done(function() {
                            alert('알림이 시작됩니다.');
                        }).fail(function (error) {
                            alert(JSON.stringify('이거' + error));
                        });
    },

Thanks in advance. any help or tip would be very helpful..


text:
Q: Insert Data into Form oracle apex I am trying to insert data into a read only form using following sql query in the pre-rendering page process:
begin
select s.ID, s.SPID, s.PHONE_NUMBER
INTO :P9_ID,:P9_SPID,:P9_PHONE_NUMBER
FROM TABLE1 s
left outer join TABLE2 f on f.ID=s.ID
where f.ID=:P9_TBL2_ID;
end;

However I always get the error no data found when using the where clause, although the page element has an explicit value (here number 5).
Modifying the where clause to:
where f.ID=5;

I get the right data inserted into the read only form.
In general the question is, how can data been loaded into a form from table?

A:
although the page element has an explicit value (here number 5).

How did :P9_TBL2_ID item get its value? It isn't enough just to see it on the screen - it has to be put into session state. We usually do it by submitting the page.
However, as it is a pre-rendering process, you must somehow be coming to that page - I presume from some other page. Usual way to do that is to push a button which redirects to another page. Its properties allow you to set items on the target page (P9 in your case) with some values (5 in your case). So, did you do that? If so, it should work properly.


text:
Q: AppendTo Div in SweetAlert with DataTable I am currently using SweetAlert to populate a dialog to allow the user to select multiple rows in a table and then save to the DB using an ajax request mapped to a controller via MVC Core.
However, I am unable to get the DataTable to populate in the view before it pops up. What is the best way to get this working?
Here is my SweetAlert call that triggers the popup with the TableView:
$('#ApplicationTable').on('change', '#enableApp', function (event) {

            if ($(this).is(':checked')) {
                $.ajax({
                    url: '@Url.Action("EnableApplication")',
                    data: {
                        'AppId': this.value, 'UserId': @Model.Id },
                    type: "post",
                    cache: false,
                    success: function (status) {
                        swal({
                            title: 'Permissions',
                            content: {
                                element: 'div',
                                attributes: {
                                    id: 'searchTableWrapPermissions'
                                }
                            }
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        swal("Error enabling app, please contact support.");
                    }
                });

The idea is to create the popup with a div that I can then append the table to the id being placed in the content.
OnDeviceReady I also call this:
 $('

Name	Description	Edit

').appendTo('#searchTableWrapPermissions');

This seems to me it would work logically but for some reason I am unable to get it to popup with the sweetalert view.

A: As you are using Ajax, you can use a JsonResult as return type from the controller (not a partialView) this way you are not depending on the razorengine, Instead you would append your data to that div with JQuery or plain JavaScript using that returned json from the controller. This also gives you more control in you frontend.

A: MVC POP UP:
1.Step 1:Create a Shared Page

_help1.cshtml

@model string

    <input type="hidden" id="ReferanceFieldID" value="" />
    <input type="hidden" id="ReferanceColumn" value="" />

                @*Take a refresh button*@

        @(new HtmlString(Model))

2>Step 2: download datatable.js
enter link description here
and link with main cshtml page
3>step 3:Views page( cshtml page)

cshtml page:
  Place  the codes:

function GetHelp(urlstring, id, colnm, caption) {
          $.ajax({
            type: 'get',
            url: path of controller page function,
            success: function (result) {
                $('#ReferanceFieldID').val(id);
                $('#ReferanceColumn').val(colnm);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#WaitingMode").hide();
                msgError("Error: " + textStatus + "," + errorThrown);
            }
        });
    }

                        @Html.EditorFor(model => model.M_WEEK.COMPCD, new { htmlAttributes = new { @class = "form-control textbox_image", id = "COMPCD", @placeholder = "COMPCD", maxlength = 4 } })

                        @Html.EditorFor(model => model.M_COMP.COMPNM, new { htmlAttributes = new { @class = "form-control", id = "COMPNM", @TabIndex = -1, @placeholder = "COMPNM", maxlength = 60, @readonly = "readonly" } })

4>Step 4:

Controller page

public string PRODGRPCD_help(ImprovarDB DB)
    {
        var query = (from c in DB.M_PRODGRP
                     join i in DB.M_CNTRL_HDR on c.M_AUTONO equals i.M_AUTONO
                     where i.INACTIVE_TAG == "N"
                     select new
                     {
                         code = c.PRODGRPCD,
                         name = c.PRODGRPNM,
                     }).ToList();
        System.Text.StringBuilder SB = new System.Text.StringBuilder();
        SB.Append("

");
        SB.Append("Product Group Name	Product Group Code

");
        SB.Append("
");
        for (int i = 0; i <= query.Count - 1; i++)
        {
            SB.Append("
" + query[i].name + "	" + query[i].code + "
");
        }
        SB.Append("

");
        return SB.ToString();
    }

 return PartialView("_Help1", PRODGRPCD_help(DB));

Here I am use LINQ query u can use
normal query
query = (from c in DB.M_PRODGRP
                         join i in DB.M_CNTRL_HDR on c.M_AUTONO equals i.M_AUTONO
                         where i.INACTIVE_TAG == "N"
                         select new
                         {
                             code = c.PRODGRPCD,
                             name = c.PRODGRPNM,
                         }).ToList();

A: Do one things make dynamic html for data table and in success function of ajax call call swalplugin.
var htmlcontent ="

"
 swal({
     title: "what ever",
     text: htmlcontent,
     html: true
 });


text:
Q: Open a file and copy/paste the 3rd sheet's data into a workbook using a dynamic path made with cells "B2" "B9" and "B4" I am trying to build code that performs the following:

*

*Opens a file path made of a string of text and cells B2, B9, and B4 in my current workbook

*Copies the data on the third sheet of the opened file

*Pastes the data in a specific sheet of my current workbook

Sub GrabData()

Dim ThisWorkbook As Workbook 'our current workbook
Dim swb As Workbook ' data source workbook we need to open
Dim sws As Worksheet ' data source worksheet we need to open
Dim Path As String ' Path for file we need to open

'Now, I will try to make a dynamic path link.
Path = "U:\1. NAME - 25\1. MONTH \SQL Recon\" & ThisWorkbook.Range("B2") & "\" & ThisWorkbook.Range("B9") & " " & ThisWorkbook.Range("B4") & "\Basic\[Dir.xls]" & ".xls"

Set swb = Workbooks.Open(Path) ' the file we want to open
Set sws = swb.Sheets(3).Range("A1:S300").Copy 'Set the sheet and the range we want to copy in our data source workbook equal to page 3, cells A1 to S300
ThisWorkbook.Worksheets("DATA DUMP").Range("A1").PasteSpecial xlPasteValues 'the sheet I want to drop the data in
swb.Close ' close the data source workbook

End Sub

A: Change Sheets(1) to the sheet where the file path values are.
Option Explicit

Sub GrabData()

    Dim swb As Workbook ' data source workbook we need to open
    Dim sws As Worksheet ' data source worksheet we need to open
    Dim mypath As String ' Path for file we need to open

    With ThisWorkbook
        'Now, I will try to make a dynamic path link.
        With .Sheets(1)
             mypath = "U:\1. NAME - 25\1. MONTH \SQL Recon\" _
             & .Range("B2") & "\" & .Range("B9") & " " & .Range("B4") _
             & "\Basic\[Dir.xls]" & ".xls"
        End With

        If Dir(mypath) = "" Then
             MsgBox mypath & " not found", vbCritical
             Exit Sub
        End If

        ' the file we want to open
        Set swb = Workbooks.Open(mypath, ReadOnly:=True)
        Set sws = swb.Sheets(3)

        ' copy data
        .Sheets("DATA DUMP").Range("A1:S300") = sws.Range("A1:S300")
    End With
    swb.Close savechanges:=False
    MsgBox "Done", vbInformation

End Sub


text:
Q: Calculate the angle when the area of section is given as the % of total area of the circle This is not a homework. Just a sudden mathematical spark of my brain prompted me to simply calculate this.

In the diagram above the area of the hatched section is 10% of total area if the circle. What the angle CAB should be to satisfy this condition. I need non calculus solution.
So far I have done this...

But my final equation cannot be simplified further, or I don't know how to proceed further. What I need is an equation in which the alpha will be the title, so that I can find this alpha for any given area of the hatched section A.

A: Another approach. From Thales' theorem we know that $\beta=90°$ and $\alpha+\gamma=90°$ Thus $\gamma=90°-\alpha$.
And the triangle $BOC$ is an isosceles triangle. Therefore the angle at $B$ of the  triangle $BOC$ is $90°-\alpha$ as well. Then the angle at $0$ of $BOC$ is
$\delta=180°-2\cdot (90°-\alpha)$=$2\alpha$
Now you can use the well known formula for the area of a circular segment:
$A=\frac{r^2}{2}\cdot\left(\frac{\delta \cdot \pi}{180}-\sin (\delta) \right) $
Remark:
You can also use the identity $\boxed{\sin(2\cdot \alpha)=2\cdot \cos(\alpha)\cdot \sin(\alpha)}$.
Your intermediate result  $ A=\frac{\alpha \cdot \pi}{180}\cdot r^2-r^2\cdot \cos(\alpha)\cdot \sin(\alpha)$ becomes
$$A=\frac{\alpha \cdot \pi}{180}\cdot r^2-r^2\cdot \frac12\cdot  \sin(2\alpha)$$

A: Let segment ABC be the given such that [segment ABC] = [yellow] + [orange] = $\dfrac {1}{10}\pi r^2$. At this stage, C is just a point on the minor arc AB.

Construction: Draw the sector OBC with its central angle = $\angle BOC = 36^0 = … = \dfrac {\pi^c}{5}$. Let $x^c$ be the central angle of sector OCA.
Then, [sector OBC] = [pink] + [orange] = $\dfrac {1}{2} r^2 \dfrac {\pi}{5}^c$.
In other words, [pink] = [yellow] and therefore, [pink] + [blue] = [yellow] + [blue].
That is, area of $\triangle OAB$ (edited) = area of sector OAC.
∴ $\dfrac {1}{2} r^2 \sin (x + \dfrac {\pi}{5}) = \dfrac {1}{2} r^2 x^c$.
After simplification, we have $x = \sin (x + \dfrac {\pi}{5})$, which is still in transcendental (but a bit simpler). From Wolframalpha, $x = 0.998435^c$


text:
Q: Automatically Update Data in a Google Fusion Table hourly? We are going to need to update data in a Google Fusion Table hourly and are looking into possibly using an SSIS package to accomplish this.
Has anyone had any experience with updating Google Fusion Tables automatically?  Any methods work better than others?

A: I would decompose your problem into smaller problems until you reach the point you have found one you can solve.
How do I perform a task at X interval
In a pure Windows world, I'd use the native Task Scheduler. It's free and works fine for your scenario of "every hour."
Since SSIS is in the mix, that means you would also have access to SQL Agent. It too is a good fit for your scenario and at this point, I would examine your organization and determine what scheduling tool is predominantly used. It might be "neither."
How can I programmatically update Google Fusion Tables
There is a full Fusion API published. They even have a DML syntax for working with data in a table. However, do observe the warning about using the query syntax for more than 500 rows/10k cells/1MB.

Note: You can list up to 500 INSERT statements, separated by
  semicolons, in one request as long as the total size of the data does
  not exceed 1 MB and the total number of table cells being added does
  not exceed 10,000 cells. If you are inserting a large number of rows,
  use the import method instead, which will be faster and more reliable
  than using many SQL INSERT statements.

How can I use SSIS to update Google Fusion Tables
For anything that's not Out Of the Box with SSIS, I usually re-ask the question as "how do I do X in .NET" because that's what it will boil down to. Since it's a web destination, while SSIS has a web service task, it's not as useful as writing your own .NET caller.
I would envision an SSIS package with at least a Data Flow Task. Depending on where your data is coming from, it'd have a source (OLE DB, flat file, etc), any transformations you need between that and the destination. Your destination will be a Script Component configured as a Destination. There you'll use C# or VB.NET to send your Insert/Update commands to the web server. I found this sample of C# that sounds logical. I've never actually used GFT API so I can't comment on whether there's a better route of doing this.
Copying sanya's comment in here

Warning: the attached sample c# script uses Client Login to
  authenticate against Google. This auth method has been deprecated
  since April 20, 2012. Usage of OAuth2 is supported.


text:
Q: NHibernate and SQL 2008 Time datatype How do I map NHibernate type to SQL Server's TIME type? I'm using NH 3.2 and map-by-code.
public class Schedule
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual TimeSpan Time { get; set; }
}

Here is my mapping class
public class ScheduleMapping : ClassMapping<Schedule>
{
    public ScheduleMapping()
    {
        Id(x => x.Id, x => x.Generator(Generators.Native));
        Property(x => x.Name, x => x.NotNullable(true));
        Property(x => x.Time, x => x.NotNullable(true));
    }
}

Now, when I create database from this column "Time" has BIGINT SQL type instead of TIME. I have read this and that article but it's not clear to me how to apply any of these solutions.
=========== EDIT ====================
I created and inserted new schedule like this:
var newSchedule = new Schedule {
                   Name = "My Schedule",
                   Time = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 0)
                   };
session.SaveOrUpdate(newSchedule);

When this data was inserted (around 7:27 PM) the Time column contained value '700200000000', which could be ticks, but the most important thing was that when I queried DB for these values
var retrievedSchedules = session.QueryOver<Schedule>().List();

the Time property was properly set to 19:27.Originally I wanted Time property to represent the time at which Schedule is supposed to run. Even though SQL Server's datatype for this column was defined as BIGINT and the value is represented as (most likely) ticks, after retrieval it was correctly transited into a time, which is what I wanted. This no longer is a question but I'm going to leave this for, hopefully, someone else's benefit.

A: This, in your mapping should solve your problem:
Property(x => x.Time, x => x => { x.NotNullable(true); x.Type<TimeAsTimeSpanType>(); });

By default, NH will use x.Type<TimeSpanType>() as the NH type for the clr Time type ... which maps to the SQL Server 2008 as a bigint.
Have a look here: http://jameskovacs.com/2011/01/26/datetime-support-in-nhibernate/. It covers the different Clr --> NH --> Db type mappings for dates & times.


text:
Q: standard error of sample mean I am asked to calculate the standard error of the sample mean using bootstrapping for this data set
y = c(4.9, 3.3, 2.2, 2.3, 1.6, 2.4, 4.7, 1.4, 1.7, 5.1)

The solutions are as follows:
set.seed(12345)

nsim = 10^6
ybar.sim = numeric(nsim)

for (i in 1:nsim){
  y.sim = sample(y, replace=T)
  ybar.sim[i] = mean(y.sim)
}

se.boot = sd(ybar.sim); se.boot

[1] 0.4322378

whereas I thought it would be this way:
mean(replicate(1000000, sd(sample(
  y, replace=T))/sqrt(length(y))))

which gives [1] 0.4264217
and using the boot lbrary gives:
bootmean <- function(d, i) mean(d[i])
bs <- boot(y, bootmean, R=1000000, stype="i")
print(bs)

Bootstrap Statistics :
    original     bias    std. error
t1*     2.96 0.00021043   0.4318501

which is similar to the first answer.
I do not understand why the first answer is correct given the formula for standard error is the standard deviation divided by the length of the vector. Why is the second answer wrong?

A: Since the $10$ values of $y_i$ have mean $2.96$, the variance of the sample mean should be $\frac1{10}\sum (y_i-2.96)^2 = 0.18684$ and the square root of that is about $0.43225$.  In effect that is what the official solution is simulating.
The distinction comes from the non-linearity of the square-root function: the square root of the mean of is usually not the same as the mean of the square root even if you adjust for the square root of the number of terms.
The official solution is simulating the square root of the variance of the mean while you are simulating the mean of the square root of the variance adjusted for sample size.  If instead you had simulated the square root of the mean of the variance adjusted for sample size, for example with
sqrt(mean(replicate(1000000, var(sample(
          y, replace=T))/length(y))))

you would have got a result closer to $0.43225$.


text:
Q: Login to the Identity Server Using Another Identity Server - SAML2 I'm currently working with WSO2 suite and I've been trying to do an example from wso2 official documentation server, that you can find here. I already configure everything step by step and when i run travelocity application in my localhost it looks like the example says, i click in the link and it redirects me to Identity Server login. I type in user and password, and then it redirects me to travelocity home page, but then i run into this error: SAML 2.0 based Single Sign-On
Error when processing the authentication request!
I check out the debuging log and it says that authentication succeeded and Identity Server sent the response to travelocity.
I have no idea what could be happening, please help me out.
I shared the log files here. My English is bad and i'm new working with WSO2, please be patient with me.

A: The logs at WSO2 IS side says Signature validation for Authentication Request failed. The possible reason could be that you have not selected the correct certificate alias at WSO2 IS.
To do that, edit your service provider's SAML configuration and update the Certificate Alias with the correct value. In default case it should have the value wso2carbon. In case you have configured it to something else, select the one you have configured.


text:
Q: Ringer Mode Vibrate no Android Gostaria de saber se é possível programaticamente chamar setRingerMode(RINGER_MODE_VIBRATE) sem o dispositivo vibrar no momento em que o método é chamado?
O Android tem um comportamento padrão quando configuramos o sound mode: vibrar quando selecionamos o modo RINGER_MODE_VIBRATE, diretamente no dispositivo. E esse comportamento também se repete quando feito via código.
Quando abro a app, o sound mode do dispositivo deve ser colocado para RINGER_MODE_NORMAL. Mas quando fecho, o estado anterior deve ser restaurado. Ao restaurar o estado RINGER_MODE_VIBRATE o telefone vibra.
Gostaria que ele não vibrasse ao configurar RINGER_MODE_VIBRATE. Há alguma forma de inibir essa vibração?

A: Chama o método startVibrate dentro do método que você espera vibrar...
private void metodoQueVibra(){
  startVibrate();
}

public void startVibrate() {
  long pattern[] = { 0, 100, 200, 300, 400 };
  vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
  vibrator.vibrate(pattern, 0);
}

Referencia:
http://www.compiletimeerror.com/2013/11/vibrate-android-device-with-example.html#.U_4eS_ldXp4


text:
Q: Hiding certain form details to particular user Can i design my form in such a way that can hide certain details to particular user?or visible only to reviewer side and not visible for client user

A: Yes, it is possible to hide certain fields from a particular category of members. In the open-source project of formsflow.ai, they are giving 2 sample forms
FOI and New business Licence in that itself they are using this feature. In that, the reviewer section of the FOI form is available only at the reviewer side and I will attach the code for the same here

const UserDetails = JSON.parse(localStorage.getItem("UserDetails"))
const groups = UserDetails["groups"]

if(groups.includes("/formsflow/formsflow-reviewer") && data.applicationStatus==="New") {
  show = true;
}
else {
show = false;
}

Also, you can design the form as per your requirements by giving conditions while designing the form


text:
Q: Vec3 storage buffer not a valid layout despite the scalar qualifier As far as I understand, the scalar layout qualifier in vulkan GLSL should allow a simple array of vec3 values to work, apparently with out any physical device features to be specified.  I've tried with and with out specifying scalar layout features like so:
VkPhysicalDeviceScalarBlockLayoutFeatures layoutfeatures = {};
layoutfeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES;
layoutfeatures.scalarBlockLayout = VK_TRUE;
VkPhysicalDeviceFeatures2 features2 = {};
features2.features = m_required_features;
features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
features2.pNext = &layoutfeatures;

VkDeviceCreateInfo create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
create_info.queueCreateInfoCount = static_cast<uint32_t>(queue_create_infos.size());
create_info.pQueueCreateInfos = queue_create_infos.data();
create_info.enabledExtensionCount = static_cast<uint32_t>(enabled_extensions_names.size());
create_info.ppEnabledExtensionNames = enabled_extensions_names.data();
create_info.pEnabledFeatures = &features2 .features;
create_info.pNext = &features2 ;
create_info.flags = flags;
VkDevice device;
VUL_EXCEPT_RESULT(vkCreateDevice(physical_device, &create_info, pAllocator, &device));

but to no avail.  I'm getting strange spec invalidation errors.
here's example code:
#version 450
#extension GL_EXT_scalar_block_layout: require

#define WORKGROUP_SIZE 128
layout (local_size_x = WORKGROUP_SIZE, local_size_y = 1, local_size_z = 1) in;
layout(scalar, binding = 3) buffer MyBufferBlock{
    vec3 example_array[];
};

void main(){
 example_array[gl_GlobalInvocationID.x] = 0.0;
}

and I get the following SPIR-V validation error:
"example.exe"
ERROR : SPEC_INVALIDATION - Message ID Number 7060244, Message ID String UNASSIGNED-CoreValidation-Shader-InconsistentSpirv:
Validation Error: [ UNASSIGNED-CoreValidation-Shader-InconsistentSpirv ] Object 0: handle = 0x6543e40, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0x6bbb14 | SPIR-V module not valid: Structure id 500 decorated as BufferBlock for variable in Uniform storage class must follow relaxed storage buffer layout rules: member 0 contains an array with stride 12 not satisfying alignment to 16
  %MyBufferBlock = OpTypeStruct %_runtimearr_v3float

First I don't understand why it is trying to call out my buffer as a uniform? and obviuosly I'm still confused on how this is at all a spec violation.


text:
Q: How to just read wanted data from JSON object in Angular 2? I have a problem in reading and logging JSON file like this:
{
"results" : [
  {
     "address_components" : [
        {
           "long_name" : "277",
           "short_name" : "277",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Bedford Avenue",
           "short_name" : "Bedford Ave",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Williamsburg",
           "short_name" : "Williamsburg",
           "types" : [ "neighborhood", "political" ]
        },
        {
           "long_name" : "Brooklyn",
           "short_name" : "Brooklyn",
           "types" : [ "sublocality_level_1", "sublocality", "political" ]
        },
        {
           "long_name" : "Kings County",
           "short_name" : "Kings County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "New York",
           "short_name" : "NY",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "11211",
           "short_name" : "11211",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "277 Bedford Ave, Brooklyn, NY 11211, USA",
     "geometry" : {
        "location" : {
           "lat" : 40.714232,
           "lng" : -73.9612889
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 40.7155809802915,
              "lng" : -73.9599399197085
           },
           "southwest" : {
              "lat" : 40.7128830197085,
              "lng" : -73.96263788029151
           }
        }
     },
     "place_id" : "ChIJd8BlQ2BZwokRAFUEcm_qrcA",
     "types" : [ "street_address" ]
  },
  ],
  "status" : "OK"
  }

I just need the name of city, not all of this data. How could I log just wanted object row.
I tried this code but that doesn't work like I want:
Object.keys(JSON[0]);

A: For your example data
>> data['results'][0]['address_components'][2]['long_name']
Williamsburg

>> data['results'][0]['address_components'][3]['long_name']
Brooklyn

If you get the data as JSON string, you need to convert it to a JavaScript objects before
data = JSON.parse(the_json_string_here);

A: You can filter by sublocality_level_1 and do it in a function to reuse it if you receive a similar JSON sorted different.
const getCity = data => data.address_components
      .filter(x => x.types && x.types.indexOf("sublocality_level_1") > -1)
      .map(x => x.long_name)[0];

//Get a city name from only the first result
const oneCity = getCity(jsonData.results[0]);

//Get an array with all cities (for all the results)
const allCities = jsonData.results.map(getCity);


text:
Q: Java URLResource, LastIndexOf,IndexOf,substring method code explanation? Can someone please help me understand this bit of code with an example. I have been struggling just to get my head around this code.
URLResource file = new  URLResource("http://www.dukelearntoprogram.com/course2/data/manylinks.html");
for (String item : file.words())
{    String itemLower = item.toLowerCase();
  int pos = itemLower.indexOf("youtube.com");

  if (pos != -1) {
        int beg = item.lastIndexOf("\"",pos);
        int end = item.indexOf("\"", pos+1);
System.out.println(item.substring(beg+1,end));

I am struggling with the lastIndexOf, IndexOf and the Substring bit.
Here is a sample YouTube URL:
youtube.com/channel/UCUZHFZ9jIKrLroW8LcyJEQQ


text:
Q: My div class is not applying to my div from another file I have an HTML page for my code and a CSS page for all my classes/styling, but my div class is not applying to my div code.
It's weird because all of my other div classes are fine, but it's just this one.
My code is simple:
<div class="box">
</div>

And my class is also fairly simple:
.box {
    border-right: 10px solid black;
    border-left: 10px solid black;
    border-top: 10px solid black;
    border-bottom: 10px solid black;
}

It is probably a simple rookie mistake as I am new to this, but as I said, all the other classes work fine and they are the same as this.
Also, I tried putting the class in the HTML file itself, in [style], and it worked perfectly. I just wanted to know why it wasn't working when it was in another file when everything else was.

A: You must specify the width and height of the div. Because of that, it isn't showing the borders. Or, you can put some content inside your div, and after that, it will show the borders.
And a little advice: you don't have to type style for all border sides especially. You can just say: border: 10px solid black; and it will be applied to all sides of the box.

A: You need to add some content to your div, or give a height to your div. If not, you will not be able to see your div and the border styles that you added.
In addition, you can make your code more efficient since all 4 border sides are the same styles. You can just use the following styling:
.box {
border: solid 10px black
}

A: So, after a bit more googling, I discovered it was as simple as doing shift + f5 to do a complete cache refresh. Turns out, if you have a completely separate file for all your CSS classes, it doesn't update the cache automatically.


text:
Q: is "%LIKE%" faster than executing multiple queries? for example, each user on my site has 2 phone numbers (i.e. let say 1234 and 6789) .
but about performance , which is faster:
to save the numbers in one column(separated by comma,like [1234,6789] ), and thus, searching the columns with :
select  userID from table where number LIKE %1234%

or saving values into 2 columns
select  userID from table where number1=1234 or number2=1234

which will be faster? lets say i have thousands or millions of rows.

A: This is bad - it is a table scan
LIKE %1234

But thousands of rows is not much
Best would be to have second table with phone
phone:
userID PK FK to user
number PK

select *
from user
join phone
       on phone.userID = user.userid
      and phone.numer = '1234'

if you don't want to fix the data design then two column with = will be faster

A: I think you've confused some syntax.
Best way to do this is
SELECT My_Fields[,,,,] FROM My_Table WHERE number LIKE '123%' OR number LIKE '456%';

This will work for VARCHARs, but not for INTEGERs. But, '%LIKE%' doesn't exist, unless you're trying to pick out the string 'LIKE' from a longer string.
A search for the string - LIKE %123% makes no sense - it has to be between two single quotes - i.e. like LIKE '%123%';
If the string you're searching for is "embedded" in the phone number string - i.e. it's  VARCHAR(25) - or similar - and you're searching for 123 in '01-24-123...', then your search string is non-sargable which can lead to significant performance hits.
To search within the string, use LIKE '%123%' - but, as I've said, it will not use indexes - check out the URL I've referenced for sargable.
All of this should be carefully analysed before system launch - unless you have only a couple of thousand records.
I was in College and the Library had introduced a new cataloguing system  -  you could be there minutes before a search came up for this very reason, - I told the librarian that this was a basic mistake and that the people who designed the system should be shot - she replied, "No, that would be too good for them!" :-)


text:
Q: Restrict the scope of an activerecord validation In a rails shopping cart app I have a cart model, a product model and a line_item model:
class Cart < ActiveRecord::Base
  has_many :line_items
  has_one :order
end

class LineItem < ActiveRecord::Base
  belongs_to :cart
  belongs_to :product
end

class Product < ActiveRecord::Base
end

Right now I'm validating the uniqueness of the delivery date (that is a string column that looks like "May 2015") against the product. So only one product "foo" can be ordered for May 2015.
class LineItem < ActiveRecord::Base
  ...
  validates :delivery, uniqueness: {scope: :product, message: 'there is already an order for this kind of outfit scheduled for this date'}
  ...
end

The problem is that if there is an abandoned cart that has a line_item scheduled for product "foo" on "May 20152 the validation kicks in and prevents the user for making the order.
1) I want to reduce the scope of my validation so that it validates skipping those line_items whose related cart has the "purchased_at" attribute set to nil (meaning that the purchase was not made).
2) It would be nice upon the successful checkout of a cart, that all the other line_items for the same product set for delivery on the same date, would be deleted. This way other people trying to but at the same time, would just see the item disappear from the cart.

A: Use the if or unless options in your validates like so:
class LineItem < ActiveRecord::Base
  belongs_to :cart

  validates :delivery,
            uniqueness: {scope: :product, message: 'message'},
            unless: Proc.new{ |line_item| line_item.cart.purchased_at.nil? }
end


text:
Q: How can I check if a llvm instruction is inside a loop? I have a filtered set of instructions with in a llvm pass. I want to check if each instruction is a part of any loop ( or sub loops). I know that I can get the parent basic block from an instruction
BasicBlock* bb = aInst->getParent();

But how to check if the instruction / the basic block is part of a loop or not ?

A: You can use LoopInfo to find loops in an llvm::Function.
As explained here, you can get the function a given instruction belongs to, compute a dominator tree for that function, and analyze the result with an llvm::LoopInfo::BaseT object.
llvm::DominatorTree DT = llvm::DominatorTree();
DT.recalculate(instr->getFunction());
auto loopInfo = new llvm::LoopInfoBase<llvm::BasicBlock, llvm::Loop>();
loopInfo->releaseMemory();
loopInfo->analyze(DT);

Then you check if instr 's surrounding function contains a loop that contains instr by passing instr and loopInfo to a routine like
bool instrIsInaLoop(llvm::LoopInfoBase<llvm::BasicBlock, llvm::Loop> &loopInfo,
                    llvm::Instruction *instr) {
    for (auto loop : loopInfo) if (instrIsInLoop(loop, instr)) return true;

    return false;
}

with subroutine
bool instrIsInLoop(llvm::Loop *loop, llvm::Instruction *instr) {
    if (loop->contains(instr))
        return true;

    else {
        for (auto subLoop : loop->getSubLoops()) {
            if (instrIsInLoop(loop, instr)) return true;
        }

        return false;
    }

}


text:
Q: How to run supported games on Steam with Proton Human Fall Flat works flawlessly on Windows, but I am having problem with Linux. I installed this game on Ubuntu 19.04 and it works fine, except it's an older verison and multiplayer doesn't work on there. I just found out about Proton on steam and so I installed it and reinstalled HFF, however, it still installs the old version that doesn't allow me to play multiplayer, help!
(Only the game's older version can port to Linux without Proton)

A: In Steam settings in the category "Steam Play" check "Enable Steam Play for all other titles".
Then right-click on the game in question, open "Properties", and on the bottom of the "General" tab, check "Force the use of a specific Steam Play compatibility tool".
That will tell Steam to run the game via Proton even if there is a native Linux version available.


text:
Q: Update SQL Server table from Excel and then populating remaining column data SQLPLUS not available
I need to be able to call a SQL script from the command line and pass in parameters for use. The script will read in data from an excel spreadsheet (file specified also at command line) to append records to an existing table in the database.
There are two additional columns in the database table that do NOT exist in the spreadsheet. Those columns are month and year. Those two values need to be entered at the command line and populated for each new record added. Whatever is entered at the command line will be the same value for each of the new records. (Any existing records in the table need to be remain untouched).
Can you help?
I was thinking about using osql to specify the user, password, database and .sql file.

A: I do and would use powershell as described by
Not sure about formating link but paste into browser.
https://www.simple-talk.com/sql/database-administration/getting-data-between-excel-and-sql-server-using-odbc/


text:
Q: Logging in readable Plink output (sshlog is too clumsy) I'm logging into to a remote SSH session using plink.exe to perform certain tasks using a batch script. Getting the output of these commands in a log file as well on the screen is very important for me.
I tried using usual batch way i.e.
plink servername -m cmd.txt>logfile.log

But the problem with this is that it wont display it on the Windows terminal that the batch script is running on.
Then I found the -sshlog option of Plink. This does the work, i.e. I can get the output on screen and in a log file, but this results in output as follows:

My actual output starts at te.... in the image above
The output has these 00000010  74 65 72 ... bla bla characters which I don't want. Plus the main output (that would be displayed if I was using Plink interactively is "word-wrapped" and looks horrible which makes it very difficult to understand for a general user
Is there any way to prevent plink output unwanted -sshlog characters in the log file?
or
Is there any other way to get the output on screen and log fail simultaneously in a Plink/PuTTY session inside a batch script?


text:
Q: EJB3/JPA entity with an aggregated attribute I wanted to know if there is a way to get in a One2Many relationship a field of the One side that is an aggregate of the Many side.
Let's take the following example:
@Entity
public class A {
 @Id
 private Long id;
 @OneToMany (mappedBy="parentA")
 private Collection<B> allBs;

 // Here I don't know how to Map the latest B by date
 private B latestB;
    // Acceptable would be to have : private Date latestBDate;
}

@Entity
public class B {
 @Id
 private Long id;
 private Date date;
 @ManyToOne (targetEntity=A.class)
 private A parentA;
}

My question is how can I make the mapping of the field latestB in the A entity object without doing any de-normalization (not keeping in sync the field with triggers/listeners)?
Perhaps this question gives some answers, but really I don't understand how it can work since I still want to be able to fetch all childs objects.
Thanks for reading/helping.
PS: I use hibernate as ORM/JPA provider, so an Hibernate solution can be provided if no JPA solution exists.
PS2: Or just tell me that I should not do this (with arguments of course) ;-)

A:
I use hibernate as ORM/JPA provider, so an Hibernate solution can be provided if no JPA solution exists.

Implementing the acceptable solution (i.e. fetching a Date for the latest B) would be possible using a @Formula.
@Entity
public class A {
    @Id
    private Long id;
    @OneToMany (mappedBy="parentA")
    private Collection<B> allBs;

    @Formula("(select max(b.some_date) from B b where b.a_id = id)")
    private Date latestBDate;
}

References

*

*Hibernate Annotations Reference Guide

*

*2.4.3.1. Formula
Resources

*

*Hibernate Derived Properties - Performance and Portability

A: See,
http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Filtering.2C_Complex_Joins
Basically JPA does not support this, but some JPA providers do.
You could also,
- Make the variable transient and lazy initialize it from the OneToMany, or just provide a get method that searches the OneToMany.
- Define another foreign key to the latest.
- Remove the relationship and just query for the latest.


text:
Q: Optaplanner - HardMediumSoftScoreHolder - How do I force the solver to minimize medium score first then soft score? I'm starting to work with optaplanner in order to do a poc, and i'll figuring an issue.
I implemented hard constraints and it is ok. Do the same with a medium constraint in order to handle a nullable planning entity and it was ok.
But, i added a soft constraint, and i'm not happy with the best solution. Let me explain.
Without the soft constraint, I have a score of 0/-2/0 and it is the optimal solution according to dataset. When I'm implementing the soft constraint, I get 0/-8/-13. But for me, I would prefer to have 0/-2/-700.
How can I managed this kind of behavior? How to minimize first the medium, then take care about soft?
With real example :

*

*i would like to affect a service to a resource if and for a period.

*MediumConstraint : Count total of unassigned services to a resource

*SoftConstraint : compute delta between desirated period, and planning optimization period.

For me, I prefer assign every services (if possible) instead of optimizing the delta between preference date and the assignment.
Below, the rules
//###########################################################################
// Medium constraints
//###########################################################################
    rule "unassigned score"
        when
            accumulate( ServiceRequestAssignment(resource == null);
                                $cnt: count(1))
        then
            scoreHolder.addMediumConstraintMatch(kcontext, -toIntExact($cnt));
    end

// ############################################################################
// Soft constraints
// ############################################################################

rule "dateDeviance"
    when
        $request : ServiceRequestAssignment(fixDate != true, $dateDeviance: dateDeviance);
    then
        scoreHolder.addSoftConstraintMatch(kcontext, -toIntExact($dateDeviance));
end

Then, the config :
<constructionHeuristic>
 <constructionHeuristicType>FIRST_FIT_DECREASING</constructionHeuristicType>

       </constructionHeuristic>
    <localSearch>
        <unionMoveSelector>
            <changeMoveSelector/>
            <swapMoveSelector/>
        </unionMoveSelector>
        <acceptor>
            <lateAcceptanceSize>600</lateAcceptanceSize>
        </acceptor>
        <forager>
            <acceptedCountLimit>4</acceptedCountLimit>
        </forager>
    </localSearch>

Thank you for your help.

A: In a step, OptaPlanner will always prefer 0/-2/-700 over 0/-8/-13, just like you want.
The problem is, that due to the change in the score function, it goes down another path and it doesn't reach the same score at the same time. There could be 2 reasons

*

*The additional score constraint's reduced the "score calculation speed". Use optaplanner-benchmarker to pit them against each other and give it 10 times as much time to prove that given enough time it reaches that score too. Then figure out the bottleneck in your score constraints (score rules) and make it faster.

*It's more prone to get stuck in local optima. Add additional out-of-the-box moves or add custom moves that escape such local optima.

In any case - not adding those soft score rules is not the recommended approach. Although that could work (first solve it without the soft constraints, then solve it again with them in, starting from the previous solution), that would be a hack. The real, good, long-term solution is to just add them, see if you can make them more efficient, set up the benchmarker (it's just a few lines now) and figure out what kind of custom move could get you from 0/-8/-13 to 0/-7/-9999.

A:
I think you can make the rule get smaller medium score or get larger soft score. for example:
//###########################################################################
// Medium constraints
//###########################################################################
    rule "unassigned score"
        when
            accumulate( ServiceRequestAssignment(resource == null);
                                $cnt: count(1))
        then
            scoreHolder.addMediumConstraintMatch(kcontext, -toIntExact($cnt)*100);
    end

// ############################################################################
// Soft constraints
// ############################################################################

rule "dateDeviance"
    when
        $request : ServiceRequestAssignment(fixDate != true, $dateDeviance: dateDeviance);
    then
        scoreHolder.addSoftConstraintMatch(kcontext, -toIntExact($dateDeviance));
end

A: According to Geoffrey's comment, I've checked again my rules and detect the problem is the definition of the "dateDeviance" rule.
For the moment, I don't know how to write the rule in order to fit my goal. But it seems more related to a definition error than a bottleneck or stuck in local optima.
I would like to compute the global date deviance of entire solution and decrements the score with this value. I can compute this score from Java method, but drools is not using the @PlanningSolution (ServiceAssignmentSolution.class) but @PlanningEntity(ServiceRequestAssignment.class). So from a move, i am currently not able to compute this value.
I tried to use accumulate and sum :
rule "dateDeviance"
    when
        accumulate(ServiceRequestAssignment($dateDeviance : dateDeviance); $sum : sum($dateDeviance))
    then
        scoreHolder.addSoftConstraintMatch(kcontext, -$sum);
end

But, the score is exactly the same of my initial post 0/-8/-13.
I need to consider the best solution according to all the assignment.
Is possible to use the class annotated as @PlanningSolution in drools file? Or using maybe kcontext variable and retrieve this one in order to compute in Java-way?


text:
Q: Can't install any OS on old laptop The laptop is an Asus A4L (a4000 series, it's old...). I ran memtest, its OK (got brand new rams).
Tried following OSes so far: Win XP, Win 7, Ubuntu, Debian, all newest versions and service packs.

*

*Win XP: throws errors all the way trough install (can't read files), it gets to the desktop eventually but it's not ideal

*Win 7: black screen on boot after POST

*Ubuntu: black screen on boot after POST

*Debian: black screen on boot after POST

I would like to use Ubuntu on this laptop. Could someone recommend me an Ubuntu version that works with this laptop? Or any ideas about the black screen?
edit: Ubuntu 10.04.4 LTS started with the options menu(install, check disk, memory, etc)
After I select the live boot option, screen turns black.
edit: Ubuntu 10.04.4 LTS install ran just fine, and at the end it gave me a ton of this:
end_request: I/O error, dev sdb, sector 4007
I would guess dead HDD, but I tried it with an external HDD too, and it gave the same error after install.
edit: removed the HDD,now it boots from a live disk, I was able to get to the ubuntu 10.0.4 desktop. I tried installing ubuntu from there, to an external hdd, but on rebooting I got the same error as before:
end_request: I/O error, dev sdb, sector xxx
After booting from the external hdd, I get this error after the POST:
grub out of disk

A: Trouble shooting an install with no display is always very difficult.
However what we realistically need to determine is if the machine is booting or not.
If at all possible can you connect this machine to a local network once it's booted, then find some way of polling the network to see if anything new shows up.  You can do this with another linux based machine and tools such as Nmap.
Alternatively, if you have access to another machine, and it has a serial port on, and you can get hold of a serial to serial cable try connecting the two machines and see if anything appears on the serial port.
Most *nix based Operating Systems (Ubuntu included) will in most cases make a terminal available on serial port if one is detected at boot up.
If you fire up a serial terminal on the working machine and get a login prompt from the other machine you know your booting ok, and the issue is likely a graphics driver and / or display resolution out of range problem.
Another thing you can also try is pressing various combinations of ctrl+fkey or ctrl+alt+fkey  In most cases this will drop you to a command line and providing your install is not trying to set a strange console resolution from the boot you may actually get something usable.
UPDATE FOLLOWING OP's addition of comment stating removal of hard drive
I can only assume that you booted from a Live distro CD, in which case it sounds to me like the primary partition on your first hard drive is not marked as bootable.
If this is the case, you need to do 2 things as follows:
1) Put the internal hard drive back in, then using the laptops BIOS configuration, set the boot priority of the machine to boot first from CD/DVD then from the first hard disk.  To get into your BIOS there will be some message on your post screen that states press XXXX to enter setup.  XXXX is often the del key, or F1, F2 so on.
2) Use the disk partitioning tools on the live CD (You'll most likely need to be in rescue mode) and set the first partition on your hard disk to be bootable.
IF all is ok and there is a working OS on that drive, then you should hopefully see it start to boot, if it tries to start from CD/DVD then remove the disk from the drive and try again, or use your BIOS as previously described to change the boot order back to hard drive first.
IF the primary hard drive partition is already marked bootable, then chances are your hard drive has a damaged first few sectors.  Now this is not as bad as it sounds, you can sometimes if your lucky manage to partition around it, but you need to start getting very creative with your partitioning tool if your going to do this, it's not a job for the feint of heart.


text:
Q: Alternate solutions to querying a mysql database with 18mil+ rows Trying to query a mysql table that has over 18 million rows. All I need is a simple:
select date, url, count(*) from table
where date > '2018-01-01' and date < current_date

But it crashes after 15-20 minutes. I tried connecting to db in python using pandas module and then appending individual day's worth of data to an empty data frame. But still sitting twiddling my thumbs...
import pandas as pd
import pymysql
import time

conn = pymysql.connect(...)

result = []
for date in pd.date_range(start='01/01/2019', end=pd.to_datetime(time.strftime('%d/%m/%Y'))):
    query = ("select * from table where time >= '{}' and time < '{}'").format(date, date + pd.DateOffset(days=1))
    df = pd.read_sql(query, con=conn)
    result.append(df)
pd.concat(result,axis=0)
print(result)

What are my options in getting this data out?
Main aim is to get this data into Tableau and take it from there...

A: I started a mysql server in docker like this, just using the defaults:
docker run -d --rm --name mysql -e MYSQL_ALLOW_EMPTY_PASSWORD=true mysql

And created database like this:
docker exec -it mysql mysql -e 'create database if not exists test'

And then connect interactive session like this:
docker exec -it mysql mysql test

I then filled it with 32 million some random dates by running this...
INSERT into dates select date(from_unixtime(rand()*unix_timestamp(now())) );

and then running this a few dozen times:
INSERT into dates select date(from_unixtime(rand()*unix_timestamp(now())) ) from dates;

Now I have almost twice as many dates as you do:
mysql> explain select * from dates;
+----+-------------+-------+------------+------+---------------+------+---------+------+----------+----------+-------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows     | filtered | Extra |
+----+-------------+-------+------------+------+---------------+------+---------+------+----------+----------+-------+
|  1 | SIMPLE      | dates | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 33497947 |   100.00 | NULL  |
+----+-------------+-------+------------+------+---------------+------+---------+------+----------+----------+-------+
1 row in set, 1 warning (0.00 sec)

Finally I can demonstrate how quickly I can search through the table:
mysql>  select count(*), d from dates where d between '2001-01-01' and '2001-12-31' group by d order by d desc;
....
365 rows in set (4 min 31.17 sec)

Makes sense, there were a few thousand results for every day in 2001.  (Remember these dates are randomly distributed between 1970 - epoch - and now).
No indexes or anything and no sql tuning.  Took 4.5 minutes.  Hopefully that gives you a baseline for expectations on your server and query performance.

A: Used python to create a for loop querying and summarising a day's worth of data from the "unqueryable" table and appended it to a csv which I then connected to the BI tool. Also tried creating a new table in the db with some indexes and then for looped the same way but appending to the table.


text:
Q: Compute Taylor expansion of a vectorial function I'm not sure this question even deserves to be posted on this great forum, but I've been stuck the past 2 hours on a relatively easy thing.
Context: (in case it helps)
Im trying to study stability of Lagrangian points in a 3 body problem:

In the picture $S$ denotes the sun, $J$ Jupiter and $L_4$ the equilibrium solution for an asteroid with relatively small mass. $R$, defined as $d(S,J)$ is the length of the edges of the equilateral triangle.
Now the idea is to perturb the position of $\vec{y_4}=L_4$ hence we set $\vec{y}=\vec{y_4}+\vec{z}$ for a "small perturbation $\vec{z}"$
This is what follows ($d_i:=||\vec{y_4}-\vec{y_i}||$, for $i=S,J )$

My interpretation:
I believe this is the Taylor expansion of the function $f(\vec{y})=\frac{\vec{y}-\vec{y_i}}{||\vec{y}-\vec{y_i}||^3}$ around $\vec{y_4}$ evaluated at $\vec{y_4}+\vec{z}$
My calculations:
$ f'(\vec{y})=\frac{1}{||\vec{y}-\vec{y_i}||^3}-3\frac{\vec{y}-\vec{y_i}}{||\vec{y}-\vec{y_i}||^4} \\
f(\vec{y_4}+\vec{z})=f(\vec{y_4})+f'(\vec{y_4})\cdot \vec{z}+\mathcal{O}(\vec{z}^2) $
Clearly there are problems with my derivative (first term is a scalar unless I interpret $\vec{1}=(1,1,1)$). Although if I evaluate the derivative at $y_4$ I get an expression very similar to the one in the image, but still with mixed scalars and vectors.
I'm pretty sure there is some theory on how to handle these functions, but I have never really handled these expressions in 2 years of mathematics and I have no clue on how to fix my lack of knowledge in this context.

A: The function of concerned:
$$
\vec{s}_i = \frac{\vec{y}-\vec{y}_i}{\Vert \vec{y}-\vec{y}_i \Vert^3}
$$
where $\vec{y} =\vec{y}_4 + \vec{z}$, and $\vec{z}$ is of small magnitude to be expanded to the first order of $z$.
$$\tag{1}
\vec{s}_i = \frac{\vec{y}_4 +\vec{z} -\vec{y}_i}{\Vert \vec{y}-\vec{y}_i \Vert^3}
= \frac{\vec{y}_4 -\vec{y}_i}{\Vert \vec{y}-\vec{y}_i \Vert^3} + \frac{\vec{z} }{\Vert \vec{y}-\vec{y}_i \Vert^3} \approx \frac{\vec{y}_4 -\vec{y}_i}{\Vert \vec{y}-\vec{y}_i \Vert^3} + \frac{\vec{z} }{\Vert \vec{y}_4-\vec{y}_i \Vert^3}
$$
The second term is already of order $z$, therefore in the denominator, the $\vec{y}$ can be replaced by $\vec{y}_4$. Denote the distance $d_i \equiv \Vert\vec{y}_4 - \vec{y}_i\Vert$.
Now, the equstion is concerned about the Taylor expansion of the denominator in series of small $\vec{z}$:
$$
 f(\vec{y}_4 + \vec{z}) = f(\vec{y}_4) + \vec{\nabla}_z f\Big\vert_{\vec{z}=0} \cdot \vec{z} + \sum_{i,j} \frac{1}{2} \frac{\partial^2 f}{\partial z_i \partial z_j}\Big\vert_{\vec{z}=0} z_i z_j + ...
$$
Apply the Taylor expansion to the denominator:
$$\tag{2}
 \frac{1}{\Vert \vec{y}_4-\vec{y}_i+\vec{z} \Vert^3} =  \frac{1}{\Vert \vec{y}_4-\vec{y}_i \Vert^3} + \vec{\nabla}_z \left[\frac{1}{\Vert \vec{y}_4-\vec{y}_i+\vec{z} \Vert^3}\right]_{\vec{z}=0} \cdot \vec{z}
$$
Calculate the gradient term:
$$\tag{3}
\vec{\nabla}_z \left[\frac{1}{\Vert \vec{y}_4-\vec{y}_i+\vec{z} \Vert^3}\right] =-3 \left[\frac{1}{\Vert \vec{y}_4-\vec{y}_i+\vec{z} \Vert^4}\right] \vec{\nabla}_z \Vert \vec{y}_4-\vec{y}_i+\vec{z} \Vert \\
= -3\left[\frac{1}{\Vert \vec{y}_4-\vec{y}_i+\vec{z} \Vert^4}\right]\frac{\vec{y}_4-\vec{y}_i+\vec{z}}{\Vert\vec{y}_4-\vec{y}_i+\vec{z}\Vert}=-3\frac{\vec{y}_4-\vec{y}_i+\vec{z}}{\Vert \vec{y}_4-\vec{y}_i+\vec{z} \Vert^5}
$$
Substitue Eq.(3) with $\vec{z}= 0$ into Eq.(2)
$$\tag{4}
 \frac{1}{\Vert \vec{y}_4-\vec{y}_i+\vec{z} \Vert^3} =  \frac{1}{\Vert \vec{y}_4-\vec{y}_i \Vert^3} - 3 \frac{\left(\vec{y}_4-\vec{y}_i\right) \cdot \vec{z}}{\Vert \vec{y}_4-\vec{y}_i\Vert^5} =  \frac{1}{d_i^3} - 3 \frac{\left(\vec{y}_4-\vec{y}_i\right) \cdot \vec{z}}{d_i^5}
$$
Plug the result of Eq.(4) into Eq.(1):
$$\tag{1}
\vec{s}_i \approx \frac{1}{d_i^3}\left(\vec{y}_4-\vec{y}_i\right) - 3 \frac{\left(\vec{y}_4-\vec{y}_i\right) \cdot \vec{z}}{d_i^5} \left(\vec{y}_4-\vec{y}_i\right)+ \frac{\vec{z} }{d_i^3}
$$


text:
Q: Cannot use 'user' resource in Chef Just learning to use Chef and I cannot seem to do even basic user creation.
Here's the recipe:
user 'bob' do
  action :create
  password '$1$NSy4M315$KfqF7bX49YgJuhdJZPqbv1'
end

And the error:
sudo chef-solo -c recipes/bob.rb
[2017-04-13T11:05:41-07:00] FATAL: Configuration error NoMethodError: undefined method `action' for nil:NilClass
[2017-04-13T11:05:41-07:00] FATAL:   /home/nicholas/dev/vagrant/current/akm/recipes/bob.rb:2:in `block in from_string'
[2017-04-13T11:05:41-07:00] FATAL:   /home/nicholas/dev/vagrant/current/akm/recipes/bob.rb:1:in `from_string'
[2017-04-13T11:05:41-07:00] FATAL: Aborting due to error in '/home/nicholas/dev/vagrant/current/akm/recipes/bob.rb'

I added depends 'user' to metadata.rb, but no success.

A: The -c flag to chef-solo (and all Chef commands) sets the path to the config file. You are trying to run a recipe, not set up a Chef config file.
You probably want something like chef-apply recipes/bob.rb for one-off learning experiments or something like chef-solo --option chef_repo_root=. -r recipe[cookbookname] for more production-y usage.


text:
Q: Xamarin set content view width to root view I'm using Xamarin Auto Layouts with Storyboard on Visual Studio 2015.
I have a root view, Scroll View and Content View.
I want the application to only scroll on the y-axis but scale on the x-axis.
I want to do something like this.
Adding a view to a scroll view that will stretch to fill available width
Which is setting the width of the content view to the root view.
But using Xamarin this does not seem possible.

So in this example, if I run the application, I have to scroll to the right to see the right most label. I want all three labels to show up on the iPhone, by scaling down on the x-axis.
I have also tried using the "I" handle on the content view in storyboard UI Designer of Xamarin VS, but it doesn't identify the root view.
If it's not possible using storyboard, I will settle with code.
I have tried this.
    public override void ViewDidLoad()
    {

        ContentView.Frame = new CoreGraphics.CGRect(ContentView.Frame.X, ContentView.Frame.Y, View.Frame.Width, ContentView.Frame.Height);
        //ScrollView.TranslatesAutoresizingMaskIntoConstraints = false;
        base.ViewDidLoad();

        // Perform any additional setup after loading the view, typically from a nib.
    }

But it doesn't do anything to help me.
How can I scale the UI down on the X-axis while on top of a scroll view using Xamarin.ios?


text:
Q: c# Json Serialization Required Fields I am using the inbuilt DataContractJsonSerializer to prepare data for transmission.
I am Serializing from a business object using the following code:
private string SerialiseRequest(RegistrationRequest request)
        {
            string strRequest = string.Empty;

            try
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(request.GetType());

                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, request);
                    strRequest = Encoding.Default.GetString(ms.ToArray());
                }
            }
            catch
            {
                return string.Empty;
            }

            return strRequest;
        }

When the data is serialized, it seems to be ignoring the settings, the most important setting is IsRequired, as I do not want to transmit a field if it doesnt contain data. Here is how I have the Business Object Defined:
 [DataContract]
    public sealed class RegistrationRequest
    {
        [DataMember(Order = 0, IsRequired = true)]
        public Registration_Header registration_header { get; set; }

        [DataMember(Order = 1, IsRequired = true)]
        public Customer_Details primary_user { get; set; }

        [DataMember(Order = 2, IsRequired = true)]
        public StaffDetails partner_attributes { get; set; }

        [DataMember(Order = 3, IsRequired = true)]
        public CustomerAddress primary_residential_address { get; set; }

        public class Registration_Header
        {
            [DataMember(Order = 0, IsRequired = true)]
            public string services_required { get; set; }

            [DataMember(Order = 1, IsRequired = true)]
            public string account_type { get; set; }

            [DataMember(Order = 2, IsRequired = true)]
            public string affiliate_number { get; set; }
        }

        public class Customer_Details
        {
            [DataMember(IsRequired = true)]
            public string title { get; set; }

            [DataMember(IsRequired = true)]
            public string first_name { get; set; }

            [DataMember(IsRequired = false)]
            public string middle_name { get; set; }

            [DataMember(IsRequired = true)]
            public string last_name { get; set; }

            [DataMember(IsRequired = true)]
            public string email { get; set; }

            [DataMember(IsRequired = true)]
            public string nationality { get; set; }

            [DataMember(IsRequired = true)]
            public string dob { get; set; }

            [DataMember(IsRequired = true)]
            public string occupation { get; set; }

            [DataMember(IsRequired = true)]
            public string residence_country { get; set; }

            [DataMember(IsRequired = true)]
            public string mobile_number { get; set; }

            [DataMember(IsRequired = false)]
            public string landline_number { get; set; }

            [DataMember(IsRequired = true)]
            public string source { get; set; }
        }

        public class StaffDetails
        {
            [DataMember(IsRequired = true)]
            public string reps_name { get; set; }

            [DataMember(IsRequired = true)]
            public string reps_location { get; set; }

            [DataMember(IsRequired = true)]
            public string customer_id { get; set; }
        }

        public class CustomerAddress
        {
            [DataMember(IsRequired = true)]
            public string postcode { get; set; }

            [DataMember(IsRequired = true)]
            public string street_or_address { get; set; }

            [DataMember(Name = "city", IsRequired = true)]
            public string city { get; set; }

            [DataMember(Name = "country", IsRequired = true)]
            public string country { get; set; }
        }

Here is a sample of the Serialized data that I am getting back from 'SerialiseRequest' Method:

{"registration_header":{"account_type":"Single","affiliate_number":"A061535","services_required":"Transfers"},
  "primary_user":{"dob":"23-10-1989","email":"k@gale","first_name":"Kathy","landline_number":"","last_name":"Gale","middle_name":"","mobile_number":"+44-79879879879","nationality":"UK","occupation":"Farmer","residence_country":"UK","source":"Other","title":"Miss"},
  "partner_attributes":{"customer_id":"273098","reps_location":"Stockton-North
  East UK","reps_name":"Richard Gale-551"},
  "primary_residential_address":{"city":"Larkhall","country":"UK","postcode":"ML9
  2LS","street_or_address":"1 The Street"}}

A: You can use the [DataMember(EmitDefaultValue = false)] attribute.
[DataContract]
public sealed class RegistrationRequest
{
    [DataMember(Order = 0, IsRequired = true)]
    public Registration_Header registration_header { get; set; }

    [DataMember(Order = 1, IsRequired = true)]
    public Customer_Details primary_user { get; set; }

    [DataMember(Order = 2, IsRequired = true)]
    public StaffDetails partner_attributes { get; set; }

    [DataMember(Order = 3, IsRequired = true)]
    public CustomerAddress primary_residential_address { get; set; }

    public class Registration_Header
    {
        [DataMember(Order = 0, IsRequired = true)]
        public string services_required { get; set; }

        [DataMember(Order = 1, IsRequired = true)]
        public string account_type { get; set; }

        [DataMember(Order = 2, IsRequired = true)]
        public string affiliate_number { get; set; }
    }

    [DataContract]
    public class Customer_Details
    {
        [DataMember(IsRequired = true)]
        public string title { get; set; }

        [DataMember(IsRequired = true)]
        public string first_name { get; set; }

        [DataMember(EmitDefaultValue = false)]
        public string middle_name { get; set; }

        [DataMember(IsRequired = true)]
        public string last_name { get; set; }

        [DataMember(IsRequired = true)]
        public string email { get; set; }

        [DataMember(IsRequired = true)]
        public string nationality { get; set; }

        [DataMember(IsRequired = true)]
        public string dob { get; set; }

        [DataMember(IsRequired = true)]
        public string occupation { get; set; }

        [DataMember(IsRequired = true)]
        public string residence_country { get; set; }

        [DataMember(IsRequired = true)]
        public string mobile_number { get; set; }

        [DataMember(EmitDefaultValue = false)]
        public string landline_number { get; set; }

        [DataMember(IsRequired = true)]
        public string source { get; set; }
    }

    public class StaffDetails
    {
        [DataMember(IsRequired = true)]
        public string reps_name { get; set; }

        [DataMember(IsRequired = true)]
        public string reps_location { get; set; }

        [DataMember(IsRequired = true)]
        public string customer_id { get; set; }
    }

    public class CustomerAddress
    {
        [DataMember(IsRequired = true)]
        public string postcode { get; set; }

        [DataMember(IsRequired = true)]
        public string street_or_address { get; set; }

        [DataMember(Name = "city", IsRequired = true)]
        public string city { get; set; }

        [DataMember(Name = "country", IsRequired = true)]
        public string country { get; set; }
    }
}

Also notice that you have to decorate the Customer_Details class with [DataContract] for it to take effect.

A: The Serializer is only going to serialize the data in the object.  It won't carry the decorations on the class.  The IsRequired attribute will trigger when the DataContract is sent back to the service.


text:
Q: Pandas select closest date in past Being a beginner with pandas, I wonder how I can select the closest date in the past? E.g. I  have a dataframe as follows:
               Terminart                        Info     Datum  Ergebnis
0       Hauptversammlung                         NaN  22.06.16       NaN
1        Jahresabschluss                        2015  10.03.16       NaN
2         Quartalszahlen                     Q3 2015  28.10.15       NaN
3         Quartalszahlen                     Q2 2015  29.07.15       NaN
4       Hauptversammlung                         NaN  05.05.15       NaN
5         Quartalszahlen                     Q1 2015  29.04.15       NaN
6  Bilanzpressekonferenz                        2014  12.03.15       NaN
7  Bilanzpressekonferenz  Jahrespressekonferenz 2015  12.03.15       NaN

I can select the Terminart with df.loc(), ie:

df.loc[df['Terminart'] == 'Hauptversammlung']

selects only two rows (which is correct).

However, how can I select the closest date in the past? It would be the first row (06/22/16) here? The dataframe is not ordered by default.

A: You can convert to_datetime column Datum and then first filter lower as no difference (timedelta=0) and then find index of max value by idxmax:
Notice : In sample is changed last datetime for better testing
import pandas as pd
import datetime as dt

print (df)
                                     Terminart     Info     Datum  Ergebnis
0                             Hauptversammlung      NaN  22.06.16       NaN
1                              Jahresabschluss     2015  10.03.16       NaN
2                               Quartalszahlen  Q3 2015  28.10.15       NaN
3                               Quartalszahlen  Q2 2015  29.07.15       NaN
4                             Hauptversammlung      NaN  05.05.15       NaN
5                               Quartalszahlen  Q1 2015  29.04.15       NaN
6                        Bilanzpressekonferenz     2014  12.03.15       NaN
7  Bilanzpressekonferenz Jahrespressekonferenz     2015  19.07.16       NaN

df['Datum'] = pd.to_datetime(df.Datum, format='%d.%m.%y')

date = dt.datetime.now().date()
print (date)
2016-07-17

diff = (df.Datum - date)
print (diff)
0    -25 days
1   -129 days
2   -263 days
3   -354 days
4   -439 days
5   -445 days
6   -493 days
7      2 days
Name: Datum, dtype: timedelta64[ns]

indexmax = (diff[(diff < pd.to_timedelta(0))].idxmax())

print (df.ix[[indexmax]])
          Terminart Info      Datum  Ergebnis
0  Hauptversammlung  NaN 2016-06-22       NaN

A: First you convert your column 'Datum' to a date field with to_datetime() then you can just sort your dataframe by date with sort_values() and then print out the first row:
df['Datum'] = pd.to_datetime(df['Datum'], format='%d.%m.%y')
df.sort_values('Datum')
print(df.iloc[0])


text:
Q: Average squared distance between two points on a disk I want to calculate the average distance between two points in D = $\left \{(x,y) \in R^2 / x^2 + y^2 \leq 1\right \}$, I thought that I could use the integral formula: $\frac{1}{m(D)^2} \cdot \int \int_D \int \int_D (x_1 - x_2)^2 + (y_1 - y_2)^2 dx_1 dy_1 dx_2 dy_2$ but I can't find a suitable change of variables to solve this integral. (m(D) is the Lebesgue measure of D)

A: Use the (squared) law of cosines $d^2 = r_1^2 + r_2^2 - r_1 r_2 \cos \theta$, if we integrate over $\theta$, the $\cos \theta$ term vanishes (as pointed out by @J.G):
$$\frac{\int\limits_{r_1 = 0}^1 \int\limits_{r_2 = 0}^1  r_1 r_2 (r_1^2 + r_2^2 )\ dr_1\ dr_2}{\int\limits_{r_1 = 0}^1 \int\limits_{r_2 = 0}^1 r_1 r_2 dr_1\ dr_2} = 1$$

where the denominator is for normalization.

A: Since $\cos\theta$ averages to $0$, @DavidG.Stork's approach simplifies to the mean squared distnce being$$\frac{\int_{[0,\,1]^2}r_1r_2(r_1^2+r_2^2)dr_1dr_2}{\int_{[0,\,1]^2}r_1r_2dr_1dr_2}=2\frac{\int_{[0,\,1]^2}r_1^3r_2dr_1dr_2}{\int_{[0,\,1]^2}r_1r_2dr_1dr_2}=2\frac{\int_0^1r_1^3dr_1}{\int_0^1r_1dr_1}=1.$$We can verify this with random points, as long as we remember $r^2,\,\frac{\theta}{2\pi}$ are $U(0,\,1)$ IIDs for a uniform probability density in the circle's interior.


text:
Q: Can't inject HTML into body without loosing everything So I'm trying to call a JS function to append a few divs into the body
When I do getElementById, I can't add to body, so this is usually basically.
document.getElementById('advertisingBrandValues').innerHTML = "Test"

And when I do
document.body.innerHTML = "Test"

ALL the HTML is replaced with that one element. I need to add new elements to the body, not replace the whole thing. Any ideas?

A: To add to the bottom:
document.body.innerHTML += "Test"

To add to the top:
document.body.innerHTML = "Test" + document.body.innerHTML


text:
Q: Change 1 data-value without changing all the three My goal with the code is to when data-isChar is true the locationsSelect is going to show only when the button on the box where it is set to true
Right now I only get that when i click SPELA and the data-isChar="true" it appears on all the boxes
I'm really new to coding and searched on the internet and not found anything of the things i noted above so this is my only try to this project
(BOOTSTRAP 4, JQUERY)

Tom karaktär

Skapa en ny karaktär

                            <button id="play-char" class="btn btn-success" data-target="#locationSelect">SPELA</button>
                            <button id="delete" class="btn btn-danger">RADERA</button>

Tom karaktär

Skapa en ny karaktär

                        <button id="play-char" class="btn btn-success" data-target="#locationSelect">SPELA</button>
                        <button id="delete" class="btn btn-danger">RADERA</button>

Tom karaktär

Skapa en ny karaktär

                        <button id="play-char" class="btn btn-success" data-target="#locationSelect">SPELA</button>
                        <button id="delete" class="btn btn-danger">RADERA</button>

    $(".buttons #play-char").click(function() {
        if ($(".col").attr("data-isChar") === "false") {
            $(this).attr("data-target", "#createModal")
            $("#createModal").modal("show")
        } else {
            $("#locationSelect").modal("show")
        }
    })


text:
Q: Change visibility of attribute field/group of field in one layer based on checkbox or value map - QGIS i'm using QGIS 2.18.3, in Win 7.
i want to know how to make attribute field or group of fields become visible or invisible based on value of other field

on picture above, i want to make my grup field "info" (red rectang) appear and disappear depend on value in my "status" field (blue rectang), either checkbox or value map.

A: Did you find any solution?
Possible solution, on Drag and Drop Designer, define a group container. Double click on the group container an define the Control visibility by expression to show only when your Status field is checked


text:
Q: Get difference with previous value and with next value I have a dataframe like this. A small sample actually the df is bigger:
LOW   1  4  NA
MID   3  4  4
HIG   2  5  4

And would like to get the difference for LOW and HIG with MID so the ending df would be like this:
LOW   2  0  NA
MID   3  4  4
HIG   1  1  0

So you're getting: LOW = 3 - 1 = 2 and HIG = 3 - 2 = 1. I cand do it via VBA macros but want to scale with R.

A: It can be done with mutate_if/mutate_at
library(dplyr)
df1 %>%
   mutate_if(is.numeric, ~ case_when(grp != 'MID' ~
         abs(. - .[grp == 'MID']), TRUE ~ .))
#   grp v1 v2 v3
#1 LOW  2  0 NA
#2 MID  3  4  4
#3 HIG  1  1  0

Or in base R
i1 <- df1$grp == 'MID'
df1[!i1, -1] <- abs(df1[!i1, -1] - rep(unlist(df1[i1, -1]), each = sum(!i1)))

data
df1 <- structure(list(grp = c("LOW", "MID", "HIG"), v1 = c(1L, 3L, 2L
), v2 = c(4L, 4L, 5L), v3 = c(NA, 4L, 4L)), class = "data.frame", row.names = c(NA,
-3L))

A: You can change the 'LOW', 'HIG' rows after subtracting by 'MID' :
df1[df1$grp == 'LOW', -1] <- abs(df1[df1$grp == 'MID',-1]- df1[df1$grp == 'LOW',-1])
df1[df1$grp == 'HIG', -1] <- abs(df1[df1$grp == 'MID',-1]- df1[df1$grp == 'HIG',-1])

df1
#  grp v1 v2 v3
#1 LOW  2  0 NA
#2 MID  3  4  4
#3 HIG  1  1  0


text:
Q: How to cleanly restart a WCF under new address? I have a WPF C# application hosting a WCF service. I have a routine to start the service, closing it if it already exists. WebServce is a property of type ServiceHost:
public void Start()
{
    try
    {

    var certificate = new X509Certificate2(certpath, "");

    String uri = "net.tcp://" + WCFAddress + "/MyService";
    Uri baseaddress = new Uri(uri);

    if (WebService != null) {
      try {
        WebService.Close();
      } catch (Exception) {
        WebService.Abort();
      }
    }

    WebService = new ServiceHost(MessageProvider, baseaddress);
    WebService.Credentials.ServiceCertificate.Certificate = certificate;
    WebService.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;

    NetTcpBinding binding = new NetTcpBinding();
    binding.Security.Mode = SecurityMode.Message;
    binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
    binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;
    WebService.AddServiceEndpoint(typeof(IMessageService), binding, baseaddress);

    WebService.Open();
    }
    catch (Exception e)
    {
        //exception handling
    }
}

This works fine on startup. It also works fine if I change the port number (in WCFAddress) and call the routine again. It also works if I change the address on the host computer and call it with the new IP address. However, if I change the IP address to an invalid one, the service goes into a Faulted state with the error:

e = {"A TCP error (10049: The requested address is not valid in its context) occurred while listening on IP Endpoint=192.168.1.4:5000."}

The Close() call in the above doesn't raise an exception.
If I then change the IP address to the correct one and call again, I get the same error, with the same old incorrect address, even though I passed it the correct one. Also this time the Close() call raises an error due to the Faulted state, which results in the Abort() call.
I thought the Abort() call would allow the service to then be recreated? Why is it giving me an error about the old address when I'm trying to create the service with a new one? It's like it's hanging onto the old ServiceEndpoint?

A: Abort(). Then just initiate a new instance with the new address.. then Open().


text:
Q: texthero scatterplot using pca and kmenas I am trying to do clustering for words and I already calculated pca and k mean using texthero.
This is my dataframe.

I want to use scatterplot for this but I get nothing, just blank. Am i missing something?

A: texthero uses plotly to render the plot, so chances are your renderer is set up properly inside the notebook you are using. You can try to update your plotly installation and also check the help page for plotly (https://plotly.com/python/renderers/) on how to display the plot.
You can see your choices of rendering with:
import plotly.io as pio
pio.renderers

If I use an example dataset, it works:
import texthero as hero
import pandas as pd
df = pd.read_csv(
    "https://github.com/jbesomi/texthero/raw/master/dataset/bbcsport.csv"
)
df['text'] = hero.clean(df['text'])
df['tfidf'] = (
    hero.tfidf(df['text'], max_features=100)
)
df['pca'] = hero.pca(df['tfidf'])
df['kmeans'] = hero.kmeans(df['tfidf'])
df['label'] = pd.Categorical(df['kmeans'],
                  categories=df['kmeans'].sort_values().unique())

You can plot with:
hero.scatterplot(df,col='pca',color = 'label',return_figure=True)

I am using jupyter notebook so you can also do:
fig = hero.scatterplot(df,col='pca',color = 'label',return_figure=True)
fig.show(renderer="notebook")


text:
Q: How can I reload ReCaptcha control after custom validation? I have ReCaptcha control on my registration form:
<recaptcha:RecaptchaControl ID="ReCaptcha" runat="server" PublicKey="<%$ appSettings:ReCaptchaPublicKey %>" PrivateKey="<%$ appSettings:ReCaptchaPrivateKey %>" Theme="white" />
<asp:CustomValidator ID="ReCaptchaCustomValidator" runat="server" ErrorMessage="ReCaptcha error message." Display="None" ValidationGroup="Step1" EnableClientScript="true" OnServerValidate="ReCaptcha_ServerValidate" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode="List" ValidationGroup="Step1" CssClass="validationSummary" />

CodeBehind
protected void ReCaptcha_ServerValidate(object source, ServerValidateEventArgs e)
    {
        ReCaptcha.Validate();

        if (ReCaptcha.IsValid)
            e.IsValid = true;

        else
            e.IsValid = false;
    }

If user enter ReCaptcha value not properly, ReCaptcha control disappear after server-side validation.
How can I reload it after validation?

A: protected void Page_PreRender(object sender, EventArgs e)
{
CaptchaControl1.Enabled = true;
}


text:
Q: Stream results in celery I'm trying to use celery to schedule and run tasks on a fleet of servers. Each task is somewhat long running (few hours), and involves using subprocess to call a certain program with the given inputs. This program produces a lot of output both in stdout and stderr.
Is there some way to show the output produced by the program to the client in near real time? Stream the output, so that the client can watch the output spewed by the task running on the server without logging into the server?

A: The one way I see how to do it is to write custom Logger which will be used for stderr and stdout (see the docs:
from celery.app.log import Logger
Logger.redirect_stdouts_to_logger(MyLogger())

Your logger can save the data into the database, Memcached, Redis or whatever shared storage you'll use to get the data.
I'm not sure about the structure of the logger, but I guess something like this will work:
from logging import Logger

class MyLogger(Logger):
    def log(lvl, msg):
        # Do something with the message

A: This is an old question but it's still pretty much the only result about this specific topic.
Here's how I went about it,
I created a simple file-like object that publishes to a specific channel over Redis
class RedisFileObject(object):
    def __init__(self, _key):
        self.connection = redis.Redis()
        self.key = _key
        self.connection.publish('debug', 'Created channel %s' % self.key)

    def write(self, data):
        self.connection.publish(self.key, data)

    def close(self):
        pass

I have a BaseTask from which all of my tasks inherits various functions incl. this one that replaces stdout and stderr with the Redis file-like object.
def capture_output(self):
    sys.stdout = RedisFileObject(self.request.id)
    sys.stderr = RedisFileObject(self.request.id)

From there on anything written to stdout/stderr will be forwarded to a Redis channel named after the task id.

A: You did not specify many requirements and constraints. I'm going to assume you already have a redis instance somewhere.
What you can do is read the output from the other process line by line and publish it through redis:
Here's an example where you can echo data into a file /tmp/foo for testing:
import redis
redis_instance = redis.Redis()
p = subprocess.Popen(shlex.split("tail -f /tmp/foo"), stdout=subprocess.PIPE)

while True:
    line = p.stdout.readline()
    if line:
        redis_instance.publish('process log', line)
    else:
        break

In a separate process:
import redis

redis_instance = redis.Redis()
pubsub = redis_instance.pubsub()
pubsub.subscribe('process log')

while True:
    for message in pubsub.listen():
        print message  #  or use websockets to comunicate with a browser

If you want the process to end, you can e.g. send a "quit" after the celery task is done.
You can use different channels (the string in subscribe) to separate the output from different processes.
You can also store your log output in redis, if you want to,
redis_instance.rpush('process log', message)

and later retrieve it in full.


text:
Q: Borrar un registro de una base de datos en Oracle Disculpen si la pregunta es tonta; pero soy nueva en base de datos y quisiera saber si me pueden apoyar, por favor. Mi duda es que tengo una base de datos en Oracle llamada (Empresa) con tablas no relacionales, en ellas manejo folios de personas y tengo distintas tablas como: datos_generales, ocupacion, salud, estudios, etc. Cada que me piden borrar un registro lo hago así:
DELETE FROM ocupacion WHERE folio=542;

Pero, ¿me gustaría saber sí es posible borrar el registro de todas las tablas de la base de datos en una sola consulta? En total tengo 40 tablas.

A: Todo depende de como te hayan creado tu base de datos o tu modelo de entidad relacion, me explico: Si esta relacionada o tienes constraints la cuestion se hace mas civilizada.
Si te crearon los constraint asi:
alter table sample1
   add foreign key (col1)
references
   sample (col2)
on delete cascade;

Si no lo tienes relacionad, el proceso tienes que hacer manualmente. Yo te recomiendo hacer un procedimiento y meter todas las tablas alli que deseas borrar de esta manera al momento de ejecutar el procedimiento borras todo de un solo golpe (como se dice coloquialmente en mi pais) esto puede ser un ejemplo sencillo:
create or replace procedure borrado_folio (p_folio IN varchar2)
is
Begin
delete from empresa.datos_generales where folio=p_folio;
delete from empresa.ocupacion where folio=p_folio;
delete from empresa.estudioswhere folio=p_folio;
//todas los datos de las tablas que vayas a borrar
end;
/

De esta forma creo, a mi parecer, te repito si no la tienes relacionada seria la mejor manera a mi parecer y te quitas eso de la borradera.

A: Podrías con un delete inner join así:
DELETE FROM tabla1
INNER JOIN tabla2 ON tabla1.id= tabla2.id
INNER JOIN tabla3 ON tabla1.id= tabla3.id
.
.
.
WHERE tabla1.id = 1;

Luego si tienes mas tablas solo tendrías que agregarlas como otros inner join