text:
Q: How to retrieve the whole page screenshot be awesomium? The problem is that width and height are set during WebView creation and I don't see any option to change it after page was loaded (and real size became known). To workaround it I use two WebView: first to get the size and second to make a screenshot:
static bool finishedLoading;
static bool finishedScroll;
static ScrollData scrollData;

static void Main(string[] args)
{
   WebCore.Initialize(new WebCoreConfig() { CustomCSS = "::-webkit-scrollbar { visibility: hidden; }" });

   var webView1 = WebCore.CreateWebView(800, 600, false);
   webView1.LoadURL("http://someurl");
   webView1.LoadCompleted += OnFinishLoading;

   while (!finishedLoading)
   {
      Thread.Sleep(100);
      WebCore.Update();
   }

   webView1.RequestScrollData();
   webView1.ScrollDataReceived += new ScrollDataReceivedEventHandler(ScrollDataReceived);

   while (!finishedScroll)
   {
      Thread.Sleep(100);
      WebCore.Update();
   }

   var webView2 = WebCore.CreateWebView(scrollData.ContentWidth, scrollData.ContentHeight, false);

   finishedLoading = false;
   webView2.LoadURL("http://someUrl");
   webView2.LoadCompleted += OnFinishLoading;

   while (!finishedLoading)
   {
      Thread.Sleep(100);
      WebCore.Update();
   }

   webView2.Render().SaveToPNG("filePath");

   WebCore.Shutdown();
}

static void ScrollDataReceived(object sender, ScrollDataEventArgs e)
{
   finishedScroll = true;
   scrollData = e.ScrollData;
}

static void OnFinishLoading(object sender, EventArgs e)
{
   finishedLoading = true;
}

I hope there is a better way...

A: Instead of creating a new WebView after you receive the scroll dimensions, you just need to resize it using WebView.Resize and then wait for the resize operation to complete (see WebView.IsResizing).
I recently wrote a tutorial on how to capture whole web-pages using Awesomium: http://labs.awesomium.com/capturing-web-pages-with-c/
The code uses the C API but it should be very similar to the .NET API. There's also a complete code example (link is near the bottom) that demonstrates how to capture very long web-pages to multiple images without killing your RAM.
Hope this helps!


text:
Q: Why isn't my !important attribute working in Google Chrome? I have two CSS files in my web app: reset.css and screen.css.  They appear in that order in the html (reset then screen).
In the reset.css, the following style definition occurs:
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {
  border-bottom-width:0;
  border-color:initial;
  border-left-width:0;
  border-right-width:0;
  border-style:initial;
  border-top-width:0;
  font-family:inherit;
  font-size:100%;
  font-style:inherit;
  font-weight:inherit;
  margin-bottom:0;
  margin-left:0;
  margin-right:0;
  margin-top:0;
  outline-color:initial;
  outline-style:initial;
  outline-width:0;
  padding-bottom:0;
  padding-left:0;
  padding-right:0;
  padding-top:0;
  vertical-align:baseline;
}

You can see that span is in this list, and by default has a font-size of 100%.
In my screen.css, I have the following:
dl.labels-left dt span.req {
  display:inline;
  font-size:14px !important;
}

My HTML has the following excerpt:

            Name:
            *

...

The problem I'm having is that the font-size: 14px !important; is being overridden by the CSS in the reset file, but only in Google Chrome.  I can't work out why!
Here's a Firebug Lite screenshot showing the font-size crossed out:
Firebug Screenshot http://www.damianbrady.com.au/images/firebug_screenshot.png
Why is my reset.css style being considered more important than the specific class definition?
According to my understanding of W3C CSS 2.1 Specificity, this shouldn't happen!

A: Maybe the inspector is crossing it out improperly but visually it's right?

A: It is a Firebug Lite bug. Firebug Lite is summing up the specificity value of each selector defined in the rule (and not only the matched ones like the CSS specification says), so it is resulting in a overestimated value.
I just filled an issue report for it. Please "star" (subscribe) the issue if you want to receive email updates about our progress with this particular problem:
http://code.google.com/p/fbug/issues/detail?id=3262
Also, next time, for Firebug / Firebug Lite issues, try using our discussion list or our bug tracking. Otherwise we may not be aware of the problem.
Thanks for the detailed report by the way!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Xamarin iOS free provisioning fails for existing project I have recently been given the task of taking over an existing iOS/Android app written with Xamarin.
When I try to set up Free Provisioning as described in here in the Xamarin guides, I run into a roadblock:
I have successfully followed these steps:

*

*Created an Apple ID

*Went to XCode -> Preferences and added my account

*Created the signing identity as described at step 4 of the guide

*Plugged in my dev iPhone (freshly updated)

*Under "General Options" I set the Bundle Identifier to the exact string that is set in the iOS project part of the Xamarin solution

*Selected myself from the team dropdown

