text:
Q: How can I make this repeat? Jquery:
var picname = ["1.jpg"];
      var pics = 0;

      $("#pic").mouseenter(function() {

        $("#pic").fadeOut(300, function() {
          $("#pic").attr("src", picname[pics]);
          pics++;
          if (pics > 2) {pics = 0;}
          $("#pic").fadeIn(500);
        });

      });

$("#pic").mouseleave(function() {

        $("#pic").fadeOut(300, function() {
          $("#pic").attr("src", picname[pics]);
          pics++;
          if (pics > 2) {pics = 0;}
          $("#pic").fadeIn(500);
        });

  });

Html:

I want to repeat itself for exemple when I put my mouse on that picture it changes and when I leave the mouse it become to normal and this repeats itself.

A: If you want it to cycle between 2 pictures, you dont need the array with picture names. just do it like this:

$("#pic").mouseenter(function() {
  $("#pic").fadeOut(300, function() {
    $("#pic").attr("src", "http://images.all-free-download.com/images/graphiclarge/banana_clip_art_13734.jpg");
    $("#pic").fadeIn(500);
  });
});
$("#pic").mouseleave(function() {
  $("#pic").fadeOut(300, function() {
    $("#pic").attr("src", "http://images.all-free-download.com/images/graphiclarge/banana_clip_art_13529.jpg");
    $("#pic").fadeIn(500);
  });
});


text:
Q: Dynamically create filter and matching checkboxes in AngularJs I have many data points, with several types;
JSON file:
{
  "items":[
    {
      "id:": 1,
      "type": "type1", //typeN isn't tied to id=N
      ... : ...
    },
    {
      "id:": 2,
      "type": "anotherType",
      ... : ...
    },
    {...},{...},{...},...
  ]
}

I want to filter these results with checkboxes in the DOM.  So first I want to get them into the DOM. So I need to find the unique types in the data.  I do this through this function in the Controller:
var itemTypeList = function(){
  if ($scope.hasOwnProperty('allItems')){ //this is to ensure async load completed
    var uniqTypes = [];
    for (var i=0 ; i < $scope.allItems.length ; i++){
      if (uniqTypes.indexOf($scope.allItems[i].type) < 0){
        uniqTypes.push($scope.allItems[i].type);
      }
    }
    $scope.uniqTypes = uniqTypes;
    return $scope.uniqTypes;
  }
};

and then I place them in the HTML like so:

    {{item.name}}

  {{uT}}

So far, my Controller Filter looks like this:
$scope.showItem = function(item){
   return item.type === $scope.Filter.item1 ||
     item.type === $scope.Filter.type2;
     //this is static, and I only typed 2 of the many....
};

and the input check box looks like
<input type="checkbox" ng-model="Filter.uT" ng-true-value="{{uT}}"/>

The problem is that the filter is static, and I had to manually put in the types.  The second problem is that the checkbox ng-model can't be defined like so ng-model="Filter.{{uT}}".  I can only find examples of statically defined models.   How do I change the filter and the input ng-repeat to use the uniqueTypes (uT) that I have already found?

A: Can't see the whole picture, but it seems like you want something like this:

  {{uT}}
  <input type="checkbox" ng-model="Filter[uT]"/>

value of checkbox will be true or false -->  $scope.Filter.type2 will be true/false
$scope.Filter = {};

$scope.showItem = function(item){
   return $scope.Filter[item.type];
};

will return true  or false
fiddle of the basic version
If you want to have them showing initially, and click to unhide, the $scope.Filter needs to be populated first by a key[val] pair.  This can be done when you dynamically create the uniqueTypes list.
Here is this fiddle of it showing and checked initially

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get the seed from a Random already created I have to be able to repeat an experiment made with my code, it makes a few random numbers and I need to get the initialization value of my new random() sentence. I have this sentence to make the random object I use
Dim r As Random = New Random()

As I have read it gets the initialization value from system datetime. If the experiment were successfull I'd needed to be able to repeat it. How could I get the initialization number to be able to do:
 Dim r As Random = New Random(OldInitializationValue)

I think I'll have to make a Initialization value myself each time I execute my app but If there were a method to save it I'd be glad to know it.
Thank you in advance for your answers.

A: Random does not expose the initial seed, it doesn't even store it so there is no way to retrieve it. So you have to use the constructor that takes the seed and store it yourself.
Dim mySeed As Int32 = Environment.TickCount ' store it somewhere '

Dim myRandom = New Random(mySeed)
For i As Int32 = 1 To 10
    Console.WriteLine(myRandom.Next(1, 100))
Next

' somehwere else
myRandom = New Random(mySeed)
For i As Int32 = 1 To 10
    Console.WriteLine(myRandom.Next(1, 100))
Next

Now you can always create a random instance with the same seed to get the same sequence of pseudo random values.


text:
Q: Show oci_parse'd statement Is there a way to show the SQL statement that has just been ociparse'd (with or without bound variables)? I maintain a legacy application and sometimes the SQL is built from many different places and lots of conditionals in between. I'd preferably do a print_r($handle) but of course that doesn't work.

A: Short answer, no.
There is no simple way for debug a parsed query via native function.
You need to create your own wrapper


text:
Q: Parsing file like .ini using bash, sed, awk I have a file like this:
[User1]  <- unique id
name=    <- values can be empty
pwd=
...
         <- empty line
[User2]
name=
pwd=
..

[User3]
name=
pwd=
..

I need ability:
to get the fields values for User2
to change the field falue (e.g. pwd).
PS Using bash, sed or awk is preferable

A: Here's a simple solution to change the value of pwd.  This will add an extra newline to the end of the record if pwd is the last field.
awk '/^\[User2\]/ { sub( "\npwd=[^\n]*(\n|$)",
    "\npwd=newvalue\n") } 1' ORS='\n\n' RS= input-file > output-file
mv output-file > input-file

A: You can do it with three rules like this (nawk compatible):
awk -F= '
  /^\[/ { user=$1; gsub("[][]","",user) }
  user == "User2" && $1 == "pwd" { $0=$1"=some_pwd" }
  1
'

Output:
[User1]
name=
pwd=
...

[User2]
name=
pwd=some_pwd
..

[User3]
name=
pwd=
..

A: This one is a clear win for Python vs. AWK, as Python comes with a built-in module for just this sort of problem.
The module's name changed from Python 2.x to Python 3.x; the try block at the top should allow this to work with either Python 2.x or Python 3.x (and I tested it with both on my computer).
EDIT: I just slightly improved the answer.  Now instead of writing a new file, it writes a temp file, and when it is successfully done it deletes the original file and renames the temp file to the original file name.  On non-Windows system the step of removing the original file is optional.
import os
import sys

try:
    import ConfigParser as cp
except ImportError:
    import configparser as cp

try:
    _, fname = sys.argv
except Exception:
    print("Usage: configedit <filename>")

temp_file = fname + ".tempfile"

c = cp.ConfigParser()
c.read(fname)

c.set("User2", "pwd", "XkcdApprovedLongerPassword")
with open(temp_file, "w") as f:
    c.write(f)

os.remove(fname)
os.rename(temp_file, fname)

A: As requested via sed:
sed -i "/\[User2\]/,/^$/{s/\(^pwd\)\=.*$/\1\=password/}"

Change "password" in the line above to whatever you want to change the password to within the file.
This script will search between "[User2]" and the next blank line.
It will then find the line starting with "pwd=" and change anything after that.
For those looking closely I didn't capture the "=" sign for readability for the requester.


text:
Q: mocking a url connection object that is dependent on a string parameter A newcomer to the world of mocks. Wondering how I could test the following method by the use of a mock object (mockito, preferrably, since I'm starting off on it)
public class WeatherServiceImpl implements IWeatherService {
    private static final Logger LOGGER=LoggerFactory.getLogger(WeatherServiceImpl.class);

    @Override
    public String getWeatherDataFromWeb(String cityName){
        return run(cityName);
    }

    public String run(String city){
        long threadId=Thread.currentThread().getId();
        String myId=String.format(" (Thread ID: %d)",threadId);

        LOGGER.info("    ");
        //System.out.println("\n Initializing...");
        LOGGER.info("    1.============Initializing...============"+myId);
        //format the string so that all 'space' characters are replaced by '%20'
        String cityFormatted=city.replaceAll(/\s+/,"%20")

        //HTTP Get Request
        String url="http://api.openweathermap.org/data/2.5/weather?q="+cityFormatted;
        URL obj=new URL(url);

        LOGGER.info("    2.>>>>>>>>>>>> OPENING Conn."+myId)
        URLConnection conn=(HttpURLConnection) obj.openConnection();
        LOGGER.info("    3.<<<<<<<<<<<< CONN. OPENED."+myId)

        //use GET
        conn.setRequestMethod("GET");
        //Get response code
        LOGGER.info("    4.---> Sending 'GET' request to URL: "+url+myId);
        int responseCode=conn.getResponseCode();

        LOGGER.info("    5.<--- Got Response Code: "+responseCode+myId);
        StringBuffer response = new StringBuffer();
        //Check for validity of responseCode
        if(responseCode==200) {
            BufferedReader inn = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            while ((inputLine = inn.readLine()) != null) {
                response.append(inputLine);
            }
            inn.close();
        } else {
            response.append("ERROR:$responseCode");
        }

        //System.out.println("\n Done.");
        LOGGER.info("    6.============ Done.============"+myId);
        LOGGER.info("    ");
        return response;
    }
}

It would be nice to test the method 'run', with some arguments that return code 200, or some arguments that return an error code. For that matter, I think I need to be able to define a mock representation for the URL class (obj), but since this is directly dependent on the 'city' parameter, I'm not sure how to inject this dependency on an instance of the URL class (obj) using mock. Any suggestion is welcome.

A: One way would be to have a getStringURL(String s) method in a new class (like some helper class) and then inject that class in your WeatherServlceImpl. You can mock this helper class and make the getStringURL() return a Mock URL object. Once you have that, you can mock all the method calls on this URL object.


text:
Q: Why no zero-copy networking in linux kernel? I'd like to know the reasons for why the linux kernel (or any other mainstream OS) does not have a feature for zero copy networking ? By zero copy I mean, that an packet/datastream does not get copied for passing to an application in userspace but e.g. uses a memory-pool type of allocator to share the memory between kernel and userspace. I've came up with 3 theory's on my own:
a) I guess there are security concerns. But is there really no way of making memory shared securily between userspace and kernel when they are just used as a buffer ?
b) I guess there are stability concerns. But can't we assume that whoever uses zero-copy networking and e.g. needs to instanciate and pass a memory-pool for the kernel call is aware of memory management? Aware enough to avoid leaks ?
c) It just haven't been done/needed so far. I can't really imagine that nobody requested this feature, as everybody who is using small packet sizes is typically bottlenecked by the "slow" TCP-stack implementation and there are 3rd party tools out there offered for 0-copy networking for usage with special network cards.
Feel free to post any guesses, but please mark whether you are assuming or have a deeper knowledge of the reasons to keep StackOverflow-quality :-)

