text:
Q: ODBC PDO returning 'No data received' I'm using CentOS 6.5 to create a PDO ODBC connection to a Microsoft Access .mdb file through PHP.
I'm using MDBTools and unixODBC.
My odbcinst.ini looks like this
[MDBToolsODBC]
Description=MDBTools Driver
Driver=/usr/lib64/libmdbodbc.so.0.0.0
FileUseage=1
Threading=1

My odbc.ini looks like this
[dashboard]
Description = Dashboard
Driver = MDBToolsODBC
Servername = localhost
Database = /mnt/inetpub/databases/dashboard.mdb
Username =
Password =

I am trying to connect through PHP like so
$db = new PDO("odbc:DRIVER=MDBToolsODBC;DSN=dashboard;");

After hours of getting error messages, I've finally been able to solve them all, but now when I try to connect, Google Chrome says
No data received
Unable to load the webpage because the server sent no data.
Error code: ERR_EMPTY_RESPONSE

I'm not sure if this is because of my DSN set up or not. When I do a isql dashboard I get
+----------------------------------+
| Connected!                       |
|                                  |
| sql-statement                    |
| help [tablename]                 |
| quit                             |
|                                  |
+----------------------------------+

Not sure how to go about resolving this as this is my first time using any form of linux.
Here is how I'm trying to call up the information from the database.
In files that need database information, I use
<?php
    include("inc/config.php");
?>

Commenting out the connection string
//$db = new PDO("odbc:DRIVER=MDBToolsODBC;DSN=dashboard;");

allows the HTML and CSS to load, but of course no data from the database is pulled. This is what makes me think there is an issue with the connection string of some sort.
I'm trying to perform a simple SQL query like so, which is a much more simple query than the ones I need to run and use in my development but if I can get something simple like this to work I can figure out the rest.
$problems = $db->prepare("SELECT problems.id FROM problems;");
$problems->execute();
$result = $problems->fetchColumn();
echo $result;

EDIT: I have identified that there is a 'Segmentation Fault' in the table I am trying to query. Other tables appear to be working fine!

A: I did a quick search for your query and found this:
http://www.wix.com/support/html5/ugc/1f678e95-c707-45c8-90ca-86a48ee98a38/2d8fe37b-cc02-4582-97da-9a93d5426a55
I think you might want to clear your browser cache/try a different browser.
The other option is to try it through the command line# php /your/script/path and see if it runs successfully that way.

A: The whole point of the datasource is that you store your configuration in odbc.ini.
try{
    $db = new PDO("odbc:dashboard");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex){
     echo 'Connection failed: ' . $e->getMessage();
     die(var_dump($ex));
}

Should be enough , if it does not work you need to get errors, read the errors and fix, the command works, so put the username and password in odbc.ini and give it a try

Also username and password are parameters to the PDO constructor, you can try connecting by specifying everything:
try {
    $db = new PDO("odbc:dashboard", $username, $password, array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
    );
}
catch(PDOException $ex){
     echo 'Connection failed: ' . $e->getMessage();
     die(var_dump($ex));
}


text:
Q: Is it possible to store unique_ptr in a QList of QPairs? To avoid a lot of unnecessary copying I'm trying to store unique_ptr's in a list of pairs. I'm using a simple class Test which takes a QString;
I'm using VS2013 with Qt5.4
using std::unique_ptr;

QList<QPair<unique_ptr<Test>, unique_ptr<Test>>> list;

auto a = std::make_unique<Test>("a");
auto b = std::make_unique<Test>("b");

// First make a pair
auto pair = qMakePair(std::move(a), std::move(b));      // Fails
// Error C2280 - attempting to reference a deleted function

Because of failure I tried:
QList<std::pair<unique_ptr<Test>, unique_ptr<Test>>> list;
auto pair = std::make_pair(std::move(a), std::move(b)); // Succes
list.append(std::move(pair)); // Fails
// Error C2280 - attempting to reference a deleted function

Because of failure I changed completely to STL containters:
std::list<std::pair<unique_ptr<Test>, unique_ptr<Test>>> list;
auto pair = make_pair(std::move(a), std::move(b)); // Succes
list.push_back(std::move(pair)); // Succes

This works. Is my conclusion correct that these Qt containers don't support move semantics and I have to use STL instead?

A: std::unique_ptr is not copyable, so nope for Qt containers.
Qt containers where created way before std::move (or even std::string) became a thing.
Maybe there will be better support in Qt6. It is poised to break a few things to integrate better with modern C++.
OTOH, you might as well use the std-containers if they work for you, unless you had some specific use case in mind?

redpajama_set_name: RedPajamaStackExchange


text:
Q: variable declaration with two const Good evening,
a new evening a new question :D
May you know what i've not understood here,
in the declaration is a 2nd const,
i've no idea what is the difference between them.
When i run the code it sounds both nice.
void theStrlnMethod() {
//TODO why need i to add const two times here? :D
const char* const TEXT1 = "123";
std::cout << TEXT1 << "\nenthält " << strlen(TEXT1) << " Zeichen\n";

//TODO does that also work without the 2nd const?
const char* TEXT_JUST_ONE_CONST = "123";
std::cout << TEXT_JUST_ONE_CONST << "\nenthält " << strlen(TEXT_JUST_ONE_CONST) << " Zeichen\n";
}

output:
123
enthõlt 3 Zeichen
123
enthõlt 3 Zeichen

A: A constant pointer to a constant character array: you cant' change neither the pointer, nor the stuff pointed to.
In the second case you could (but are not compelled to) modify TEXT_JUST_ONE_CONST i.e. make TEXT_JUST_ONE_CONST point to other memory.
(Sorry, I didn't notice it's a duplicate)


text:
Q: Performance issues in iPhone game using HTML and JS, with appMobi I'm making my first game with appMobi after creating some games for Android using Java.
I basically intend to create a endless runner arcade game, 2d, top view.
I'm using appMobi with plain JS and CSS3 (without any other library such as Impact).
I started by doing some tests with canvas and created a very simple demo where you control a ball (basically a circle rendered using canvas) with the accelerometer and need to collect other balls. I've tested it with my Galaxy S2, and an iPhone 4 and it looked like the iPhone ran it much better, so I started writing a simple engine to use dom elements instead.
I basically created an object that connects to a  tag, and holds a position vector, also added a draw function that basically does the following: this.element.style.left=x+'px' (and the same for top and y).
On my main loop i've called the draw function on the objects and updated their location according to my game logic, and re-called the mainLoop using this window.requestAnimationFrame wrapper:
window.requestAnimFrame = (function(){
       return  window.requestAnimationFrame       ||
              window.webkitRequestAnimationFrame ||
              window.mozRequestAnimationFrame    ||
              window.oRequestAnimationFrame      ||
              window.msRequestAnimationFrame     ||
              function( callback ){
                window.setTimeout(callback, 1000 / 60);
              };
    })();

Then I moved on to creating a camera object to control screen positioning and made it successfully scroll the background using css background-position property.
I've tested it with my new Galaxy s3 and with a s2 with some graphics on (2 200x200 pngs, and a background) and everything ran smooth at ~60 fps.
I was very pleased with the results and really got excited to test on an iPhone 4 iOS 4.x , but to my disappointment it ran at 2-3 FPS ! 30 times slower than my android.
I started making a lot of changes (currently I'm using a viewport of 720x1280) so I've tried using 320*480, using canvas instead, removing scrolling background, resizing images, but to no avail, while the android performed well on all variations.
Best I got was 5 FPS. I got another iPhone to test, an iPhone 4S with iOS5 and got very very unstable FPS. ranged from 3 - 50 but was unplayable - no chances anyone would play it, and I've not even started to pack it with content.
I really want to take advantage of cross-platforming and it would be a shame for me to give up on the Apple market, so any tips or advise will be warmly received!
Thanks,
Gabriel

A: This is the answer I got on appMobi's forums, if anyone has this issue:

Use Direct Canvas
JS/CSS3 will perform horrible on every device, no matter what. The
  stock browser in iOS (Safari) has NitroJS enabled, but not in the
  UIWebView...but if you have the time, read up and you'll see that you
  can't write a JS game without tapping into hardware acceleration like
  Direct Canvas.

A: Find some samples and links to get you started with directCanvas here:
http://www.appmobi.com/documentation/index.php?DOC=DIRECTCANVAS_SDK


text:
Q: Android onAttach - Passing value from JSON data I have a JSON data to be parsed by JSON request in a ListFragment A. That did well. This is how part of my JSON look like:
[
  {
    "id": "17",
    "name": "Accessories",
    "slug": "accessories",
    "count": "630",
    "child": [
      {
        "id": "371",
        "name": "Belt",
        "slug": "belt",
        "count": "15"
      }
    ]
  },

Right now, I'm trying to make another ListFragment B that shows the detail of category. So I have to pass the id from this JSON to ListFragment B.
I'm using an interface to communicate between fragments. I've done that as well.
The problem is how do I pull out the id and attach it to the main activity to be used in ListFragment B?
This is the code snippet when an item in A is pressed. I'm passing a String variable to main activity:
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    try{
        mListener = (OnCategorySelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + "Must implement OnCategorySelectedListener");
    }
};

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    //Toast.makeText(getActivity(), "category id: " + id, Toast.LENGTH_SHORT).show();
    String category_id = id+"";
    mListener.onCategorySelected(category_id);
}