*Pressed "Fix Issues" as per guide, and this is where the procedure fails
The error I get is "An App ID with identifier 'xx.xx.xxxx.xxx.xxxx.xxx.xxxxxxx' is not available. Please enter a different string.
If I try and add a anything to the identifier, it works (so it's not the format of the identifier).
The error message also makes sense to me as the identifier is, indeed, globally taken since the app has already been published.
My question here is:
How can I get my project deployed to my dev iPhone?

A: You can choose : "com.companyname.yourapp1" or  "com.companyname.yourapp2".
Make sure this ID is same like your bundle identifier in "Info.plist" in xamarin.ios project

A: As I have already posted as a comment:
A possible workaround could be to change the BundleIdentifier for the time you are working on a specific task. This should work but it brings the disadvantages of changing the identifier every time and if you do not watch out to check in the false identifier by accident.


text:
Q: Gitlab - AutoSync / Replicate Local Server from/to Cloud Server I have 2 Gitlab servers:
Server A that runs on the cloud and accessible from https://git.example.com
and
Server B that runs on the local network and accessible only through local computers by an IP address or a fake domain that redirects locally http://local.git (DNS spoof)
How can I make both git servers A & B mirrored/synced/replicated where:

*

*Server B would automatically push any local work/changes to server A
After that (or before)

*

*Server B will check server A for any differences in any repo and make sure both are 100% synced - in another meaning, server B would pull the changes from server A because some people might push changes directly to server A from outside this local network.

I don't think the priority matters because both servers will be 100% the same at the end - sorry I'm not a developer (or use git a lot) but more of an IT guy.

A: The most stable solution would be to mirror your servers at the repository level.
GitLab has an internal mechanism for doing this for you (see: https://gitlab.com/help/workflow/repository_mirroring).
The alternative (since you won't have access to the file system on your hosted GitLab instance) would be to create a script to iteratively "mirror" your repositories using git push --mirror ...


text:
Q: how do I get win32 file browser with SDL? I want to create an editor in C++ using SDL & OpenGL and have decided to use the win32 api to access the window bar menus (for file, edit and so on) and it seems quite simple, but I don't know how to create a "file-> open" file browser/loader... I'm hoping it's quite simple but I'm finding it hard to look up any tutorials on google because of the phrasing...
I just want to have an "open" or "import" option in the file menu that will open a standard windows file browser... then grab the file location, place it into a string then pass it into a function that is activated by selection a file... (I hope that makes sense).
The method I'm using to create the win32 menus are from this post:
http://www.gamedev.net/topic/400677-sdl-with-a-win32-menu/
Half way down the page there is a comment by "caseyd"... that's how I learnt how to use it, so that is my current understanding of win32 menus in SDL... I wanted to post the code here, but I didn't know how to paste it here in codeblocks without reformatting every line.
I'm hoping this is quite simple... Thanks to anyone who can teach me how or just point me in the right direction.
Oh, and I'm not trying to convert this to other operating systems, I just like SDL.

A: Use GetOpenFileName().  Note that that function blocks until the user selects a file, so if you want to continue rendering etc. in the background, make sure to run it on a separate thread.


text:
Q: facebook is this feature exists? I have a facebook page
https://www.facebook.com/Best.Brain.Teasers
and my website
http://gpuzzles.com
I have read ob facebook link below
https://developers.facebook.com/docs/plugins/comments/
The Comments box lets people comment on content on your site using their Facebook profile and shows this activity to their friends in news feed. It also contains built-in moderation tools and special social relevance ranking.
can i link my facebook page with my website
i.e all comments posted on my fb page wall automatically come under my post on webiste/blog.

A: Yes you can do that.
Just paste the below code in your website where you need to post. Just make sure your server is Curl enabled and edit the code to fit in your facebook id.

<?php
//function to retrieve posts from facebook's server
function loadFB($fbID){
$url="http://graph.facebook.com/".$fbID."/feed?limit=3";
//load and setup CURL
 $c = curl_init($url);
 curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
//get data from facebook and decode JSON
 $page = json_decode(curl_exec($c));
//close the connection
 curl_close($c);
//return the data as an object
 return $page->data;
}

/* Change These Values */
// Your Facebook ID
$fbid = "YOUR_FB_ID";
// How many posts to show?
$fbLimit = 10;
// Your Timezone
date_default_timezone_set("America/Chicago");

/* Dont Change */
// Variable used to count how many we've loaded
 $fbCount = 0;
// Call the function and get the posts from facebook
 $myPosts = loadFB($fbid);

//loop through all the posts we got from facebook
foreach($myPosts as $dPost){
//only show posts that are posted by the page admin
if($dPost->from->id==$fbid){
    //get the post date / time and convert to unix time
     $dTime = strtotime($dPost->created_time);
    //format the date / time into something human readable
    //if you want it formatted differently look up the php date function
     $myTime=date("M d Y h:ia",$dTime);
    ?>

<?php echo($dPost->message) . $myTime; ?>

    <?php
    //increment counter
     $fbCount++;
    //if we've outputted the number set above in fblimit we're done
     if($fbCount >= $fbLimit) break;
}
}
?>


text:
Q: While deleting the parent ,child is updating rather than deleting My problem is that when  i am deleting the parent child is not deleted instead of deleting the child ,child  is updating
this is the output
Hibernate: update employee_project set employeeNumber=null where employeeNumber=?
Hibernate: delete from employee where EMPLOYEE_NUMBER=?

when i deleting the parent this is the snippet of code i run
 public boolean deleteEmployee(Employee employee) {
        Transaction transaction = null;
        boolean flag;
        try {
            transaction = session.beginTransaction();
            session.delete(employee);
            session.flush();
            transaction.commit();
            flag = true;
        } catch (HibernateException exception) {
            if (transaction != null)
                transaction.rollback();
            flag = false;
        }
        return flag;
    }

this is my parent table Employee.hbm.xml

<hibernate-mapping package="com.nousinfo.tutorial.model">
    <class name="Employee" table="employee">
        <meta attribute="class-description">
            This class contains the employee detail
        </meta>
        <id name="employeeNumber" type="int" column="EMPLOYEE_NUMBER">

        </id>
        <property name="firstName" type="string" column="FIRST_NAME"></property>
        <property name="lastName" type="string" column="LAST_NAME"></property>
    </property>
        <set name="employeeProjects" cascade="all-delete-orphan">
            <key column="employeeNumber" />
            <one-to-many class="com.ravindrainfo.tutorial.model.EmployeeProject" />
        </set>

    </class>

</hibernate-mapping>

and this is child table project.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.nousinfo.tutorial.model">
    <class name="EmployeeProject" table="employee_project">
        <meta attribute="class-description">
            This class contains the employee detail
        </meta>
        <composite-id>
            <key-property name="employeeNumber" type="int"
                column="EMPLOYEE_NUMBER"></key-property>
            <key-property name="projectCode" type="string" column="PROJECT_CODE"></key-property>
        </composite-id>
        <property name="startDate" type="date" column="START_DATE"></property>

        <many-to-one name="employee" class="com.ravindrainfo.tutorial.model.Employee"></many-to-one>
    </class>
</hibernate-mapping>

this is my Employee Pojo
import java.io.Serializable;
import java.util.Date;

import java.util.Set;

public class Employee implements Serializable {

    private static final long serialVersionUID = 4314638638373270669L;
    private int employeeNumber;
    private String firstName;
    private String lastName;
        private Set<EmployeeProject> employeeProjects;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
        public Set<EmployeeProject> getEmployeeProjects() {
        return employeeProjects;
    }

    public void setEmployeeProjects(Set<EmployeeProject> employeeProjects) {
        this.employeeProjects = employeeProjects;
    }
        public int getEmployeeNumber() {
        return employeeNumber;
    }

    public void setEmployeeNumber(int employeeNumber) {
        this.employeeNumber = employeeNumber;
    }

}

A: I am not sure this works with xml as well, but try to modify
<set name="employeeProjects" cascade="all-delete-orphan">
      <key column="employeeNumber" />
      <one-to-many class="com.ravindrainfo.tutorial.model.EmployeeProject" />
</set>

with
<set name="employeeProjects" cascade="all-delete-orphan" orphanRemoval="true">
      <key column="employeeNumber" />
      <one-to-many class="com.ravindrainfo.tutorial.model.EmployeeProject" />
</set>

so adding orphanRemoval="true".
This works with annotation @OneToMany(orphanRemoval=true), so I am pretty sure it works with xml as well (and actually you can even remove cascade="all-delete-orphan" quite safely)
EDIT: I checked out more info and found this page Hibernate Unidirectional Parent/Child relationship - delete() performs update on child table instead of delete, so you can try to modify your mapping adding inverse="true" instead of orphanRemoval. So
<set name="employeeProjects" cascade="all-delete-orphan" inverse="true">
    <key column="employeeNumber" />
    <one-to-many class="com.ravindrainfo.tutorial.model.EmployeeProject" />
</set>

A: I think the cascade should be all,delete-orphan rather than all-delete-orphan
An excerpt from hibernate documentation:

If the child object's lifespan is bounded by the lifespan of the
  parent object, make it a life cycle object by specifying
  cascade="all,delete-orphan"(@OneToMany(cascade=CascadeType.ALL,
  orphanRemoval=true)).

ref: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/objectstate.html#objectstate-transitive


text:
Q: How can I make add firepad to my reactjs project? So I've been learning react, and wanted to make a basic firepad instance. My current setup is having one container div in my index.html, and having all of my react components rendering through that div. My current attempts and the code I'm showing with this have been in an environment with gulp and browserify, but I'm also playing around with ES6 and webpack. So I'm pretty flexible about getting this working as I learn. Here's the code:
"use strict"

var React = require('react')
  , Firebase = require('firebase')
  , fbRoot = 'myURL'
  , CodeMirror = require('codemirror')
  , Firepad = require('firepad')
  , firepadRef = new Firebase(fbRoot + 'session/')
  , myCodeMirror = CodeMirror(document.getElementById('firepad'), {lineWrapping: true})
  , myFirePad = Firepad.fromCodeMirror(firepadRef, myCodeMirror, { richTextShortcuts: true, richTextToolbar: true, defaultText: 'Hello, World!'});

var WritePage = React.createClass({
  render: function(){
    return (

    );
  }
});

module.exports = WritePage;

The first error I was getting was that it couldn't find the codemirror.js file. Although CodeMirror was being correctly defined in Chrome's dev tools, I moved that from requiring the npm package to just linking the 2 needed codemirror files to my html. It then gave me an error about not being able to take .replaceChild of undefined. I then tried moving all of the dependency files over to my index.html, but still had the same .replaceChild error. Anyone have any experience with react and firepad? I read in the reactfire docs that it's one way binding from firebase to my site, which for my case making a read-only firepad would be fine. Like I said, I'm flexible all of this stuff is new to me.

A: From the link that Michael provided.

The problem is that you are trying to reference a DOM element before React has rendered your component.

, myCodeMirror = CodeMirror(document.getElementById('firepad'),{lineWrapping: true})
, myFirePad = Firepad.fromCodeMirror(firepadRef, myCodeMirror, {richTextShortcuts: true, richTextToolbar: true, defaultText: 'Hello, World!'});

By moving this code into componentDidMount(), it runs after the CodeMirror DOM element has been constructed and you'll be able to reference the DOM node. You will also probably find it easier to use the React ref attribute instead of document.getElementById().

A: Use these npm packages - brace, react-ace, firebase, firepad.
Since firepad needs aceto be present globally, assign brace to global var
like(not the best way, but works) before importing firepad
import firebase from 'firebase/app';
import 'firebase/database';
import brace from 'brace';
global.ace = brace;
global.ace.require = global.ace.acequire;
import Firepad from 'firepad';

Use ref to get instance of ReactAce and initialize it in componentDidMount using:
new Firepad.fromACE(this.firepadRef, this.aceInstance.editor, options);

Similarly for CodeMirror editor.
Hoping, this would be of some help.


text:
Q: Cost of Developing Bluetooth 4.0 BLE applications for iOS or OSX? I have HW applications that uses BLE i.e. Bluetooth 4.0. I would like to get it working in Apple products such as iOS or OSX. My friend said that earlier developers had to be pay at least some 20k USD + margin of profits to get their hardware device accepted by Apple. The services have online frontend and specific hardware that are supposed be connected via BLE to phones/laptops.
What is the cost currently to develop BLE services for Apple?

A: BLE devices do not require Apple's MFi Program certification (which is apparently $20k+). Your only costs would be standard iOS Developer Program ($100) and the cost of developing the actual app to communicate with your BLE device.
From Apple's MFi FAQ:

I want to develop an accessory that communicates with an Apple device
  using only Bluetooth Low Energy. Do I need to join the MFi Program?
No. Accessories which connect to an Apple device using only Bluetooth
  Low Energy/BTLE/Bluetooth 4.0 or standard Bluetooth profiles supported
  by iOS are not part of the MFi Program.


text:
Q: Prove that a closed ball is closed without using complement Let $(X,d)$ be a metric space. The set $\{x \in X: d(x,x_0) \le r\}$ is a closed set.
My text have not introduced the property that if $E$ is closed in $X$, then $X \setminus E$ is open in $X$. So I am trying to prove in a different way.
My text defines a close set to be the set which contains its boundary. In addition, I know that if $E$ is closed, then for every convergent sequence in $E$, its limit also lies in $E$.
How can I use this definition and property to prove this?

A: Use the triangle inequality between $x_0$, a sequence $y_n$, and its limit $y$:
$$
d(y, x_0) \leq d(y, y_n) + d(y_n, x_0) \leq d(y, y_n) + r
$$
and use the convergence of $y_n$ to $y$.

A: The boundary of a closed ball of radius $r$, a sphere of the same radius and center, is indeed contained in the ball.

A: Suppose $x_n \to x$ where all $x_n \in D(p,r):=\{x: d(x,p) \le r\}$ for some $p \in X, r>0$.
I claim that $x \in D(p,r)$, because if $x \notin D(p,r)$ we have $d(x,p)>r$ and we define $\varepsilon = d(x,p)-r >0$ and by convergence:
$$\exists N: \forall n \ge N: d(x_n, x) < \varepsilon\tag{1}$$
and then note that, taking $(1)$ for $n=N$ and using that $x_N \in D(p,r)$ (so $d(x_N,p) \le r$) we have by the triangle inequality:
$$d(x, p) \le d(x_N,x) + d(x_N,p) < d(x_N,p) + \varepsilon \le r + \varepsilon = d(x,p)$$
and $d(x,p) < d(x,p)$ is a contradiction. So $x \in D(p,r)$ as well and the set is (sequentially) closed.


text:
Q: Call method on any array of structs that have underlying field Let's say I have a bunch of structs (around 10).
type A struct {
    ID int64
    ... other A-specific fields
}

type B struct {
    ID int64
    ... other B-specific fields
}

type C struct {
    ID int64
    ... other C-specific fields
}

If I have an array of these structs at any given time (either []A, []B, or []C), how can I write a single function that pulls the IDs from the array of structs without writing 3 (or in my case, 10) separate functions like this:
type AList []A
type BList []B
type CList []C

func (list *AList) GetIDs() []int64 { ... }
func (list *BList) GetIDs() []int64 { ... }
func (list *CList) GetIDs() []int64 { ... }

A: As far as I know, there is no easy way.
You might be tempted to use embedding, but I'm not sure there's any way to make this particular task any easier. Embedding feels like subclassing but it doesn't give you the power of polymorphism.
Polymorphism in Go is limited to methods and interfaces, not fields, so you can't access a given field by name across multiple classes.
You could use reflection to find and access the field you are interested in by name (or tag), but there are performance penalties for that and it will make your code complex and hard to follow. Reflection is not really intended to be a substitute for Polymorphism or generics.
I think your best solution is to use the polymorphism that Go does give you, and create an interface:
type IDable interface {
    GetId() int64
}

and make a GetId method for each of your classes. Full example.

A: With general method on the slice itself
You can make it a little simpler if you define a general interface to access the ID of the ith element of a slice:
type HasIDs interface {
    GetID(i int) int64
}

And you provide implementation for these:
func (x AList) GetID(i int) int64 { return x[i].ID }
func (x BList) GetID(i int) int64 { return x[i].ID }
func (x CList) GetID(i int) int64 { return x[i].ID }

And then one GetID() function is enough:
func GetIDs(s HasIDs) (ids []int64) {
    ids = make([]int64, reflect.ValueOf(s).Len())
    for i := range ids {
        ids[i] = s.GetID(i)
    }
    return
}

Note: the length of the slice may be a parameter to GetIDs(), or it may be part of the HasIDs interface. Both are more complex than the tiny reflection call to get the length of the slice, so bear with me on this.
Using it:
as := AList{A{1}, A{2}}
fmt.Println(GetIDs(as))

bs := BList{B{3}, B{4}}
fmt.Println(GetIDs(bs))

cs := []C{C{5}, C{6}}
fmt.Println(GetIDs(CList(cs)))

Output (try it on the Go Playground):
[1 2]
[3 4]
[5 6]

Note that we were able to use slices of type AList, BList etc, we did not need to use interface{} or []SomeIface. Also note that we could also use e.g. a []C, and when passing it to GetIDs(), we used a simple type conversion.
This is as simple as it can get. If you want to eliminate even the GetID() methods of the slices, then you really need to dig deeper into reflection (reflect package), and it will be slower. The presented solution above performs roughly the same as the "hard-coded" version.
With reflection completely
If you want it to be completely "generic", you may do it using reflection, and then you need absolutely no extra methods on anything.
Without checking for errors, here's the solution:
func GetIDs(s interface{}) (ids []int64) {
    v := reflect.ValueOf(s)
    ids = make([]int64, v.Len())
    for i := range ids {
        ids[i] = v.Index(i).FieldByName("ID").Int()
    }
    return
}

Testing and output is (almost) the same. Note that since here parameter type of GetIDs() is interface{}, you don't need to convert to CList to pass a value of type []C. Try it on the Go Playground.
With embedding and reflection
Getting a field by specifying its name as a string is quite fragile (think of rename / refactoring for example). We can improve maintainability, safety, and somewhat the reflection's performance if we "outsource" the ID field and an accessor method to a separate struct, which we'll embed, and we capture the accessor by an interface:
type IDWrapper struct {
    ID int64
}

func (i IDWrapper) GetID() int64 { return i.ID }

type HasID interface {
    GetID() int64
}

And the types all embed IDWrapper:
type A struct {
    IDWrapper
}

type B struct {
    IDWrapper
}

type C struct {
    IDWrapper
}

By embedding, all the embedder types (A, B, C) will have the GetID() method promoted and thus they all automatically implement HasID. We can take advantage of this in the GetIDs() function:
func GetIDs(s interface{}) (ids []int64) {
    v := reflect.ValueOf(s)
    ids = make([]int64, v.Len())
    for i := range ids {
        ids[i] = v.Index(i).Interface().(HasID).GetID()
    }
    return
}

Testing it:
as := AList{A{IDWrapper{1}}, A{IDWrapper{2}}}
fmt.Println(GetIDs(as))

bs := BList{B{IDWrapper{3}}, B{IDWrapper{4}}}
fmt.Println(GetIDs(bs))

cs := []C{C{IDWrapper{5}}, C{IDWrapper{6}}}
fmt.Println(GetIDs(cs))

Output is the same. Try it on the Go Playground. Note that in this case the only method is IDWrapper.GetID(), no other methods needed to be defined.

A: Generic methods require the use of interfaces and reflection.


text:
Q: Magento 2 knockout js translation is not working I'm using Magento 2.3.4
I'm looking at the translation issue for the last few days but I didn't get any answer.
I have used mageplaza one step checkout module.
Very recently I have upgraded the magento version to 2.3.4. previously I have 2.3.3.
Now the js translation on the checkout page is not working. But my custom phtml and php via translation were working fine. But only the knockout js translation is not working.
See the below screen.

I have checked the js translation file from pub/static/frontend/Fillme/default/de_CH/js-translation.json
On this file, the translation was reflected perfectly.
Eg : "Shipping Address":"Lieferadresse",
But in the frontend, it showing like Shipping Address.
There was an i18n translation available in one step checkout module itself and in my custom language package also.
Can anybody help on this issue

A: Please follow this step.

*

*Clear cache.

*Delete file js-translation.json in the pub folder.

*Remove the browser's cache in browser local storage (include
mage-translation-file-version and mage-translation-storage ).

If your problem didn't resolve, please let me know.

A: I have solved the above-mentioned issue.
In my case, the issue was in lib folder. I have tried to upload magento 2.3.4 lib folder on my local environment. And it's working. So, I conclude that, while upgrading the magento version, the library folder was not successfully upgraded. May be of any permission issue or something. I'm not sure about that.
So, in later anybody have such an issue, keep this step in your debugging scenario.


text:
Q: Change the color and content in cell (static) by clicking and keep changes after reload I am trying to make a status overview site for my work. I would like to make it like a table and where you click the cell then the cell will change between 3 options. I made an example here but I would like to have everything in one row.

    Name
      Status

    Martin
    Option 1

    Martin
    Option 2

    Martin
    Option 3

Then I would like the page to save the changes. Do I need SQL or can I run some javascript or something?
Hope you can help me.

A: you can do it without using any server side database. you can use sessionStorage or localStorage (html5) it's easy. take a look at:
http://zenorocha.com/html5-local-storage/
or
http://www.w3schools.com/html/html5_webstorage.asp
if you're not able to get it by yourself, come back again and tell your new troubble

A: also, you can use cookies
https://github.com/carhartl/jquery-cookie
Set your td index and color,
and when page is reloaded - read all available cookies


text:
Q: x86 dissasembler that shows instruction extensions needed I need to check the minimal set of x86 instruction extensions needed to execute a given binary object (not a general binary, but the output of gcc -c somefile.s). Doing it by hand is time consuming and error prone. I am looking for an automated process.
What I need is some binary that given a binary object as input returns an objdump-like output augmented with x86 instruction extensions. Something like the following example:
$ objdump-extended -d someobject.o
...
66 41 0f 38 00 c0    SSSE3    pshufb %xmm8,%xmm0
66 0f 6f d8          SSE2     movdqa %xmm0,%xmm3
66 0f fe 00          SSE2     paddd  (%rax),%xmm0
0f 38 cb d1          SHANI    sha256rnds2 %xmm0,%xmm1,%xmm2
...
Extensions used: SSE2, SSSE3, SHANI, ...

Is there a similar tool available?

A: The simplest and most reliable option is the one @PeterCordes mentions: using the assembler command line options to limit the set of available instructions.
If you need a compile-time warning/error when using non allowed instructions extensions with gas through gcc the following snippet illustrates an example allowing only generic x86_64 instructions plus SSSE3 and SHANI extensions; anything else will report an error:
$ gcc -c -Wa,-march=generic64+ssse3+sha somefile.s

For already compiled binary objects I hacked a simple script that extends objdump output with per instruction extension with the help of the excellent tool Zydis:
#!/bin/bash

REGEX='^([0-9a-f]+)\s+<(.*)>\s+([0-9a-f][0-9a-f]( [0-9a-f][0-9a-f])*)\s+(.*?)$'
EXTS=

while read -r LINE ; do
  if [[ $LINE =~ $REGEX ]] ; then
    ADDR=${BASH_REMATCH[1]}
    LABEL=${BASH_REMATCH[2]}
    HEX=${BASH_REMATCH[3]}
    INSTR=${BASH_REMATCH[5]}
    EXT=$(ZydisInfo -64 $HEX | grep '    ISA-EXT:' | cut -d ' ' -f 6)
    [[ " $EXTS " != *" $EXT "* ]] && EXTS="$EXTS $EXT"
    echo -e "$LABEL\t$EXT\t$INSTR"
  fi
done < <(objdump --disassemble --wide --prefix-addresses --show-raw-insn "$1")

echo "Extensions:$EXTS"

NOTE: The previous code makes no attempt to check for errors or unexpected states. Use at your own risk.

A: You can use Intel's X86 Encoder Decoder (XED) to obtain a similar output.
Instructions:
git clone https://github.com/intelxed/xed.git xed
git clone https://github.com/intelxed/mbuild.git mbuild
cd xed
./mfile.py examples

obj/wkit/examples/obj/xed -A -i someobject.o

This produces the following output:
...
XDIS 0: SSE       SSSE3      66410F3800C0             pshufb %xmm8, %xmm0
XDIS 6: DATAXFER  SSE2       660F6FD8                 movdqa %xmm0, %xmm3
XDIS a: SSE       SSE2       660FFE00                 padddx  (%rax), %xmm0
XDIS e: SHA       SHA        0F38CBD1                 sha256rnds2 %xmm1, %xmm2
...

If you prefer Intel syntax, you can omit the -A parameter.


text:
Q: :32 ReferenceError: "document" is not defined javax.script.ScriptException I need to generate a symbol (in canvas or SVG format) using Spatial illusions javascript library and use that symbol in my java (Proprietary Framework) project. the java script code is available here. I am using below code for the same.
public class TestSymbolCreation {

    public static void main(String args[]) {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine scriptEngine = scriptEngineManager.getEngineByExtension("js");

        System.out.println(new File(".").getAbsoluteFile());

        File file = new File("./src/resources/milsymbol.js");
        try {

            Reader reader = new FileReader(file);
            scriptEngine.eval(reader);
            Bindings obj = (Bindings) scriptEngine.eval("var canvasElement = {value : new ms.Symbol('SFG-UCI----D',{size:35}).asCanvas() };  canvasElement;");
            Object canvas = obj.get("value");
            System.out.println("Canvas =>"+canvas);

        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ScriptException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

But I keep on getting the following exception. How to get this working? Can someone help me please?
javax.script.ScriptException: ReferenceError: "document" is not defined in <eval> at line number 32
    at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:467)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:451)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:403)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:399)
    at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
    at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
    at TestSymbolCreation.main(TestSymbolCreation.java:30)
Caused by: <eval>:32 ReferenceError: "document" is not defined
    at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57)
    at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:319)
    at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:291)
    at jdk.nashorn.internal.objects.Global.__noSuchProperty__(Global.java:1432)
    at jdk.nashorn.internal.scripts.Script$Recompilation$149$403515A$\^eval\_.L:1-1$L:32-8$exports(<eval>:32)
    at jdk.nashorn.internal.scripts.Script$87$\^eval\_.:program(<eval>:1)
    at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:640)
    at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:228)
    at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:446)
    ... 5 more