A: There are a few options nowadays for zero-copy networking:

*

*PF_RING ZC (Zero Copy).

*Linux native zero-copy TCP.

*Intel Data Plane Development Kit.

*OpenOnload for proprietary hardware.

Note, that zero-copy with TCP may be inconvenient, because TCP segments carry headers and payload, but applications are only concerned with payload, so that payload but not headers must be copied into a contiguous buffer for your application.


text:
Q: Why does my Swagger UI try to access non http content when loaded on https? I'm using AWS:ALB, so I have a rule which forwards all traffic to a specific target group. When working locally, I am able to access the swagger ui page with no issues since HTTP. When deployed to AWS with a HTTPS ALB, I see it trying to load some HTTP content; which of course get blocked by browser.
Error:
Mixed Content: The page at 'https://alb.com/alert/docs/swagger-ui.html' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://alb.com/swagger-resources/configuration/ui'.
This request has been blocked; the content must be served over HTTPS.

I have the following in my config in my project so that swagger ui can load under /alert/docs/swagger-ui.html:
@Configuration
@EnableWebMvc
@ComponentScan
public class DocumentationConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/alert/docs/v2/api-docs", "/v2/api-docs");
        registry.addRedirectViewController("/alert/docs/configuration/ui", "/configuration/ui");
        registry.addRedirectViewController("/alert/docs/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui");
        registry.addRedirectViewController("/alert/docs/swagger-resources/configuration/security", "/swagger-resources/configuration/security");
        registry.addRedirectViewController("/alert/docs/configuration/security", "/configuration/security");
        registry.addRedirectViewController("/alert/docs/swagger-resources", "/swagger-resources");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/alert/docs/**").addResourceLocations("classpath:/META-INF/resources/");
    }
}

Am I missing any configuration which causes this to happen?

A: If you are using SpringBoot you can add this:
server:
    tomcat:
        remote-ip-header: x-forwarded-for
        protocol-header: x-forwarded-proto`

to your application.yaml or application.properties.
More details available here: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-security.html#howto-enable-https


text:
Q: How to conver datetime to timestamp epoch i am new to python 2.7, wondering and facing issue how to convert datetime to timestamp epoch.
Also the date time is in current UTC.
example :
2016-05-11 18:33:44  to 1462958071

A: Convert string to python datetime object and then parse the seconds
a ="2016-05-11 18:33:44"
b= datetime.strptime(a,"%Y-%d-%m %H:%M:%S")
print b.strftime('%s') # returns time in epoch


text:
Q: Electric flux through a cube centered at the origin with a charge, $q$, centered at the origin So the problem is a point charge is located at the origin of the coordinate system and a cube of side length 2a is centered at the origin and I am trying to find the electric field, and flux due to the point charge.
So far, I have said that the electric field, $E = \frac{q(r_2-r_1)}{4πe_o|r_2-r_1|^3}$ and attempted to convert from radial to cartesian coordinates. To do that, I replaced $r_2 - r_1$ in the equation with the cartesian coordinates $<x_2 - x_1, y_2 - y_1, z_2 - z_1>$. Firstly, would this step be correct? It seems as if I might be overlooking something, as I could use identities like x = $r\sin(\theta)\cos(\phi)$, but I can't figure out how to work it into the equation.
If it is correct, I should be able to get something like $E(x,y,z) = \frac{q(x_2-x_1, y_2 - y_1, z_2 - z_1)}{4πe_o|x_2 - x_1, y_2 - y_1, z_2 - z_1|^3} $, and since the point charge at the origin is at (0,0,0), simplifies down to $E(x,y,z) = \frac{q(x_2, y_2, z_2)}{4πe_o|x_2^ , y_2 , z_2|^3} = \frac{q(x_2, y_2, z_2)}{4πe_o(x_2^2 + y_2^2 + z_2^2)^{3/2}} $ But my main problem is that I don't know how I would integrate such an equation in order to get the flux through the surface.
Also, once I finally integrate this equation, should I get something that would be consistent with Gauss's law, so that the total flux is equal to $Q_{enc}/e_0$, or am I mistaken?
Edit:
I believe that I can find the flux through one face using $\iint\limits_ \, \mathrm{E}  \cdotp {d}S$.  If I use the face along the y-axis, I can set ${d}S = \hat{y}dxdz$ (would y be a unit vector in this case) and set $y = a$, ending with the integral $4\int_0^{a} \int_0^{a}  \frac{qa}{4πe_o(x^2 + a^2 + z^2)^{3/2}}$.

A:
Also, once I finally integrate this equation, should I get something
that would be consistent with Gauss's law, so that the total flux is
equal to $Q_{enc}/e_0$, or am I mistaken?

No, you're not mistaken. If the charge is in fact located in the center of the cube, then by Gauss' law the net flux over the entire surface of the cube is $Q_{enc}/e_0$ and by symmetry the net flux through each face of the six faces of the cube is $Q_{enc}/6e_0$.
Only if you want to know the net flux over a limited surface of a face of the cube would you need to integrate. That's because the flux is $\int E.dA$ where $E$ and $A$ are vectors with the $A$ normal (perpendicular) to the surface. The flux is then maximum near the center of each face where $E.dA$ is maximum and minimum near the edges of each face where $E.dA$ is a minimum.
Hope this helps.

A: Put the point charge at the center of the xyz system. Then the $r_1$ in your expression for E is zero and the vector $r_2$ locates a segment of area on the surface of the cube (call it r). Given the symmetry of the cube you need only the flux though one quarter of one side (then multiply by 24).  I would work with the xy plane at z = a. Then you need a double integral with x and y both going from 0 to a. The dot product of r with dA reduces to z(dx)(dy) so you will be integrating:  $\frac{k{qa}(dx)(dy)}{(x^2 + y^2 + a^2)^{3/2}}$.


text:
Q: ToC, article class, adding a dot next to the number of section Similar to this question I would like to add a dot after the section-numbers in my table of content. However I am using the article class for which the solution mentioned in the link does not work. Is there a workaround for this scenario?

A: Under tocloft, using
\renewcommand{\cftsecaftersnum}{.}

inserts . after the sectional unit number. For visuals (despite the different document class), the following example is a taken completely from ToC, chapter problem, adding a dot next to the number of chapter with the above addition:

%...
\usepackage{tocloft}% http://ctan.org/pkg/tocloft
\renewcommand\cftchapaftersnum{.}% adds dot after chapter title in ToC
\renewcommand\cftchapdotsep{\cftdotsep}% adds leader dots from chapter titles to page numbers
\renewcommand{\cftsecaftersnum}{.}% adds dot after section title in ToC
%...

A: The definition of the macro \numberline is
% latex.ltx, line 5772:
\def\numberline#1{\hb@xt@\@tempdima{#1\hfil}}

so you can add to your document preamble
\makeatletter
\renewcommand\numberline[1]{\hb@xt@\@tempdima{#1.\hfil}}
\makeatother


text:
Q: Does Morris traversal visit some nodes more than once? I'm solving LeetCode problem of inorder tree traversal and implemented Morris traversal as suggested on the solutions page. Here it is:
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode() {}
    public TreeNode(int val) { this.val = val; }
    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public static List<Integer> inorderTraversalMorris(TreeNode root){
    if(root == null){
        return Collections.emptyList();
    }
    List<Integer> result = new ArrayList<>();
    TreeNode current = root;
    while(current != null){
        if(current.left != null){
            TreeNode next = current.left;
            TreeNode appendTo = next;
            while(appendTo.right != null){
                appendTo = appendTo.right;
            }
            current.left = null;
            appendTo.right = current;
            current = next;
        } else {
            result.add(current.val);
            current = current.right;
        }
    }

    return result;
}

The problem I see is that while re-balancing the tree to be a Threaded binary tree the algorithm visits some nodes twice. Is it possible to avoid it?


text:
Q: Can I convert a gradle report after creating it as xml to html Example:
I create a Findbugs report of type xml.
I put this xml somwhere and now I want to convert it to HTML without running Findbugs again but using the report converter.
Same for Unit Test etc
Any idea?


text:
Q: Asp.net page crashes other asp pages I have a couple Asp.net pages that use a few database connections - the problem is when these two pages are separately loaded they crash all the other .asp pages but none of the .aspx pages.
I get this error however for the asp pages that don't load: HTTP/1.1 New Session Failed

A: Here's a snippet that I found:
"This can have something to do with the permissions of the anonymous user account (IUSR) — see KB #210842. You can also try unloading the application and reloading it, changing the memory settings (e.g. isolated vs. shared) or application pool, and finally rebooting the box."
Reference: http://classicasp.aspfaq.com/general/why-do-i-get-non-database-related-80004005-errors.html
Could you run the aspx pages in a separate application pool from the asp pages?  How much memory is available after running the aspx pages?


text:
Q: How to take only some columns after filtering vba? I have 2 sheets in my excel and would like to take from 1 sheet where I have customer information to 2 sheet where I would like to have filtered data.
So I did this macro for having filtered data on the sheet 2.
`Sub choice()
'
' choice Macro
'
Dim parameter As Range, data As Range, result As Range
Set parameter = Range("param").CurrentRegion
Set data = Range("table").CurrentRegion
Set result = Range("result").CurrentRegion.Offset(1, 0)
result.ClearContents
Set result = Range("result").CurrentRegion
    data.AdvancedFilter Action:=xlFilterCopy, CriteriaRange:=parameter _
        , CopyToRange:=result, Unique:=False

End Sub`

data = "table" - customer table on 1 sheet
However it copy pastes me all the data from customer information.
Is it possible somehow add code in this macro to take only FirstName and Lastname from there?

A: It's probably something to do with the way you've defined the ranges for the data, criteria and destination. The code below should help showing explicit ranges.
Assume you have data to filter in Sheet1 columns A:F, criteria to filter are in range I1:N2 and the filtered data to be copied into columns P:U
The first line of the code will only place columns E:F into columns T:U based on criteria in I1:N2
The second line will place all of the filtered data from A:F into P:U based on same criteria.
Also, ensure that the field/column headings match exactly for data/criteria/destination
Sub test()

     'Returns E:F in destination range T:U based on filter criteria
     Sheet1.Columns("A:F").AdvancedFilter Action:=xlFilterCopy, CriteriaRange:= _
         Sheet1.Range("I1:N2"), _
         CopyToRange:=Sheet1.Range("T1:U1"), Unique:=True

     'Returns full range A:F in destination range P:U based on filter criteria
     Sheet1.Columns("A:F").AdvancedFilter Action:=xlFilterCopy, CriteriaRange:= _
         Sheet1.Range("I1:N2"), _
         CopyToRange:=Sheet1.Range("P1:U1"), Unique:=True
 End Sub


text:
Q: RegEx not recognizing slash (/) in mod_rewrite search query Can't seem to figure this one out. Here are the rewrite rules:
RewriteRule ^search\/(.*)$ index.php?route=product/search&filter_name=$1

RewriteRule ^search&(.*)$ index.php?route=product/search&$1 [QSA,L]

RewriteRule ^search?(.*)$ index.php?route=product/search&$1 [QSA,L]

Works for http://mysite.com/search/whatever+terms
But, does not work for http://mysite.com/search/whatever+terms/with+slash+in+search
Returns zero results, even when there should be results.
As I'm using a wildcard, shouldn't that include the slash? What am I missing here...
EDIT:
Now, when I write the slash directly into the URL bar, it works... but when typed directly into the search box and rewritten as %2F, it does not. Is % a reserved character as well?

A: Have you tried to just use:
search/[a-zA-Z+?&/-]+


text:
Q: Write a script with a for loop that counts from 0.5 Here is my script:
#!/bin/bash
        for ((i=0.5; i<=2.0; i+= 0.05)); do
            (   ./myExe -l t2000.bin i
            ) &
        done
        wait

and the error is:
((: i=0.5: syntax error: invalid arithmetic operator (error token is ".5")

I know this doesn't work but I've heard that there's a way to do something like it,  any suggestions?

A: You can only (easily) loop over integers; use bc to reduce to the correct floating-point value when calling myExe.
for ((i=50; i <= 200; i+=5)); do
    ./myExe -l t2000.bin $(bc <<< "scale=2; $i/100") &
done
wait

Note that bash doesn't work with floating-point values at all. Here, the output of the bc command is just a string, which bash doesn't process, but just passes on to the command as an argument.

A: Without using bc:
for ((i = 50; i <= 200; i+=5)); do
  f=$((i/100)).$((i%100))
  echo $f
done

A: for i in 0.{5..9}{,5} 1.{0..9}{,5} 2.0; do echo $i; done

or:
for i in $(seq 0.5 0.05 2); do echo $i; done


text:
Q: Getting a client connection initated from MySQL I'm trying to solve the problem described by CWE-798, specifically how to allow my application to authenticate to a database securely. I would like to set a mysql password within mysqld and push that information out to a PHP application server. This entails communicating the new password from mysqld to PHP before a PHP instance attempts to connect to the mysqld.
(I did read through the suggested approaches on mitre.org and have some knowledge of privileged access management - however NONE of the recommendations actually solve the problem).
Unless this is initiated within the mysqld e.g. using its event scheduler, then I need to maintain some sort of script outside MySQL which will need credentials to connect - thus defeating the objective.
My problem is that I don't know how to get MySQL to initiate a client connection to the application to inject the new password; it does not appear to provide a standard function for invoking a URL nor for executing a program.
Is my only option to implement a UDF?

A: The vulnerability you're describing seems to primarily relate to applications that are in the hands of users that can freely inspect what they've been given, such as might be the case in a desktop application or a mobile app. If you have credentials in there you must take great pains to encrypt them, and then prevent that encryption from being cracked by protecting your key, but seeing as how all of this has to happen on the user's hardware you're fighting a battle you may never win.
This is how the DVD encryption was cracked, the private key for decrypting DVD data was stored in a desktop application and eventually uncovered.
Server-side code has different concerns. Here you want to avoid hard-coding credentials into your application not because you're concerned about hostile users per-se, though that can be an issue, but because you do not ever want your credentials to end up in a version control system.
One way to ensure this never happens is to have the credentials stored in a file external to your application, like a config file that the application can reference. Most frameworks have some kind of configuration file (.yml, .ini, .xml) that define how they connect to the database. This file should be stored on the server and only on the server, not on developer workstations, not in your version control, and especially not somewhere shared.
You can go down the road of using something like Zookeeper to manage your configuration files but the investment of time required makes this a futile exercise unless you're managing hundreds of servers.
So the short answer here is: Don't put your credentials in your code, or store it with your code. Put it in a config file that's kept on the server and the server alone.


text:
Q: How do I add synonyms to system entity in dialogflow? I am a novice in dialogflow.
I am exploring options building a bot with dialogflow where a user enters an item an its ordering quantity as shown below
Cashewnuts 2 kg
Dialogflow provides a system entity (@sys.unit-weight )which will readily identify this. But the user not necessarily enters in the same way every time. instead of Cashewnuts 2 Kg, he may enter cashewnuts 2 kilo or cashewnuts 2 Kgs or  cashewnuts 2 Kilograms.
In all these case, the user really mean Cashewnuts 2 kg.
Now, there should be someway where I define Kg ( which is in @sys.unit-weight entity) synonyms as (Kgs, Kilograms, kilo etc.) Where should I do that.
Pls help.

A: As far as I know Dialogflow sys.unit-weight already detects kilograms, kilo, kgs, etc. If it doesn't try the following: write something that its recognized by the entity then change it manually by rewriting like so:

Then press Save. Usually it will be saved as a synonym for @sys.unit-weight


text:
Q: Input strings and integers Just a quick question because I really can't find a simple solution to my problem.
Is there a way to get a user input that is meant to be a integer, but when a string is entered
the program will not break and instead displays "Error"
I've been trying to work around it by converting strings to integers and vice-versa, but I constantly get "invalid literal for int() with base 10" error, or when it displays "Error" it does so in an infinite loop.
Here's my code just to help clear the question
choice = input("Enter your choice: ")

while choice != 3:
    if choice == 1:
        get_songs()
        print
        main()
    elif choice == 2:
        read_songs()
        print
        main()
    else:
        print "Invalid choice"

So essentially I want the else operation to work for strings as well as for an integer that is greater than 3 or less than 1.

A:
but I constantly get "invalid literal for int() with base 10" error

You get an exception, specifically a ValueError. You can catch the exception using an except block. For more info, refer to whatever language tutorial you've been using thus far, or try Google for except block Python.

when it displays "Error" it does so in an infinite loop.

When you detect that the input isn't correct, you need to get new input before you try the loop again. Put the input-getting stuff inside your loop. Do not use recursion (calling main() from within main) in addition to the loop; you're only going to confuse yourself this way. Because you don't get a value for choice until you're inside the loop, it's easier to explicitly break out of the loop when you find the appropriate choice value, instead of trying to control the loop with it (i.e. testing for it in the while condition).
We can also use continue to simplify the loop structure: instead of doing all the work in the try block, we limit that to the part where we extract a number. We use continue in the except block to skip the rest of the loop when we don't have an actual number, and only do the rest of the loop when we do. (After all, maybe the code we call for choice == 1 or choice == 2 could raise ValueError for some totally different reason, and we'd want to do something different about that.)
while True:
    try:
        choice = int(raw_input("Give me a number"))
    except ValueError:
        print "Could you at least give me an actual number?"
        continue

    if choice == 1:
        do_something()
    elif choice == 2:
        do_something_else()
    elif choice == 3:
        break
    else:
        print "Try a different number"

A: Since that choice always != 3, you will get an infinite loop.
You should get input again if it jumps into the "else" condition.

A: Here's something: I dislike making the user enter "" around the strings.
ch = raw_input("Enter choice: ")
#ch *is* a string at this point
if ch.isdigit():
   choice = int(ch)
else:
    print "Invalid choice"

Edit (from comments):

isdigit may not handle locale encoding correctly. In Python 3, you can use isdecimal instead.
   — J.F. Sebastian

A: In your code, the while loop should encapsulate the input() line. The following is a clearer alternative, however:
Create a function which gets user input:
def getInteger(prompt):
    while True:
        userIn = input(prompt)
        try:
            return int(userIn)
        except ValueError:
            print "Error"


text:
Q: ember cli app with bootstrap drop down menu immediately closes on mouse release I have only recently started using ember and I wanted to include bootstrap. I added bootstrap via bower: bower install --save bootstrap then added the following into my ember-cli-build.js file:
app.import('bower_components/bootstrap/dist/css/bootstrap.css');
app.import('bower_components/bootstrap/dist/js/bootstrap.js');

All appears to be working, but when I added a drop down menu, clicking on the menu expands as expected, but then immediately closes on mouse release - I.e. a single click looks like nothing happens, but if you click and hold the menu appears and then disappears as soon as you release the button. If I use the tab keys to tab to the menu and then hit the down arrow the drop down menu appears too. I suspect it has something to do with jquery, as the debugger jumps into jquery.js and somewhere in there the menu closes but I am not proficient enough to figure out what is going on...
here is my bower.json file:
{
  "name": "ember-mm-phone-app",
  "dependencies": {
    "ember": "1.13.3",
    "ember-cli-shims": "ember-cli/ember-cli-shims#0.0.3",
    "ember-cli-test-loader": "ember-cli-test-loader#0.1.3",
    "ember-data": "1.13.5",
    "ember-load-initializers": "ember-cli/ember-load-initializers#0.1.5",
    "ember-qunit": "0.4.1",
    "ember-qunit-notifications": "0.0.7",
    "ember-resolver": "~0.1.18",
    "jquery": "^1.11.1",
    "loader.js": "ember-cli/loader.js#3.2.0",
    "qunit": "~1.17.1",
    "ember-simple-auth": "0.8.0",
    "bootstrap": "~3.3.5"
  },
  "devDependencies": {
    "ember-localstorage-adapter": "0.5.4"
  }
}

Here is the drop down menu:

            Account

{{link-to 'Profile' 'user'}}

{{link-to 'Settings' 'application'}}

{{link-to 'Terms and Conditions' 'application'}}

              Logout

A: If you read the Bootstrap guide on dropdown menus, it says that the Javascript adds the open class to the element. The problem with that is Ember wants to manage the DOM itself, it doesn't want any third party libraries doing it. So when Bootstrap adds a class to the DOM, it's likely going to be overwritten the next time Ember updates the DOM.
There are a few potential solutions to this depending on your use case. You could wrap the dropdown in a component, but that might be overkill. The simplest method would be to use Ember's click events instead of calling $(element).dropdown().

    Account

{{link-to 'Profile' 'user'}}

{{link-to 'Settings' 'application'}}

{{link-to 'Terms and Conditions' 'application'}}

      Logout

Notice the condition class on the li and the action on the a. Now, in your controller, do this:
dropdownOpen: false,

actions: {
    toggleDropdown() {
        this.toggleProperty('dropdownOpen');
    }
}

That will add and remove the open class for you, avoiding the need for the Bootstrap Javascript plugin. If that doesn't cover all of your bases, you may want to look into wrapping the dropdown in a component. Wrapping in a component will require a little more work though. There's also some Ember Bootstrap projects out there, but I don't know how well they work.
Short story long: it's not working for you because Ember is overwriting the changes to the DOM that Bootstrap is making. You'll need a way to integrate the two.

A: There must have been something else happening as a result of other bower installs I had done this morning because my machine gradually ground to a halt about an hour after posting this question. I had to reboot and then the drop down menu magically starting working! Very frustrating when you spend several hours on an issue and it it solved by a reboot.


text:
Q: pandas df.eval gives ValueError: data type must provide an itemsize I'll give a sort simple code that reproduces the issue that I have:
import pandas as pd

df = pd.DataFrame(dict(a=[1,2,3]))
df=df.eval('x=2')  # this one is ok
df.eval('y="num"')  # here it will fail

The error that I get is:
ValueError: data type must provide an itemsize

What is the issue? How can i make it work?
It wasnt like this at older pandas versions...

I know that I can replace it with:
df['y']="num"
# or
df.assign(y='num')

But this is not the answer that I need...
I also tried replacing "num" with:
np.str_("num")

Which do has .itemsize, but it didn't help...
Note that when using df.query, with another content, gives me that same issue which I'm trying to solve here. I'm just assuming it's the same issue.

A: Use engine='python' parameter:
print(df.eval('y="num"', engine='python'))
   a  x    y
0  1  2  num
1  2  2  num
2  3  2  num

A: You should probably prefer assign here:
df.assign(y='num')

With multiple assignments and handling variable as strings
df.assign(**{'x': 2, 'y': 'num'})

output:
   a  x    y
0  1  2  num
1  2  2  num
2  3  2  num


text:
Q: Using a for loop to create a linked list Newb C programmer here, assuming I have a struct for a node as follows
struct node{

    int data;
    struct node *next;

};

How would I use a loop to make a linked list where the first node's data is 0, and a pointer to the next node whose data is 1. etc.
EDIT:
int main(int argc, char* argv[]){

struct node a;
a.data = 0;

struct node * tempnode = &a;
for (int i = 1; i < 5; i++){
    struct node * next;
    next->data = i;
    tempnode->next = next;
    tempnode = next;
}

Heres what i tried but it doesn't work

A: This might help..
#include<stdio.h>
#include<stdlib.h>

// Prototypes
void InitList(struct list *sList);
void push(struct list *sList, int data);
void pop(struct list *sList);
void print(struct list *sList);

/* Node Structure */
struct node {
    int data;
    struct node *next;
};