Above is just an example to see if it works. This is a method I used for parsing JSON (using Volley):
private void parseJSON(JSONArray json) {
    if (json != null) {
        try {
            // JSONObject value = json.getJSONObject("value");
            // JSONArray categories = json.getJSONArray(TAG_CHILD);
            // categories = new JSONArray(json);
            for (int i = 0; i < json.length(); i++) {
                JSONObject category = json.getJSONObject(i);

                CategoryModel cm = new CategoryModel();
                // cm.setTitle(category.optString(TAG_TITLE));
                // cm.setCount(category.optString(TAG_COUNT));
                cm.setCategoryId(category
                        .getString(Constants.TAG_CATEGORY_ID));
                cm.setTitle(category
                        .getString(Constants.TAG_CATEGORY_TITLE));
                cm.setCount(category
                        .getString(Constants.TAG_CATEGORY_COUNT));

                arrCategory.add(cm);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        Log.d("Categories: ", "null");
    }
}

How do I get the CATEGORY_ID and put it in a String variable? If I create a String variable in the loop, it will only store the last value of the id. How do make so that it stores the id correspondingly to the item in the list? I hope that makes sense.
Please let me know if anything confusing.


text:
Q: Is it possible to set up split tunneling in AnyConnect Secure Mobility Client on Mac OS X? I don't find a way to set up split tunneling.
I basically need to use VPN to access certain websites behind a firewall and not to use VPN for anything not in the firewall. With Cisco AnyConnect Secure Mobility Client, I can either use the VPN or not to use it. I don't see a way to set for what domains and IP addresses to use VPN and for what domains and IP addresses not to use VPN.
It seems that my Cisco AnyConnect Secure Mobility Client is a customized version by my administrator (I am not quite sure. Can an administrator customize the software so that it will disable split tunneling?)
In that case, is there no way to set up split tunneling on Mac OS X while the VPN is on?

A: You will need to talk to your network administrator.  The split tunneling feature is configured on the security appliance (Cisco ASA presumably), not on the AnyConnect client side.
When you are connect to the VPN either Cisco AnyConnect chooses to either (a) route all your traffic through the tunnel, or (b) split only traffic destined for networks on the other end of the tunnel.
There is an AnyConnect option on the client side to "Allow Local LAN Access", but this only allows your computer to see other devices, such as printers and whatnot, on your LAN (but not beyond).
Unless your network admin(s) want to create a custom connection for you with split tunneling, all traffic normally routed to your internet gateway will be sent through the tunnel.  The rationale is that your network admins can filter / protect your web traffic to reduce an attack vector .. versus allowing you to connect insecurely to the internet at large while at the same time being connected as a remote node to the secure corp network.  This creates a serious security vulnerability.


text:
Q: Project Reactor: Enriching the result of a Flux with the result of a Mono I am working to introduce reactive programming to my company. I'm in the process of building a simple demo of an activity recommendation system to prove the performance benefits.
One of the challenges I have come up against is enriching the results in one stream with the results of another. I have a working example which is shown below but I am not sure if there are any issues with this approach. Could somebody take a look and provide any potential improvements.
    public Flux<Integer> getRecommendedActivities(Long userId, String location, Integer limit) {
        Flux<ActivityData> activities = activityDatabaseService.getByLocation(location);
        Mono<Map<String,BigInteger>> userCategoryScores = userScoresDatabaseService.get(userId);

        return activities
            .zipWith(userCategoryScores.cache().repeat(), this::scoreActivitiesBasedOnUserCategoryScores)
            .sort(compareActivityScoreStrength)
            .map(ScoredActivityData::getActivityId)
            .take(limit);
    }

    private ScoredActivityData scoreActivitiesBasedOnUserCategoryScores(ActivityData deal,Map<String, BigInteger> categoryScores){
        //This method combines the deal score and user category scores to come up with a final score
    }

Thanks,
Carl

A: Nothing inherently wrong with the code you have there. A few stylistic points which may or may not be helpful:

*

*The "norm" with reactive programming is to use a fluent style and inline everything throughout, rather than declare separate local variables at the top of your method and use those in the reactive chain.

*The x.zipWith(y.cache().repeat()) pattern will work just fine, but I find it a bit ugly if it can be avoided (zipWith() implies two real Flux of data in my head, rather than a Mono that's been arbitrarily cached and repeated - so the behaviour is not necessarily as "stand out" obvious as it could be.) Instead, I prefer y.flatMapMany(x) - it makes it clearer that you're taking one value and applying a transformation to many values through a real Flux. So in your case, that might look something like:
userScoresDatabaseService.get(userId)
        .flatMapMany(c -> activityDatabaseService.getByLocation(location)
                .map(a -> scoreActivitiesBasedOnUserCategoryScores(a, c))
        )
        .sort() //etc.

*Flux.sort() should really be a "last resort" operation, especially since you cite performance benefits as a reason for exploring reactive. (Reading the entire data in from a database service, then sorting it, then only taking the first n values screams inefficiency - you'd be much better sorting and limiting the values in the data layer.) Bear in mind Flux.sort() will have to wait for the entire source Flux to finish before sorting & returning the values, storing every value in memory as it goes, so doing so loses many benefits of the Flux in the first place. It also makes your reactive chain shorter & simpler, since it doesn't need to worry about sorting and limiting.

*Nit: Some of your method names & variable names appear to be quite long. I'd shorten them if possible - I find this makes things much easier to read in the context of a reactive chain.

With the above points, your entire getRecommendedActivities() could read something like:
scoresDb.get(userId)
        .flatMapMany(c -> activityDb.getByLocation(location, limit, comparator)
                .map(a -> score(a, c).getActivityId())
        )

...which to me at least, reads much shorter & simpler.


text:
Q: validate if documents have same data as I send I've the following documents in database: (each document is a room with members)
[
  {
    "id": "room1",
    "members": [{
      "id": "member1",
      "acks": "XXX",
    },{
      "id": "member2",
      "acks": "XXX",
    },{
      "id": "member3",
      "acks": "XXX",
    },{
      "id": "member4",
      "acks": "XXX",
    }]
  },
  {
    "id": "room2",
    "members": [{
      "id": "memberA",
      "acks": "XXX",
    },{
      "id": "memberB",
      "acks": "XXX",
    },{
      "id": "memberC",
      "acks": "XXX",
    },{
      "id": "memberD",
      "acks": "XXX",
    },{
      "id": "memberE",
      "acks": "XXX",
    },{
      "id": "memberF",
      "acks": "XXX",
    }]
  },
  {
    "id": "room3",
    "members": [{
      "id": "memberX",
      "acks": "XXX",
    },{
      "id": "memberY",
      "acks": "XXX",
    },{
      "id": "memberZ",
      "acks": "XXX",
    }]
  }
]

Sending from frontend next data:
[{
  "id": "room1"
  "members": ["member1", "member2"]
},{
    "id": "room2"
  "members": ["memberA", "memberB", "memberC", "memberF"]
},{
  "id": "room3"
  "members": ["memberX", "memberY"]
}]

I want to check if all members match for each room and return an unique boolean as a response --> True if all match and False if is someone that doesn't match.
This data should return false:
[{
  "id": "room1"
  "members": ["memberA", "member2"] //Because memberA is not in room1
},{
  "id": "room2"
  "members": ["memberA", "memberB", "memberC", "memberF"]
},{
  "id": "room3"
  "members": ["memberX", "memberY"]
}]

Playground
Is it possible to achieve it with one query?
Thank you very much in advance.

A: You can try a query,

*

*Prepare your query request from frontend request

// consider this is your request parameter
let request = [{
  "id": "room1",
  "members": ["member1", "member2"]
},{
    "id": "room2",
  "members": ["memberA", "memberB", "memberC", "memberF"]
},{
  "id": "room3",
  "members": ["memberX", "memberY"]
}];
// prepare query
let query = request.map((r) => {
  return {
    id: r.id,
    members: r.members.map((m) => {
      return { "members.id": m }
    })
  }
});
console.log(query)

*Try countDocuments function and get total count of rooms with request

async function hasRooms (query) {
  let count = await Schema.countDocuments({ $or: query });
  return (count === request.length);
}

Playground

*Use your function

console.log(await hasRooms(query));


text:
Q: Can I use a DrawItem event handler with a CheckedListBox? I would like to override the text displayed when an item is added to a checked list box. Right now it is using obj.ToString(), but I want to append some text, without changing the objects ToString method. I have seen examples of handling the DrawItem event for ListBoxs, but when I try to implement them, my event handler is not called. I have noted that the Winforms designer does not seem to allow me to assign a handler for the DrawItem event. Being stubborn, I just added the code myself
        listbox1.DrawMode = DrawMode.OwnerDrawVariable;
        listbox1.DrawItem += listbox1_DrawItem;

Am I trying to do the impossible?

A: Not impossible, but incredibly difficult.  What you suggest will not work, note the meta-data in class CheckedListBox for method DrawItem:
// Summary:
//     Occurs when a visual aspect of an owner-drawn System.Windows.Forms.CheckedListBox
//     changes. This event is not relevant to this class.
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public event DrawItemEventHandler DrawItem;

Therefore, your only option is to derive your own class from CheckedListBox, and in my limited testing, this will be a long road.  You can handle the drawing simply enough, as such:
public class CustomCheckedListBox : CheckedListBox
{
    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        String s = Items[e.Index].ToString();
        s += "APPEND";  //do what you like to the text
        CheckBoxState state = GetCheckBoxState(e.State);  // <---problem
        Size glyphSize = CheckBoxRenderer.GetGlyphSize(e.Graphics, state);
        CheckBoxRenderer.DrawCheckBox(
            e.Graphics,
            e.Bounds.Location,
            new Rectangle(
                new Point(e.Bounds.X + glyphSize.Width, e.Bounds.Y),
                new Size(e.Bounds.Width - glyphSize.Width, e.Bounds.Height)),
            s,
            this.Font,
            false,
            state);
    }
}

Note the method GetCheckBoxState().  What you get in the DrawItemEventArgs is a DrawItemState, not the CheckBoxState you need, so you have to translate, and that's where things started to go downhill for me.
Soldier on, if you like, this should get you started.  But I think it'll be a messy, long road.

A: I continued the work in DonBoitnotts answer.
The "GetCheckBoxState" is implemented using a very limited set with only two states.
var state = GetItemChecked(e.Index) ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal;

Vertically aligned the checkbox and left aligned the text.
var b = e.Bounds;
int checkPad = (b.Height - glyphSize.Height) / 2;
CheckBoxRenderer.DrawCheckBox(g, new Point(b.X + checkPad, b.Y + checkPad),
    new Rectangle(
        new Point(b.X + b.Height, b.Y),
        new Size(b.Width - b.Height, b.Height)),
    text, this.Font, TextFormatFlags.Left, false, state);


text:
Q: How ICMP works without transport layer I was told that ICMP doesn't involve transport protocols such as TCP, UDP.
So how ICMP get generated?So I want to confirm one thing to see if my understanding is correct:
let's say I want to send an ICMP request to a server. The ICMP message doesn't have transport header and transport payload(data), is it correct?

A: ICMP is a little confusing if you consider it as a separate protocol layer than IP layer (just because ICMP packets are encapsulated in IP packets), but as mentioned in comments above it is an integral part of IP layer.
The job of transport layer like TCP or UDP is to send data from end-to-end. But ICMP is not concerned with data transfer, rather its job is to help routers figure out the shape of internet and what direction to send packets.

I was told that ICMP doesn't involve transport protocols such as TCP, UDP. So how ICMP get generated?

Your assumption that all packets on wire strictly needs to have a transport layer is incorrect as well.


text:
Q: String Set being passed in as multiple parameters PHP MYSQL I'm calling a stored procedure which takes 3 parameters (1 IN, 2 OUT) through PHP. I pass the following string set "1,2,3,4" to PHP from JavaScript using :
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();

From PHP I get the string and call it like this (after making all proper SQL connections etc):
$q=$_GET["q"];
$result = mysql_query("CALL mst2($q, @eset, @leng)");

The error I get is Invalid query: Incorrect number of arguments for PROCEDURE fall12018.mst2; expected 3, got 6
If I remove @eset and @leng I still get the error but with 4 instead of 6, it seems that the procedure is reading in each comma separated member as a separate input, does anybody know how to send the entire set as a single argument?

A: Seems like right now your call looks like this (6 params, due to the commas in the value of $q):
$result = mysql_query("CALL mst2(1,2,3,4, @eset, @leng)");

Try encasing $q in quotes.
$result = mysql_query("CALL mst2('{$q}', @eset, @leng)");

Which will result in this (3 params):
$result = mysql_query("CALL mst2('1,2,3,4', @eset, @leng)");


text:
Q: Unable To Make Front Control Transparent Over PictureBox I am trying to place a custom user control over the top of a PictureBox control but I cannot seem for the life of me how to set the transparency of the user control so it doesn't chop out the PictureBox image.
My User Control consists of a RectangleShape with text in the middle to create a 'Badge' icon on top of an image (see pictures below).  The PictureBox and User Control both sit inside a Panel control and I have set the PictureBox.SendToBack() property and UserControl.BringToFront() property.
What I am left with is this:

My Code looks like this:
Option Explicit On
Option Strict On

Imports Microsoft.VisualBasic.PowerPacks

Public Class BadgeIcon
    Inherits UserControl

    Private _value As Integer
    Private canvas As New ShapeContainer
    Private Badge_Icon As New RectangleShape
    Private rect As New Rectangle
    Private m_BorderColor As Color = Color.White
    Private m_FillColor As Color = Color.Red
    Private m_BorderThickness As Integer = 2
    Private m_BadgeFont As New Font("Segoe UI", 7, FontStyle.Bold)
    Private m_BadgeText As String
    Private m_TextColor As New SolidBrush(Color.White)
    Private m_TextSize As Size
    Private m_TextPadding As Integer = 5

    Public Property Value() As Integer
        Get
            Return _value
        End Get
        Set(value As Integer)
            _value = value
            m_BadgeText = CStr(_value)
            m_TextSize = TextRenderer.MeasureText(m_BadgeText, m_BadgeFont)
            rect.Width = m_TextSize.Width + m_TextPadding
            rect.Height = m_TextSize.Height + m_TextPadding
            Me.Refresh()
        End Set
    End Property

    Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
        Get
            Dim cp As CreateParams = MyBase.CreateParams
            cp.ExStyle = &H20
            Return cp
        End Get
    End Property

    Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        SetStyle(ControlStyles.SupportsTransparentBackColor, True)
        SetStyle(ControlStyles.Opaque, False)
        SetStyle(ControlStyles.DoubleBuffer, True)
        SetStyle(ControlStyles.AllPaintingInWmPaint, True)
        SetStyle(ControlStyles.UserPaint, True)
        Me.BackColor = Color.FromArgb(0, 0, 0, 0)
        UpdateStyles()

        ' Add any initialization after the InitializeComponent() call.
        canvas.Parent = Me
        Badge_Icon.Parent = canvas
        canvas.BackColor = Color.FromArgb(0, 0, 0, 0)

        'Create Badge Icon
        With Badge_Icon
            .BackColor = Color.FromArgb(0, 0, 0, 0)
            .BorderColor = m_BorderColor
            .BorderWidth = m_BorderThickness
            .BorderStyle = Drawing2D.DashStyle.Solid
            .CornerRadius = 11
            .FillColor = m_FillColor
            .FillStyle = FillStyle.Solid
            .SelectionColor = Color.Transparent
        End With

        AddHandler Badge_Icon.Paint, AddressOf BadgeIcon_Paint
    End Sub

    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        MyBase.OnPaint(e)
        DrawBadgeIcon(e)
    End Sub

    Public Sub DrawBadgeIcon(e As PaintEventArgs)
        Try
            'Alter the size of the icon to fix the text
            With Badge_Icon
                .Location = New Point(rect.Left + 1, rect.Top + 1)
                .Size = New Size(rect.Width, rect.Height - 1)
            End With

        Catch ex As Exception
            ErrorTrap(ex, "cls_NotificationBadgeIcon: DrawBadgeIcon()")
        End Try
    End Sub

    Private Sub BadgeIcon_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs)
        Dim textRect As New Rectangle(2, 2, m_TextSize.Width + m_TextPadding - 1, m_TextSize.Height + m_TextPadding - 2)

        'Draw the Text
        Dim flags As New StringFormat
        flags.Alignment = StringAlignment.Center
        flags.LineAlignment = StringAlignment.Center
        e.Graphics.TextRenderingHint = Drawing.Text.TextRenderingHint.ClearTypeGridFit
        e.Graphics.DrawString(m_BadgeText, m_BadgeFont, m_TextColor, textRect, flags)
    End Sub

End Class

Then to add everything to my main form I call the following:
Dim pic As New PictureBox
        pic.Image = My.Resources.Notifications
        pic.SizeMode = PictureBoxSizeMode.StretchImage
        pic.Location = New Point(21, 221)
        pic.Size = New Size(42, 29)
        pnlLeftMenuBar.Controls.Add(pic)
        pic.SendToBack()

Dim Counter_Notify As New BadgeIcon
Counter_Notify.Location = New Point(50, 240)
        pnlLeftMenuBar.Controls.Add(Counter_Notify)
        Counter_Notify.BringToFront()

And simply use Counter_Notify.Value = 1 to update the counter value.
How can I remove the square rectangle chopping out the background image?  Or should I be setting this up an entirely different way?  I'm a little new to User Controls.
Any help appreciated.  Thanks

A: Using the paint event you can draw right on the picturebox itself.
Private Sub pb__Paint(sender As System.Object, e As System.Windows.Forms.PaintEventArgs) Handles pb.Paint
 Dim bgRect As New Rectangle({x,y,width,height})
 Dim textRect As New Rectangle(bgRect.X - {?}, bgRect.Y = {?}, width, height)
 e.Graphics.FillEllipse(New SolidBrush(Color.Red), bgRect)
 e.Graphics.DrawEllipse(New Pen(Color.White, 10), bgRect)
 Using sf As New StringFormat
  sf.LineAlignment = StringAlignment.Center
  sf.Alignment = StringAlignment.Center
 e.Graphics.DrawString("1", {your font}, {your brush}, textRect, sf)
 End Using
End Sub


text:
Q: Unreal Online Subsystems NULL not working, Online Subsystem Steam working I'm running into an odd issue regarding the Online Subsystem NULL. I am able to create and join sessions just fine. Once I join the session all client's pawns are experiencing a rubber band effect upon movement. There is also other odd behavior such as clients returning null when getting the GameState class.
The odd thing is everything works fine and as expected using the Online Subsystem Steam. Testing on two separate computers logged into separate steam accounts the rubber band movement problem goes away and the odd behavior of clients getting null for the GameState class does not exist.
I release this would be a bigger issue if the cases were reversed. Development is just taking longer due to this issue.
When changing between the Steam and NULL Subsystems I change the following in the DefaultEngine.ini file
NULL
[/Script/Engine.GameEngine]
 +NetDriverDefinitions=(DefName="GameNetDriver",DriverClassName="OnlineSubsystemSteam.SteamNetDriver",DriverClassNameFallback="OnlineSubsystemUtils.IpNetDriver")

[OnlineSubsystem]
DefaultPlatformService=NULL

[OnlineSubsystemSteam]
bEnabled=false
SteamDevAppId=480

[/Script/OnlineSubsystemSteam.SteamNetDriver]
NetConnectionClassName="OnlineSubsystemSteam.SteamNetConnection"

Steam
[/Script/Engine.GameEngine]
+NetDriverDefinitions=(DefName="GameNetDriver",DriverClassName="OnlineSubsystemSteam.SteamNetDriver",DriverClassNameFallback="OnlineSubsystemUtils.IpNetDriver")

[OnlineSubsystem]
DefaultPlatformService=Steam

[OnlineSubsystemSteam]
bEnabled=true
SteamDevAppId=480

[/Script/OnlineSubsystemSteam.SteamNetDriver]
NetConnectionClassName="OnlineSubsystemSteam.SteamNetConnection"

Are there any other settings in the DefaultEngine.ini file that need to be changed for the Null Subsystem for function correctly? Thanks!


text:
Q: how to import min files with webpack I am trying to import a third party min js and min css from a folder with webpack, but I can not find this folder with webpack.
My structure is
-node_modules
-src
-lib
  -min.js
  -css
    -min.css

But I can not recognize this lib folder. I tried alias on my webpack.config.js
resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      'lib': './lib/'
    }
  },