A: This is Script executor only so it will not provide the document object as the browser provides.
To use the document object you need to integrate third party browser which can integrate with swing component e.g. JTidy


text:
Q: Could not be found or it does not implement IController I am working on an application which contains some ASP Classic, ASP.Net and ASP.Net MVC pages.
The main landing page of the application is developed in MVC and a sub directory which contain simple ASP.Net code.
I am getting a error when calling any ASP.Net page from sub directory.
The controller for path '/subdirectory/Recent.aspx' could not be found or it does not implement IController
Please help
Thanks in advance.

A: Your request is handled by the MVC handler before the ASP.NET, thus it will complain that you don't have the controller for subdirectory.
Phil Haack provided an overview on how to use the routing for ASP.NET webform:
http://haacked.com/archive/2008/03/11/using-routing-with-webforms.aspx


text:
Q: Reading a linked XML file with JavaScript In the <head> section of my HTML document, I have linked an XML file:
<link id="data" type="text/xml" href="Data.xml" />

I would like to read the contents of this file via JavaScript, but I can't even seem to get access to the contents of the file.
I tested it this way:
<script type="text/javascript">
    var link = document.getElementById("data");
    document.write(link.innerText);
    document.close();
</script>

What should I try next?
P.S. ...Can't use AJAX for this since it's all local files.