/* List Structure */
struct list {
    struct node *start;
};

 int main(int argc, char** argv)
{
    int x;

    struct list MyList;
    InitList(&MyList);

    for(x = 0; x < 100; x++) push(&MyList, x);
    print(&MyList);
    printf("\n");
    for(x = 0; x < 25; x++) pop(&MyList);
    print(&MyList);
    printf("\n");
    for(x = 0; x < 80; x++) pop(&MyList);
    print(&MyList);
    printf("\n");

    return 0;
}

/* Initializes the list structure */
void InitList(struct list *sList)
{
    sList->start = NULL;
}

 /* Adds a value to the front of the list */
void push(struct list *sList, int data)
{
    struct node *p;
    p = malloc(sizeof(struct node));
    p->data = data;
    p->next = sList->start;
    sList->start = p;
}

/* Prints the list */
void print(struct list *sList)
{
    struct node *p = sList->start;
    while(p != NULL) {
        printf("%d ", p->data);
        p = p->next;
    }
}

/* Removes the first value of the list */
void pop(struct list *sList)
{
    if(sList->start != NULL) {
        struct node *p = sList->start;
        sList->start = sList->start->next;
        free(p);
    }
}

A: You are not allocating memory to store your struct data. Here's how you can do it
for(int i = 1; i < 5; i++) {
    struct node *next = malloc(sizeof *next); // allocate memory to store the struct
    next->data = i;
    tempnode->next = next;
    tempnode = next;
}