I tried resolve.modules:
resolve: {
    modules: [path.resolve(__dirname, "lib")],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
    }
  },

But did not work as well. What am I doing wrong?

A: You only need to reference those files in one of your *.js files that already is in bundle.
Assuming the following structure:
-node_modules

-src
    -app.js

-lib
  -min.js
  -css
    -min.css

and the entry point of your project is ./src/app.js, add these 2 lines of code there:
app.js:

import { min } from '../lib/min.js'
import '../lib/css/min.css'

That's it! Webpack will take care of those library and stylesheet.
If you need to know more about required webpack loaders and how to extract style file, refer to my previous answer here.


text:
Q: Using the "urxvt::term" Class I wanted to know if there are any resources
available for understanding and using
the 'term' class in urxvt.
The documentation makes a very general
set of references to it, but doesn't really
define the terms.
The uxrvt perl extensions also make very limited use
of the 'term' object, so there isn't much code
to study for reference.
My goals are simple:

*

*To open a new terminal window.

*To pass a command to the new terminal window,
then leave the window open for further input.
(example: "ls" or "echo 'Hello World'", then
leave the cursor awaiting further input)

*To be able to specify which desktop the
new terminal will appear on.
Questions:
1. How exactly is $term defined?
The documentation says:
$term = new urxvt::term $envhashref, $rxvtname, [arg...]

I've used "my $env = $self->env;" to define the
$envhashref. So I suppose that the existing terminal's
environment variables are used for the new terminal.
I suppose this corresponds directly to the environment
variables themselves, since the following reproduces
those variables...
my @envv = $self->envv;
foreach (@envv) {
  print "$_\n";
}

...and the following creates a reference to the 'env' hash:
my $env = $self->env;

Is this correct? It seems odd to have to explicitly declare
the environment if that setting will remain unchanged in the
vast majority of cases.

2. How should $rxvtname be set? Setting it to a name of my
choice results in two windows opening rather than one.
That behavior is odd... what is the correct way to define
the $rxvtname variable?
What exactly does ", [arg...]" refer to?

3. How is $term itself used? It apparently isn't
a reference to the new terminal window. What is its
purpose and how do you use it? An example would
probably be extremely useful here.

4. How can $term->exec_async ($cmd) send a command
to the new terminal window? Is there a better way
to send commands to a new window? Examples?

5. Is there a way to specify which desktop a terminal
window should appear in?

Hopefully this thread can serve as 'documentation' for anyone else
who has already scoured the man pages for urxvt, urxvtperl (as well as
urxvt.pm) and is left without a clear understanding. And if there's
a comprehensive reference on the web somewhere that contains full
explanations and examples, that would be great to know about, too.
Thanks in advance for your help.


text:
Q: static final methods in enum So I have looked around google and SO , I cannot find a example or explanation of : What is the purpose of static final methods in enum?
What I understand :

*

*Methods declare static can be accessed like function/procedural languages.

*final means you can't override it. Can't change the reference. As assylias pointed out in comments static can't be overridden either.

*enums can't be subclassed, explained here.

So what's the point of static final methods in enums if it will never be overridden since there won't be a subclass?

A: It's easy to see why static methods make sense, so I guess the question is about the final modifier.
final serves no purpose here, except maybe make the code a bit easier to read, but not by much.
It's similar to the way interface methods are often written as public void foo();, even though interface members are always public anyway.

A: In Java Enum types are used to represent fixed set of constants and making it static final helps its initialisation only once, single copy to be shared across all instances, accessing the variable with the class name and with final its more like a read-only

A: By making a static method final, you prevent it from being hidden (only instance methods can be overriden) by a subclass.
Since enum can't be subclassed, making a static method final is superfluous but not forbidden.
Note: technically, each enum constant that has a class body implicitly defines an anonymous class that extends the enum. But since inner classes may not declare static methods, the static final method could not be hidden in such a constant's class body.

A: When you declare instances of an enum you can override the enum's methods, essentially enum instances are implemented as (or thought of) as subclasses.  static methods can't be overridden in any case but the implication in the OP and other answers that final is superfluous for an enum is false.