A: The link doesn't have a rel attribute, so the browser doesn't do anything with the URL (not that any value for rel means "Download and make it available to JS").
It doesn't have any innerText because it is an element defined as being empty. It exists only for the attributes it has on it.
You'll need to get the URL by using getAttribute and then fetch the data using an XMLHttpRequest object (i.e. Ajax).
The usual security restrictions for local files will apply. So you'll need to use a browser that supports access to them via XMLHttpRequest or install a local web server.


text:
Q: Windows Phone 8: In app purchase screen not showing I'm trying to add in-app purchase functionality to my game made with Unity3D in C#. To my knowledge when a user initiates a purchase - that is clicks say a 'buy' button from within your game they should be taken to a purchase screen?
Without going into the details of how plugins work, this is the function being called from the phone to initiate the purhase:
private static async Task<string>PurchaseUpgrade(string ID)
{
    var listings = await CurrentApp.LoadListingInformationAsync();

    var purchaseItem = listings.ProductListings.FirstOrDefault(x => x.Value.ProductId == ID &&
                                                                x.Value.ProductType == ProductType.Durable);
    try
    {
        if (CurrentApp.LicenseInformation.ProductLicenses[purchaseItem.Value.ProductId].IsActive)
        {
            return false.ToString();
        }
        else
        {
            Receipt = await CurrentApp.RequestProductPurchaseAsync(purchaseItem.Value.ProductId, true);
            return true.ToString();
        }
    }
    catch (Exception w)
    {
        return w.ToString();
    }
}

This gets called when the user clicks a 'buy' button from within unityplayer.
This is the first time I've worked with IAP so to my knowledge when the else block is entered which contains the line:
Receipt = await CurrentApp
              .RequestProductPurchaseAsync(purchaseItem.Value.ProductId, true);

It should 'bring up' a purchase screen? To confirm the purchase?
Anyway this is not the case, anyone got any experience with this?

A: This guide will help you test IAP in local machine Local IIS Web Service and WP8 Emulator
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj681689(v=vs.105).aspx

A: I would say you have to run this on UI thread
Deployment.Current.Dispatcher.BeginInvoke(() => ShowBuyDialog(productId));


text:
Q: Laravel Eloquent "with" / "load" return null I am trying to get ralation (product owner) using with method but it returns me null.
After some tests i see my relation is ok if im using simple way to get it ($goodRelation in example), but if im trying to get relation with with method it any way returns null
EXAMPLES
$goodWith = Good::where('id', '4d7d36f2-75ad-4a9f-a5a5-ba8b56840414')->with('user')->first()->user;
$goodsLoad = Good::where('id', '4d7d36f2-75ad-4a9f-a5a5-ba8b56840414')->first()->load('user')->user;
$goodFirstUserFirst = Good::where('id', '4d7d36f2-75ad-4a9f-a5a5-ba8b56840414')->first()->user()->first();
$goodsRelation = Good::where('id', '4d7d36f2-75ad-4a9f-a5a5-ba8b56840414')->first()->user;

dd($goodWith, $goodsLoad, $goodFirstUserFirst, $goodsRelation);

Result:
$goodWith           -> NULL
$goodsLoad          -> NULL
$goodFirstUserFirst -> USER MODEL
$goodsRelation      -> USER MODEL

My User model:
public function goods()
{
    return $this->hasMany(Good::class);
}

My Good model:
public function user()
{
    return $this->belongsTo(User::class);
}

Problem in real example:

Why i can not get relation with with of load method ?

A: From the Laravel 7 docs;

If your primary key is not an integer, you should set the protected $keyType property on your model to string:

<?php

class Flight extends Model
{
    /**
     * The "type" of the auto-incrementing ID.
     *
     * @var string
     */
    protected $keyType = 'string';
}

A: SOLUTION: If you are using uuid or not default integer - you should set $keyType in your model.
class Flight extends Model
{
    /**
     * The "type" of the auto-incrementing ID.
     *
     * @var string
     */
    protected $keyType = 'string';
}


text:
Q: How to remove a partition and create a new partition for usr in cloud environment I'm working with a AWS environment with 8G root and there is only 1.4G free space at the beginning.
$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda1      8.0G  6.7G  1.4G  83% /
devtmpfs        7.8G     0  7.8G   0% /dev
tmpfs           7.8G  4.0K  7.8G   1% /dev/shm
tmpfs           7.8G   17M  7.8G   1% /run
tmpfs           7.8G     0  7.8G   0% /sys/fs/cgroup
/dev/xvdc1       30G  1.4G   27G   5% /data
/dev/xvdb1       30G   45M   28G   1% /appl
tmpfs           1.6G     0  1.6G   0% /run/user/601

$ lsblk
NAME    MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
xvda    202:0    0   8G  0 disk
└─xvda1 202:1    0   8G  0 part /
xvdb    202:16   0  30G  0 disk
└─xvdb1 202:17   0  30G  0 part /appl
xvdc    202:32   0  30G  0 disk
└─xvdc1 202:33   0  30G  0 part /data

Start from now I need to install many rpms which will go into /usr. Since it is on the cloud, I don't have root login nor can't mount CD. And I suppose I can't boot into rescue mode neither.
I tried the following ways to expand space for /usr but got no luck.

*

*resize /dev/xvdc1 and free space for /usr, got Invalid path for Logical Volume error.
$ sudo umount /dev/xvdb1
$ sudo e2fsck -f /dev/xvdb1
e2fsck 1.42.9 (28-Dec-2013)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
/dev/xvdb1: 13/1966080 files (0.0% non-contiguous), 167455/7864064 blocks
$ sudo resize2fs /dev/xvdb1 10G
resize2fs 1.42.9 (28-Dec-2013)
Resizing the filesystem on /dev/xvdb1 to 2621440 (4k) blocks.
The filesystem on /dev/xvdb1 is now 2621440 blocks long.

$ sudo lvreduce -L 10G /dev/xvdb1
  "/dev/xvdb1": Invalid path for Logical Volume.
  Run `lvreduce --help' for more information.
$ sudo lvresize -L 10G /dev/xvdb1
  "/dev/xvdb1": Invalid path for Logical Volume.
  Run `lvresize --help' for more information.
$ sudo lvreduce -L 10G /dev/xvdb/xvdb1
  Volume group "xvdb" not found
  Cannot process volume group xvdb

*clear /appl and mount /usr on /dev/xvdb1
following the steps on this link, after finished, I lost all the commands...
$ sudo rm -rf /appl/*
$ sudo rsync -a /usr /appl
$ sudo umount /appl
$ sudo cat /etc/fstab

#
# /etc/fstab
# Created by anaconda on Mon May  1 18:59:01 2017
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
UUID=29342a0b-e20f-4676-9ecf-dfdf02ef6683 /                       xfs     defaults        0 0
/dev/xvdb1      /usr    ext4    defaults        0       0
/dev/xvdc1      /data   ext4    noatime 0       1
$ sudo mount /dev/xvdb1 /usr
$ df -h
-bash: /usr/bin/df: No such file or directory

I'm wondering whether there is a way to achieve it. Thanks in advance!


text:
Q: Error message is not displayed in freemarker template for custom FieldMatchValidator in Spring application As stated in the title I can't make the error message for the FieldMatchValidator to show in my freemarker template. All the other "regular" error messages, such as @NotNull are displayed with the accurate message from message.properties. The validation with FieldMatchValidator works since the result.hasErrors() returns true and the result objects holds the FieldMatch error. What have I missed?
applicationContext.xml:

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">

            <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
                <property name="validator" ref="validator"/>
            </bean>
        </property>
    </bean>

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="messageInterpolator">
            <bean class="com.reco.web.mvc.validator.CustomMessageInterpolator">
                <property name="messageSource" ref="messageSource"/>
            </bean>
        </property>
    </bean>

Controller:
@Controller
public class RegisterController extends MyWebController{

    private static final String REGISTER_FORM_VIEW = "/action/register/register";
    private static final String REGISTER_SUCCESS_VIEW = "/action/register/success";

    private org.springframework.validation.Validator validator;

    @Autowired
    public RegisterController(MessageSource messageSource, Validator validator) {
        super(messageSource);
        this.validator = validator;
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator((org.springframework.validation.Validator)validator);
    }

    @RequestMapping(value = "/action/register", method = RequestMethod.GET)
    public ModelAndView getRegisterForm() {
        ModelAndView mav = new ModelAndView(REGISTER_FORM_VIEW);
        mav.addObject("registerForm", new RegisterForm());
        return mav;
    }

    @RequestMapping(value = "/action/register", method = RequestMethod.POST)
    public final String register(@Valid RegisterForm registerForm, BindingResult result, ModelMap model, HttpServletRequest request) {

        if (result.hasErrors()) {
            return REGISTER_FORM_VIEW;
        }

        return "redirect:" + REGISTER_SUCCESS_VIEW;
    }

}

Annotation:
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = FieldMatchValidator.class)
@Documented
public @interface FieldMatch {

    String message() default "{constraints.fieldmatch}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * @return The first field
     */
    String first();

    /**
     * @return The second field
     */
    String second();

    /**
     * Defines several @FieldMatch annotations on the same element
     *
     * @see FieldMatch
     */
    @Target({TYPE, ANNOTATION_TYPE})
    @Retention(RUNTIME)
    @Documented
            @interface List {
        FieldMatch[] value();
    }

}

Validator:
public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object>
{
    private String firstFieldName;
    private String secondFieldName;

    @Override

public void initialize(final FieldMatch constraintAnnotation)
{
    firstFieldName = constraintAnnotation.first();
    secondFieldName = constraintAnnotation.second();

}

   @Override
    public boolean isValid(final Object value, final ConstraintValidatorContext context)
    {
        try
        {
            final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
            final Object secondObj = BeanUtils.getProperty(value, secondFieldName);

            return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
        }
        catch (final Exception ignore)
        {
            // ignore
        }
        return true;
    }
}

freemarker template:
<!doctype html>

    <meta charset="utf-8"/>
    <title></title>

    <form id="registerForm" action="${rc.contextPath}/action/register" method="POST">

            firstname
        <@spring.formInput "registerForm.firstName" />
        <@spring.showErrors "", "error"/>

            lastname
        <@spring.formInput "registerForm.lastName" />
        <@spring.showErrors "", "error"/>

            email
        <@spring.formInput "registerForm.email" />
        <@spring.showErrors "", "error"/>

            email_again
        <@spring.formInput "registerForm.confirmEmail" />
        <@spring.showErrors "", "error"/>

            password
        <@spring.formPasswordInput "registerForm.password" />
        <@spring.showErrors "", "error"/>

            password_again
        <@spring.formPasswordInput "registerForm.confirmPassword" />
        <@spring.showErrors "", "error"/>
        <@spring.showErrors "", "confirmPassword"/>

        <input type="submit"/>
    </form>