text:
Q: What is the temperature dependence of the critical current in weak links? I am now working on hybrid Josephson junctions that are supposed to be tunnel junctions, so that the temperature dependence of the critical current should be
$$ I_c (T)=\frac{\pi}{2}\frac{\Delta(T)}{eR_N}\tanh\frac{\Delta(T)}{2k_BT} $$
according to textbooks such as Tinkham (Introduction to superconductivity - second edition, chapter 6, section 2, page 200, formula (6.10)) and Barone-Paternò (Physics and application of the Josephson effect, chapter 3, section 2, page 54, formula (3.2.10)).
However, the agreement between the theory and my experimental data is very poor, and I can't fit my data with this formula. Given the particular material of the barrier, it is possible that proximity effects have to be taken into account; in this case the $I_c(T)$ dependence is no longer given by the above mentioned Ambegaokar-Baratoff formula. I am now looking for the $I_c(T)$ equation for weak links, to try and see if it fits my data but I can't find it. I read Likharev's review on weak links and the only equation I found is the one for the supercurrent as a function of the phase difference $I_S(\varphi)$.
Where can I find a direct relation between $I_c$ and $T$? Or, if it is not so easy to find, how can I obtain the $I_c(T)$ relation from the $I_S(\varphi)$ equations listed in Likharev review?

A: The expression you wrote is strange. It looks close to the current-phase relation for a ballistic and short junction:
$$j\left(\varphi\right)=2ev_{F}N_{0}\Delta\sin\dfrac{\varphi}{2}\tanh\left(\dfrac{\Delta}{2k_{B}T}\cos\dfrac{\varphi}{2}\right)$$
when $\varphi=\pi/2$, which is not the critical current at low temperatures, since $j_{c}=\max\left\{ j\left(\varphi\right)\right\} $. You can plot the above expression for different temperature (or large ratios $\Delta/2k_{B}T$ since it's simpler then) to realise that the current-phase relation becomes less and less sinusoidal at low temperatures.
Anyway, there is no reason why your junction should be ballistic, short, and the contacts with the superconductors should be perfect.
I didn't open it since a while, but the reference :

A. Golubov, M. Kupriyanov, and E. Il'ichev, The current-phase relation in Josephson junctions Rev. Mod. Phys. 76, 411 (2004)

might be of interest for you. It should be a discussion about the role of contacts, diffusive and ballistic limits, short vs. long junctions, etc...

A: This is a recent formula for current-temperature relationship
$I^\tau_e=\frac{k_BT^2}{\mu_0c\hbar}\frac{\partial \Phi_B}{\partial T}$


text:
Q: ACL package for Laravel 5.4 I'am using Klaravel\Ntrust for ACL in my Laravel 5.3 application.I wish  to upgrade it to a Laravel 5.4 application. But Klaravel\Ntrust don't support Laravel 5.4
Also doesn't see any ACL Package for Laravel 5.4 .
Klaravel\Ntrust\NtrustServiceProvider::class,
'Ntrust' => Klaravel\Ntrust\NtrustFacade::class,

A: I am using laratrust package and worked very well. I upgraded laravel 5.3 to 5.4 and it was working without breaking it.
Check it out.
Repository is active and support is fantastic.


text:
Q: Clearly understand matrix calculation I have this code snippet. I don't understand the Matrix.preScale and the Bitmap.createBitmap with the matrix passed. What does it mean? Is there any simulation website to understand matrix calculation? Could you give me some websites about mathematics used for graphics? I'm sorry I'm not good at mathematics. :)
public Bitmap createReflectedImages(final Bitmap originalImage) {
    final int width = originalImage.getWidth();
    final int height = originalImage.getHeight();
    final Matrix matrix = new Matrix();
    matrix.preScale(1, -1);
    final Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, (int) (height * imageReflectionRatio),
            width, (int) (height - height * imageReflectionRatio), matrix, false);
    final Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (int) (height + height * imageReflectionRatio + 400),
            Config.ARGB_8888);
    final Canvas canvas = new Canvas(bitmapWithReflection);
    canvas.drawBitmap(originalImage, 0, 0, null);
    final Paint deafaultPaint = new Paint();
    deafaultPaint.setColor(color.transparent);
    canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
    final Paint paint = new Paint();
    final LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0,
            bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);
    paint.setShader(shader);
    paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
    canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint);
    return bitmapWithReflection;
}

A: Don't think about it too hard, at least not at the early stages.
Just think of a matrix as an array of numbers.  In this case, an Android Matrix has 3 rows of 3 numbers.  Each number tells an Android graphics function what to do to scale (bigger/smaller), translate (move), rotate (turn) or skew (distort in a 2D plane) the "thing" which the matrix is applied to.
The matrix looks like this (see the docs here).
{Scale X, Skew X, Transform X
Skew Y, Scale Y, Transform Y
Perspective 0, Perspective 1, Perspective 2}

The good news is that you don't need to know any matrix maths, indeed almost no maths, to use matrices in Android.  That's what methods like preScale() do for you.  To understand the maths behind is not that hard, for most things you only need add, multiply and SOHCAHTOA.
matrix-transform-for-the-mathematically-challenged/
When you read the Matrix documentation, you will see methods for rotate, translate etc with prefixes of 'set', 'post' or 'pre'.
Imagine that you create a new matrix.  You then use setRotate() to setup the matrix to do a rotation.  You then use preTranslate() to do a translation.  Because you used 'pre', the translation happens before the rotation.  Had you used 'post', the rotation would happen first.  'set' clears whatever is in the matrix and starts again.
To answer your specific question, new Matrix() creates the 'identity matrix'
{1, 0, 0
 0, 1, 0
 0, 0, 1}

which scales by 1 (therefore same size) and does no translation, rotation or skew.  Therefore, applying the identity matrix will do nothing.  The next method is preScale() which is applied to this identity matrix and in the case you've shown, results in a matrix that scales, and does nothing else so could also be done using setScale() or postScale().