text:
Q: Setting default DisplayDateStart on all DatePickers There is a set start date that I want to apply for every DatePicker in my app, because repeating the following snippet is not a good idea.
<DatePicker SelectedDate="{Binding Date}"
            DisplayDateStart="05/01/2006"/>

As well as setting the default DisplayDateStart in one place I need to be able to bind the SelectedDate property of the DatePicker.
I have tried creating a custom UserControl, but pressing the calendar icon does nothing (well, the text box is flashing but no calendar pop-up appears)
<UserControl x:Class="MyWpfAdd.ModDatePicker"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DockPanel>
        DatePicker x:Name="DatePicker" DisplayDateStart="05/01/2006"/>
    </DockPanel>
</UserControl>

With underlying code:
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace MyWpfApp
{
  public partial class ModDatePicker : UserControl
  {
    public DateTime? SelectedDate
    {
      get => (DateTime?)GetValue(SelectedDateProperty);
      set
      {
        this.DatePicker.SelectedDate = value;
        SetValue(SelectedDateProperty, value);
      }
    }

    public static readonly DependencyProperty SelectedDateProperty =
      DependencyProperty.Register("SelectedDate", typeof(DateTime?), typeof(ModDatePicker), new PropertyMetadata(null));

    public DateTime? DisplayDateEnd
    {
      get => (DateTime?)GetValue(DisplayDateEndProperty);
      set
      {
        this.DatePicker.DisplayDateEnd = value;
        SetValue(DisplayDateEndProperty, value);
      }
    }

    public static readonly DependencyProperty DisplayDateEndProperty =
      DependencyProperty.Register("DisplayDateEnd", typeof(DateTime?), typeof(ModDatePicker), new PropertyMetadata(null));

    public ModDatePicker()
    {
      InitializeComponent();
    }
  }
}

A: First of all create a class with a static property which provides for the default date that you need:
public static class DatePickerHelper
{
    private static DateTime defaultDisplayDateStart = new DateTime(2006, 1, 5);

    public static DateTime DefaultDisplayDateStart
    {
        get
        {
            return defaultDisplayDateStart;
        }
    }
}

Then use it in a global default style for DatePickers:
<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1"

             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Style TargetType="{x:Type DatePicker}" BasedOn="{StaticResource {x:Type DatePicker}}">
            <Setter Property="DisplayDateStart" Value="{x:Static local:DatePickerHelper.DefaultDisplayDateStart}" />
        </Style>
    </Application.Resources>
</Application>

I hope this hint can help you

A: The PropertyMetadata object takes default value as first argument. Specify your date there...
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace MyWpfApp
{
  public partial class ModDatePicker : UserControl
  {
    public DateTime? SelectedDate
    {
      get => (DateTime?)GetValue(SelectedDateProperty);
      set
      {
        this.DatePicker.SelectedDate = value;
        SetValue(SelectedDateProperty, value);
      }
    }

    public static readonly DependencyProperty SelectedDateProperty =
      DependencyProperty.Register("SelectedDate", typeof(DateTime?), typeof(ModDatePicker), new PropertyMetadata(null));

    public DateTime? DisplayDateEnd
    {
      get => (DateTime?)GetValue(DisplayDateEndProperty);
      set
      {
        this.DatePicker.DisplayDateEnd = value;
        SetValue(DisplayDateEndProperty, value);
      }
    }

    public static readonly DependencyProperty DisplayDateEndProperty =
      DependencyProperty.Register("DisplayDateEnd", typeof(DateTime?), typeof(ModDatePicker), new PropertyMetadata(new DateTime(2006,5,1)));

    public ModDatePicker()
    {
      InitializeComponent();
    }
  }
}


text:
Q: Unzipping the zipfiles within a url zipfile python I can unzip a url zip file of csvs using the below code:
import requests
from zipfile import ZipFile
from io import BytesIO
import pandas as pd

z = 'www.someurl.zip'
r = requests.get(z)
getnames = ZipFile(BytesIO(r.content))
names = getnames.namelist()
for name in names:
    df = pd.read_csv(getfiles.open(name), header=None, on_bad_lines='skip')
    print(df)

But doing the same approach to unzip a url zipfile of zipfiles doesn't seem to work as there is no URL path
z = 'www.someurl.zip'
r = requests.get(z)
getnames = ZipFile(BytesIO(r.content))
names = getnames.namelist()
for name in names:
    r = requests.get(name)
    getfiles = ZipFile(BytesIO(r.content))
    files = getfiles.namelist()
    for file in files:
        df = pd.read_csv(getfiles.open(file), header=None, on_bad_lines='skip')
        print(df)

Is this possible without a url of the nested Zip file? And can you do this on the nth iteration?


text:
Q: how to show retrived data from mysql table in sequential serial nos i have to show the retrieved data from MySQL table using Php in orders like where the no should come link:
sln0   data1    data2

1      data     data

2      data     data

3      data     data

but the serial nos should not the primary key auto increment id and one thing each data i have to show in each table definition.

A: You might be expecting this
SET @slno=0;
SELECT @slno:=@slno+1 AS slno, data1, date2 FROM your_table


text:
Q: Make .val() trigger each time a new value appears then update a data-attribute I need to make .val() trigger each time a new value appears then update a data attribute in a button
I can get the number from:
<input type="text" id="quantity" name="quantity" class="form-control input-number" value="1" min="1" max="100">

Using:
$("input#quantity").val();
Now I want this to be triggered every time the .val() HTML value changes.
I have a plus and minus arrow which can update the HTML value, the full mark up is as follows:
<form class="cart-num" action="index.html" method="post">
    <input type="text" id="quantity" name="quantity" class="form-control input-number" value="1" min="1" max="100">

         <button type="button" class="quantity-left-minus btn btn-number"  data-type="minus" data-field="">

         </button>

           <button type="button" class="quantity-right-plus btn btn-number" data-type="plus" data-field="">

     </button>

Each time the above is fired I need to update the data-quantity in the following code:
<a data-quantity="3" data-product_id="<?php echo $product->get_id() ?>" class="button product_type_simple add_to_cart_button ajax_add_to_cart add_to_cart_variable">Add to cart