FormObject:
@FieldMatch.List({
        @FieldMatch(first = "password", second = "confirmPassword", message = "validation.message.confirm.password"),
        @FieldMatch(first = "email", second = "confirmEmail", message = "validation.message.confirm.email")
})
public class RegisterForm implements Serializable {

    private static final int MAX_TEXT_FIELD_SIZE = 32;

    /**
     * Password min size.
     */
    private static final int PASSWORD_MIN_SIZE = 8;

    /**
     * Password max size.
     */
    private static final int PASSWORD_MAX_SIZE = 36;

    @NotNull(message = "validation.message.firstname.empty")
    @Size(min = 1, max = MAX_TEXT_FIELD_SIZE, message = "validation.message.firstname.length")
    @Pattern(regexp = "^[^<>]*$", message = "validation.message.invalid.characters")
    private String firstName;

    @NotNull(message = "validation.message.lastname.empty")
    @Size(min = 1, max = MAX_TEXT_FIELD_SIZE, message = "validation.message.lastname.length")
    @Pattern(regexp = "^[^<>]*$", message = "validation.message.invalid.characters")
    private String lastName;

    @NotNull(message = "validation.message.email.empty")
    @Pattern(regexp = ".+@.+\\.[a-z]+", message = "validation.message.email", flags = { Pattern.Flag.CASE_INSENSITIVE })
    private String email;

    @NotNull(message = "validation.message.email.empty")
    @Pattern(regexp = ".+@.+\\.[a-z]+", message = "validation.message.email", flags = { Pattern.Flag.CASE_INSENSITIVE })
    private String confirmEmail;

    @NotNull
    @Size(min = PASSWORD_MIN_SIZE, max = PASSWORD_MAX_SIZE)
    private String password;

    @NotNull
    @Size(min = PASSWORD_MIN_SIZE, max = PASSWORD_MAX_SIZE)
    private String confirmPassword;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getConfirmEmail() {
        return confirmEmail;
    }

    public void setConfirmEmail(String confirmEmail) {
        this.confirmEmail = confirmEmail;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getConfirmPassword() {
        return confirmPassword;
    }

    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }
}

A: I solved the problem by adding the proper constraint validation message:
errorMessage = constraintAnnotation.message();

to the proper field inside the custom FieldMatchValidator. In my case I added the error to the second field:
context.buildConstraintViolationWithTemplate(errorMessage).addNode(secondFieldName).addConstraintViolation();

FieldMatchValidator
public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object>
{
    private String firstFieldName;
    private String secondFieldName;
    private String errorMessage;

    @Override
    public void initialize(final FieldMatch constraintAnnotation)
    {
        firstFieldName = constraintAnnotation.first();
        secondFieldName = constraintAnnotation.second();
        errorMessage = constraintAnnotation.message();

    }

    @Override
    public boolean isValid(final Object value, final ConstraintValidatorContext context)
    {
        try
        {
            final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
            final Object secondObj = BeanUtils.getProperty(value, secondFieldName);

            boolean valid = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);

            if(!valid){
                context.buildConstraintViolationWithTemplate(errorMessage).addNode(secondFieldName).addConstraintViolation();
            }

            return valid;
        }
        catch (final Exception ignore)
        {
            // ignore
        }
        return true;
    }
}


text:
Q: A term for an island reclaimed from sea by adding sand What's the correct English term (adjective or a noun) for an island or a small peninsula that have been reclaimed from the sea by merely adding a lot of sand (gravel, dirt, stones, etc.) to the sea? I am especially interested in a term related to the times earlier than 200 years ago. For example, the spit of Vasilyevsky Island in Saint-Petersburg, Russia, was obtained in that way:

Dictionaries give me Hydraulic fill, but that term strikes me as too technical and rather modern.
I am interested either in a noun or an adjective (or, if possible, both). For example:

*

*This peninsula is a(n) ____________________.

or

*This is a(n) __________________ peninsula.

Nouns containing one or more spaces (like hydraulic fill) are also fine.

A: You can call it an artificial island:

Osaka airport was built on an artificial island in the bay, as there was no more space in the city.

When land is reclaimed from side of a river, it is called an embankment.

Cleopatra's needle was installed in London on the embankment of the Thames.

A large flat area reclaimed from the sea and protected by dykes, especially in the Netherlands, is a polder

The tulip fields on the Dutch polders are a popular tourist attraction.

In the particular case of Vasilyevsky Island, it seems that the island has been enlarged by land reclamation, and this is how I would describe it: "The western part of Vasilyevsky island was reclaimed from the Gulf of Finland." or "... is built on reclaimed land."

A: Land reclamation  or "infilled land" are two ways I've seen of describing this process.


text:
Q: IBM Websphere 9 Second server I have IBM Websphere running with the default server1.
I wanted to try and add another server (called server2), where I will install the same application as in server1, however it will have different connections (different database, different ActiveMQ connections).
I have reached to the point where i need to start the application, however I am getting the following error:
Test application is deployed to the server2 server. Stop or start the application from a console running on that server.

If i Try to go to the IBM admin console running on port 9044, i get the following error:
SRVE0255E: A WebGroup/Virtual Host to handle /ibm/console/login.do has not been defined.

SRVE0255E: A WebGroup/Virtual Host to handle localhost:9044 has not been defined.

I tried to look for solution however i cannot find anything. I created the second server using the wsadmin command.
Thank you


text:
Q: Android+Gradle download a file on build I need to download a file before the build and place it in my local "assets" folder.
I found this but I'm not familiar enough with gradle to use it in an android project.
https://github.com/michel-kraemer/gradle-download-task
I have the "android" task of course, but can I say this file downloading task should be done before that task?
Part of my build file:
android {
...
download {
        src 'https://example.com/data.json'
        dest assets
    }
...
}

This builds but nothing happens. Any help would be appreciated.

A: From the link you have provided, after configuring the plugin, write this task outside the android closure
task myTask << {
    //do something ...
    //... then download a file
    download {
        src 'http://www.example.com/index.html' // replace with your link
        dest buildDir // replace it with assets directory path
    }
    //... do something else
}

Add this line to run it before build
preBuild.dependsOn(mytask)

A: Please make the changes according to this sample code give
First make changes to project level gradle file like ,
https://github.com/michel-kraemer/gradle-download-task/blob/master/build.gradle
Next go to your main module build.gradle
Sample Download Task From The Same source


text:
Q: AWS Step Function Redshift Authentication I am building an AWS Step Function to trigger on SQS event messages. These messages will carry a simple payload with a startTime & endTime to run some Redshift queries.
I am clearly not giving Redshift the authentication it needs:
{
  "error": "RedshiftData.ValidationException",
  "cause": "To use IAM Authorization, both Cluster ID and DB User are required unless you're using Redshift Serverless. (Service: RedshiftData, Status Code: 400, Request ID: 3c7ef18f-ad28-46a2-8668-25cb6f5563bd, Extended Request ID: null)"
}

The question is how to configure the authentication properly.
Do I create a DB user as here? https://awsbytes.com/how-to-create-user-in-redshift-database/
How would I pass this in the step function?
Should I use a Secrets Manager? Is there a good guide on this?
There is my step Function code:
{
  "Comment": "Run Redshift Queries",
  "StartAt": "ReceiveMessage from SQS",
  "States": {
    "ReceiveMessage from SQS": {
      "Type": "Task",
      "Parameters": {
        "QueueUrl": "https://sqs.us-east-2.amazonaws.com/******/dev-queryProcessingQueue"
      },
      "Resource": "arn:aws:states:::aws-sdk:sqs:receiveMessage",
      "Next": "Run Analysis Queries",
      "ResultSelector": {
        "body.$": "States.StringToJson($.Messages[0].Body)"
      }
    },
    "Run Analysis Queries": {
      "Type": "Task",
      "Parameters": {
        "ClusterIdentifier": "test-*****-redshift-cluster",
        "Database": "prod",
        "Sql": "select * from my_test_table"
      },
      "Resource": "arn:aws:states:::aws-sdk:redshiftdata:executeStatement",
      "End": true
    }
  },
  "TimeoutSeconds": 3600
}

A: The solution is to add the Redshift access to the step function IAM Role.


text:
Q: BCrypt::Password Ruby I'm currently working on Ruby and I can't get, what is the difference between
def create_hash_digest(password)
  BCrypt::Password.create(password)
end

def verify_hash_digest(password)
  BCrypt::Password.new(password)
end

This sample is taken from Udemy course on complete Ruby on Rails

A: #create converts your password into a hash:
'my_password' ~> '$2a$12$C5.FIvVDS9W4AYZ/Ib37...'

while #new converts it back.

A: #create is used to Hash a secret, returning a BCrypt::Password instance i.e encryption
#new is used to decrypt BCrypt::Password instance with the data from a stored hash.
include BCrypt
# hash a user's password
@password = Password.create("my grand secret")
@password #=> "$2a$12$C5.FIvVDS9W4AYZ/Ib37YuWd/7ozp1UaMhU28UKrfSxp2oDchbi3K"

# store it safely @user.update_attribute(:password, @password)

# read it back
@user.reload!
@db_password = Password.new(@user.password)

# compare it after retrieval
@db_password == "my grand secret" #=> true
@db_password == "a paltry guess" #=> false


text:
Q: Soldering 2 usb cables into a single micro usb Sorry if this in the wrong place, but I'm not sure where else to post, and I'm not sure where to look, either.
Basically, I want to solder 2 female USB-A ports to a single micro USB-B plug, so that 2 devices (such as a keyboard and mouse) can be plugged in simultaneously. Is this a straight-forward process or does this require a whole interface to be built?
Reason for this is that I would like to plug those into my android device, but currently I can only plug in 1 device at a time.
Any replies will be appreciated.

A: This requires at minimum, a USB hub. USB's architecture doesn't allow for the line to be split electrically like that by just connecting two sockets to a single plug.
For your use case, you might be able to just use a regular USB hub (with appropriate connector cable) to connect multiple USB devices to your android device. I don't know if there is a limitation on the android device on if it can support hubs when it is in host mode, that's something you'd want to look into.
And there's a stack exchange website for electronic engineering, which might be a great place for this type of question.

A: This would not work, what you need is a USB hub. Two USB devices on a single header without a hub is not a supported configuration within the USB standard and just plain wouldn't work.


text:
Q: Can't read date variables in Python from SPSS (.sav) files I'm working with a .sav (SPSS) file in Python. All the variables look fine after import while using PyreadStat (also when using Pandas) except for the datetime variables. They read in as exponential numbers of type float using Python. But their original SPSS format is dd-mmm-yy (e.g., 02-feb-2021) of type date.
This is how the date variable looks like

1.383160e+10