text:
Q: jQuery mouseup event on checkbox not working correctly? I am trying to capture the selected checkboxes in order to send that off via AJAX. But I am only getting the selected element one click to late; that is, my first click on a checkbox is not recognized by the "elm" loop as a checkbox being selected; only when I click a second time, it spits out that element. On a third click it spits out first and second click, but not third.
$(".datatype").mouseup(function()
{
    /* check keyword */
    var searchbox = document.forms['formIndex'].searchbox.value;

    /* check datasetype */
    var vals = [], datasettype =  document.forms['formIndex']['datasettype[]'];
    for(var i=0,elm;elm = datasettype[i];i++)
    {
        alert(i + ': ' + elm.value);
        if(elm.checked)
        {
            alert(i + ': ' + elm.value);
            vals.push(elm.value);
        }
    }
    contents = vals.join(',');

HTML code:
<fieldset>
  <legend style="font-size: 1.2em; font-weight: bold; border: 1px solid aaa" for="selectedRegion">Data Set Type</legend>
  <input type="checkbox" class="datatype" name="datasettype[]" value="1">National

  <input type="checkbox" class="datatype" name="datasettype[]" value="3">Sub-Regional

  <input type="checkbox" class="datatype" name="datasettype[]" value="2">Regional

Can anyone give me a hint why that would be? Thanks a lot for any help.

A: I think you need to use change event instead of mouseup
$(".datatype").change(function()


text:
Q: How to draw 2D shapes onto a JPanel so I just started learning java GUI and I have layouts and components down but I am just dreadful at event handling. This is my first meaningful GUI project and I desperately need some guidance. I have my layout good to go I just do not know how to get it to draw a Rectangle, Oval or Line based on selections in the ComboBoxes. Here is my code so far:
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;

import java.awt.Graphics2D;
import java.util.ArrayList;

public class PaintApp extends JFrame {

    private int x, y, posX, posY, width, height;
    private Graphics2D g;

    private JButton undo;
    private JButton clear;
    private JComboBox color;
    private JComboBox shape;
    private JCheckBox fill;
    private JLabel statusBar;

    private static final String[] pickColor =
        {"Black", "Blue", "Green", "Red"};

    private static final String[] pickShape =
        {"Line", "Oval", "Rectangle"};

    PaintApp(){
        super("Paint");

        // north panel
        JPanel buttonPanel = new JPanel();
        undo = new JButton("Undo");
        buttonPanel.add(undo);
        add(buttonPanel, BorderLayout.NORTH);

        clear = new JButton("Clear");
        buttonPanel.add(clear);
        add(buttonPanel, BorderLayout.NORTH);

        color = new JComboBox(pickColor);
        buttonPanel.add(color);
        add(buttonPanel, BorderLayout.NORTH);
        color.addItemListener(new ItemListener() {
              public void itemStateChanged(ItemEvent e) {
                  if(color.getSelectedItem().equals("Red")){
                      System.out.println("Color: " + color.getSelectedItem());
                  }else if(color.getSelectedItem().equals("Blue")){
                      System.out.println("Color: " + color.getSelectedItem());
                  }else if(color.getSelectedItem().equals("Green")){
                      System.out.println("Color: " + color.getSelectedItem());
                  }else if(color.getSelectedItem().equals("Black")){
                      System.out.println("Color: " + color.getSelectedItem());
                  }
              }
            });

        shape = new JComboBox(pickShape);
        buttonPanel.add(shape);
        add(buttonPanel, BorderLayout.NORTH);
        shape.addItemListener(new ItemListener() {
              public void itemStateChanged(ItemEvent e) {
                  if(shape.getSelectedItem().equals("Line")){
                      System.out.println("Shape: " + shape.getSelectedItem());
                  }else if(shape.getSelectedItem().equals("Oval")){
                      System.out.println("Shape: " + shape.getSelectedItem());
                  }else {
                      System.out.println("Shape: " + shape.getSelectedItem());
                  }
              }
            });

        fill = new JCheckBox("Filled");
        buttonPanel.add(fill);
        add(buttonPanel, BorderLayout.NORTH);

        // center panel
        JPanel paintPanel = new JPanel();
        paintPanel.setBackground(Color.WHITE);
        add(paintPanel, BorderLayout.CENTER);

        // south panel
        statusBar = new JLabel("Mouse is off the canvas!");
        add(statusBar, BorderLayout.SOUTH);

        // mouse handler
        MouseHandler handler = new MouseHandler();
        paintPanel.addMouseListener(handler);
        paintPanel.addMouseMotionListener(handler);
        buttonPanel.addMouseListener(handler);
        buttonPanel.addMouseMotionListener(handler);
    }

    private class MouseHandler implements MouseInputListener {

        public void mouseDragged(MouseEvent e) {
            statusBar.setText(String.format("(%d,%d)",
                    e.getX(), e.getY()));
        }

        public void mouseMoved(MouseEvent e) {
            statusBar.setText(String.format("(%d,%d)",
                    e.getX(), e.getY()));

        }

        public void mouseClicked(MouseEvent e) {
            String x = String.valueOf(color.getSelectedItem());

        }

        public void mousePressed(MouseEvent e) {
            posX = e.getX();
            posY = e.getY();
            width = posX - x;
            height = posY - y;
        }

        public void mouseReleased(MouseEvent e) {
            posX = e.getX();
            posY = e.getY();
            width = posX - x;
            height = posY - y;

        }

        public void mouseEntered(MouseEvent e) {

        }

        public void mouseExited(MouseEvent e) {
            statusBar.setText("Mouse is off the canvas!");

        }
    }
}

public interface MyShape {

    void draw(Graphics2D g);
}

public class MyRect extends Rectangle2D.Float implements MyShape{

    Graphics2D g;
    int x, y, posX, posY;
    Color color;

    MyRect(Graphics2D g, int x, int y, int posX, int posY, Color color){
        this.g = g;
        this.x = x;
        this.y = y;
        this.posX = posX;
        this.posY = posY;
        this.color = color;
    }

    public void draw(Graphics2D g){
        g = (Graphics2D) g;
        g.setColor(color);
        g.drawRect(x, y, (posX - x), (posY - y));
    }

}

public class MyOval extends Ellipse2D.Float implements MyShape{

    Graphics2D g;
    int x, y, posX, posY;
    Color color;

    MyOval(Graphics2D g, int x, int y, int posX, int posY, Color color){
        this.g = g;
        this.x = x;
        this.y = y;
        this.posX = posX;
        this.posY = posY;
        this.color = color;
    }

    public void draw(Graphics2D g){
        g = (Graphics2D) g;
        g.setColor(color);
        g.drawOval(x, y, (posX - x), (posY - y));
    }
}

public class MyLine extends Line2D.Float implements MyShape{

    Graphics2D g;
    int x, y, posX, posY;
    Color color;

    MyLine(Graphics2D g, int x, int y, int posX, int posY, Color color){
        this.g = g;
        this.x = x;
        this.y = y;
        this.posX = posX;
        this.posY = posY;
        this.color = color;
    }

    public void draw(Graphics2D g){
        g = (Graphics2D) g;
        g.setColor(color);
        g.drawLine(x, y, (posX - x), (posY - y));
    }
}

    public static void main(String[] args){

        PaintApp p = new PaintApp();
        p.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        p.setSize(700,700);
        p.setResizable(false);
        p.setVisible(true);

    }

}

A: Start by taking a look at

*

*Performing Custom Painting

*Painting in AWT and Swing

*2D Graphics
Basically, you need some kind of surface onto which to render your shapes.  Probably the easiest is to use a JPanel and override it's paintComponent method.
To this I would attach your MouseListener, because this where you want to physically add the shapes and mouse events are contextual to the component that generated them.
You will need to provide some means by which the controls can tell the "paint surface" what to paint.  This can be done via a simple setter and some agreed on values (like an enum or static final constants).
When the user presses and releases the mouse, you will need to determine what shape to create and add that shape to some kind of List, you will need to call repaint to notify the repaint manager that you want your component repainted.
When paintComponent is called, you would then loop through the list of shapes and call Graphics2D#draw and/or Graphics2D#fill depending on what it is you want to do with the shape...
You could also take a look at this simular question for more ideas.


text:
Q: What are the key components of a desktop environment? I'm a relatively new Linux user. I started with Ubuntu 20.04 a few months ago, and eased myself into the experience, learning a bit of the command line and becoming familiar with the system structure
I'd now like to move up a bit in the world, and improve my productivity by working on a tiling window manager. I've started using AwesomeWM, and I've loved the experience so far. The only issue is that, being a window manager rather than a full DE, there are a number of key features missing, like volume control. I've made due without some, and I've had to go back into Gnome for others (such as my workflow or interests required). For example, I've figured out how to add volume control to my rc.lua file, and I installed the ranger file manager. But because I don't know what my experience might be on a day-to-day basis, I can't move over to the WM entirely (say, with a brand-new netinst).
All this leads to my question:What are the things that make you a (relatively) fully-fleshed-out desktop environment? What are the general things I should be installing/setting up to get a DE experience without having to install one like Gnome or KDE and using everything provided out of the box?

A: I use a pretty minimal i3 install.
The only things I've had to add are:

*

*dmenu to launch applications,

*i3status for a status bar in the bottom.

*nm-applet for networking from the status bar

*Commands in a config file to map XF86Audio* keys to pactl actions.

The other things that DEs give you are default applications for most desktop uses:  browser, email client, text editor, file manager, photo viewer.  If you find you are missing a PDF viewer, just install one.
This setup has worked for me for over a year and I don't feel like I'm missing too much.  If I ever want a GUI for something (like pavucontrol for audio-devices or spectacle for screenshots) then I just run that specific thing from dmenu.
Anything outside of that is probably opinion-based.


text:
Q: Как с помощью getElementById выбрать сразу несколько элементов? Как сделать так чтобы сразу двум элементам с помощью getElementById сработала функция скрытия текста?

var length = 10;

var text = document.getElementById('subscription_desc')// как сюда добавить второй элемент?

var string = text.innerHTML
var trimmedString = string.length > length ?
  string.substring(0, length - 3) + "..." :
  string

text.innerHTML = trimmedString

Ваши подписки

Секрет фирмы

Оставайтесь рисковать

Медуза

Но есть и хорошие новости

Яндекс

Найдется все

Spark

Сообщество предпринимателей

BOOM

Твоя музыка у нас!

A: Не смотря на то, что хоть и через пятую точку, но можно вытащить элементы с одинаковым id (НО НЕ С ПОМОЩЬЮ getElementById) cамый правильный вариант использовать class для одинаковых групп. и использовать getElementsByClassName или querySelectorAll (для Jquery: $('.MY_CLASS_NAME'))

идеалогически НЕПРАВИЛЬНЫЙ вариант, но рабочий:

var length = 10;

var text = document.querySelectorAll('h6[id="subscription_desc"]')// как сюда добавить второй элемент?

for (var i = 0; i < text.length; ++i) {
  text[i].innerHTML = 'Секрет фирмы ' +  (++i);
}

Ваши подписки

Секрет фирмы

Оставайтесь рисковать

Медуза

Но есть и хорошие новости

Яндекс

Найдется все

Spark

Сообщество предпринимателей

BOOM

Твоя музыка у нас!


text:
Q: AngularJS and gulp - getting less errors than I think I should in the console I'm building a site. First I made myself familiar with AngularJS in general and tried to make sense of all the new things for me: grunt, livereload, angularjs... I soon realized some mistakes I made and started building a new project from the ground up.
When I was building the site whilst on the grunt server. It displayed me more messages than it is now with gulp. I'm not sure why is that?
For example, since I was moving some existing code from my "study-project" to a new clean-start-gulp-project. I forgot to add one service: FlashService - responsible for displaying simple messages on my site.
And I was already using that as a dependency in another service. But for some reason all I was presented was a blank site with no messages in the console. Whereas in my previous project I always got messages like "No such provider found" or something similar. Can anybody help me make debuging easier?
Some other things have changed also. I changed the general folder structure of the code and I'm trying to modularize my new app. Currently I can't think of anything else that might even be remotely related.
My current folder structure is like this:
src/app
    app.js
    /services
        auth-service.js
        flash-service.js

Some important parts from my code:
app.js
angular.module('myapp', [

   ...
   'myapp.home'

]).config(function ($stateProvider) {

    $stateProvider.state('main', {
        'abstract': true,
        resolve: {
            promiseUser: ['AuthService', function (AuthService) { AuthService.promiseUser; }]
        },
        template: '

'
    });
})

AuthService
angular.module('myapp').service('AuthService', ['FlashService', function (FlashService){

    // As soon as I created the missing service 'FlashService' everything started working.
    // Or when I simply removed the FlashService from dependencies.
    // What I don't understand is why didn't I get any errors in the console?

}

Since I already spent too much time looking the bug in a wrong place I can only imagine that some other messages might also not make it into the console. This would eventually make debuging quite hard.
What am I missing here? Why didn't I get any errors in the console?
Edit:
The first project was generated using Yeoman and for the second one I used gulp slush. Don't think this will help, but I figured might be worth mentioning.
Edit2
Found out that if I change angular.js and add console.log(message) inside the first minError function, I almost get what I want.
function minErr(module) {
    ...
    console.log(message);
    return new Error(message);
}

Now I just need to figure out an alternative way to do this or what was different with yeoman generated application and why I am not getting these messages by default:
[$injector:unpr] Unknown provider: aProvider <- a <- AuthService
http://errors.angularjs.org/1.2.25/$injector/unpr?p0=aProvider%20%3C-%20a%20%3C-%20AuthService

A: Loading modules with Angular if you want error messages always try and catch.  My guess that gulp slush is not generating a try/catch scenario for loading modules while yeoman does.  The difference between gulp and grunt shouldn't matter so long as you are trying to catch the error.  The thing with gulp is that it is all process based some of something failed in the process sometimes the process will just sit there or just stop all together.
Disclaimer: I have never generated a project with slush only yeoman.

A: Okay, so I'll try to explain what I figured out.
This had nothing to do with gulp nor grunt. Also the directory structure was completely irrelevant.
First, let's take a look at some of the most important parts of both config files.
current:
angular.module('myapp', [])

.config(function ($stateProvider) {

    $stateProvider.state('main', {
        'abstract': true,
        resolve: {
            promiseUser: ['AuthService', function (AuthService) { AuthService.promiseUser; }]
        },
        template: '

'
    });
})

...

before:
angular.module('myapp', [])

.config(function ($stateProvider) {

    $stateProvider.state('main', {
        'abstract': true,
        resolve: {
            promiseUser: ['AuthService', function (AuthService) { AuthService.promiseUser; }]
        },
        template: '

'
    });
})

...

.run(['AuthService', function (AuthService) { ... }]);

...

So the first part is the same in both cases. What was different before is that I also used AuthService inside a run block.
I was checking that on state change the authenticated user had permissions to access the new state.
So what happened inside the resolve stayed inside the resolve! But what happened inside the run block was displayed in the console.
By modifying these parts of the code - both projects displayed the same errors and had the same behavior.


text:
Q: Can we mix c++ standard compile with MSVC? I think gcc is try to support this.
But, I can't find any referrence for MSVC.
My code base is currently build on c++17. I would like to use the new coroutine feature in c++20 but don't want to migrate all code rightnow. The goal is to build some components with coroutine support.

A: The rules of MSVC binary compatibility apply. Objects are link-compatible (as long as you don't use link-time code generation or whole-program optimization) between versions. Since that page doesn't say that any other compiler switches beside /LTCG and /GL break this promise, /std: won't do that either.


text:
Q: Limit of the series of functions $f_n$ $$f_n(x)=
\begin{cases}
 1&\text{if }\, x\geq 1/n\\
 n|x|&\text{if }\, x< 1/n.
\end{cases}$$
We want to find the pointwise limit of this function. I think the answer should be $f(x)=1\thinspace \forall x\in\mathbb{R}$. But the answer given is
$$f_n(x)=
\begin{cases}
 1&\text{if }\, x\neq 0\\
 0&\text{if }\, x=0.
\end{cases}$$
This is confusing me.

A: But clearly $f_n(0)=0$ for each $n\in\mathbb N$. Therefore, $f(0)=\lim_{n\to\infty}f_n(0)=0$.


text:
Q: Pytorch batch-wise Augmentation I'm trying to fix the class imbalance of my dataset for a classification-task by adding augmented images. As the network didn't improve, I noticed, that I'm transforming the whole dataset while not keeping the original image.
What is the best method to fix that?
My training function looks like this (excerpt):
def train(mu,lr,batch_size,n_epochs,k,model,use_gpu,size_image,seed,num_workers,root):
    set_seed(seed, use_gpu)
    train_loader, test_loader, dataset_attributes = get_data(size_image,root,batch_size, num_workers)

    criteria = CrossEntropyLoss()
    optimizer = SGD(model.parameters(), lr=lr, momentum=0.9, weight_decay=mu, nesterov=True)
    best_acc = 0.0

    for epoch in tqdm(range(n_epochs), desc='epoch', position=0):
        t = time.time()
        optimizer = update_optimizer(optimizer, lr_schedule=dataset_attributes['lr_schedule'], epoch=epoch)

        loss_epoch_train, f1_epoch_train, acc_epoch_train, topk_acc_epoch_train = train_epoch(model, optimizer, train_loader,
                                                                              criteria, loss_train, f1_train, acc_train,
                                                                              topk_acc_train, k,
                                                                              dataset_attributes['n_train'],
                                                                              use_gpu)
        if acc_epoch_test > best_acc:
            best_acc = acc_epoch_test
            save(model, optimizer, epoch, os.path.join(save_dir, 'weights_best_acc.tar'))

This in an excerpt of my get_data function:
def get_data(size_image,root,batch_size, num_workers):

    transform = transforms.Compose(
        [MaxCenterCrop(),
        transforms.Resize(size_image),
        transforms.ToTensor()])

    trainset = Plantnet(root, 'images_train', transform=transform)
    testset = Plantnet(root, 'images_test', transform=transform)
    train_class_to_num_instances = Counter(trainset.targets)
    test_class_to_num_instances = Counter(testset.targets)
    ...
    sampler = WeightedRandomSampler(torch.DoubleTensor(weights), int(num_samples))
    trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
                                                sampler=sampler,
                                              shuffle=False, num_workers=num_workers)

    testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
                                             shuffle=False, num_workers=num_workers)

    return trainloader, testloader, dataset_attributes

Now my idea for an easy fix would be to add a transformed dataset and concatenate it to the original one. But I think this idea would have a bad impact on performance and wouldn't really fix the problem of class imbalance.
I'm thinking that applying the tranformation on each batch would make the most sense. But how do I add this to my code?


text:
Q: Interface for http headers in the fetch method I have a method that fires a fetch function. It also sets headers over which type I would like to have control.
    // Request headers
    let headers: HttpHeaders = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    };

    // Checks if user have x-auth-token cookie
    const token = getCookie(AUTH.COOKIE_NAME);
    if (token !== null) {
        headers = {
            ...headers,
            [AUTH.API_TOKEN]: token
        };
    }

    // Request body
    const request = {
        method,
        headers,
        body: JSON.stringify(body)
    };

    if (body || method.toUpperCase() === HttpMethod.GET) {
        delete request.body;
    }

I have also enum, which holds all allowed headers:
export enum HttpHeader {
    ACCEPT = 'Accept',
    CONTENT_TYPE = 'Content-Type',
    X_AUTH_TOKEN = 'x-auth-token'
}

I already know that you can't specify enum as the expected index value in the ts interface. Can you give me another option to control http request headers? I saw the idea of using an array of objects, but I have the impression that it is a bit of a form over content.

A: You can use an enum to define a type that has all the enum values as keys using a mapped type (what you can't do is have an enum as an index parameter).
The predefined Record and Partial mapped types will do the job nicely:

type HttpHeaders = Partial<Record<HttpHeader, string>>

export enum HttpHeader {
    ACCEPT = 'Accept',
    CONTENT_TYPE = 'Content-Type',
    X_AUTH_TOKEN = 'x-auth-token'
}

// Request headers
let headers: HttpHeaders = {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
};

headers = {
    ...headers,
    [HttpHeader.X_AUTH_TOKEN]: "token"
};

Play


text:
Q: How to increase the thickness of the edge in a random image This is a Voronoi Diagram. I really want to know how to change the thickness of the "wall" of each V-cell, in another words, the thickness of the edge in this diagram.

A: Use Erosion[image, DiskMatrix[radius]]:
img = Import["http://i.stack.imgur.com/WVmnm.jpg"];
Erosion[img, DiskMatrix[2]]

Intuitively, you can imagine that this places a disk with radius 2 at every black pixel. If you're more concerned about speed than accuracy, you can also use Erosion[image, radius] which places a square with some radius at every black pixel - which of course makes diagonal lines thicker than horizontal or vertical lines:
circle = Image[
   Rasterize[Graphics[{Circle[]}, PlotRangePadding -> 0.5]],
   ImageSize -> All];
Row[{Labeled[Erosion[circle, DiskMatrix[10]],
   "Erosion[...,Disk[10]]"],
  Labeled[Erosion[circle, 10],
   "Erosion[..., 10] or MinFilter[..., 10]"]}]

Note: MinFilter seems to do mostly the same thing Erosion does, except it can only use rectangular masks. The differences between MinFilter and Erosion seem to be:

*

*Erosion can use non-rectangular structuring elements (like Disk above)

*MinFilter can process TimeSeries data

*for color images Erosion processes each channel separately, while MinFilter replaces each pixel with the (r,g,b) value of the darkest pixel in the neighborhood.

(There may be more differences - I had to guess these these from the documentation. No idea why there is no mention in each function's "Properties and Relations" section. IMHO, MinFilter could have been implemented as Method option to Erosion instead of a new function.)


text:
Q: How to change the height of table rows in HTML? I have a table, and I want to increase the height of each row. So far, I've tried adding the height attribute to the <th tag but no success, because the <th controls the header and not the rows.

                            ID:
                            Action*
                            Detailed Action*
                            IAW *
                            Discrepancy Narrative *

I've also tried taking the height attribute out of the <th tag and adding it to the <tr tag, but still no success. What am I doing wrong?

                            ID:
                            Action*
                            Detailed Action*
                            IAW *
                            Discrepancy Narrative *

A: You can do it using CSS line-height on tr. Example:

                            ID:
                            Action*
                            Detailed Action*
                            IAW *
                            Discrepancy Narrative *


text:
Q: "A non-numeric value encountered" laravel5.1 php7.1 dompdf 0.8 I understood that this error was already solved but i don't manage to fix it, so sorry and thanks for your advises:
I'm working on a Laravel 5.1 project (FusionInvoice) and use dompdf to create pdf files. My aim is to use php7.1 for this project.
After enable php7.1 I had the "A non-numeric value encountered" error
so i did the easy installation procedure of dompdf, with composer method (https://github.com/dompdf/dompdf) to fix it using the dompdf 0.8.1 release. My requierements seems ok.
Now i have this error:

FatalThrowableError in domPDF.php line 30: Class 'DOMPDF' not found

we are talking about this file "app/Support/PDF/Drivers/domPDF.php" and this function:
private function getPdf($html)
    {
        $pdf = new \DOMPDF();
        $pdf->set_paper($this->paperSize, $this->paperOrientation);
        $pdf->load_html($html);
        $pdf->render();

        return $pdf;
    }

I understood that the "new \DOMPDF();" is calling this file '/vendor/dompdf/dompdf/src/Dompdf.php' to build his object.
so i tried this : "new \Dompdf\Dompdf();"
and i'm back to the first place:

ErrorException in Page.php line 499: A non-numeric value encountered

Does someone knows how i can solve this issue ? Thanks...

A: Please check dompdf version and compare with php and laravel version
check this https://github.com/barryvdh/laravel-dompdf/issues/294


text:
Q: Return column names based on condition I've a dataset with 18 columns from which I need to return the column names with the highest value(s) for each observation, simple example below. I came across this answer, and it almost does what I need, but in some cases I need to combine the names (like abin maxcolbelow). How should I do this?
Any suggestions would be greatly appreciated! If it's possible it would be easier for me to understand a tidyverse based solution as I'm more familiar with that than base.
Edit: I forgot to mention that some of the columns in my data have NAs.
library(dplyr, warn.conflicts = FALSE)

#turn this
Df <- tibble(a = 4:2, b = 4:6, c = 3:5)

#into this
Df <- tibble(a = 4:2, b = 4:6, c = 3:5, maxol = c("ab", "b", "b"))

Created on 2018-10-30 by the reprex package (v0.2.1)

A: Continuing from the answer in the linked post, we can do
Df$maxcol <- apply(Df, 1, function(x) paste0(names(Df)[x == max(x)], collapse = ""))

Df

#      a     b     c maxcol
#  <int> <int> <int> <chr>
#1     4     4     3  ab
#2     3     5     4  b
#3     2     6     5  b

For every row, we check which position has max values and paste the names at that position together.

If you prefer the tidyverse approach
library(tidyverse)
Df %>%
  mutate(row = row_number()) %>%
  gather(values, key, -row) %>%
  group_by(row) %>%
  mutate(maxcol = paste0(values[key == max(key)], collapse = "")) %>%
  spread(values, key) %>%
  ungroup() %>%
  select(-row)

# maxcol     a     b     c
#  <chr>  <int> <int> <int>
#1 ab         4     4     3
#2 b          3     5     4
#3 b          2     6     5

We first convert dataframe from wide to long using gather, then group_by each row we paste column names for max key and then spread the long dataframe to wide again.

A: Here's a solution I found that loops through column names in case you find it hard to wrap your head around spread/gather (pivot_wider/longer)
out_df <- Df %>%
  # calculate rowwise maximum
  rowwise() %>%
  mutate(rowmax = max(across())) %>%
  # create empty maxcol column
  mutate(maxcol = "")

# loop through column names
for (colname in colnames(Df)) {
  out_df <- out_df %>%
    # if the value at the specified column name is the maximum, paste it to the maxcol
    mutate(maxcol = ifelse(.data[[colname]] == rowmax, paste0(maxcol, colname), maxcol))
}

# remove rowmax column if no longer needed
out_df <- out_df %>%
  select(-rowmax)


text:
Q: How to use custom fact in Ansible dynamically to evaluate conditional statement I'm trying to evaluate the condition
hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']
The external_ip is set on the host_variable . I have set the ipify_ip on the custom facts and trying to evaluate this condition
when: hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']
I have tried this option also but it failed there too
when: hostvars[inventory_hostname].external_ip ==  {{ ipify_ip }}
Here is the complete playbook file
- name: Get public ip for the host
  ipify_facts:
   api_url: https://api.ipify.org/
   timeout: 20
  tags: always

- name: Set fact
  set_fact:
   ipify_ip: "{{ ipify_public_ip }}"
  tags: always

- name: ipify_ip External IP
  debug:
   var: ipify_ip
  tags: always

- name: is extrnal_ip in hostvars is same with ipify_ip
  debug:
   var=hostvars[inventory_hostname].external_ip
  when: hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']
  tags: always

The error
fatal: [localhost]: FAILED! => {"msg": "The conditional check 'hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']' failed. The error was: error while evaluating conditional (hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']): 'dict object' has no attribute 'ipify_ip'\n\nThe error appears to be in '/home/anish/playbook/prereqs.yml': line 29, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n    - name: extrnal_ip on hostvars\n      ^ here\n"}
What is the right way to do this ??

A: Simply use the variables. For example, given the inventory
shell> cat hosts
host01 external_ip=1.2.3.4

and the playbook
shell> cat playbook.yml
- hosts: host01
  tasks:
    - set_fact:
        ipify_ip: 1.2.3.4
    - debug:
        var: ipify_ip
    - debug:
        var: external_ip
    - debug:
        msg: "{{ external_ip }} is equal to {{ ipify_ip }}"
      when:  external_ip == ipify_ip

gives
shell> ansible-playbook -i hosts playbook.yml

PLAY [host01] *******************************

TASK [set_fact] *****************************
ok: [host01]

TASK [debug] ********************************
ok: [host01] =>
  ipify_ip: 1.2.3.4

TASK [debug] ********************************
ok: [host01] =>
  external_ip: 1.2.3.4

TASK [debug] ********************************
ok: [host01] =>
  msg: 1.2.3.4 is equal to 1.2.3.4

PLAY RECAP **********************************
host01: ok=4 changed=0 unreachable=0 failed=0 ...


text:
Q: On app startup Attached Property Callback Event return null for a Control property binding Story & Problem:
I create IsActivated property as an Attached Property to be able to add it to any control in XAML page I want. Then when any control set it to true, I want PropertyChangedCallback event fired and examine binding of specific Property of that control. The app is running without any problem, also all controls with setting IsActivated property to true will fired that event and binding object show the value correctly in UI too.
But the problem is, When PropertyChangedcallback event executing, GetBinding() or GetBindingExpression() methods will return null value for those Properties.
(For now I only Check on TextBox and on its TextProperty)
Background & What I already tried
I used the same technique in my production applications, But when I try to simplify it to demonstrate it to a friend, It is not working!
I find out, if I Set/Change IsActivated property for a TextBox at MainWindow.OnLoaded() event, Then in its Callback event it will correctly return binding info for TextBox.TextProperty:
private void OnLoaded(object sender, RoutedEventArgs e)
{
    MyTextBox.SetValue(ChangeBehavior.IsActivatedProperty, false);
}

but I did not do this in my real apps and I do not like this solution!
Source Codes
This is GitHub full sample codes.
But here is my Attached Property class:
public static class ChangeBehavior
{
    public static readonly DependencyProperty IsActivatedProperty;

    static ChangeBehavior()
    {
        IsActivatedProperty = DependencyProperty.RegisterAttached
            (
                "IsActivated",
                typeof(bool),
                typeof(ChangeBehavior),
                new PropertyMetadata(false, OnIsActivatedPropertyChangedCallback)
            );
    }

    public static bool GetIsActivated(DependencyObject obj)
        => (bool)obj.GetValue(IsActivatedProperty);
    public static void SetIsActivated(DependencyObject obj, bool value)
        => obj.SetValue(IsActivatedProperty, value);

    private static void OnIsActivatedPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is TextBox)) return;

        // ===> Here I get null value
        var binding = BindingOperations.GetBinding(d, TextBox.TextProperty);
        if (binding == null) return;

        if ((bool)e.NewValue)
        {
            var sourceObject = binding.Path.Path;
            //Doing some stuff...
        }
        else
        {
            //Doing some stuff...
        }
    }
}

and this is my UI XAML:
<Grid>
    <TextBox Name="MyTextBox"
             Text="{Binding Model.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
             local:ChangeBehavior.IsActivated="True"/>
</Grid>

MainWindow Code-Behind:
public partial class MainWindow : Window
{
    private readonly ViewModel _viewModel;

    public MainWindow(ViewModel viewModel)
    {
        InitializeComponent();

        _viewModel = viewModel;
        DataContext = _viewModel;
    }
}

ViewModel class: (Omit NotifyProperty... parts to make it shorter)
public class ViewModel : INotifyPropertyChanged
{
    private Model _model;

    public ViewModel()
    {
        Model = new Model {Name = "Model One"};
    }

    public Model Model
    {
        get => _model;
        set
        {
            _model = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEvent...
}

Model class: (Omit NotifyProperty... parts to make it shorter)
public class Model : INotifyPropertyChanged
{
    private string _name;

    public string Name
    {
        get => _name;
        set
        {
            if (value == _name) return;
            _name = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEvent...
    }
}

What's wrong with my code!
I expect when InitializeComponent(); execute from my MainWindow constructor (just like my real app) any control that set local:ChangeBehavior.IsActivated to true in XAML, I get correct bindig info of their Properties at OnIsActivatedPropertyChangedCallback method!
Why almost the same technique (and almost the same code!) work in my real applications, but it doesn't work in this simple code!?
What I am missing here!?
Updated: Second way to Fix my problem is:
Instead of using my IsAttached Property Directly on an Element, I should use it in a ResourceDictionary. (The other way is that I marked as answer)

A: I'd like to see where this is being used in your real projects. In this one, it's getting set before the binding is set on Text. Never let attached properties depend on order of initialization, because that's totally out of your control.
What we want to do is: If we can do it, do it. If not, do it after the control is loaded, unless it's already loaded, in which case there's almost certainly not going to be anything to do. It's OK to do it in a Loaded handler here because a) consumers of the class don't have to look at it, and b) you have no other choice.
We ideally would like to do this whenever a binding is set on Text, but there's no event for that, and it's relatively uncommon for bindings to be replaced at runtime.
private static void OnIsActivatedPropertyChangedCallback(DependencyObject d,
    DependencyPropertyChangedEventArgs e)
{
    if (d is TextBox textBox)
    {
        if (!tryGetBinding() && !textBox.IsLoaded)
        {
            void onLoaded(object sender, RoutedEventArgs e2)
            {
                tryGetBinding();

                textBox.Loaded -= onLoaded;
            };

            textBox.Loaded += onLoaded;
        }

        bool tryGetBinding()
        {
            // ===> Here I get null value
            var binding = BindingOperations.GetBinding(textBox, TextBox.TextProperty);

            if (binding == null)
                return false;

            if (GetIsActivated(textBox))
            {
                var sourceObject = binding.Path.Path;
                //Doing some stuff...
            }
            else
            {
                //Doing some stuff...
            }

            return true;
        };
    }
}


text:
Q: android what to worry about when deprecated API still working in higher API version Made an app targeting API8 and it's running fine
on all emulator images all the way up to API15.
I cannot test the app on other higher apis so I'm not
setting the android:targetSdkVersion.
What about this deprecated warnings:
android.view.Display.getHeight()

This method is deprecated.
Use getSize(Point) instead.

Can I ignore this and just keep on using Display.getHeight()?
I read about reflection or programmatically testing what Android version the device is using.
Why do people do that when it's working for me?

A:
I cannot test the app on other higher apis so im not
  setting the android:targetSdkVersion.

If you are testing "on all emulator images all the way up to API15", then you are "test[ing] the app on other higher apis".

Can i ignore this and just keep on using Display.getHeight()?

In Android, "deprecated" usually means "we have a better solution that you should consider using, but we will keep the deprecated one working as long as we can". Sometime after you drop support for API Level 12 and down, you might wish to move to getSize(). For now, getHeight() should work fine on all Android API levels.

Why do people do that when it's working for me?

They do not do that for deprecated APIs. They use version checks and the like for accessing things that simply do not exist in older versions of Android, so they do not try referring to non-existent APIs on older devices.


text:
Q: Value gets changed upon comiting. | CallableStatements I having a weird problem with a DAO class and a StoredProcedure, what is happening is that I use a CallableStatement object which takes 15 IN parameters, the value of the field id_color is retrieved correctly from the HTML forms it even is set up how it should in the CallableStatement setter methods, but the moment it is sent to the database the id_color is overwriten by the value 3 here's the "context":
I have the following class DAO.CoverDAO which handles the CRUD operations of this table

CREATE TABLE `cover_details` (
  `refno` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `shape` tinyint(3) unsigned NOT NULL ,
  `id_color` tinyint(3) unsigned NOT NULL ',
  `reversefold` bit(1) NOT NULL DEFAULT b'0' ,
  `x` decimal(6,3) unsigned NOT NULL ,
  `y` decimal(6,3) unsigned NOT NULL DEFAULT '0.000',
  `typecut` varchar(10) NOT NULL,
  `cornershape` varchar(20) NOT NULL,
  `z` decimal(6,3) unsigned DEFAULT '0.000' ,
  `othercornerradius` decimal(6,3) unsigned DEFAULT '0.000'',
  `skirt` decimal(5,3) unsigned NOT NULL DEFAULT '7.000',
  `foamTaper` varchar(3) NOT NULL,
  `foamDensity` decimal(2,1) unsigned NOT NULL ,
  `straplocation` char(1) NOT NULL ',
  `straplength` decimal(6,3) unsigned NOT NULL,
  `strapinset` decimal(6,3) unsigned NOT NULL,
  `spayear` varchar(20) DEFAULT 'Not Specified',
  `spamake` varchar(20) DEFAULT 'Not Specified',
  `spabrand` varchar(20) DEFAULT 'Not Specified',
  PRIMARY KEY (`refno`)
) ENGINE=MyISAM AUTO_INCREMENT=143 DEFAULT CHARSET=latin1 $$

The the way covers are being inserted is by a stored procedure, which is the following:

CREATE DEFINER=`root`@`%` PROCEDURE `putCover`(
                                    IN shape TINYINT,
                                    IN color TINYINT,
                                    IN reverse_fold BIT,
                                    IN x DECIMAL(6,3),
                                    IN y DECIMAL(6,3),
                                    IN type_cut VARCHAR(10),
                                    IN corner_shape VARCHAR(10),
                                    IN cutsize DECIMAL(6,3),
                                    IN corner_radius DECIMAL(6,3),
                                    IN skirt DECIMAL(5,3),
                                    IN foam_taper VARCHAR(7),
                                    IN foam_density DECIMAL(2,1),
                                    IN strap_location CHAR(1),
                                    IN strap_length DECIMAL(6,3),
                                    IN strap_inset DECIMAL(6,3)
                                    )
BEGIN
    INSERT INTO `dbre`.`cover_details`
    (`dbre`.`cover_details`.`shape`,
     `dbre`.`cover_details`.`id_color`,
     `dbre`.`cover_details`.`reversefold`,
     `dbre`.`cover_details`.`x`,
     `dbre`.`cover_details`.`y`,
     `dbre`.`cover_details`.`typecut`,
     `dbre`.`cover_details`.`cornershape`,
     `dbre`.`cover_details`.`z`,
     `dbre`.`cover_details`.`othercornerradius`,
     `dbre`.`cover_details`.`skirt`,
     `dbre`.`cover_details`.`foamTaper`,
     `dbre`.`cover_details`.`foamDensity`,
     `dbre`.`cover_details`.`strapLocation`,
     `dbre`.`cover_details`.`strapInset`,
     `dbre`.`cover_details`.`strapLength`
     )
    VALUES
    (shape,color,reverse_fold,
     x,y,type_cut,corner_shape,
     cutsize,corner_radius,skirt,foam_taper,foam_density,
     strap_location,strap_inset,strap_length);
END

As you can see basically it just fills each field, now, the CoverDAO.create(CoverDTO cover) method which creates the cover is like so:

public void create(CoverDTO cover) throws DAOException {
        Connection link = null;
        CallableStatement query = null;
        try {
            link = MySQL.getConnection();
            link.setAutoCommit(false);
            query = link.prepareCall(
                "{CALL putCover(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"
                                    );
            query.setByte(1,cover.getShape().byteValue());
            query.setByte(2,cover.getColor().byteValue());
            query.setBoolean(3, cover.getReverseFold());
            query.setBigDecimal(4,cover.getX());
            query.setBigDecimal(5,cover.getY());
            query.setString(6,cover.getTypeCut());
            query.setString(7,cover.getCornerShape());
            query.setBigDecimal(8, cover.getZ());
            query.setBigDecimal(9, cover.getCornerRadius());
            query.setBigDecimal(10, cover.getSkirt());
            query.setString(11, cover.getFoamTaper());
            query.setBigDecimal(12, cover.getFoamDensity());
            query.setString(13, cover.getStrapLocation());
            query.setBigDecimal(14, cover.getStrapLength());
            query.setBigDecimal(15, cover.getStrapInset());
            query.executeUpdate();
            link.commit();
        } catch (SQLException e) {
            throw new DAOException(e);
        } finally {
            close(link, query);
        }
    }
The CoverDTO is made of accessesor methods, the MySQL object basically returns the connection from a pool.
Here is the pset Query with dummy but appropriate data:
putCover(1,10,0,80.0,80.0,'F','Cut',0.0,0,15.0,'4x2',1.5,'A',10.0,5.0) (removed some trailing zeros)
As you can see everything is fine just when I write to the DB instead of 10 in the second parameter a 3 is written. I have done the following:

*Traced the id_color value to the create method, still got replaced by a 3

*Hardcoded the value in the DAO create method, still got replaced by a 3

*Called the procedure from the MySQL Workbench, it worked fined so I assume something is happening in the create method, any help is really appreciated.

A: There is a mistake in stored procedure declaration:
IN color TINYINT(3)

change it to:
IN color TINYINT

Hopefully it will work.

A: Given the atribute definitions shape tinyint(3) and id_color tinyint(3), I am surprised to see PROCEDURE putCover() having formal parameters IN shape TINYINT and IN color TINYINT(3), respectively. Moreover, I'd expect create() to use setByte(), accordingly.


text:
Q: Improve Harmonic Mean efficiency in Pandas pivot_table I'm applying harmonic mean from scipy.stats for aggfunc parameter in Pandas pivot_table but it is much slower than a simple mean by orders of magnitude.
I would like to know if this is excepted behavior or there is a way to turn this calculation more efficient as I need to do this calculation thousands of times.
I need to use harmonic mean but this is taking a huge amount of processing time.
I've tried using harmonic_mean from statistics form Python 3.6 but still the overhead is the same.
Thanks
import numpy as np
import pandas as pd
import statistics

data = pd.DataFrame({'value1':np.random.randint(1000,size=200000),
                     'value2':np.random.randint(24,size=200000),
                     'value3':np.random.rand(200000)+1,
                     'value4':np.random.randint(100000,size=200000)})

%timeit result = pd.pivot_table(data,index='value1',columns='value2',values='value3',aggfunc=hmean)
1.74 s ± 24.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit result = pd.pivot_table(data,index='value1',columns='value2',values='value3',aggfunc=lambda x: statistics.harmonic_mean(list(x)))
1.9 s ± 26.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit result = pd.pivot_table(data,index='value1',columns='value2',values='value3',aggfunc=np.mean)
37.4 ms ± 938 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

#Single run for both functions
%timeit hmean(data.value3[:100])
155 µs ± 3.17 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit np.mean(data.value3[:100])
138 µs ± 1.07 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

A: I would recommend using multiprocessing.Pool, the code below has been tested for 20 million records, it is 3 times faster than the original, give it try please, for sure code still needs more improvements to answer your specific question about the slow performance of statistics.harmonic_mean.
note: you can get even better results for records  > 100 M.
import time
import numpy as np
import pandas as pd
import statistics
import multiprocessing

data = pd.DataFrame({'value1':np.random.randint(1000,size=20000000),
                     'value2':np.random.randint(24,size=20000000),
                     'value3':np.random.rand(20000000)+1,
                     'value4':np.random.randint(100000,size=20000000)})

def chunk_pivot(data):
    result = pd.pivot_table(data,index='value1',columns='value2',values='value3',aggfunc=lambda x: statistics.harmonic_mean(list(x)))
    return result

DataFrameDict=[]
for i in range(4):
    print(i*250,i*250+250)
    DataFrameDict.append(data[:][data.value1.between(i*250,i*250+249)])

def parallel_pivot(prcsr):
# 6 is a number of processes I've tested
    p = multiprocessing.Pool(prcsr)
    out_df=[]
    for result in p.imap(chunk_pivot, DataFrameDict):
        #print (result)
        out_df.append(result)
    return out_df

start =time.time()
dict_pivot=parallel_pivot(6)
multiprocessing_result=pd.concat(dict_pivot,axis=0)
#singleprocessing_result = pd.pivot_table(data,index='value1',columns='value2',values='value3',aggfunc=lambda x: statistics.harmonic_mean(list(x)))
end = time.time()
print(end-start)


text:
Q: Create MLCP log in text file with timestamp I am ingesting data in MarkLogic using MLCP. I want to create log file as text file with timestamp.
My current code is writing the log into text file but the file name is not being created with the timestamp.
Below are the settings that I have in my mlcp\conf\log4j.properties:
log = D:/2019/mlcp-inspecdirect/Log
log4j.rootLogger = INFO, FILE

#Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${current.date.time}.log

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%d{dd/MM/yyyy HH:mm:ss} %p %c{2}: %m%n


text:
Q: How can this numpy 2D sorted array creation be optimized? I have a NxM matrix called coefficients that I want to sort:
import numpy
N = 10
M = 42
coefficients = numpy.random.uniform(size=(N, M))

I have an array called order with N elements that says the order that the rows of coefficients should be in:
order = numpy.random.choice(range(N), N, False)

I'm sorting coefficients by sorting order:
coefficients = numpy.array([mag for (orig, mag)
                            in sorted(zip(order, coefficients),
                                      key=lambda pair: pair[0])])

This works, but it's probably slower than it should be. If this was in 1D, I'd use fromiter, but I don't know how to tackle this since it's 2D. Is there an optimization I can make here?

A: To answer your question, just coefficients[order.argsort()] is enough :)
See also Numpy: sort by key function.