A: I recreated the plus/minus functionality so you might just ignore that part, but this should work as expected (and I also don't check for negative quantity for simplicity reason):

$(function(){
 $('span.glyphicon').on('click', function(){
     if($(this).hasClass('glyphicon-minus')){
         $('input#quantity').val(parseInt($('input#quantity').val()) - 1);
        } else {
         $('input#quantity').val(parseInt($('input#quantity').val()) + 1);
        }
        $('a.add_to_cart_variable').attr('data-quantity', $('input#quantity').val());
        logDataQuantityAttribute();
    });

 $('input#quantity').on('keyup', function(){
  $('a.add_to_cart_variable').attr('data-quantity', this.value);
        logDataQuantityAttribute();
 });
});

function logDataQuantityAttribute(){
 console.log('data-quantity Attribute: ' + $('a.add_to_cart_variable').attr('data-quantity'));
}

<input type="text" id="quantity" name="quantity" class="form-control input-number" value="1" min="1" max="100">

         <button type="button" class="quantity-left-minus btn btn-number"  data-type="minus" data-field="">
             MINUS
         </button>

           <button type="button" class="quantity-right-plus btn btn-number" data-type="plus" data-field="">
        PLUS
     </button>

Add to cart

A: To detect input value  change you can use
$("#quantity").on("change paste keyup", function() {
      alert($(this).val());
 });

A: Here I completed your requirement. You need to update the attribute whenever you want to change the value of text box. Also you want to change the value and attribute when you click "-" & "+" button. This code will work for all your scenario.

$(function(){
$("#update_tag").attr("data-update-val",$("#quantity").val());
$("#quantity").on("change",function(){
$("#update_tag").attr("data-update-val",$("#quantity").val());
});

$(".quantity-left-minus").on("click",function(){
if($("#quantity").val()<2)
return false;
 $("#quantity").val($("#quantity").val()-1);
 $("#update_tag").attr("data-update-val",$("#quantity").val());
});

$(".quantity-right-plus").on("click",function(){
 $("#quantity").val(+$("#quantity").val()+1);
 $("#update_tag").attr("data-update-val",$("#quantity").val());
});

});

<input type="text" id="quantity" name="quantity" class="form-control input-number" value="1" min="1" max="100">

         <button type="button" class="quantity-left-minus btn btn-number"  data-type="minus" data-field="">
             -

         </button>

           <button type="button" class="quantity-right-plus btn btn-number" data-type="plus" data-field="">

        +
     </button>
     add

A: $(function(){
  $('form.cart-num button').on('click',function(){
    var $this = $(this),
        $quantity = $this.closest('form').find('input[name=quantity]'),
        $addToCart = $('a.ajax_add_to_cart');
        newQuantity = parseInt( $quantity.val() ) + ( $this.hasClass('quantity-left-minus') ? -1 : 1 );
    if( newQuantity < 1 ){
      newQuantity = 1;
    }
    $quantity.val( newQuantity );
    $addToCart.attr('data-quantity', newQuantity )
  });
});

Codepen: https://codepen.io/jamespoel/pen/zzjrqE


text:
Q: Is there any way to compile scss file from code in .net MVC I am trying to develop theme customization for .Net MVC project. I am using sass for styles. I am able to edit variable scss file from Code but scss files are not getting compiled at runtime. Is there any way to achieve this ?

A: as per my suggestion install one Extension in VS name is "Web Compiler". I am using same since 10 months and its working fine.
Here is the link you can go step by step:
https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebCompiler


text:
Q: XSLT Transformation not working I have the following xslt definition
<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:fo="http://www.w3.org/1999/XSL/Format" >
    <xsl:output method="text" omit-xml-declaration="yes" indent="yes"/>
    <xsl:template match="/">
        <xsl:value-of select="concat(//RedemptionFileName)"/>
            <xsl:for-each select="//ErrorMessageList/ErrorMessage">
                <xsl:value-of select="concat(',',OrderNumber,',',OrderLineItemNumber,',',ErrorCode)"/>
            </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

to tranform Data below
 <?xml version="1.0" encoding="utf-8"?>
<ReceiptDetails xmlns="http://centivesolutions.com/AAA_Receipt.xsd">
    <schemaVersion>10.4</schemaVersion>
    <RedemptionFileName>IncommBIFCFS_Order_20140319110741741.xml</RedemptionFileName>
    <ErrorMessageList>
        <ErrorMessage>
            <OrderNumber>1615296</OrderNumber>
            <OrderLineItemNumber>1910642</OrderLineItemNumber>
            <ErrorCode>SNF</ErrorCode>
            <ErrorDesc>street not found in city (finance number)</ErrorDesc>
        </ErrorMessage>
        <ErrorMessage>
            <OrderNumber>1615297</OrderNumber>
            <OrderLineItemNumber>1910643</OrderLineItemNumber>
            <ErrorCode>SNF</ErrorCode>
            <ErrorDesc>street not found in city (finance number)</ErrorDesc>
        </ErrorMessage>
        <ErrorMessage>
            <OrderNumber>1615298</OrderNumber>
            <OrderLineItemNumber>1910644</OrderLineItemNumber>
            <ErrorCode>BNC</ErrorCode>
            <ErrorDesc>PO Box not found in city (finance number)</ErrorDesc>
        </ErrorMessage>
        <ErrorMessage>
            <OrderNumber>1615299</OrderNumber>
            <OrderLineItemNumber>1910645</OrderLineItemNumber>
            <ErrorCode>ANS</ErrorCode>
            <ErrorDesc>address not on street</ErrorDesc>
        </ErrorMessage>
    </ErrorMessageList>
</ReceiptDetails>

The expected output should look like this
IncommBIFCFS_Order_20140319110741741.xml,1615296,1910642,SNF,1615297,1910643,SNF,1615298,1910644,BNC,1615299,1910645,ANS

When I run a sample test using Netbeans IDE i get the desired results but running on mule standalone server 3.7.0 throws an exception
org.apache.xpath.functions.FuncConcat only allows >1 arguments

Also online formatters like this says the xslt is wrong.

A: I think this:
<xsl:value-of select="concat(//RedemptionFileName)"/>

Should be:
<xsl:value-of select="//RedemptionFileName" />

You're trying to concat (join) only one thing, the error is saying you need two or more things to join together.


text:
Q: basic clang: sprintf resets int counter to 0 Consider the following:
int fileNo = 0;
sprintf(outfile, "%03d.jpg", fileNo);

then later
fileNo++; // fileNo equals 1 now

Then if you call this again:
sprintf(outfile, "%03d.jpg", fileNo);

fileNo now equals 0 again.
The goal here is to keep a counter in fileNo, and then pass that value to sprintf in order to set a filename. Is there an easier way to convert a counter to a string value? Or am I just missing a step that might prevent the fileNo from being reset to zero?
I've been digging into malloc, but it isn't really clear when that is necessary. Help?
(I'm not new to programming, but new to C.)
Update
This is a very simple program. There are no reassignments. When I step into the debugger, fileNo is reset to 0 immediately after the sprintf line is executed.
...
static int fileNo = 0;
char outfile[7];
sprintf(outfile, "%03d.jpg", fileNo);

...
 while(fread(buffer, 1, 512, inptr) == 512)
 {
    // 0xff 0xd8 0xff
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff)
    {
        if (!found1stJPG)
        {
            found1stJPG = true;

        } else {
            fileNo++;
            fclose(outptr);
            sprintf(outfile, "%03d.jpg", fileNo); // fileNo is 1 before this executes
            printf("outfile: %s,\n", outfile); // in the debugger fileNo is now 0
        }

A: You have the following:
char somecharvariable;
char outfile[7];
int fileNo = 0;
sprintf(outfile, "%03d.jpg", fileNo);

Oops. The string null terminator wrote over fileno. outfile should be length 8. If you allow fileNo to exceed 999 your code will crash anyway.
Putting the static flag on fileNo does not fix the problem. It merely relocates the problem to some other variable.


text:
Q: Circular buffers I have a coastal line layer ( us-medium-shoreline from http://shoreline.noaa.gov/data/datasheets/medres.html ), which is loaded into a project with On-The-Fly reprojection ( WGS 84 / World Mercator CRS with +proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs) and  I'd like to create a 500m buffer around this shoreline with the ultimate goal of intersecting the shoreline with inland polygons.
I'm expecting a polygon with the coastal line as its center, but I keep getting a circular region as resulting layer (with empty attributes table). Clearly I'm missing something as a GIS newbie.

A: I'm guessing it is b/c your layer is in geographic coordinate system (Nad83) not projected coordinate system.  Perform a save as on the layer and change the CRS to a projected coordinate system then try the buffer on the new projected layer.

A: You have not mentioned what buffer size you entered.
If the source data is in degrees, the buffer size will be in degrees too, while a source in meters results in a buffer size in meters.
To avoid confusion, turn OTF off and see if both layers still align.


text:
Q: Why convert to a function I have following code snippet:
def foo(x:Int, y:Int, z:Int) : Int = x * y * z
def boo(x: Int) : Int = foo(10, 20, x)

Look at the second line, how can I know as scala beginner, that the second return a function?

A: This line
def boo(x: Int) : Int = foo(10, 20, x)

it is not returning the function call foo, it returns Int, which is what you have between : and =
foo(10, 20, x) is the implementation of boo function, which makes sense considering that foo also returns Int.
I hope it is clear now.


text:
Q: Autoload related race condition in Cucumber with AJAX requests I'm using Cucumber with capybara-webkit for my app's integration tests on Ruby 2.0.0, Rails 4.1. A handful of test in my cucumber test suite unexpectedly began spitting out errors like this:
  Circular dependency detected while autoloading constant UiValidators::ParameterFinder (RuntimeError)
  /Users/kingp/.rvm/gems/ruby-2.0.0-p451@triquest/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:484:in `load_missing_constant'
  /Users/kingp/.rvm/gems/ruby-2.0.0-p451@triquest/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:180:in `const_missing'
  /Users/kingp/Projects/rails-triquest/app/controllers/contacts_controller.rb:2:in `<class:ContactsController>'
  /Users/kingp/Projects/rails-triquest/app/controllers/contacts_controller.rb:1:in `<top (required)>'
  /Users/kingp/.rvm/gems/ruby-2.0.0-p451@triquest/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:247:in `require'
  ...

The error says 'circular dependency', but it is actually thrown at any time the Rails autoloader tries to load a constant that is already in its set of loaded constants. Typically this is indeed due to a circular dependency, but I'm pretty sure that's not the case in my app. A diff between the branch with the crashing test and the stable branch I forked from shows that the only changes are to coffeescript files, view templates, a migration, and the new cucumber features I was writing. I haven't touched any controller or model code.
I ended up inserting some logging code into the rails autoloader to help me figure out what's going on:
  # Inserted at activesupport-4.1.1/lib/active_support/dependencies.rb:467
  _thread_id_for_debug = Thread.current.object_id
  STDERR.puts "*** #{loaded.count} #{from_mod} #{const_name} - #{_thread_id_for_debug}"

loaded is a set of paths to autoloaded code files, from_mod the context where the request came from, const_name the constant we're trying to load. Which all ultimately got me this, immediately before the crash:
  *** 104 Object SitesController - 70180261360940
  *** 105 Object ContactsController - 70180240113760
  *** 105 SitesController UiValidators - 70180261360940
  *** 105 Object UiValidators - 70180261360940
  *** 105 UiValidators ParameterFinder - 70180261360940
  *** 107 UiValidators ParameterFinder - 70180240113760

It looks like two threads are attempting to autoload the same constant. My guess is that the name of the constant is added to Rails' set of 'loaded' constants by the first thread before it has finished loading. The second thread can't resolve the constant (since the load hasn't finished yet), asks the autoloader to find it, and the autoloader raises when it sees the constant in its 'loaded' set.
At this point in the test, two controllers (SitesController and ContactsController) are responding to AJAX requests, launched nearly simultaneously.
I have found a way to work around the crash, by just including a reference to the module UiValidators::ParameterFinder ahead of the AJAX. But this seems fragile, and also not very elegant. Short of turning on eager loading for the test environment, is there any other way to avoid this problem?

A: I had the same problem (without Cucumber, just Capybara & Poltergeist). setting config.eager_load = true didn't even work for me (don't quite understand why not..).
I ended up using Spring and haven't had a circular dependency error since.

A: I have the same issue with Rails 4.1.4 when using Sidekiq. I assume that a race condition inside the threaded Sidekiq workers caused all kinds of hijinks when const_missing inside active_support was called.
In addition to make sure that my current environment would perform eager loading i.e. via config.eager_load = true I also had to add all components that my workers were using from the lib directory into config.eager_load_paths (via config.eager_load_paths += %W(#{config.root}/lib) inside config/application.rb).
This was necessary because I assume that setting config.eager_load = true only makes Rails eager load the contents of the app/ directory.
App::Application.config.eager_load_paths
=> [
  [0] "/home/archive/releases/20140721180504/app/assets",
  [1] "/home/archive/releases/20140721180504/app/controllers",
  [2] "/home/archive/releases/20140721180504/app/helpers",
  [3] "/home/archive/releases/20140721180504/app/mailers",
  [4] "/home/archive/releases/20140721180504/app/models",
  [5] "/home/archive/releases/20140721180504/app/services",
  [6] "/home/archive/releases/20140721180504/app/workers"
]

The combination of both seemed to have helped with the issue.


text:
Q: Weights of Mask R-CNN working on certain computers but not on others I'm using Mask R-CNN to obtain instance segmentation in my own dataset. The training process seems to be successful since the predictions seem to make sense. Nevertheless, I've encountered an unexpected issue. When I evaluate the results from training in different computers using the exact same files, hyperparameters, and weights, the predictions make no sense in certain cases. I tested them in four different computers (and in both Ubuntu and Windows) and in two of them, I obtain results such as the ones presented in the attached images.
I really don't understand what the issue can be. Has anybody encountered something like this?
Please find the images here:


text:
Q: Create a stored procedure only if the procedure does not exist in mysql In SQL Server I am able to achieve this using dynamic sql string, but now I need to do the same thing for mysql but am getting nowhere, is there any way to achive this
IF  NOT EXISTS (SELECT 1 FROM mysql.proc p WHERE NAME = 'stored_proc_name')
BEGIN
  DELIMITER $$
    CREATE PROCEDURE justATest()
    BEGIN
 -- some SP logic here
    END$$
END

I am storing the whole sql as a string inside a database column and execute the statement using a prepared statement Execute inside another stored procedure.

A: IF NOT EXISTS(SELECT 1 FROM mysql.proc p WHERE db = 'db_name' AND name = 'stored_proc_name') THEN
....
taken from
Older Post

A: Control statements like if then else are only allowed inside Stored Procedures in MySQL (unfortunately). There are usually ways around this, but it depends why you are conditionally creating the sproc.
E.g. If you're trying to avoid errors when running build scripts because sprocs already exist then you can use a conditional drop statement prior to your create like this:
DROP PROCEDURE IF EXISTS justATest;
CREATE PROCEDURE justATest()
BEGIN
  -- enter code here

END;

This will ensure the any changed code gets run (rather than skipped).


text:
Q: How to check if html5 video is buffered enough to play without stopping to buffer? So My question is how would you check a video to see if its buffered enough to play but without stopping to buffer again and if this is true then play the video.
OR how would I check if the video has buffered 50% and then if it has play the video.
What I've tried (But it didn't seem right when I looked at the buff amount in the controls it seemed to not of buffered alot)
var Video = document.getElementById("videoPlayer");
Video.oncanplaythrough = function HasBuff() {
    alert("Is Buffered");
    Video.play();
};

As said before this code didnt seem to have alot of buff when looking in the controls of the video not even 1/4 was buffered, Prehaps What would be better is to check if the video has buffered 50% or so and then play it, though I'm not to sure of how to do this or go about it.
Thank you for reading,
I'm at "beginer level" so Sorry if this seems an easy or silly question but we all have to start somewhere right? :)
Thanks again.

A: I think you can use this onplaying event
var vid = document.getElementById("myVideo");
vid.onplaying = function() {
    alert("The video is now playing");
};

or if you want to check the video is currently buffer you can use onwaiting event more info here http://www.w3schools.com/tags/ref_av_dom.asp

A: I made a little test:
var vid = document.getElementById("video");

var buffered = function() {
    var bufferedPercent =
        vid.duration > 0 && vid.buffered.length > 0 ?
        vid.buffered.end(0) / vid.duration * 100 :
        0;
    return 'buffered ' + bufferedPercent.toFixed(0) + '%';
};

vid.onprogress = function() {
    console.log('progress: ' + buffered());
};

vid.oncanplay = function() {
    console.log('canplay: ' + buffered());
};

vid.oncanplaythrough = function() {
    console.log('canplaythrough: ' + buffered());
};

vid.onsuspend = function() {
    console.log('suspend: ' + buffered());
};

On Chrome I get output like this:
canplay: buffered 5%
canplaythrough: buffered 5%
progress: buffered 15%
progress: buffered 25%
suspend: buffered 25%

With my test video "buffered" never gets beyond 25% (autoplay disabled). On Firefox in stops at 19%.
So it looks like you cannot force the browser to buffer more than it wants to. I also tried calling load() explicitly, no difference. Maybe if you seek forward it might buffer more, but then it might discard the already buffered part (I didn't try that out). But the browsers seemed to buffer quite a bit more after firing canplaythrough event, and then fired suspend event when they stopped buffering, so maybe you can use that.
In summary, the options I see are:

*

*The ideal way: Trust the browser's estimation on when to start playing (autoplay = true).

*The hacky way: Wait for the suspend event and start the video then (autoplay = false). These two browsers seemed to buffer a bit more that way.

Something like this:
vid.onsuspend = function() {
    if (vid.paused) {
        vid.play();
    }
};


text:
Q: Maven3 antrun: failed to create task or type replaceregexp I'm trying to write a simple task using Maven:
<plugin>
 <artifactId>maven-antrun-plugin</artifactId>
 <version>1.3</version>
 <executions>
  <execution>
    <phase>install</phase>
    <goals>
        <goal>run</goal>
    </goals>
    <configuration>
    <tasks>
     <replaceregexp file="dir=target/liquibase/*.sql" match="**DATABASECHANGELOGLOCK**"
             replace="" byline="true" />
        </tasks>
    </configuration>
    </execution>
  </executions>
</plugin>

When I run this, I get
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.3:run (default) on project Tik
[ERROR] Cause: the class org.apache.tools.ant.taskdefs.optional.ReplaceRegExp was not found.
[ERROR] This looks like one of Ant's optional components.
[ERROR] Action: Check that the appropriate optional JAR exists in
[ERROR] -ANT_HOME\lib
[ERROR] -the IDE Ant configuration dialogs
[ERROR]
[ERROR] Do not panic, this is a common problem.
[ERROR] The commonest cause is a missing JAR.
[ERROR]
[ERROR] This is not a bug; it is a configuration problem
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

I have included the ant and ant-nodeps dependencies, but can't make it run, and googling around hasn't been any help.
Does anyone have a solution for this?

A: I'm writing this in case anyone gets this problem
The problem was that maven doesn't care about ANT_HOME or anything. Dependencies must be declared inside the antrun plugin.
So I changed my pom.xml to look like this:
<plugin>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.3</version>
    <dependencies>
        <dependency>
            <groupId>ant</groupId>
            <artifactId>ant-nodeps</artifactId>
            <version>1.6.5</version>
        </dependency>
    </dependencies>
    <executions><execution>...</execution></executions>
</plugin>

A: maven-antrun-plugin version 1.8 no longer has this problem. Its dependencies point to a newer version of Ant, so you no longer need to add a dependency to the plugin declaration in your pom.


text:
Q: Solve integro-differential equations I am trying to numerically solve the following integro-differential equation and get some plots for $n(s)$ vs $s$:
$$
\dot{n}(s)-\frac{\dot{w}(s)}{2w(s)}\int_{-\infty}^s ds'\frac{\dot{w}(s')}{w(s')}(1+2n(s'))\,\cos[2\int_{s'}^s ds'' w(s'')]=0
$$
with $\dot{w}(x)=\frac{dw(x)}{dx}$. The initial condition for $n(s=-\infty)=0$ can be considered and $w(s)$ is a general function of $s$ which one can consider as an example a function like $w(s)=a^2+\sqrt{c-d(1+Tanh[s])}$ with $a,c,d$ constants. I am new in Mathematica that is why I do not have a clear idea where to start. There are some different methods to solve these type of problems in the literature like Adomian, Galerkin methods, etc... but what I have here is a bit more involved than what people used to consider based on those methods...so I thought a numerical solution would be good idea to start with.
MMA code:
w[s_] := a^2 + Sqrt[c - d (1 + Tanh[s])]
Inactivate[n'[s] - w'[s]/(2 w[s])*Integrate[Cos[2 Integrate[w[x], {x, t, s}]]*(w'[t]/
w[t])*(1 + 2 n[t]), {t, -Infinity, s}] == 0, Integrate] // ExpandAll// TeXForm

$\frac{d \text{sech}^2(s) \int _{-\infty }^s\left(-\frac{d \cos \left(2 \int _t^s\left(a^2+\sqrt{c-d-d \tanh (x)}\right)dx\right)
   \text{sech}^2(t)}{2 \sqrt{c-d-d \tanh (t)} a^2+2 c-2 d-2 d \tanh (t)}-\frac{2 d \cos \left(2 \int _t^s\left(a^2+\sqrt{c-d-d \tanh
   (x)}\right)dx\right) n(t) \text{sech}^2(t)}{2 \sqrt{c-d-d \tanh (t)} a^2+2 c-2 d-2 d \tanh (t)}\right)dt}{4 a^2 \sqrt{c-d \tanh
   (s)-d}+4 c-4 d \tanh (s)-4 d}+n'(s)=0$

A: UPDATE 11.10.2018 for speed-up the code.
w[s_] := a^2 + Sqrt[c - d (1 + Tanh[s])]
D[w[s],s]/ w[s]

(* -((d Sech[t]^2)/(2 Sqrt[c - d (1 + Tanh[t])] (a^2 + Sqrt[c - d (1 + Tanh[t])]))) *)

Simplifying and putting to integro-differential equation, and next compute integral:
Integrate[w[x], {x, t, s}, Assumptions -> {a > 0, c > d, d > 0, c > 0, t ∈ Reals, s ∈ Reals, s > t}]

(* ? *)

Mathematica tires to solve and does not give a solution within 1 hour computation.
With Maple 2018.2 I have the answer:

$Version
(* 11.3.0 for Microsoft Windows (64-bit) (March 7, 2018) *)

ClearAll["Global`*"]; Remove["Global`*"];

inf = -17; B = 2;             (* inf is Infinity. With -18 value - > error occurs!! *)
a = 1; c = 3; d = 1;          (* At some c,d values, the integral is divergent *)
steps = 1/100;
tolerance = 10^-8;

SOL = FixedPointList[Function[n, Module[{INT, int1, n1},
 INT =
  ParametricNDSolveValue[{int1'[t] ==
     Cos[2*(a^2 s - a^2 t +
          Sqrt[-c + 2 d]
            ArcTan[Sqrt[c + c E^(2 s) - 2 d E^(2 s)]/(
            Sqrt[-c + 2 d] Sqrt[1 + E^(2 s)])] -
          Sqrt[-c + 2 d]
            ArcTan[Sqrt[c + c E^(2 t) - 2 d E^(2 t)]/(
            Sqrt[-c + 2 d] Sqrt[1 + E^(2 t)])] -
          Sqrt[c] ArcTanh[Sqrt[c + c E^(2 s) - 2 d E^(2 s)]/(
            Sqrt[c] Sqrt[1 + E^(2 s)])] +
          Sqrt[c] ArcTanh[Sqrt[c + c E^(2 t) - 2 d E^(2 t)]/(
            Sqrt[c] Sqrt[1 + E^(2 t)])])]*(-((d Sech[t]^2)/(
        2 Sqrt[c -
          d (1 + Tanh[t])] (a^2 + Sqrt[
           c - d (1 + Tanh[t])]))))*(1 + 2*n[t]), int1[inf] == 0},
    int1, {t, inf, B}, {s}, PrecisionGoal -> 20];
 NDSolve[{n1'[
       s] - (-((d Sech[s]^2)/(
         4 Sqrt[c -
           d (1 + Tanh[s])] (a^2 + Sqrt[c - d (1 + Tanh[s])]))))*
       Evaluate[INT[s][s]] == 0, n1[inf] == 0}, n1, {s, inf, B},
   PrecisionGoal -> 20][[1, 1, 2]]]],
    Function[s, s],
SameTest -> (Max[Abs[Table[#1[s] - #2[s], {s, inf, B, steps}]]] <
   tolerance &)];

Plot[Evaluate[SOL[[-1]][s]], {s, inf, B}, PlotRange -> All,
PlotLegends -> {"n[s]"}, AxesLabel -> {"s", "n[s]"}]

Numeric errors check:
M[s_] := (SOL[[-1]][s]);

CHECK[s_?NumericQ] := M'[s] - (-((d Sech[s]^2)/(
 4 Sqrt[c - d (1 + Tanh[s])] (a^2 + Sqrt[c - d (1 + Tanh[s])]))))*
NIntegrate[
Cos[2*(a^2 s - a^2 t +
     Sqrt[-c + 2 d]
       ArcTan[Sqrt[c + c E^(2 s) - 2 d E^(2 s)]/(
       Sqrt[-c + 2 d] Sqrt[1 + E^(2 s)])] -
     Sqrt[-c + 2 d]
       ArcTan[Sqrt[c + c E^(2 t) - 2 d E^(2 t)]/(
       Sqrt[-c + 2 d] Sqrt[1 + E^(2 t)])] -
     Sqrt[c] ArcTanh[Sqrt[c + c E^(2 s) - 2 d E^(2 s)]/(
       Sqrt[c] Sqrt[1 + E^(2 s)])] +
     Sqrt[c] ArcTanh[Sqrt[c + c E^(2 t) - 2 d E^(2 t)]/(
       Sqrt[c] Sqrt[1 + E^(2 t)])])]*(-((d Sech[t]^2)/(
   2 Sqrt[c -
     d (1 + Tanh[t])] (a^2 + Sqrt[c - d (1 + Tanh[t])]))))*(1 +
   2*M[t]), {t, inf, s},
Method -> {Automatic, "SymbolicProcessing" -> 0},
PrecisionGoal -> 20]

Plot[CHECK[s], {s, inf, B}, PlotRange -> All, PlotLegends -> {"n[s]"},
AxesLabel -> {"s", "n[s]"}] // Quiet


text:
Q: ListView doesnt refresh while deleting in a loop I have a ListView which is to bind to an ObservableCollection. When i delete items manually (per button event), the items are getting removed and the ListView gets refreshed immediately.
When i delete the items in a for loop, only the list is getting refreshed at the end of the operation, after all elements are deleted. Before the items are getting deleted, there are some time-consuming operations on them and also notification to the user in another ListView.
So how can it be achieved, that the list gets refreshed after every single deletion of an item.
The question is not, how to delete items in a loop from an list, because this works (in reverse order). The question is, why is the UI not refreshing while deleting the items.
Here i have simplified sample code, which is showing this behaviour:
Xaml
<Window x:Class="ListViewTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ListViewTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
        </Grid.RowDefinitions>

        <ListView ItemsSource="{Binding LstFiles}" Grid.Column="0" Grid.Row="0"/>
        <Button Content="Los" Name="losBtn" Click="losBtn_Click" Grid.Column="0" Grid.Row="1" />
        <Button Content="del" Name="delBtn" Click="delBtn_Click" Grid.Column="0" Grid.Row="2" />
    </Grid>
</Window>

C# behind
using System.Collections.ObjectModel;
using System.Windows;

namespace ListViewTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public ObservableCollection<string> LstFiles { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            LstFiles = new ObservableCollection<string>();

            for (int i = 0; i < 20; i++)
            {
                LstFiles.Add(string.Format("file_{0}", i));
            }

            DataContext = this;
        }

        private  void losBtn_Click(object sender, RoutedEventArgs e)
        {

            for (int i = LstFiles.Count - 1; i >= 0; i--)
            {
                LstFiles.RemoveAt(i);
                System.Threading.Thread.Sleep(50);
            }
        }

        private void delBtn_Click(object sender, RoutedEventArgs e)
        {
            LstFiles.RemoveAt(0);
        }
    }
}

The sleep is for simulating the time-consuming operations.

A:
why is the ui not refreshing while deleting the items

This is because you are calling Thread.Sleep(), which simply blocks the UI thread. You must never call that in a UI application.
While it's unclear why you want to have this "delete loop" at all (instead of just clearing the ObservableCollection), you may use Task.Delay() instead of Sleep in an async Click handler method:
private async void losBtn_Click(object sender, RoutedEventArgs e)
{
    for (int i = LstFiles.Count - 1; i >= 0; i--)
    {
        LstFiles.RemoveAt(i);
        await Task.Delay(50);
    }
}

If instead of a simple delay there is some time-consuming operation to be invoked, you may simply wrap that in a Task.Run call:
private async void losBtn_Click(object sender, RoutedEventArgs e)
{
    for (int i = LstFiles.Count - 1; i >= 0; i--)
    {
        LstFiles.RemoveAt(i);
        await Task.Run(() =>
        {
            // some long running operation
        });
    }
}


text:
Q: Adicionar sistema de favoritos Recentemente em um projeto, surgiu a necessidade da criação de um sistema que pode-se ser avaliado pelo usuário, e neste caso, foi solicitado somente o "favorito". O usuário apenas irá clicar sobre o "coração" e será somado +1 a cada clique. Porém sem a utilização de plugin e tals, apenas em Jquery, HTML e CSS.

A: Você pode usar a Web Storage API visto que o único requisito é manter estas informações ao recarregar a página, por meio das funções window#localStorage() e window#sessionStorage() é possível persistir os dados. Além dos dois links acima, nessa pergunta tem a explicação da diferença entre elas.
Eu montei um exemplo mas não consegui postar aqui, o SOpt não deixa por conta da segurança. Então criei um Fiddle para visualizar e testar online. Clique no botão Favoritos algumas vezes e atualize a página.
Incrementar contagem

Total:

/***
 * Chave usada para armazenar e recuperar as informações salvas
 * no mapa do localStorage.
 */
var FAVORITES_KEY = 'fav';

/** Altera o texto da 'badge' com o total de Favoritos. */
function updateBadge(){
  $('.badge').text(getFavoritesCount());
}

/** Obtém o total de favoritos. */
function getFavoritesCount() {
  var count = localStorage.getItem(FAVORITES_KEY);
  return !count ? '0' : count;
}

/** Adiciona '1' ao total de favoritos. */
function incrementFavorites(){
  var count = parseInt(getFavoritesCount()) + 1;
  localStorage.setItem(FAVORITES_KEY, count);
}

// Quando '#count' for pressionado, é incrementado '1' ao total de
// Favoritos e atualizado a contagem em '.badge'.
$('#count').on('click', function(){
  incrementFavorites();
  updateBadge();
});

// É feita uma primeira chamada para exibir o '0' quando
// ainda não existir nenhum valor em 'FAVORITES_KEY'.
updateBadge();

Lembrando que estes dados ficam salvos localmente, se houver necessidade de recuperar o valor para enviar para o servidor você pode chamar getFavoritesCount() e obter o total de Favoritos.
E uma observação final, este recurso não foi implementado no Opera Mini como pode ser visto neste link.


text:
Q: How to add object to context handling duplicates correctly? I'm using Entity Framework 4.4 and I have a One-To-Many relationship model like this:
class A {
   public int Id { get; set; }
   public virtual B { get; set; }
   public int BId;
}
class B {
   public Id { get; set; }
   private ICollection<A> _As;
   public virtual ICollection<A> As
   {
      get { return _As ?? (_As = new HashSet<A>()); }
      protected set { _As = value; }
   }
}

Now, supposing I have 2 A instances, both with the same B instance. Then I'd have something like this (JSON representation):
A: { Id: 1, BId: 1, B: { Id: 1, As: [ 1, 2 ] } }
A: { Id: 2, BId: 1, B: { Id: 1, As: [ 1, 2 ] } }

I want to then cycle through my current list of A instances and add the to the db context:
foreach (var a in LocalAList)
{
   dbContext.Add(a);
   dbContext.SaveChanges();
}

The problem is that I get exceptions informing me that I've inserted duplicate objects. I've looked around and found things dealing with Entity modification and attachment, but I'm still pretty new to EF. I would imagine that this is a typical thing and there's an idiom for handling object insertion where the object already exists.
How can I efficiently add new objects to the context while avoiding the addition of duplicates? Should I just capture the duplicate exception and ignore it? Is there a better way to check?

A: You could do a simple test to see if a already exists in the database, the simplest one is to see if the Id is 0.  This is because once the A is added to the DB, an Id is given to your entity.  At that point, you should just reattach it rather than re-adding it
Example:
foreach (var a in LocalAList)
{
  if (a.Id == 0)
    dbContext.Add(a);
   else
    dbContext.As.Attach(a)

   dbContext.SaveChanges();
}


text:
Q: Cannot install chromium or chrome inside 12.04 LTS I am new to ubuntu and linux, i am not able to install chrome from the software center it gives me these errors:-
The following packages have unmet dependencies:

chromium-browser: Depends: libgcc1 (>= 1:4.1.1) but 1:4.6.3-1ubuntu5 is to be installed
                  Depends: libudev0 (>= 147) but 175-0ubuntu9.4 is to be installed
                  Depends: libx11-6 (>= 2:1.4.99.1) but 2:1.4.99.1-0ubuntu2.3 is to be installed
                  Depends: libxcomposite1 (>= 1:0.3-1) but 1:0.4.3-2build1 is to be installed
                  Depends: libxdamage1 (>= 1:1.1) but 1:1.1.3-2build1 is to be installed
                  Depends: libxfixes3 (>= 1:5.0) but 1:5.0-4ubuntu4.4 is to be installed
                  Depends: libxi6 (>= 2:1.2.99.4) but 2:1.7.1.901-1ubuntu1~precise3 is to be installed
                  Depends: libxrandr2 (>= 2:1.2.99.2) but 2:1.3.2-2ubuntu0.3 is to be installed
                  Depends: libxss1 but it is not going to be installed
                  Depends: zlib1g (>= 1:1.1.4) but 1:1.2.3.4.dfsg-3ubuntu4 is to be installed

A: If you run in terminal
 sudo apt-get install -f

the browser should install OK.


text:
Q: How to apply digital signature to my code Is it possible to apply a digital signature to my code or to the whole project?
I need to protect my Java code and my Angular code to prevent anyone from possibly tampering with or editing it. I would that no one could modify It.
Searching on internet I can't find any solution except to use MD5 but I don't understand It very well.. so can you help me?

A: For backend - you can sign the code assuming you have a keypair..

I would that no one could modify It.

The purpose of the signing is ensure that no one changed the code. That's more assurance for the client of the origin and integrity of the code.
If you are runnig the code on a server under your control, you have to worry less, but you may still get the assurance.
If you want to make sure no-one changed the code on the runnig on the client side, your options are limited. Someone changing part of the code may as well change the code checking for integrity (see how much money and time are game companies spending on DRM and how long it lasts)
For the client side (JS), you may check https://blog.bitsrc.io/the-importance-of-integrity-checks-in-javascript-c6fde630e7   but as well, it's assurance for the client, not for the service provider


text:
Q: Swift @autoclosure evaluation influenced by type annotations? (compiler bug?) I played around with Swift again today and was in need of a undefined() function. Basically a function that can be any type you want but crashes when it's actually run/evaluated. That's useful if you haven't had the time to implement a certain expression yet but want to see if the program type checks.
I also implemented a Result<T> and a (questionable) function chain that returns the left Result<> if not successful, otherwise the right Result<>. Therefore, the signature is chain<L,R>(l : Result<L>, r : @autoclosure () -> Result<R>) -> Result<R>. I defined the right Result<> as @autoclosure because there's no need to evaluate it iff the left is a failure.
I'm not interested in the usefulness (or improvements) for any of this, I'm just interested why my program crashes in the line marked [L3].
Please note that

*

*as expected [L1] works fine (|| is lazy evaluated)

*[L2] works fine (chain is also lazy in its right argument)

But, weirdly

*

*[L3] crashes the program evaluating undefined()
From my understanding L2 and L3 should be equivalent at runtime: L3 is just telling the type checker something it already knows... The same effect happens by the way if you change the type of undefined to () -> Result<T> (instead of () -> T), then it all works even without the as Result<String>.
This is all my code:
import Foundation

enum Result<T> {
    case Success(@autoclosure () -> T);
    case Failure(@autoclosure () -> NSError)
}

func undefined<T>(file:StaticString=__FILE__, line:UWord=__LINE__) -> T {
    fatalError("undefined", file:file, line:line)
}

func chain<L,R>(l : Result<L>, r : @autoclosure () -> Result<R>) -> Result<R> {
    switch(l) {
    case .Failure(let f):
        return .Failure(f())
    case .Success(let _):
        return r()
    }
}

func testEvaluation() {
    let error = NSError(domain: NSPOSIXErrorDomain, code: Int(ENOENT), userInfo: nil)
    let failure : Result<String> = .Failure(error)
    assert(true || undefined() as Bool) // [L1]: works
    let x : Result<String> = chain(failure, undefined() as Result<String>) // [L2]: works
    print("x = \(x)\n")
    let y : Result<String> = chain(failure, undefined()) // [L3]: CRASHES THE PROGRAM EVALUATING undefined()
    print("y = \(y)\n")
}

testEvaluation()

Believe it or not, the output of the program is:
x = (Enum Value)
fatal error: undefined: file main.swift, line 27
Illegal instruction: 4

That can't be right! Why would as Result<String> (which is the only difference between L2 and L3) change the output of the program? That should be entirely handled in the type checker and that means at compile time, no? Compiler bug?
The quickest way for you to reproduce this should be:

*

*copy all my code into the clipboard

*cd /tmp

*pbpaste > main.swift

*xcrun -sdk macosx swiftc main.swift

*./main
actual output:
x = (Enum Value)
fatal error: undefined: file main.swift, line 27
Illegal instruction: 4

expected output:
x = (Enum Value)
y = (Enum Value)

A: Confirmed as a bug by Swift developer Joe Groff via Twitter.


text:
Q: VSCode pipenv run REPL program receives environment activation causing initial syntax error The auto-sourcing/enable of Python environment is a great feature! But I don't know how to disable it for tasks. Pyenv for example automatically activates and runs commands in its virtualenv, so I end up having errors for my pipenv run commands.
I've made a little GIF with the behavior.

For reference, this is my .vscode/tasks.json file
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [{
        "label": "Run IPython Shell",
        "problemMatcher": [],
        "type": "shell",
        "command": "pipenv run ipython",
        "presentation": {
            "echo": true,
            "reveal": "always",
            "focus": true,
            "panel": "shared",
            "showReuseMessage": true,
            "clear": false
        }
    }]
}

And the output is the following:
> Executing task: pipenv run ipython <

source /Users/nahuel/.virtualenvs/pysrv-RjlHvHY5/bin/activate
Python 3.6.6 (default, Aug  6 2018, 12:14:58)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.1.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: source /Users/nahuel/.virtualenvs/pysrv-RjlHvHY5/bin/activate
  File "<ipython-input-1-944ce73c2717>", line 1
    source /Users/nahuel/.virtualenvs/pysrv-RjlHvHY5/bin/activate
                         ^
SyntaxError: invalid syntax

In [2]:

A: This is not an issue in current versions of VSCode. The environment activation works for both pipenv and poetry, and can be customized from settings.


text:
Q: Encrypt password C# Im implementing users account in my website.I need to encrypt passwords from new members,however im getting crazy with many options that ive found to accomplish that.
Symmetric and asymmetric cryptosystems, public versus private keys, digital signatures, hash algorithms, RSA, DES, Rijndael, PGP, MD5, SHA-1, https, secure sockets, Camellia, IDEA; what does it all mean?
I dont even know the difference between MD5 and rinjdael,can somenone tell me the best option to encrypt?

A: What is the easiest way to encrypt a password when I save it to the registry?
you dont encrypt passwords you hash them, see the link for a similar issue

A: If you are using asp.net, you can use the built in user account features.
If you insist on building your own, you shouldn't encrypt, you should hash and ONLY store the hash, not the actual password.
Here is a link to get you started.
comment updatemembership providers for MySqlmembership providers for Oracle

A: If you want to store passwords in a database for example, I would recommend you to use HMAC (Hash-based Message Authentication Code); you'll need a cryptographic hash function (e.g. SHA-512) in combination with a secret key to generate the MAC. Also, it's important to note here that you don't encrypt the password, but you rather hash it.
For the encryption of locally saved passwords for example (though Bruce Schneier says you should write your passwords down on paper), you can use an asymmetric-key cryptosystem like RSA. In this case you'll have a key pair consisting of a public key, which you'll share with your friends, and a private key, which you should, well, keep private. The nice thing about RSA is that you can either encrypt messages with your public key and then decrypt them with your private key; or you can use it to digitally sign documents by using your private key to calculate the hash of a document, and then validate it using your public key. Pretty nifty!

A: You shouldn't encrypt the password but take a hash of it using a salt (to protect against rainbow tables) and SHA-256 or better. This means you don't have to keep a secret key and worry about loads of key management stuff and also means that no one (including yourself) can find out a users password from the data in your database (they can only confirm that they have guessed the right password).
It is also suggested that you use a lot (1000+) of iterations of the hash to make it slow to calculate (not too slow for the user entering the correct password but far too slow if you're hashing loads of words to see if any match the contents of your db).
If you google salts, rainbow tables, hashes etc there is loads of information out there.

A: Here is a really good article that I used when I was first learning how to store passwords. This is a really good primer and it is written in C#

A: This has been answered before, but the short version is that you salt the password, hash it with at least SHA-256, and preferably use strengthening.  If this doesn't make sense to you, you're not ready to write anything yet; keep researching.

A: I think you could use MD5, it's simple to implement on .Net and it's a 128 bits (one way) cryptographic hash function. It has hash colission problems on wide ranges though.
Or you could check at Gost which is a 256 bits cryptographic hash function.
GOST Hash function

A: i have used this code to encrypt the password in binary format.. may be this will help you
private string Encrypt(string clearText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(clearBytes, 0, clearBytes.Length);
                cs.Close();
            }
            clearText = Convert.ToBase64String(ms.ToArray());
        }
    }
    return clearText;
}


text:
Q: Linq query (sql to linq) Having three tables (Item, Purchase, PurchaseItem) I am trying to write a linq query which finds how many valid purchases an item is included in.
In standard SQL I would use the subquery with a count, but I can't seem to get a linq query to do this.

SQL:
select i.name,
InTrade = (select count(*) from Purchase p join PurchaseItem pi on p.id = pi.PurchaseId where p.Isvalid = 1 and pi.ItemId = i.Id)
from Item i

Linq:
from i in Items select new
{
    i.Name,
    InTrade = from pi in PurchaseItems where pi.ItemId == i.ID
        select new
            {
                pi,
                Purchase = from p in Purchases where p.ID == pi.PurchaseId
                select new { p }
            }
}

Here I am trying to retrieve all my data in a query, and I would perhaps need another query to actually get what I want. I am probably headed down a troublesome road with this approach, so perhaps someone could shed some light on the "best practice" of achieving this in linq.
I've prepared some test data for this example:
if exists (select * from sysobjects where name = 'PurchaseItem') drop table PurchaseItem
if exists (select * from sysobjects where name = 'Item') drop table Item
if exists (select * from sysobjects where name = 'Purchase') drop table Purchase
go

create table Item
(
    ID int not null primary key,
    Name nvarchar(30) not null
)

create table Purchase
(
    ID int not null primary key,
    Name nvarchar(30) not null,
    ConfirmedDate datetime,
    Isvalid bit not null
)

create table PurchaseItem
(
    ID int not null primary key,
    PurchaseId int null references Purchase(ID),
    ItemId int null references Item(ID)
)

insert Item values (1, 'Bread')
insert Item values (2, 'Beer')
insert Item values (3, 'Wine')
insert Item values (4, 'Milk')
insert Item values (5, 'Apple')
insert Item values (6, 'Steak')
insert Item values (7, 'Hamburger')
insert Item values (8, 'Vinegar')

insert Purchase values (1, 'Purchase 1', null, 1)
insert Purchase values (2, 'Purchase 2', null, 0)
insert Purchase values (3, 'Purchase 3', '2008-1-7', 1)

insert PurchaseItem values (1, 1, 1)
insert PurchaseItem values (2, 1, 2)
insert PurchaseItem values (3, 1, 3)
insert PurchaseItem values (4, 1, 4)
insert PurchaseItem values (5, 1, 5)
insert PurchaseItem values (6, 1, 6)
insert PurchaseItem values (7, 2, 2)
insert PurchaseItem values (8, 3, 2)
insert PurchaseItem values (9, 3, 1)
insert PurchaseItem values (10, 3, 5)

A: There are several ways I think you can accomplish that, through a single query to the database. Here are two I can think of:
Using a bi-directional association between items and their purchases:
var resultUsingSubItems = context.PurchaseItems.Select(x => new
    {
        Item = x,
        ValidPurchases = x.Purchases.Count(y => y.IsValid)
    });

And another approach, grouping by Item:
var resultUsingGrouping = context.Purchases.GroupBy(x => x.Item).Select(
        g => new
            {
                Item = g.Key,
                ValidPurchases = g.Count(y => y.IsValid)
            });

Please use SQL profiler to ensure that Linq2SQL is transforming that into a single SQL query.

A: You can also do this:
var results = from i in db.Items
              select new InTradeResult
              {
                ProductName = i.Name,
                InTradeCount = i.PurchaseItems.Count(pi => pi.Purchase.IsValid)
              };

Here is a sample Console application that shows the results:
class Program
{
  static void Main(string[] args)
  {
    using (var db = new Context())
    {
      var results = from i in db.Items
                    select new InTradeResult
                    {
                      ProductName = i.Name,
                      InTradeCount = i.PurchaseItems.Count(pi => pi.Purchase.IsValid)
                    };

      foreach (var result in results)
      {
        System.Console.WriteLine("{0} - {1}", result.InTrade, result.ProductName);
      }

      System.Console.ReadKey();
    }
  }
}

public class InTradeResult
{
  public string ProductName { get; set; }
  public int InTradeCount { get; set; }
}

public class Context : IDisposable
{
  public IList<Item> Items { get; set; }
  public IList<Purchase> Purchases { get; set; }
  public IList<PurchaseItem> PurchaseItems { get; set; }

  public Context()
  {
    Items = new List<Item>();
    Items.Add(new Item { ID = 1, Name = "Bread" });
    Items.Add(new Item { ID = 2, Name = "Beer" });
    Items.Add(new Item { ID = 3, Name = "Wine" });
    Items.Add(new Item { ID = 4, Name = "Milk" });
    Items.Add(new Item { ID = 5, Name = "Apple" });
    Items.Add(new Item { ID = 6, Name = "Steak" });
    Items.Add(new Item { ID = 7, Name = "Hamburger" });
    Items.Add(new Item { ID = 8, Name = "Vinegar" });

    Purchases = new List<Purchase>();
    Purchases.Add(new Purchase { ID = 1, Name = "Purchase 1", ConfirmedDate = null, IsValid = true });
    Purchases.Add(new Purchase { ID = 2, Name = "Purchase 2", ConfirmedDate = null, IsValid = false });
    Purchases.Add(new Purchase { ID = 3, Name = "Purchase 3", ConfirmedDate = null, IsValid = true });

    PurchaseItems = new List<PurchaseItem>();
    PurchaseItems.Add(new PurchaseItem(1, Purchases[0], Items[0]));
    PurchaseItems.Add(new PurchaseItem(2, Purchases[0], Items[1]));
    PurchaseItems.Add(new PurchaseItem(3, Purchases[0], Items[2]));
    PurchaseItems.Add(new PurchaseItem(4, Purchases[0], Items[3]));
    PurchaseItems.Add(new PurchaseItem(5, Purchases[0], Items[4]));
    PurchaseItems.Add(new PurchaseItem(6, Purchases[0], Items[5]));
    PurchaseItems.Add(new PurchaseItem(7, Purchases[1], Items[1]));
    PurchaseItems.Add(new PurchaseItem(8, Purchases[2], Items[1]));
    PurchaseItems.Add(new PurchaseItem(9, Purchases[2], Items[0]));
    PurchaseItems.Add(new PurchaseItem(10, Purchases[2], Items[4]));
  }

  public void Dispose()
  {
    //Do nothing
  }
}

public class Item
{
  public int ID { get; set; }
  public string Name { get; set; }

  public IList<PurchaseItem> PurchaseItems { get; set; }

  public Item()
  {
    PurchaseItems = new List<PurchaseItem>();
  }
}

public class Purchase
{
  public int ID { get; set; }
  public string Name { get; set; }
  public DateTime? ConfirmedDate { get; set; }
  public bool IsValid { get; set; }

  public IList<PurchaseItem> PurchaseItems { get; set; }

  public Purchase()
  {
    PurchaseItems = new List<PurchaseItem>();
  }
}

public class PurchaseItem
{
  public int ID { get; set; }

  public int PurchaseId { get; set; }
  public Purchase Purchase { get; set; }

  public int ItemId { get; set; }
  public Item Item { get; set; }

  public PurchaseItem(int id, Purchase purchase, Item item)
  {
    ID = id;

    PurchaseId = purchase.ID;
    Purchase = purchase;
    purchase.PurchaseItems.Add(this);

    ItemId = item.ID;
    Item = item;
    item.PurchaseItems.Add(this);
  }
}