Is there a way to convert this format to datetime using Python?
I've tried various ways of using the datetime module and time module. But what I get is a date from the year 2408
 # Here I'm using the float from the first row in the dataframe
 time.gmtime(13831603200)

The results

time.struct_time(tm_year=2408, tm_mon=4, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=113, tm_isdst=0)

When I use the datetime module:
python_date = datetime.fromtimestamp(13831603200).strftime('%d-%b-%Y, %H:%M:%S')
print(python_date)

22-Apr-2408, 00:00:00

[How the datetime variable (Vdatesub) is showing when using Python][1]
[1]: https://i.stack.imgur.com/I7yza.png

A: This is answered under these two posts (one Python, one R):
Convert 'seconds since October 14, 1582' to Python datetime
Read SPSS file into R, the data format for date is wrong, and generate more variable
In short: the date is stored as number of seconds from 14 Oct 1582, while Python starts at the Epoch date (01 Jan 1970).
You would need to calculate the number of seconds between 1582-10-14 and 1970-01-01 to adjust the timestamp value as per this post:
Timestamp out of range for platform localtime()/gmtime() function
(Possibly 12,218,515,200 seconds)


text:
Q: Can't access to power bi api from ROPC I try to get reports from power bi api. There is app with permissions, enter image description here. My request enter image description here. If i insert "openid" to scopes or any of Microsoft Graph scopes, request return access token. This token dont let me access to reports. If i insert "Report.Read.All" or any of Power BI scopes, i recieve invalid_grant error: 'The user or administrator has not consented to use the application with ID  named 'Интеграция с Битрикс24'. Send an interactive authorization request for this user and resource.'. Request from error message was send was sent by me many times. enter image description here. Please tell me what could be the mistake. What setting could I forget?

A: need to insert full url scope in request body to access power bi token. https://analysis.windows.net/powerbi/api/Report.Read.All instead of Report.Read.All

A: I could help you with an alternative where you can update the Graph Client to a Newer version. The admin of the subscription can grant the consent through the portal as shown below from Home > App > API Permissions.
We have done the following steps:
Using the following Steps:

*

*Revoke all admin consent.

*Remove all permissions

*Add removed permissions back.

*Grant admin consent.

Here is the Microsoft Document which you can refer to : Construct the URL for granting tenant-wide admin consent


text:
Q: Ubuntu 16.04 unity faild to load I am a beginner in Ubuntu 16.04. Read almost every similar post but cannot find a permanent solution. My graphic card settings:
*-display
       description: VGA compatible controller
       product: Curacao PRO [Radeon R7 370 / R9 270/370 OEM]
       vendor: Advanced Micro Devices, Inc. [AMD/ATI]
       physical id: 0
       bus info: pci@0000:01:00.0
       version: 00
       width: 64 bits
       clock: 33MHz
       capabilities: pm pciexpress msi vga_controller bus_master cap_list rom
       configuration: driver=amdgpu latency=0
       resources: irq:29 memory:d0000000-dfffffff memory:fda80000-fdabffff ioport:ce00(size=256) memory:c0000-dffff

Almost every time i boot, launcher bar is missing. When i reboot the system almost every time  is fine. I applied almost every solution i found here but with as i said no permanent solution.
Any suggestion?


text:
Q: How to handle blank space in Snowflake I am trying to replace null values with a blank space but its throwing an error in snowflake.
select
    case when CALL_DATE IS NULL then ' ' ELSE CALL_DATE end as CALL_DATE_NEW
from Table_x

A: The problem is the derived column CALL_DATE_NEW gets implicitly cast to type timestamp. As the error indicates, you can't specify a space as a timestamp. You can; however, specify a timestamp as a varchar:
create or replace temp table X (CALL_DATE timestamp);
insert into X values ('2021-12-03'), (null);

select case when CALL_DATE IS NULL then ' ' ELSE CALL_DATE end as CALL_DATE_NEW from x; -- Timestamp '' is not recognized

select case when CALL_DATE IS NULL then ' ' ELSE to_varchar(CALL_DATE) end as CALL_DATE_NEW from x; -- Works by keeping the types consistent

A: Date data types can be null or contain data and/or time data.
They cannot contain Space. Sorry.


text:
Q: Is there anything magical/logical/scientific about the number 125 in "The One"? Currently watching The One for the nth time in my entire life but as I watched it today, I noticed a small detail that intrigued me. As the Multiverse Authority was about to transport Jet Li to the Hades universe, it was said that he had 123 counts of murder and illegal travel.
Including himself (Bad Jet Li), and the last living parallel self he's about to kill (Good Jet Li), there should be a total of 125 universes that exist in the movie.
Is there anything magical/logical/scientific about the number 125?

A: When agent Funsch (Jason Statham) is explaining the whole multiverse business to Law (good Jet Li), he mentions something about how universes are created:

Every time a massive star dies and becomes a black hole, a new universe is created

He also mentions:

In this universe you are you, in another you don't exist [...]

Which implies that there are more universes than just the one with Jet Lis in them.
So I'm guessing the amount of kills is just about completely arbitrary, it's the amount of black holes that have been created in Statham's universe that happen to contain Jet Lis.

A: Actually, there is a very nice proof to show that every single natural number (and by extension every rational number) is interesting and special.
For the sake of contradiction, assume one natural number is not interesting or special. Then due to the canonic order of the natural numbers, there must be a smallest uninteresting and un-special number. Clearly being the smallest number is something special and quite interesting. Hence, we have established a contradiction and our initial assumption must be flawed. Therefore, every single number is interesting and special.
As a corollary, the number 125 (as well as 123) is quite thrilling and exciting. You can adapt the proof for the classification of your choice.

A: I think the number 125 was chosen at random and demonstrates critical research failure. 137 (the reciprocal of the fine-structure constant) would have been a better choice and would have shown an understanding of quantum theory.


text:
Q: Function is not defined (even though it is) I call this function inside a .then promise
this.retrieveMatches();

this function looks like the following
retrieveMatches: function(){
    var tableResult = makeHTMLMatchesTable(fetchMatches());
    var matches = document.getElementById('matches')
    matches.parentNode.insertBefore(tableResult, matches);
  },

this function is just above it:
 makeHTMLMatchesTable: function(array){
    //does stuff
    }

so why does the console say this:
Uncaught (in promise) ReferenceError: makeHTMLMatchesTable is not defined
when it clearly has been defined?

A: Change this code
retrieveMatches: function(){
    var tableResult = makeHTMLMatchesTable(fetchMatches());
    var matches = document.getElementById('matches')
    matches.parentNode.insertBefore(tableResult, matches);
  },

to
retrieveMatches: function(){
    var tableResult = this.makeHTMLMatchesTable(fetchMatches());
    var matches = document.getElementById('matches')
    matches.parentNode.insertBefore(tableResult, matches);
  }.bind(this),


text:
Q: Trouble with test code I am attempting to write test code for this simple trigger but it is failing.
This is the trigger :
trigger SetOverallContractEndDate on Contract_Terms__c (before update, before insert) {
  for (Contract_Terms__c ct : Trigger.new) {
          if (ct.Auto_Renewal_Contract_End_Date__c== null)
          ct.Overall_End_Date__c= ct.Contract_End_Date__c;
        else
          ct.Overall_End_Date__c = ct.Auto_Renewal_Contract_End_Date__c;
  }

}

This is my test code :
@isTest
private class SetContractEndDatesTriggerTest
{

  static TestMethod void SetContractEndDatesTest1()
  {
    Test.startTest();
                // Insert Contract_Terms__c record
    Contract_Terms__c  obj = new Contract_Terms__c(Name = 'test record 001', Contract_End_Date__c =  System.Today() +1, Auto_Renewal_Contract_End_Date__c = System.Today() + 2);
           insert obj;
                 Test.stopTest();
  }
}

Does anybody have an idea of what that might be ... ?
Thank you very much.

A: why dont you employee Field Updates for this? Configuration over Code


text:
Q: CSS3 ignore Child element when animating I am trying to scale a div containing a child div (with css background image) on hover. When I scale the div, the child div is also scaled. How can I get the child div to not inherit the animation of the parent? See my structure and fiddle here:

http://jsfiddle.net/B8bGE/

A: I worked around this by doing the following:

Then applying some css to .icoback. See the fiddle for details: http://jsfiddle.net/xtW22/2/


text:
Q: Closest distance between two lines I want to make a function to get the closest/shortest distance between any two lines (assuming they don't intersect). I know there are several posts about the shortest distance between a point and a line, but I couldn't find any for two lines.
I have consulted several math and vector learning sites and managed to crack out the algorithm below. It gives an answer, but not the correct one. For instance, when finding the shortest distance between:
l1 = [(5,6),(5,10)]
l2 = [(0,0),(10,10)]
print _line2line(l1,l2)

...it gives the answer as...
5.75223741636

As can be seen in the graph of the two lines (it shows a 10x10 frame with ticks mark every 1 unit) and theoretically speaking, the distance should be much smaller, around 1, between the points (6,5) and (5,5).
So I'm wondering if anyone can spot what I'm doing wrong in my code? (If possible I would also like to know how to get the actual points where the two lines are closest...)

Notes on the code below: L1 and L2 stands for line1 and line2, and x/y1 vs x/y2 being the start and endpoints of each line, respectively. The suffixes dx and dy stands for the delta or x and y, ie the vector if its origin is at 0,0.
def _line2line(line1, line2):

    """
    - line1 is a list of two xy tuples
    - line2 is a list of two xy tuples
    References consulted:
    http://mathforum.org/library/drmath/view/51980.html
    and http://mathforum.org/library/drmath/view/51926.html
    and https://answers.yahoo.com/question/index?qid=20110507163534AAgvfQF
    """

    import math
    #step1: cross prod the two lines to find common perp vector
    (L1x1,L1y1),(L1x2,L1y2) = line1
    (L2x1,L2y1),(L2x2,L2y2) = line2
    L1dx,L1dy = L1x2-L1x1,L1y2-L1y1
    L2dx,L2dy = L2x2-L2x1,L2y2-L2y1
    commonperp_dx,commonperp_dy = (L1dy - L2dy, L2dx-L1dx)

    #step2: normalized_perp = perp vector / distance of common perp
    commonperp_length = math.hypot(commonperp_dx,commonperp_dy)
    commonperp_normalized_dx = commonperp_dx/float(commonperp_length)
    commonperp_normalized_dy = commonperp_dy/float(commonperp_length)

    #step3: length of (pointonline1-pointonline2 dotprod normalized_perp).
    # Note: According to the first link above, it's sufficient to
    #    "Take any point m on line 1 and any point n on line 2."
    #    Here I chose the startpoint of both lines
    shortestvector_dx = (L1x1-L2x1)*commonperp_normalized_dx
    shortestvector_dy = (L1y1-L2y1)*commonperp_normalized_dy
    mindist = math.hypot(shortestvector_dx,shortestvector_dy)

    #return results
    result = mindist
    return result


text:
Q: Deleting files from a folder - android I have a folder which contains some files that I want to deleted after processing them. The files have the extension .FIR After some googling I found a recursive method that I modified a bit:
void delete(File f) throws IOException {
      if (f.isDirectory()) {
        for (File c : f.listFiles())
            if(f.listFiles().toString().contains(".FIR"))
                delete(c);
      }
      if (!f.delete())
        throw new FileNotFoundException("Failed to delete file: " + f);
    }

This function will throw an IOException telling me:
07-31 11:02:31.885: E/DELETE:(5694): Failed to delete file: /mnt/sdcard/ExtractedFiles

The folder has been set to RW operations. And in my manifest file:
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

I couldn't find another permission that sounded something like MODIFY_FILES
Any ideas?

A: try this:
void delete(File f) throws IOException {
    if (f.isDirectory()) {
        for (File c : f.listFiles()) {
            delete(c);
        }
    } else if (f.getAbsolutePath().endsWith("FIR")) {
        if (!f.delete()) {
            new FileNotFoundException("Failed to delete file: " + f);
        }
    }
}

A: Better use temp files....
File f = File.createTempFile("pattern", ".suffix");
Once the application is closed, the temp files are first closed then deleted.
See this link for more details:
http://www.roseindia.net/java/example/java/io/create-temp-file.shtml

A: I think the problem is here:
if(f.listFiles().toString().contains(".FIR"))

change this to:
if(c.getName().contains(".FIR"))

And make sure your directory contains files with extension .FIR only, otherwise (if any other extension files are available) it will still fail to delete a non-empty directory

Otherwise use the following method to get it done:
private static boolean delete(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = delete(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }
    return (dir.getName().contains(".FIR"))? dir.delete() : false;
}

A: check this
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

A: i was using this code and it;s working:
 String root_sd = Environment.getExternalStorageDirectory().toString();
 File file = new File(path) ;
  File list[] = file.listFiles();
    for(File f:list)
      {
     name =  file.getName();
    filestv.setText(f.getName());
    //add new files name in the list
   //  delete.setText(name );

      }

}

and you can follow the complete tutorials


text:
Q: difflib.get_close_matches GET SCORE I am trying to get the score of the best match using difflib.get_close_matches:
import difflib

best_match = difflib.get_close_matches(str,str_list,1)[0]

I know of the option to add 'cutoff' parameter, but couldn't find out how to get the actual score after setting the threshold.
Am I missing something? Is there a better solution to match unicode strings?

A: I found that difflib.get_close_matches is the simplest way for matching/fuzzy-matching strings. But there are a few other more advanced libraries like fuzzywuzzy as you mentioned in the comments.
But if you want to use difflib, you can use difflib.SequenceMatcher to get the score as follows:
import difflib
my_str = 'apple'
str_list = ['ape' , 'fjsdf', 'aerewtg', 'dgyow', 'paepd']
best_match = difflib.get_close_matches(my_str,str_list,1)[0]
score = difflib.SequenceMatcher(None, my_str, best_match).ratio()

In this example, the best match between 'apple' and the list is 'ape' and the score is 0.75.
You can also loop through the list and compute all the scores to check:
for word in str_list:
    print "score for: " + my_str + " vs. " + word + " = " + str(difflib.SequenceMatcher(None, my_str, word).ratio())

For this example, you get the following:
score for: apple vs. ape = 0.75
score for: apple vs. fjsdf = 0.0
score for: apple vs. aerewtg = 0.333333333333
score for: apple vs. dgyow = 0.0
score for: apple vs. paepd = 0.4

Documentation for difflib can be found here: https://docs.python.org/2/library/difflib.html

A: To answer the question, the usual route would be to obtain the comparative score for a match returned by get_close_matches() individually in this manner:
match_ratio = difflib.SequenceMatcher(None, 'aple', 'apple').ratio()

Here's a way that increases speed in my case by about 10% ...
I'm using get_close_matches() for spellcheck, it runs SequenceMatcher() under the hood but strips the scores returning just a list of matching strings. Normally.
But with a small change in Lib/difflib.py currently around line 736 the return can be a dictionary with scores as values, thus no need to run SequenceMatcher again on each list item to obtain their score ratios. In the examples I've shortened the output float values for clarity (like 0.8888888888888888 to 0.889). Input n=7 says to limit the return items to 7 if there are more than 7, i.e. the highest 7, and that could apply if candidates are many.
Current mere list return
In this example result would normally be like ['apple', 'staple', 'able', 'lapel']
... at the default cutoff of .6 if omitted (as in Ben's answer, no judgement).
The change
in difflib.py is simple (this line to the right shows the original):
return {v: k for (k, v) in result}  # hack to return dict with scores instead of list, original was ... [x for score, x in result]

New dictionary return
includes scores like {'apple': 0.889, 'staple': 0.8, 'able': 0.75, 'lapel': 0.667}
>>> to_match = 'aple'
>>> candidates = ['lapel', 'staple', 'zoo', 'able', 'apple', 'appealing']

Increasing minimum score cutoff/threshold from .4 to .8:
>>> difflib.get_close_matches(to_match, candidates, n=7, cutoff=.4)
{'apple': 0.889, 'staple': 0.8, 'able': 0.75, 'lapel': 0.667, 'appealing': 0.461}

>>> difflib.get_close_matches(to_match, candidates, n=7, cutoff=.7)
{'apple': 0.889, 'staple': 0.8, 'able': 0.75}

>>> difflib.get_close_matches(to_match, candidates, n=7, cutoff=.8)
{'apple': 0.889, 'staple': 0.8}


text:
Q: JSON to be passed from Apex to Lightning Component and display it in a data table Below is my JSON, out of which I need ID, StartTime,DurationMilliseconds,LogLength. Below is the code that I tried but it is returning only all the values in a single line.Any help would be apreciated:
{
   "size":6,
   "totalSize":6,
   "done":true,
   "queryLocator":null,
   "entityTypeName":"ApexLog",
   "records":[
      {
         "attributes":{
            "type":"ApexLog",
            "url":"/services/data/v50.0/tooling/sobjects/ApexLog/07L0o00005Y2fE1EAJ"
         },
         "Id":"07L0o00005Y2fE1EAJ",
         "StartTime":"2020-12-18T08:46:24.000+0000",
         "DurationMilliseconds":230,
         "LogLength":3883
      },
      {
         "attributes":{
            "type":"ApexLog",
            "url":"/services/data/v50.0/tooling/sobjects/ApexLog/07L0o00005Y2fE1EAJ"
         },
         "Id":"07L0o00005Y2fE1EAJ",
         "StartTime":"2020-12-18T08:46:24.000+0000",
         "DurationMilliseconds":230,
         "LogLength":3883
      }
   ]
}

================Controller.js==================
({
    doInit : function(component, event, helper) {
        var action = component.get("c.GetLogs");

        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {

                var conts= JSON.stringify(response.getReturnValue());
                console.log(conts);
                var res=conts.split(',');

                console.log('alert'+res[0].replace('{',' '));
                component.set("v.record",res);
            }
    });
        $A.enqueueAction(action);
    }
})

=====================Component==================
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" controller="DebugLogCallout">

    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="record" type="String[]" description="Debug Logs visible below"/>

    <aura:handler name ="init" value ="{!this}" action = "{!c.doInit}"/>

Key

Value

                <aura:iteration items="{!v.record}" var="opp" indexVar="key">

{!opp}

                </aura:iteration>

</aura:component>

========================Apex=================
public class DebugLogCallout {

    @AuraEnabled
    public static List<Object> GetLogs(){
        List<Object> objMap= new List<Object>();
        Map<String,Object> map1= new Map<String,Object>();
        Map<String,Object> finalMap= new Map<String,Object>();
        List<Map<string, object>> rec = new List<Map<String,Object>>();
        Map<string, object> attr = new Map<String,Object>();
        List<String> recIds = new List<String>();
        Http h = new Http();

        HttpRequest req = new HttpRequest();
        String FirstName = UserInfo.getFirstName();

        req.setHeader('Authorization', 'BASIC {!$Credential.OAuthToken}');
        req.setHeader('Content-Type', 'application/json');
        req.setEndpoint('callout:Debug_Log/services/data/v50.0/tooling/query/?q=Select+id,StartTime,DurationMilliseconds,LogLength+from+ApexLog+Where+LogUser.FirstName=\''+FirstName+'\'');
        req.setMethod('GET');
        system.debug(req);
        HttpResponse res = h.send(req);
        if (res.getStatusCode() == 200) {
            map1=(Map<String,Object>)JSON.deserializeUntyped(res.getBody());
            System.debug(res.getBody());
            System.debug('map1----'+map1);
             objMap = (List<Object>)map1.get('records');
            System.debug('objMap----'+ObjMap);
            for(Object o : objMap)
            {
                attr = (Map<string, object>)o;
                attr.remove('attributes');
                rec.add(attr);
            }
        }

        System.debug('strMapList'+rec);
        return rec;
    }
}

===============================================================

A: This is the wrong way to handle JSON.
            var conts= JSON.stringify(response.getReturnValue());
            console.log(conts);
            var res=conts.split(',');

            console.log('alert'+res[0].replace('{',' '));
            component.set("v.record",res);

You're turning your JSON, a nice structured object that you can process easily in code, into a string, and then doing replaces on it. Don't do that.
You really do not need to do any of the data manipulation you're currently doing. Simply return the entire response body from Apex:
    HttpResponse res = h.send(req);
    if (res.getStatusCode() == 200) {
        return res.getBody();

and in JavaScript, extract the record data that you want:
        var state = response.getState();
        if (state === "SUCCESS") {
            component.set("v.records", response.getReturnValue()["records"]);

and wire your Lightning data table component up to the v.records attribute, with an appropriate column set for the record data.


text:
Q: Arrangement of 2 by 2 condition in if statement in C-family language When programming, I'm usually dealing with two sets of conditions combined together, like:
if (A && B){...}
else if (!A && B){...}
else if (A && !B){...}
else if (!A && !B){...}

It can also be resolved using nested if statements.
if (A){
    if (B) {...}
    else {...}
}
else {
    if (B) {...}
    else {...}
}

EDIT: Some new thoughts, what about I firstly evaluate both A and B and store as temporary variable (then do as the first approach) in case that the evaluation of A and B both have no side-effect?

So my question is there any performance difference between them and what about their readability?
I code in C++, if matters.

A: The two cases are not the same. In the second case, A and B will each be evaluated exactly once. In the first case, A and B will evaluated a number of times, depending upon their value.
While this almost certainly won't affect the optimization of the typical case, it will matter if A or B have side effects.

A: There's no way to predict which code generation strategy the compiler will choose in cases like that (and it can actually depend on surrounding context). This makes your question unanswerable in general case. One should normally expect the compiler to be smart enough to recognize the equivalence of both of your constructs (assuming they are indeed equivalent) and choose the most optimal one automatically.
The most optimal code generation strategy might be something else altogether, e.g.
// Assuming A and B are either 0 or 1
switch ((A * 2) + B) {
  case 0: ...; break;
  case 1: ...; break;
  case 2: ...; break;
  case 3: ...; break;
}

Just choose whatever makes your code more readable.

A: It's a hard question; honestly, I think everyone looks at this a little bit differently.  As people have mentioned here it does not matter as a compiler should generate the same output for both (should! not necessarily will — it honestly depends on the code).
Yet, for example, let's look at this code:
int  Nested(int a)
{
    if(a > 0)
    {
        if( a > 1)
        {
            if( a % 2 == 0)
            {
                if( a % 10 == 4)
                {
                    printf("a is valid");
                    return 1;
                }
                else
                {
                    printf("a's last digit inst 4");
                }
            }
            else
            {
                printf(" a is not odd");
            }
        }
        else
        {
            printf(" a is not bigger than 1");
        }
    }
    else
    {
        printf(" a is not bigger than 0");
    }

    return 0;

}

int NotNested(int a)
{
    if(a <= 0)
    {
        printf(" a is not bigger than 0");
        return 0;
    }

    if(a <= 1)
    {
        printf(" a is not bigger than 1");
        return 0;
    }

    if(a % 2 != 0)
    {
        printf(" a is not odd");
        return 0;
    }

    if( a % 10 != 4)
    {
        printf("a's last digit inst 4");
        return 0;
    }

    printf("a is valid");

    return 1;

}

I personally think that NotNested in my example is much more readable,
yet it's my personal opinion and both of these functions should do the same.
So yeah, in terms, of readability try to avoid nesting.


text:
Q: Delete a character in excel until the first character I have data in a column that is structured like this:

s1 ma(av) course title

And i want to delete everything up till and including the ")"
BUT sometimes in my data something like this occures:

s1 ma(av) course title(extra info)

So if i do a find and replace with this "*)" it deletes everything.
Is there a way to delete everything up until the first ")"?
The result should be:

course title(extra info)

Thanks in advance

A: Unfortunately my Excel is in german only, but im sure you can translate the functions.
This should work:
=TEIL(A1;FINDEN(")";A1)+2;55)

The "+2" deletes the following whitespace.

A: you can specify the number of characters you want to remove from the left string by changing the Number 10 in the formula
=RIGHT(A1;LEN(A1)-10)


text:
Q: Test set for reflexive, symmetric, or transitive using a struct I have this struct in my code
struct Pair
{
  int x,y;
  friend bool operator==(Pair a, Pair b)
  {
     return a.x == b.x && a.y == b.y;
  }
  friend istream& operator>>(istream& is, Pair& a)
  {
    is >> a.x >> a.y;
    return is;
 }
 friend ostream& operator<<(ostream& os, Pair a)
 {
    os << '(' << a.x << ',' << a.y << ')';
    return os;
 }
};

int main(){
Pair p;
fstream file;
string fileName = "Text.txt";
file.open(fileName.c_str(), fstream::in);
if(!file){
    cout << "Could Not Open " << fileName << " File" << endl;
}else{
    int size = 43;
    int * myArray = new int[size];
    for(int i = 0; i < size; i++){
        file >> myArray[i];
    }
    printArray(myArray,size);
}
return 0;

}
Reading From A text File

5 1 1 2 2 3 3 4 4 5 5
7 1 1 2 2 3 3 4 4 4 7 7 4 7 7
8 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64

This file has 3 relations in it, each one starts with an int which is the number of pairs in that relation, then that many pairs follows. Then (if not eof) read another int and that many pairs again, and so on.
How can I read this data into my struct pair?

A: More or less something like this:
#include <fstream>
#include <iostream>
#include <list>
#include <vector>

struct Pair
{
    int x,y;
    friend bool operator==(Pair a, Pair b)
    {
        return a.x == b.x && a.y == b.y;
    }
    friend std::istream& operator>>(std::istream& is, Pair& a)
    {
        is >> a.x >> a.y;
        return is;
    }
    friend std::ostream& operator<<(std::ostream& os, Pair a)
    {
        os << '(' << a.x << ',' << a.y << ')';
        return os;
    }
};

int main()
{
    std::fstream file;
    file.open("Text.txt", std::fstream::in);

    std::list<std::vector<Pair> > relations;
    int size = 0;
    while(file >> size)
    {
        relations.emplace_back(size);
        for(int i=0; i < relations.back().size() && file >> relations.back()[i]; i++);
    }

    //Print
    for(auto &r : relations)
    {
        std::cout << "[";
        for(auto &p : r)
        {
            std::cout << p;
        }
        std::cout << "]\n";
    }

    return 0;
}

Example


text:
Q: "COM object that has been separated from its underlying RCW cannot be used." with static WMI event I am trying to implement an USB device notifier which  has static events when e.g. a USB device is unpugged. I tried this with a class like the following:
public static class WmiUsbNotifier
{
    private static ManagementEventWatcher watcherDetach;

    public static event EventHandler<EventArgs<WmiDeviceNotifyEventArgs>> DeviceNotify;

    public static void Initialize()
    {
        var detachQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_USBControllerDevice'");
        watcherDetach = new ManagementEventWatcher();
        watcherDetach.EventArrived += ManagementEventWatcher_Detaching;
        watcherDetach.Query = detachQuery;
        watcherDetach.Start();
    }
    public static void ShutDown()
    {
        watcherDetach?.Stop();
        watcherDetach?.Dispose();
        watcherDetach = null;
    }

    private static void ManagementEventWatcher_Detaching(object sender, EventArrivedEventArgs e)
    {
        var targetInstance = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
        var id = targetInstance.Properties["Dependent"].Value.ToString();
        DeviceNotify?.Invoke(watcherDetach, new WmiDeviceNotifyEventArgs(EventType.DeviceRemoveComplete, id));
    }
}

This works fine and everything is well IF I call ShutDown() before closing my app (e.g. in OnExit of my WPF App). But if I do not call that I get the following error when closing my app:

An unhandled exception of type 'System.Runtime.InteropServices.InvalidComObjectException' occurred in System.Management.dll
Additional information: COM object that has been separated from its underlying RCW cannot be used.

Now I would like to avoid this WITHOUT the need to "externally call ShutDown()", because this is part of a library which can be used by others and the chances are high the will forget to call that method in their apps.
I tried already calling it in AppDomain.CurrentDomain.DomainUnload, but the exception occures before that. I also tried making the class above not static and adding a finalizer/IDisposable and setting an instance as a static property of another class, but there the finalizer is also called to late.
Is there any way to call the ShutDown() method "automatically" before this exception occurs?
Or is there a way to catch and swallow exactly this exception? (As it happens when shutting down it can be ignored anyway)


text:
Q: Use a for-loop for the same procedure on multiple databases I want to condense my code by using a for-loop. Currently I have the following:
log.1 = log(canine.dg.16.1$claimedamountSum)
log.2 = log(canine.dg.16.2$claimedamountSum)
log.3 = log(canine.dg.16.3$claimedamountSum)

etc. for 1:36
Is there a way to not have 36 lines of code but instead have a for-loop that will repeat this process for each data frame (1:36)?

A: We can get the datasets into a list and apply the code in the list
lst1 <- lapply(mget(ls(pattern = "canine\\.dg\\.16\\.\\d+$")), function(x)
         log(x$claimedamountSum))

Instead of creating multiple objects in the global environment, it is better to store the output in a list


text:
Q: Slow query performance and error troubleshooting - the 'where' clause is looking up a value in @Table on SQL Server 2012 I have a query that has multiple parts. I get certain information and put it into a table using DECLARE @TABLENAME TABLE(). I then have a query directly below which has a 'where' clause that looks like this:
WHERE a.PatientAccountID IN (
    SELECT Encounter
    FROM @TOC
)

In this query, @TOC.Encounter = A.PatientAccountID, so it is my understanding that this query will only look at encounters from the @TOC table.
This is not the case, so I am assuming there is a full table load going on and then the 'where' clause is being used. Am I understanding this correctly?
Should I instead put that 'where' clause in the JOIN above it? I know this is not working as I thought because I had to add:
AND A.PatientAccountID NOT IN (
    '12345678910', '99990000999'
)

to prevent errors.

I later changed the join to this (the error persisted):
FROM smsmir.sc_patientvisit                   AS A
    LEFT OUTER JOIN smsdss.QOC_vst_summ_v    AS B
    ON a.PatientAccountID = b.episode_no
        --test
        AND a.PatientAccountID IN (
            SELECT Encounter
            FROM @TOC
        )
    LEFT OUTER JOIN...

I have checked the @TOC table Encounter column. The offending numbers of 12345678910 and 99990000999 do not exist in that table. I have tried using
WHERE a.PatientAccountID IN (
    SELECT t.Encounter
    FROM @TOC t
)

and
WHERE EXISTS (
    SELECT T.Encounter
    FROM @TOC T
    WHERE T.Encounter = A.PatientAccountID
)

Both to no avail so far... Also strangely enough, when I do the following,
SELECT t.Encounter
FROM @TOC t

the offending encounter id's do not come out, but when I do
SELECT t.Encounter
FROM @TOC t
WHERE t.Encounter = '12345678910'

I get the varchar conversion error as @TOC.Encounter is of type INT. So I guess, as initially indicated by Gordon Linoff, my error lies there.

A: [EDIT] Judging by the error that you are getting and the new information, it sounds like you also need to cast PatientAccountID to an INT when comparing it with Encounter. This can be done by using CONVERT(INT, @Val) or cast(@Val as INT).
When using the IN clause with a subquery, the subquery will return everything, even if a.PatientAccountID was found, so yes you are right that a full table load is happening. If you want to minimize the table load then you could change it to an EXISTS like so:
WHERE EXISTS
(
    SELECT t.Encounter
    FROM @TOC t
    WHERE t.Encounter = CONVERT(INT, a.PatientAccountID)
)

This would exit the subquery once a match is found, which makes this option the more appropriate choice for your fix.
As a side note you could also do an INNER JOIN on @TOC with a join condition matching Encounter with PatientAccountID like so:
FROM smsmir.sc_patientvisit AS a
    LEFT OUTER JOIN smsdss.QOC_vst_summ_v AS b ON a.PatientAccountID = b.episode_no
    INNER JOIN @TOC AS t ON CONVERT(INT, a.PatientAccountID) = t.Encounter

A: WHERE a.PatientAccountID IN (
    SELECT t.Encounter
    FROM @TOC t
)

One possibility is that the column in @TOC is not really called Encounter -- perhaps a slight misspelling. Without the qualified column name, SQL will take the field from a table in the outer scope -- and that field and the patient id might always be equal. That would explain the fact that no filtering occurs.
In any case, it is a good idea to always used qualified column names to avoid any confusion.
This is just an idea.