convert string to php arguments

Question: so suppose I have a function:
function j($a, $b){
 return $a + $b;
}

and then I put the intended arguments of the function into a string:
$str = '1,3';

is there a way to make the function treat the single string argument as if it were the arguments that the programmer inserted into the function....so when you do
j($str),
instead of having the function treat the $str as a single string argument, it fetches the content of the string and treats it as if the programmer wrote j(1,3) instead of j($str)
also this is a rather simple example, but I'd like it to work for even more complicated argument strings involving arrays, multidimensional arrays, associative arrays, array within arrays, as well as string arguments that have commas in it (so just exploding by comma is not really feasible)
also I'd rather not use eval() in the solution
EDIT
Also I'm trying to get this to work on any function not just mine (and not just this specific function which is just a worthless example function) so preferably the operation is to be done outside of the function
Answer: This should work for a single, comma-separated string:
function j($str){
 list($a, $b) = explode(',', $str);
 return $a + $b;
}

What do you want to sum in a multi-dimensional array? All of the values?
If yes: You only have to check the type of your argument (e.g. using is_array()) and then iterate through it. When it is multi-dimensional, call your function recursively.
Comment: see: also this is a rather simple example, but I'd like it to work for even more complicated argument strings involving arrays, multidimensional arrays, associative arrays, array within arrays, as well as string arguments that have commas in it (so just exploding by comma is not really feasible)
Comment: @kamikaze_pilot This needs to be done on a per-case basis, if you give us a real world example of what you are trying to achieve, we can help - but for any given situation the answer will probably be totally different to another...
Answer: make all parameter but except the first one optional and then use list() and explode() if the first parameter is a string (or contains ,):
function j($a, $b=null){
  if(strpos($a,',')!==false){
    list($a,$b) = explode(',',$a)
  }
  return $a + $b;
}

this is just a basic example, but the principle should be clear:

check if one of the arguments is composed of multiple parameters
if so, parse it on your own to get the single parameters
Answer: function j($a, $b = 0){ // make second arg optional
  if (! $b) { // is second arg specified and not zero
    if (strpos($a, ',') !== false){ // has provided first arg a comma
       list($first, $second) = explode(',' $a); // yes then get two values from it
       return $first + $second; // return the result
    }
  }
  else {
     return $a + $b; // two args were passed, return the result
  }

}

Now your function will support both formats, with one argument eg:
$str = '1,3'
j($str);

as well as two arguments:
j(5, 10);

Answer: call_user_func_array('j', explode(',', $str));

http://www.php.net/call_user_func_array
I have no idea how you want to make this work for "more complex argument strings including arrays of arrays", since it's hard to express those as strings. If you can format whatever string you have into an array though, for example using JSON strings and json_decode, call_user_func_array is your friend.
Comment: eg the string 'array(array(1))' should be evaluated as one variable that is an array that contains another array that contains 1
Comment: To do that without `eval` you will need some custom string parsing function. You could easily go for `json_decode('[[1]]', true)` though. In general, literal PHP is not exactly the best choice for expressing complex data structures as strings. For that, use formats that were made for this like JSON or serialized PHP.
Answer: This works :)
function f($str, $delimiter = ';')
{
    $strargs = explode($delimiter, $str);
    $args = array();
    foreach($strargs as $item)
        eval("\$args[] = " . $item. ";");
    // $args contains all arguments
    print_r($args);
}

Check it:
f("6;array(8,9);array(array(1,0,8), 5678)");

Answer: Most of the answers assume, that everything is nicely separated with coma ",", but it's not always the case. For example there could be different variable types, even strings with coma's.
$values = "123, 'here, is, a, problem, that, can\'t, be, solved, with, explode() function, mkay?'";

This can be handled with eval() and dot's "..." args retrieval in php 7.
function helper_string_args(...$args) {
    return $args;
}

$func = "\$values = \\helper_string_args($values);";
try {
    eval($func);
} catch (Exception $e) {
    var_dump($e);
    exit;
}

convert string to php arguments


Prove that $I^2$ is principal.

Question:
Consider the ideal $I=(2,\sqrt{-10})$ of $\mathbb{Z}[\sqrt{-10}]$. Prove that $I^2$ is principal.

My Try:
$I^2=(4,-10,2\sqrt{-10})$. I tried to prove that $I^2=(\sqrt{-10})$. But failed. Is my claim correct? Can anybody please help me how to show this?
Answer: No, $I^{\cdot2}=(2)$.  Note that $I^{\cdot2}$ contains $(4,-10)=(2)$.  On the other hand, every element of $I^{\cdot2}$ is clearly a multiple of $2$.
Comment: Why is $2\sqrt{-10}$ not a generator of $I^2$?
Comment: I'm not sure how to answer this kind of questions.  For example, $2$ can be a generator of $\mathbb{Z}$ as an ideal of $\mathbb{Z}$ since there exists a subset of $\mathbb{Z}$ containing $2$ that generates $\mathbb{Z}$ (e.g., $\{2,3\}$).  Of course, there exists a subset of $I^{\cdot 2}$ with $2\sqrt{-10}$ in it such that this set generates $I^{\cdot 2}$.
Comment: I proved that $I^{\cdot 2}\supseteq(2)$ and $I^{\cdot 2}\subseteq (2)$, if that is what you are asking.

Prove that $I^2$ is principal.


How to add the Shipping Charge on the selected products in commerce kickstart?

Question: I am using Drupal commerce kickstart. Can anyone tell  me how to create the field for Shipping charge in the product creation form and I could enter the Shipping charge in that field for selected products.
Answer: There are couple of modules for it:

Commerce Shipping

Commerce Shipping provides a shipping rate calculation system for
  Drupal Commerce, integrating shipping service selection into both the
  checkout form and order edit form.

Commerce Shipping Field


How can I hide a Virtual Machine in the Hyper-V Manager, so that only administrators can see it?

Question: I have a domain controller that is a virtual machine, last week a user logged on to it and shut it down accidentally. I need to prevent this from happening so I would like to hide this VM in Hyper-V so that users can not see it there. I have already restricted RDP connections to it, but they can still connect locally in Hyper-V.
We have a script that we use to do this called SetScope.VBS that we found online and it usually works well, I used it for a different VM DC on a different physical server and it worked perfect, that VM no longer shows up for anyone but admins.
On this particular server and VM though, it gives me a 4096 error (in case anyone is familiar with this script: http://projectdream.org/wordpress/2008/07/03/delegating-hyper-v-virtual-machines/   )
There's really no help for this error online so I think I'm out of luck trying to use this script for this VM.
Any other ideas how I can prevent certain users from logging on locally to a Virtual Machine in Hyper-V?
Comment: You have a method for getting this done, and are getting an error.  Posting details about the error might help people to solve your issue without reinventing the wheel, a quick google indicates it's a fairly common error that can be caused by many things, and more detail would help you get this answered.
Comment: I'm sorry but unfortunately I don't really have much more detail, all I get is a 4096 error running this script and that's it. I'm not sure what else I can say. I googled this too before posting here and only found one concrete idea to try which was no help. If you are finding a lot of resources on google, please pass me the links and I'd be happy to research them on my own. If there are specific questions I can answer for you or anyone else to help I am happy to as well. I'll also add that the error itself is not helpful - it simply says "4096" - which the website says indicates a failure
Answer: Why on earth are your regular users allowed to log into a Hyper-V host that is running production VMs? What you need to do is not let regular users administer Hyper-V hosts. That's just crazy. They have to either belong to a group like Domain Admins or be a local admin on the host to be able to do this. You should take these privileges away immediately.
Comment: I can't +1 this enough times.
Comment: @Mike That's no better. Why can they access the Hyper-V manager?
Comment: In short: While your problem can likely be fixed via technical means, you do not have a technical problem, you have a fundamental design problem. You should be working to fix that instead.
Comment: @Mike Right, that's what I was asking. Why on earth do normal users have this ability? That's not a standard design. What business case would there be for a regular (non-IT) user to be able to power up and down servers? They shouldn't even have physical access!
Comment: @Mike What you're describing is not normal at all. Typically, if a user needs access to a remote workstation, it's done via Remote Desktop, not Hyper-V Manager, precisely because of what you're seeing. If your regular users need centralized resources, you should be using Remote Desktop Services (formerly Terminal Services) and they should be using Remote Desktop for access. It's rare (to the point that I've never ever seen it) for users to have console access to a server hosting VMs, whether it be Hyper-V, ESXi, etc.
Comment: Well they can't actually log on to the physical server that hosts our VM's. They can open up Hyper-V, connect the VM server, and then see all the VM's that are stored on that server, and connect to them through the Hyper-V manager this way. That's all I meant
Comment: Hmm, I never really questioned it - been that way since I started working here. But in some cases they do need to shutdown/start up the virtual machines and they are allowed to do this.
Comment: I've never even realized this was abnormal - all of our users have the hyper-v manager installed on their machines and use it to work with certain machines as if they were physical machines - we've been using the script in my original post to hide the important ones from them - but I can't get it to work for this one DC
Comment: Ok thanks for that - we do have users connect to most of our resources using Remote Desktop - They've just always had access to the VM's to for certain machines - I'll re-assess this
Comment: accessing RDP does not require admin acccess to the hyper-v hosts..
Comment: @Rex I didn't say that it did, but managing the virtual machines on that host does (or close to it).
Comment: @MDMarra - my comment was mostly directed at Mike who stated users were using remote desktop. My point being, they can user remote desktop to the guests but shouldn't be using remote desktop to jump on the hyper-v host. In rereading his comment, I may have misunderstood what he was saying.
Comment: Ohh, ok. I see now :)
Comment: The only plausible business case I can see for that sort of access would be to let users create vms for test/dev/etc use without needing to go through an admin (being able to do this would make my life easier at times).  However, those VMs should be isolated on separate hardware and a separate admin console so that the developers/etc can't accidentally screw up any production systems.
Answer: I gathered from the comments to MDMarra's answer that some users need (need or want?) to be able to start and stop VMs. If users do have a valid case for having direct control over a server, such as when they are used for dev work, consider placing those VM's on the users' workstations. Use whatever virtualisation product you like for the job, such as Virtualbox, VMWare Player, Virtual PC, etc.
Your situation screams two fundamental problems:

The rule of least privileges should always be applied.
Never allow users to access or do anything for which you might be held accountable. It's easy enough to make mistakes. You don't need users making them for you.


GPO Comparison Tool

Question: Does anyone know of a GPO comparison tool, preferably free (or cheap).
I need to compare settings from two GPOs to see what's missing in the target GPO.
edit:  just to clarify, I need a tool which can compare the settings for me. I can do it manually, but it is cumbersome and also has the potential for me making mistakes.
Comment: Although I started out with Greg Askew's approach. This ended up getting too tedious for more complex GPOs. Very recently, I found "GPO Compare" by "SDM Software" http://www.sdmsoftware.com/group_policy_compare.php hope it helps someone else.
Answer: Use Group Policy Management Console to save the GPO's as XML files, open them in Notepad++ and press Alt-D to compare the files.
Comment: Any variation on this will work.  Basically, export the GPO's as XML and diff the files with your diff tool of choice.
Answer: You can use two instances of the Group Policy Management Console and go to the "settings" tab while having the GPOs to compare selected. Click the "show all" to show all the applied settings.
Comment: that's the backup plan, but there has to be a better tool, something like BeyondCompare, but for GPOs.
Comment: Are you creating an identical GPO?  Is the target GPO going to reside in the same domain as the source?
Comment: not creating new GPOs. Same domain, differen OUs. Basically, it seems like one of our regions neglected updating their GPOs for past few years and are running into issues (don't get me started on the architechure, was in place long before I got to it lol)
Answer: Use the SCM v2 GPO import function to import the GPO's as baselines.  You can then use the compare tool to show settings differences.  V2 is in CTP right now but seems to work just fine so far.  here is the  link to the blog post and download
Answer: Another alternative, (If you're just attempting to compare registry entries within the GPOs) is using Powershell. The particular way shown below worked for my environment, but may be able to be utilized/modified to work within yours

This way assumes you are comparing similar GPOs from two different domains, and you have a trust configured between the two domains to be able to perform the backup from within one of them.
This way also assumes you don't have the registry entries organized into collection items within the GPO. You'll needs to move all the registry entries into the root in order to make this work.
PowerShell 5.1

Create backups of each GPO within the directory structures you created

<code>$farms = 'AppFarm1','AppFarm2'

foreach ($farm in $farms) {

Backup-Gpo -Domain qa01domain -Name "$farm Settings" -Path "C:\GpoBackupsDiff\qa01\farms\$farm"
Backup-Gpo -Domain qa02domain -Name "$farm Settings" -Path "C:\GpoBackupsDiff\qa02\farms\$farm"

}
</code>

This could be looped as well, but if you just want to do each gpo diff one-by-one then use the logic as-is

<code>$farm = 'AppFarm1'

#Obtains the GUID of the qa01 backup by using the folder name (Must only have one backup in the folder)
[string]$qa01GUID = (Get-ChildItem C:\GpoBackupsDiff\qa01\farms\$farm).Name | Select-String -Pattern "{"

#Extracts the registry entries from the gpo backup into a powershell xml object
[xml]$qa01gpo = Get-Content -Path "C:\GpoBackupsDiff\qa01\farms\bridge\$qa01GUID\DomainSysvol\GPO\Machine\Preferences\Registry\registry.xml"

#Obtains an object of each registry entry
$qa01gpoCompare = $qa01gpo.RegistrySettings.Registry.Properties

#Obtains the GUID of the qa02 backup by using the folder name (Must only have one backup in the folder)
[string]$qa02GUID = (Get-ChildItem C:\GpoBackupsDiff\qa02\farms\$farm).Name | Select-String -Pattern "{"

#Extracts the registry entries from the gpo backup into a powershell xml object
[xml]$qa02gpo = Get-Content -Path "C:\GpoBackupsDiff\qa02\farms\bridge\$qa02GUID\DomainSysvol\GPO\Machine\Preferences\Registry\registry.xml"

#Obtains an object of each registry entry
$qa02gpoCompare = $qa02gpo.RegistrySettings.Registry.Properties

#Compares the registry entries against each other. Google the ms docs for Compare-Object for details on how it works if you're new to it.

Compare-Object -ReferenceObject $qa01gpoCompare -DifferenceObject $qa02gpoCompare

</code>
Comment: Hi Zachary, that is a good approach. However, it is not comprehensive. You are only comparing the Group Policy Preference (GPP) items. The original question was around compared the entire GPO, including Policy items which are not stored within the registry.xml.
Comment: Ah that's true, thanks for pointing that out

GPO Comparison Tool


Navbar bootstrap 2.3 to 3

Question: I decided to upgrade a website, from bootstrap 2.3 to bootstrap 3, but it has some small problems, the main one is with the navbar, which was working perfectly now adds the unordered list in vertical instead of horizontal, at the same time there is one empty border in the left right.
the current code for the css is the following, sorry if there is something wrong I'm jus a noob in website programming:
<code>.navbar ul.nav { padding-top: 15px; }
.navbar ul.nav li a {
     color:#333;
     position:relative;
      display:inline;
      font-weight: 800; text-decoration:none; font-size:12px; text-transform:uppercase; text-decoration:none; display:inline;
   -webkit-transition: all 300ms linear;
   -moz-transition: all 300ms linear;
   -o-transition: all 300ms linear;
   -ms-transition: all 300ms linear;
   transition: all 300ms linear;

   background: none;
   -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow:none;
}

.navbar ul.nav li.active a,
.navbar ul.nav li.active a:hover,
.navbar ul.nav li a:hover,
.navbar ul.nav li a.selected { color:/*#FFCC00*/#E9322D; text-decoration: none;
   background: none;
   -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow:none;
}
</code>
Comment: Any way we can see the HTML? The issue may not be CSS related.
Comment: Try http://upgrade-bootstrap.bootply.com/
Answer: See if this helps.
http://code.divshot.com/bootstrap3_upgrader/
Its a bootstrap upgrading tool. Hope this helps........

Navbar bootstrap 2.3 to 3


"Page cache maximum age" is set to "no caching" but the block seems to be cached

Question: I have a Drupal 8 standard installation on Azure. I wrote a block that uses PHP to load external content; I added a timestamp to the block as well. Under Page cache maximum age, the site is set to no caching. When I refresh the page, the timestamp doesn't update telling me it's not attempting to reload. If I manually clear the cache, all is good and the timestamp updates.
Why would this be?
As I mentioned before, these blocks are loading external content. Ideally I could set it so that these blocks alone wouldn't be cached. Is this possible?
Answer: To disable caching of the block add this to the php code:
<code>  $build['#cache']['max-age'] = 0;
  \Drupal::service('page_cache_kill_switch')->trigger();
</code>
This is a similar question Caching of blocks for anonymous user


The length of execution ouput is over limit (around 1M currently) in azure adf webactivity rest api

Question: Calling azure rest api (/consumption/usagedetails) in webactivity using azure data factory .It throws error The length of execution output is over limit (around 1M currently).Any suggestion
Comment: Hi Shipra Nigam,If my answer is helpful for you, you can accept it as answer( click on the check mark beside the answer to toggle it from greyed out to filled in.). This can be beneficial to other community members. Thank you.
Answer: Please reference this blog: Web activity throws overlimit error when calling rest api, Jay Gong has given the answer.
Web activity has times out limitation for 1 minute. Also, based on the above error The length of execution ouput is over limit (around 1M currently)., web activity also has output size limitation for 1 MB.
You could find the limitation rules from Data Factory limits and some of the them could be adjusted if you ask for Contact Support.
According the Data Factory limits and your data size, choose the right Azure Data Factory component. Such as Yuvarajan said: You can create a HTTP link service and HTTP data set and pull the data from REST API.
Hope this helps.
Answer: Web activity has  limitation of output size of 1 MB. You can create a HTTP link service and
HTTP data set and pull the data from REST API.
Answer: If you have SQL Server 2017 (14.x) and later (or SQL Managed Instance), you can use python to do this instead. Recommend to use Postman to generate the python script. As an additional extra, you can use the openjson function to convert turn this into tabular format too.
DECLARE @response NVARCHAR(MAX)

EXECUTE sp_execute_external_script @language = N'Python'
    , @script = N'

import requests
import json

url = "https://..................................."

payload = json.dumps({
  "api_key": "............................"
})
headers = {
  ''Subscription-Key'': ''.........................'',
  ''Content-Type'': ''application/json'',
  ''Ocp-Apim-Trace'': ''false''
}

response = requests.request("POST", url, headers=headers, data=payload)
response = response.text
'
,@params = N'@response NVARCHAR(MAX) OUTPUT'
,@response=@response OUTPUT

INSERT INTO dbo.mytable ([response])
SELECT @response


Content access based on the content author's role

Question: I have a content type named "Files". I have given access for users with roles editor 1, editor 2 and editor 3 to update and delete their own content.
Now If a user with editor 1 creates a files content. I need to allow other users with same role (editor 1) to update and delete the content.
I tried Content Access Module but it doesn't helps.
Can anyone give me a working example for this scenario.
Answer: The permission on "own content" is connected to the node's author's uid and only relates to role in that a user with the role holding that permission can edit a node they created.
How I would solve your use case is with a hook_node_access in a custom module.
https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_access/7
WARNING: I just threw this together as an example, I did not test, and you need to put in the right role values.
hook_node_access($node, $op, $account) {
  if( $op !== 'update'){
    // not my use-case
    return NODE_ACCESS_IGNORE;
  }

  $author = user_load($node->uid);
  if( in_array( 'role1', $author->roles) && in_array( 'role1', $account->roles) ) {
    // the user editing has the same role as the author
    return NODE_ACCESS_ALLOW;
  }
  // repeat ... etc.

  // we did not find what we were looking for, continue with normal access check
  return NODE_ACCESS_IGNORE;
}

Answer: It seems to me that with the Rules module (together with the Content Access module you already have) you can get this to work ... The rule to create in this case woud be a variation of what's described in Tutorial: editorial workflow with rules (within the paragraph "Create rules to publish the content").
In this case, the "action" would be to "Grant access by role".


Completing the square for a quartic expression

Question: By completing the square, find (for real $x$) the minimum value of:
$$x^4 + 2x^2 + 2.$$
Comment: As all terms are non-negative, the minimum must be when $x=0$... For a change completing the square seems overkill!
Comment: take $y=x^2$ and complete the square, just a tip
Answer: $$x^4+2x^2+2=(x^2+1)^2+1$$
Now for real $x,x^2\ge0$
Answer: We can observe that
$$x^4+2x^2\geq 0$$
for all $x\in\mathbb R$ and so,
$$x^4+2x^2+2\geq 2$$
for all $x\in \mathbb R$. Moreover, for $x=0$, we have that
$$0^4+2\cdot 0^2+2=2$$
and so $2$ is the minimum.
Answer: $$ x^4+x^2+2=(x^2+1)^2+1\\x^2\geq 0\\x^2+1  \geq 0+1 \\(x^2+1)^2 \geq (1)^2\\so\\(x^2+1)^2+1\geq 1+1 $$


How can I extract an element from list and assign it to a variable (python)

Question: I have a list:
data=[['link.com/fy6ocfid1gon'], ['link.com/9nvbmgarcou0'], ['link.com/23053636'], ['link.com/wn348oqec4jpm9'], ['link.com/P6Oj72a2rdI0ZVl'], ['link.com/1r0da0npo8mz'], ['link.com/fhe9tfkyl334']]

I want to extract (fy6ocfid1gon) and save it to a var.
I tried this:
var = data.replace('link.com/','')
print(var)

it doesn't work:
error: AttributeError: 'list' object has no attribute 'replace'

Any suggestion?
Comment: you are not running the code I added exactly as it is. My code is tested and working
Comment: You can try `print([a[0].split("/")[1] for a in data])`. But why is data 2D list to begin with?
Comment: it didn't work same error: AttributeError: 'list' object has no attribute 'split'
and for your question: I extracted data using BeautifulSoup from
Comment: Your approach `data.replace()` is not working because `data` is a list, not a string. You need to access items inside data like `data[][]` to call replace on them
Answer: You can extract the element from the list by indexing into the list and then use string slicing to remove the prefix 'link.com/':
data = [
    ['link.com/fy6ocfid1gon'],
    ['link.com/9nvbmgarcou0'],
    ['link.com/23053636'],
    ['link.com/wn348oqec4jpm9'],
    ['link.com/P6Oj72a2rdI0ZVl'],
    ['link.com/1r0da0npo8mz'],
    ['link.com/fhe9tfkyl334']
]

var = data[0][0].replace('link.com/', '')
print(var)

data[0][0] accesses the first element of the list (which is itself a list)
.replace('link.com/', '') removes the 'link.com/' prefix from the string
The result is saved into var

So this will extract 'fy6ocfid1gon' from the list and save it to var.
To extract the id from every element in the list, you can loop through the list:
data = [
    ['link.com/fy6ocfid1gon'],
    ['link.com/9nvbmgarcou0'],
    ['link.com/23053636'],
    ['link.com/wn348oqec4jpm9'],
    ['link.com/P6Oj72a2rdI0ZVl'],
    ['link.com/1r0da0npo8mz'],
    ['link.com/fhe9tfkyl334']
]

ids = []
for item in data:
    id = item[0].replace('link.com/', '')
    ids.append(id)

print(ids)

Loop through each item in the data list
For each item, extract the id using .replace(), same as before
Append the id to a new list ids
After the loop, ids will contain all the extracted ids

This allows you to extract the id from every element in the list into a new list.


Typescript - Uncaught (in promise) TypeError: v.toPixiPoint is not a function

Question: I am trying to create some the extension toPixiPoint() for my Vector2 class but when running npm build and viewing it in the browser. I get the following error in the console.

I only get errors when I open the build in the browser. There are no errors in vs code and the function gets autocompleted. What could this mean? The weird thing is my colleague is using this exact same code in his project and it's working fine? I'm reasonably new to typescript and just can't figure it out.
globals.d.ts
import { Vector2 } from "~/ts/Physics/Vector2";
import * as PIXI from 'pixi.js';

declare module '~/ts/Physics/Vector2' {
    interface Vector2 {
        toPixiPoint(): PIXI.Point;
    }
}

ExtensionMethods.ts
import { Vector2 } from "~/ts/Physics/Vector2";
import * as PIXI from 'pixi.js';

Vector2.prototype.toPixiPoint = function() : PIXI.Point {
    return new PIXI.Point(this.x, this.y);
}

The call placed in the constructor of a Tank.TS
let v = new Vector2(0,0);
console.log(v.toPixiPoint());

TSConfig
{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "~*": ["./*"]
    },
    "lib": ["es2015.core", "es2015.promise", "es2015.collection", "es2015.iterable", "dom"]
  },
  "include": ["src/**/*"]
}

Package.JSON
{
    "name": "typescriptgame",
    "version": "1.0.0",
    "description": "",
    "main": "",
    "dependencies": {
        "@types/pngjs": "^3.4.0",
        "pixi.js": "^5.2.0",
        "public": "^0.1.5",
        "strongly-typed-events": "^1.6.3",
        "typescript": "^3.7.2"
    },
    "scripts": {
        "serve": "parcel ./src/index.html --open",
        "build": "parcel build src/index.html --no-source-maps --public-url ./"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "@types/node": "^12.12.17",
        "cssnano": "^4.1.10"
    }
}

EDIT
When looking at my colleague's project, I found that he is using Babel besides Parcel. Could this have anything to do with it? He started with a setup project so he doesn't actually know why it's using Babel. I set up the project from scratch. The only big difference is that he is using Babel besides Parcel. But isn't it wierd to use two compilers? I'm researching this as we speak.

Answer: The solution was to use import "~ts/Extensions/ExtensionMethods" in the Tank.ts. I did not think I would need that because my colleague did not use that either. But it works.


Highcharts set xAxis values starting 12am and ends in 11pm

Question: I'm using a highcharts plugin, my aim is to draw a graph for the wholeday by hour.
How to set the xAxis to use 12hour format (w/ AM&PM), start => end of the day. Or some option to have 3hours interval.
For example i have filter for today & yesterday
My Data, looks like this (timestamp & value):
[ [1561593600000, 102.5], [1561658400000, 177.45] ]

Heres my full script:
  $(function(){
    var moneySign = "$";

    Highcharts.setOptions({
      lang: {
        thousandsSep: ','
      }
    });

    // Sales Chart
    var SalesChart = Highcharts.chart('ba-chart-sales', {
      title: { text: '' },
      exporting: { enabled: false },
      subtitle: { text: '' },
      yAxis: {
        title: { text: '' },
        useHTML: true,
        labels: {
          formatter: function() {
            return moneySign + this.axis.defaultLabelFormatter.call({
              axis: this.axis,
              value: this.value
            });
          }
        }
      },
      xAxis: {
        // Default for 7days & 30days (will change for today||yesterday)
        type: 'datetime',
        dateTimeLabelFormats: { day: '%b %e' },
        tickInterval: 24 * 3600 * 1000 // interval of 1 day
      },
      legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle',
        enabled:false
      },
      tooltip: {
        dateTimeLabelFormats: { day: '%B %e, %Y' },
        shared: true,
        useHTML: true,
        headerFormat: '{point.key}
',
        pointFormat: '

' +
                     '
 ' + moneySign + '{point.y}
',
        footerFormat: '
',
        crosshairs: {
          color: '#ccc',
          className: 'chart-crosshair',
          dashStyle: 'solid',
          width: 1
        }
      },
      plotOptions: {
        series: {
          label: {
            connectorAllowed: false
          },
          marker: {
            enabled: false,
            symbol: 'circle'
          }
        }
      },
      series: [{
        tooltip: { xDateFormat: '%B %e, %Y' },
        showInLegend: false,
        name: '',
        data: []
      }],
      responsive: rules: [{
        condition: {
          maxWidth: 600
        },
        chartOptions: {
          legend: {
            layout: 'horizontal',
            align: 'center',
            verticalAlign: 'bottom'
          }
        }
      }],
      credits: { enabled: false }
    });

    // Initial
    var SalesChartExtremes = SalesChart.yAxis[0].getExtremes();

    // Change Cart Type `line` || `column`
    function reDrawChart(filter, chart) {
      var series  = SalesChart.series[0];
      var newType = ['today', 'yesterday'].includes(filter) ? 'column' : 'line';
      series.chart.addSeries({
        type: newType,
        name: series.name,
        color: series.color,
        data: series.options.data,
      }, false);
      series.remove();
    }

    // Get Offer Analytics Data
    function getAnalytics(filter=''){
      $.ajax({
        type: "GET",
        url: "<%= analytics_url %>",
        data: {chart_filter: filter},
        dataType: "JSON",
        success: function(data){
          var todayLocalDate = "<%= @local_time.strftime("%Y-%m-%d") %>".split('-').map(Number);
          var yesterdayLocalDate = "<%= @local_time.yesterday.strftime("%Y-%m-%d") %>".split('-').map(Number);

          if( ['30', '7', ''].includes(filter) ){
            var toolTipProp = { xDateFormat: '%B %e, %Y' };
            var pointIntervalProp = 24 * 3600 * 1000; // one day
            var pointStartProp = '';
            var chartType = 'line';
          }else{
            if (filter == 'today'){
              var pointStartProp = Date.UTC(todayLocalDate[0], todayLocalDate[1], todayLocalDate[2]);
            }else if (filter == 'yesterday'){
              var pointStartProp = Date.UTC(yesterdayLocalDate[0], yesterdayLocalDate[1], yesterdayLocalDate[2]);
            }
            var toolTipProp = { xDateFormat: '%B %e, %Y %I:%M%p' };
            var pointIntervalProp = 3600000 * 3; // 3 hours
            var chartType = 'column';
          }

          var markerEnabled = data.sales.length == 1
          var salesOpts = {
            tooltip: toolTipProp,
            data: data.sales,
            animation: { duration: 1000 },
            pointInterval: pointIntervalProp,
            pointStart: pointStartProp,
            crosshair: true,
            marker: {
              enabled: markerEnabled
            }
          }

          // Sets yAxis min & max values for empty result
          if(data.sales.length == 0){
            SalesChart.yAxis[0].setExtremes(0,100);
            SalesChart.yAxis[0].update({tickInterval: 20});
          }else{
            // return to previous categories based on data
            SalesChart.yAxis[0].setExtremes(SalesChartExtremes.min, SalesChartExtremes.max);
            SalesChart.yAxis[0].update({tickInterval: 500});
          }

          if(filter == 'today' || filter == 'yesterday'){
            var defaultTimeOpt = {
              tickInterval: 1,
              type: 'datetime',
              dateTimeLabelFormats: {
                millisecond: '%l:%M:%S.%L %P',
                second: '%l:%M:%S %P',
                minute: '%l:%M %P',
                hour: '%l:%M %P',
                day: '(%e. %b) %l:%M %P'
              }
            }
            SalesChart.xAxis[0].update(defaultTimeOpt, true);

          }else{
            // return to day options
            var defaultDayOpt = {
              type: 'datetime',
              dateTimeLabelFormats: { day: '%b %e' },
              tickInterval: 24 * 3600 * 1000 // interval of 1 day
            }

            SalesChart.xAxis[0].update(defaultDayOpt, false);
          }

          SalesChart.series[0].update(salesOpts, true);
          reDrawChart(filter, 'sales');

        },
        error: function(data) {
          flashError("Error getting analytics");
        }
      });
      return false;
    }

  });

// Call getAnalytics when select dropdown filter change (e.g. today, yesterday, lastweek ...)
getAnalytics();

Current progress,

TODO 1: If only have few data, the time where NO data should have 0 value (so there's still progress in chart).
TODO 2: Set the time/hour in xAxis & have an option for hour gap/interval like 3hours ... 12AM, 3AM, 6AM ....
Comment: If you have multiple issues I'd suggest trying to separate them into separate questions, as it can be hard to sufficiently address all the sub-questions, as each of them might have several viable solutions. Also it makes it easier for those having similar issues to find a single source of truth for that specific issue.
Answer: If you already have the value then you can do something like
xAxis: {
    labels: {
        //isPm() is a function that checks for am and pm of your timestamp
        format: '{value} ' + (isPm() ? "pm":"am")
    }
}

also you need to show how you are plotting the chart so as to know the best way of implementation
Answer: You can change your datetime label format (API):
xAxis: {
    type: 'datetime',
    dateTimeLabelFormats: {
      millisecond: '%l:%M:%S.%L %P',
      second: '%l:%M:%S %P',
      minute: '%l:%M %P',
      hour: '%l:%M %P',
      day: '(%e. %b) %l:%M %P',
    }
}

See this JSFiddle demonstration.
The values set in dateTimeLabelFormats is a subset of PHPs strftime. In this case:

%l: Hour in 12-hour format, with a space preceding single digits. 1 through 12
%P: Lower-case 'am' or 'pm' based on the given time.    Example: am for 00:31, pm for 22:23
Comment: Hi @Halvor , i see its working, but in my case I'm switching chart types (line, column) depends on selected filter. How can I dynamically apply that options.

ex. chart.series[0].setData({
  pointStart: date_beginning_of_time_here,
  pointInterval: 3600 * 1000 * 3, // 3 hours
}); but this didn't worked.
Comment: Hi @aldrien.h, You need to use `update` method: https://api.highcharts.com/class-reference/Highcharts.Series#update


Give me hints for evaluating this limit

Question: Evaluate this limit:
$$\lim_{n\to\infty}{\left\{\left(1+\frac{1}{n}\right)^n-\left(1+\frac{1}{n}\right)\right\}}^{-n}$$
Please give me some hints. If you provide a complete answer instead, please include a spoiler tag.
Comment: Then the part inside the curls goes to $(e-1)$. It powered to n goes to $\infty$. So, the limit is 0. Am I right? @Christian Ivicevic
Comment: **Hint.** $e^x=\lim_{n\to\infty}(1+x/n)^n$
Comment: If I am not overlooking anything this is true indeed. I guess you just need to explain your reasoning more detailed. Moreover you have to check whether you are allowed to apply my hint - if it is for a homework, then the question is whether you have already proven the hint in a lecture etc.
Comment: Yes. I think I'm allowed to do so. @Christian Ivicevic
Answer: Hint.
$$\lim_{n\to\infty}\left(1+\frac{x}{n}\right)^n=e^x=\exp(x)$$
From here on you can easily conclude the result as you mentioned in the comments of your post.
Comment: There's one problem though. Rather, a confusion. I know that $\lim_{x\to a}{f(x)^n}=(\lim_{x\to a}{f(x)})^n$. But, can the same be said when $n$ is replaced with $x$ itself?
Comment: @SayantanSantra No $\lim_{x \to a} f(x)^{g(x)} \ne (\lim_{x \to a} f(x))^{g(x)}$  Unless $g$ is constant function
Comment: Then? How would I solve it? @Ekaveera Kumar Sharma
Comment: By applying Log on both sides
Answer: HINT:
$$\lim_{n\to\infty}\left(\left(1+\frac{1}{n}\right)^n-\left(1+\frac{1}{n}\right)\right)^{-n}=$$
$$\lim_{n\to\infty}\left(-1+\left(1+\frac{1}{n}\right)^n-\frac{1}{n}\right)^{-n}=$$
$$\lim_{n\to\infty}\exp\left(\ln\left(\left(-1+\left(1+\frac{1}{n}\right)^n-\frac{1}{n}\right)^{-n}\right)\right)=$$
$$\lim_{n\to\infty}\exp\left(-n\ln\left(-1+\left(1+\frac{1}{n}\right)^n-\frac{1}{n}\right)\right)=$$
$$\exp\left(\lim_{n\to\infty}-n\ln\left(-1+\left(1+\frac{1}{n}\right)^n-\frac{1}{n}\right)\right)=$$
$$\exp\left(-\lim_{n\to\infty}n\lim_{n\to\infty}\ln\left(-1+\left(1+\frac{1}{n}\right)^n-\frac{1}{n}\right)\right)$$

Give me hints for evaluating this limit


Trigonometry equation, odd-function.

Question: So I have the following equation:
$\sin\left(x-\frac{\pi}{6}\right) + \cos\left(x+\frac{\pi}{4}\right)=0$
It should be solved using the fact that Sin is an odd function, I can not really get the gripp of how and what I need to do? Any sugestions?
Comment: Why not to try  expanding the two terms first ?
Comment: Do you mean by using the trigonometric addition formulas?
Comment: You can solve it. Just use the hint given by BLAZE and put the numbers; you should end with something looking like $a\sin(x)+b\cos(x)=0$.
Comment: Yes; this is just the first idea which came to my mind.
Comment: I have tried this, but all I end up with is the same expression as i start with, or an expression that I can not solve.
Answer: $$\cos(x+\frac\pi4)=\sin(\frac\pi4-x)$$ and
the equation turns to
$$\sin(x-\frac\pi6)=\sin(x-\frac\pi4),$$
i.e.
$$2x-\frac{5\pi}{12}=(2k+1)\pi.$$
Comment: @ Yves i dint get your step after you got sin on both the sides as when you remove sine eqn is 0=-π/6+π/4??
Comment: @ArchisWelankar: $a=b$ is not the only solution of $\sin(a)=\sin(b)$...
Answer: So i found the solution using the fact that Sin is odd, here is my solution:
$\sin\left (x-\frac{\pi}{6}\right ) + \cos\left (x+\frac{\pi}{4}\right ) = 0\Leftrightarrow \cos\left (x+\frac{\pi}{4}\right ) = -\sin\left (x-\frac{\pi}{6}\right )$
Since sin is an odd function, $-\sin\left (x-\frac{\pi}{6}\right ) = \sin\left (x-\frac{\pi}{6} + \pi\right )$
This the gives the following:
$\cos\left (x+\frac{\pi}{4}\right ) = \sin\left (x-\frac{\pi}{6} + \pi\right ))\Leftrightarrow \cos\left (x+\frac{\pi}{4}\right ) = \cos\left (\frac{\pi}{2} -\frac{5\pi}{6} -x\right )$
This happends when:
$x + \frac{\pi}{4} = \frac{-2\pi}{6}-x+n2\pi \Leftrightarrow x=\frac{-7\pi}{24}+n\pi$
Thanks alot for the help, special thanx to @BLAZE, you gave me the hints to find the solution.
Comment: You're welcome.
Answer: Sorry that this approach does not use the oddness of the Sine function, after I finishing writing this it was too late for me to turn back and utilize that property.
Using trigonometric addition formulae as mentioned in the comments:
$$\sin(A \pm B)= \sin A\cos B\pm\cos A\sin B$$
$$\cos(A \pm B)= \cos A\cos B\mp\sin A\sin B$$
Write $$\sin\left(x-\frac{\pi}{6}\right) + \cos\left(x+\frac{\pi}{4}\right)=0$$
as $$\sin(x)\cos\left(\frac{\pi}{6}\right)-\cos(x)\sin\left(\frac{\pi}{6}\right)+\cos(x)\cos\left(\frac{\pi}{4}\right)-\sin(x)\sin\left(\frac{\pi}{4}\right)$$
$$=\frac{\sqrt{3}}{2}\sin(x)-\frac{1}{2}\cos(x)+\frac{1}{\sqrt{2}}\cos(x)-\frac{1}{\sqrt{2}}\sin(x)$$
$$=\cos(x)\left(\frac{1}{\sqrt{2}}-\frac{1}{2}\right)+\sin(x)\left(\frac{\sqrt{3}}{2}-\frac{1}{\sqrt{2}}\right)$$
$$\implies\cos(x)\left(\frac{2-\sqrt{2}}{2\sqrt{2}}\right)+\sin(x)\left(\frac{\sqrt{6}-2}{2\sqrt{2}}\right)=0$$
Since
$$\cos(x)\ne 0$$
$$\implies\left(\frac{2-\sqrt{2}}{2\sqrt{2}}\right)+\tan(x)\left(\frac{\sqrt{6}-2}{2\sqrt{2}}\right)=0$$
$$\implies\tan(x)\left(\frac{\sqrt{6}-2}{2\sqrt{2}}\right)=\left(\frac{\sqrt{2}-2}{2\sqrt{2}}\right)$$
$$x=\tan^{-1}\left(\frac{\sqrt{2}-2}{\sqrt{6}-2}\right)$$
$$x=\tan^{-1}\left(\frac{(\sqrt{2}-2)(\sqrt{6} + 2)}{(\sqrt{6}-2)(\sqrt{6} + 2)}\right)=\tan^{-1}\left(\frac{(\sqrt{2}-2)(\sqrt{6} + 2)}{2}\right)$$
$$=\tan^{-1}{(\sqrt{2}+\sqrt{3}-\sqrt{6}-2)}+k\pi$$
where $k \in \mathbb{N}$
Comment: The final answer can be simplified.
Comment: Your value is correct, though (modulo $\pi$).
Comment: Well, the answer is correct, but I do not think that this is the method that should be used. This method does not include using that Sin(x) is an odd function.
Comment: Hem, the function is periodic.
Comment: @Yves Oh yes I see what you mean, $\pi$ is periodicity for $\tan x$
Comment: @Per Yes good point, I kind of lost track of that condition, sorry
Answer: More unorthodoxly, we first take the midpoint of $x-\frac{\pi}{6}$ and $x + \frac{\pi}{4}$ before applying the angle sum and difference identities:
Let $A = x + \frac{\pi}{24}$ (the midpoint). Then we need
$$\sin\left(A - \frac{5\pi}{24}\right) + \cos \left(A + \frac{5\pi}{24}\right) = 0$$
$$\sin A\cos\frac{5\pi}{24} - \cos A\sin\frac{5\pi}{24} + \cos A\cos\frac{5\pi}{24} - \sin A\sin\frac{5\pi}{24} = 0$$
$$\sin A\left(\cos \frac{5\pi}{24} - \sin \frac{5\pi}{24}\right) + \cos A\left(-\sin\frac{5\pi}{24} + \cos \frac{5\pi}{24}\right) = 0$$
$$\left(-\sin\frac{5\pi}{24} + \cos \frac{5\pi}{24}\right)\left(\sin A + \cos A\right) = 0$$
so we need
$$\sin A + \cos A  = 0$$
$$\tan A = -1$$
$$\tan \left( x + \frac{\pi}{24}\right) = -1$$
which can be solved directly as per normal.

Trigonometry equation, odd-function.


Como manter fixa a cor do item selecionado

Question: Adicionando o listener ao Listview através do método setOnItemClickListener, sempre que se clica sobre um dos seus itens, este muda momentaneamente de cor. Existe alguma forma de manter esta cor fixa no item que for clicado ?
Comment: Você está se referendo ao efeito do click? @VitorMendanha
Comment: Está a usar uma *custom view* para o item da sua lista?
Comment: Está usando `Array adapter`?
Comment: Estou a usar uma classe que extende a BaseAdapter para construir os itens da ListView. O método "setOnItemClickListener" executo-o na classe MainActivity logo a seguir ao método "setAdapter":
Comment: listView.setAdapter(new ListViewAdapter(this, arrayList));

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "Lista " + position, Toast.LENGTH_SHORT).show();

            }
        });
Answer: 1 - Adicione o atributo android:choiceMode à ListView,
para permitir seleccionar apenas uma linha:
android:choiceMode="singleChoice"

para permitir seleccionar mais de uma linha:
android:choiceMode="multipleChoice"

2 - Adicione o seguinte atributo ao layout do item da lista:
android:background="?android:attr/activatedBackgroundIndicator"

Se quiser customizar a aparência da selecção crie, na pasta res/drawable, um selector para o efeito:
listselector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
   android:exitFadeDuration="@android:integer/config_mediumAnimTime">

   <item android:drawable="@android:color/holo_green_light" android:state_pressed="true"/>
   <item android:drawable="@android:color/holo_purple" android:state_selected="true"/>
   <item android:drawable="@android:color/holo_purple" android:state_activated="true"/>

</selector>

Altere as cores ao seu gosto!
O atributo background do item da lista deverá ser declarado assim:
android:background="@drawable/listselector"

EDIT após comentários
Como está a utilizar mais de uma cor para o backgroud das linhas da ListView, é necessário definir um Selector para cada uma delas:
Para atribuir a cor de fundo por defeito é criado no Selector um item sem "State", este item tem de ser o último do Selector:
listselector_par.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
   android:exitFadeDuration="@android:integer/config_mediumAnimTime">

   <item android:drawable="@android:color/holo_green_light" android:state_pressed="true"/>
   <item android:drawable="@android:color/holo_purple" android:state_selected="true"/>
   <item android:drawable="@android:color/holo_purple" android:state_activated="true"/>

    <item android:drawable="@android:color/holo_green_dark"/>
</selector>

Crie outro Selector, listselector_impar.xml, indicado outra cor para o fundo.
No Adapter atribua ao background o respectivo Selector conforme a linha seja par ou ímpar.
Nota:
Se não gostar do efeito de animação elimine a linha:
android:exitFadeDuration="@android:integer/config_mediumAnimTime"

ou altere o valor config_mediumAnimTime
Comment: Declare uma variável assim: `final Boolean vemDoLongClick = false;`. Troque `return true` por `return false` e na linha anterior faça `vemDoLongClick = true;` no inicio do método `onItemClick()` faça o teste assim `if(vemDoLongClick){vemDoLongClick = false; return;}`
Comment: ramaral, agora surgiu-me o seguinte problema: Se o click for longo através do método "setOnItemLongClickListener" a cor volta a não ficar fixa no item selecionado. Sabe a solução para este problema?
Comment: ramaral, a sua lógica funcionou perfeitamente! Mais uma vez um grande obrigado.


If my IV (denoted Z) equals 1, my endogenous var D always equals 1; is this a problem?

Question: I have a binary instrumental variable Z={0,1} and a binary endogenous variable D={0,1}. By construction, D=1 necessarily holds if Z=1. There are also cases where D=1 if Z=0, but there are no cases where D=0 if Z=1. (Side note: in the first stage of 2SLS, I get an F-value of around 3000.) Intuitively, I feel I should have more variation, i.e., that I should also have cases where D=0 if Z=1. Are my intuitive worries justified?
Answer: I am no expert in the IV literature, so please comment on this answer if I miss anything. But consider these two very nice answers here.
Usually under strong monotonicity there are three groups,
Always-taker ($D=1\,$ for $\,Z=0/1$),
Compliers ($D=1\, \& \,Z=1$ or $D=0\, \& \,Z=0$) and
Never-taker ($D=0\,$ for $\,Z=0/1$)
You do not observe the never-taker with $D=0\,\&\,Z=1$. So you have to assume that
$$Pr(D=0|Z =1)=0 \text{ or } Pr(D=1|Z =1)=1$$
What does this means?
It means that those with $Z=1$, or the treatment, always receive the treatment. There are no never-taker with $Z=1$ (this a somewhat strange form of one-sided non-compliance, usually you assume that the control group never receives the treatment under non-sided non-compliance).
The formula for the Wald estimator is (copied from this answer) in this case
$$\begin{align}
\text{LATE} &= \frac{E(Y|Z=1)−E(Y|Z=0)}{Pr(D=1|Z =1)−Pr(D=1|Z =0)}\\
&= \frac{E(Y|Z=1)−E(Y|Z=0)}{1-Pr(D=1)}\\
&=\text{Average Treatment Efect On the Untreated}
\end{align}
$$
Your analysis is valid, but you make strong assumptions (in addition to independence and monotonicty) by implicitly assuming that the local average treatment effect (LATE) is equal to the average treatment effect on the untreated units.
(see Imbens and Wooldridge Lecture Notes)


How to find image style URL from within twig template?

Question: I'm implementing a node template that uses an image twice; once in a 'normal' way (i.e. using the image style defined in the field's display configuration for that view mode), and the other is as a css background-image property.
I need one of two things:

(ideally) a way to get the URL for a different image style of the same image.
a way to get the URL for the image field.

I'm struggling to use dump() and kint() to help myself to an answer. They both output far far too much (thanks to embedded links to "parent" etc.) and seem to not have the info I need. e.g. looking at dump(content.field_image) output the actual URL of the image is not there (so where does it come from such that it can be rendered with {{ content.field_image }}?!). kint() on the other hand dies completely if I pass an argument to it and the top-level version is again far too big to navigate. Debugging was soo much easier with phptemplate + xdebug. (Yes I know it's good that themers can't drop the database.)
There's an answer to (1) that implies you can't do it, but I don't understand why I can't get the existing URL in (2)?
Answer: The first part is already answered in the linked question, where there is the code how to do this. To answer the second part of the question, you can access the original image in the node object:
{{ file_url(node.field_image.entity.uri.value) }}

One remark about content:
In a node template the image field in content is not ready to be rendered. The field contains the configuration how it should be displayed and the field object which contains all raw data. Later this will be put together in the field, image-formatter and image templates. That is the reason you don't find the url you are looking for in content at this point.
In the node template you can use the fields on the top level of the content array, for example display the image field
{{ content.field_image }}

as configured in the view mode.
Edit:
There is a new filter in the module Twig Tweak. Now you can generate the image style url in twig directly from an uri or url of the original image:
{{ node.field_image.entity.uri.value | image_style('thumbnail') }}

Comment: @paulcap1, for example `{{ node.field_ref.entity.field_image.entity.uri.value }}`
Comment: Thanks. So all the preprocess hooks get called when twig calls render e.g. at the point you go `{{ content.field_image }}` and not before? Also, I think the url i'll get from your suggestion is the original url - part 2 of my Q was asking for the url of the image style, as configures by the view mode. Is that possible?
Comment: This only works for regular uploaded images and not for entity referenced images. How can this be made to work with entity referenced images?
Comment: @paulcap1, don't know exactly what you mean, because an image field is a reference field (to a file entity). If you mean you have the image inside of a referenced entity, then you need `.entity` twice, first to get to the entity and second to the image.
Comment: @4k4. I am using the default Page content type. I have an entity referenced field called field_global_image. This uses the Image Bundle. The Bundles image field is called ""image" I tried it your way using {{ node.field_global_image.entity.image.entity.uri.value }} I also tried switching the fields like this {{ node.image.entity.field_global_image.entity.uri.value }} Neither worked. In my Answer in a seperate post, that is what worked for me.
Answer: You can get the image style url in a preprocess function and pass it to the node template. (in my case, I needed at the page level, I'm guessing this would still work for node)
Something like this, with "myimagefield" being the machine name for your image field, and "myimagestyle" being the machine name for your style, also make sure you include the Entity\ImageStyle.
use Drupal\image\Entity\ImageStyle;

/**
 * Implements hook_preprocess_page().
*/
function mytheme_preprocess_page(&$variables, $hook) {
  if ($variables['node']) {
    $node = $variables['node'];
    if($node->myimagefield[0]){
        $cover_image = $node->myimagefield[0]->entity->getFileUri();
        $image_url = ImageStyle::load('myimagestyle')->buildUrl($cover_image);
        $variables['my_image'] = $image_url;
    }
  }
}

Comment: the question says to pull the view mode from the field's display configuration. By doing the $image_url = ImageStyle::load('myimagestyle')->buildUrl($cover_image); how are you pulling the image style from the field's configuration? You simply added myimagestyle, but what if the same field is on multiple entities (e.g. nodes) where it requires different image styles?
Answer: Install the Twig Tweak Module
https://www.drupal.org/project/twig_tweak
And this module Twig Field
https://www.drupal.org/project/twig_field_value
If you are using regular image upload field images use this in your node template:

If you are using entity reference image use this:

Comment: Thanks! The entity reference example can also be accomplished without the twig_field_value module by: `file_url(node.field_image.entity.field_referenced_image.entity.uri.value | image_style('thumbnail'))`
Comment: Note that in the example about using referenced entities `image` after `field_target_entity` refers to the image field on the referenced entity. You might have to adjust it.
Answer: With twig tweaks you don't need the twig_field_value module as in @paulcap1's answer.
{% set image_uri = content.field_sbb_background_image['#items']|file_uri %}
{% set image_url =  file_url(image_uri) %}

Or if you are printing out with an image style you don't even need the image url. To print, say, the image style thumbnail:
{{ image_uri|image_style('thumbnail') }}

Answer: Thanks to the other contributors. In my situation I needed something slightly different to get it working:
My solution that I found to work, with background image application of it
I found this to work with Drupal 9.2.4, with contrib module twig tweak 3.1.2
url({{ node.field_background_media.entity.field_media_image.0.entity.uri.value | image_style('background_image_xl') }});

Example - Background image for page
Here's my example to illustrate the above
I have a field in my content type 'Landing Page', the field is called 'Background Media', machine name field_background_media
In my twig template in my own custom theme, (in my case, web/themes/custom/clau2/templates/content/node--landing-page.html.twig )for my content type I have:
{%
  set bg_img_styled_url = node.field_background_media.entity.field_media_image.0.entity.uri.value | image_style('background_image_xl')
%}

Where background_image_xl is the machine name of an existing style, listed in admin/config/media/image-styles
And then also in my twig, I have, which performs the purpose of providing a background image for the whole page that my content of my content type is on.

Where #clau-page-container-id is set in in my html.html.twig template, web/themes/custom/clau2/templates/layout/html.html.twig : -

( As an aside, in manage display tab of content type, this field is actually in the disabled section of the 'Full' view mode in 'manage display' for my content type ( admin/structure/types/manage/landing_page/display/full ), for my purpose - I am using it to provide a background image and don't want it output again by {{ content }}  . This is only really relevant to my case. If the field is enabled the other steps will still work, because I've seen them myself to have. )
As another aside, my example means that Media entity (and convenient media browser of existing content) can be used for choosing a background image, re-using existing images, without the need for an additional contrib module.
There are good modules like bg_img_field, look and modifiers but at time of writing I'm not aware of them using the Media field type, instead they seem to use the 'legacy' image field type - less flexibility - i.e. can't browse for and re-use existing images. See further discussion about this here
See my example in action here:
(website I'm working on). I think the screenshot gives good value as to how the above twig actually provides the markup and image output.

And from that we can observe that the required image with the image style applied is used - in that markup shown in the screenshot, the image path is: sites/default/files/styles/background_image_xl/public/2020-10/Join-us-img.jpg which contains the background_image_xl image style machine name, so that the path as a whole selects the image of that style.
Answer: I had a similiar scenario, and needed to get the URL of an image to use for the CSS for a background image for the whole page, except I was using a media entity instead of a file entity. I thought it might be useful to note it here. I also wanted to use the original image URL instead of a particular style. I used a modified version of the first answer:
use Drupal\file\Entity\File;

    // Get media file path to add to template variables to use as background image in template

    function mytheme_preprocess_page(&$variables, $hook) {
      if (isset($variables['node'])) {
        $node = $variables['node'];

        if($node->field_image_media[0]){
          $media_entity = $node->field_image_media[0]->entity;
          $file_id = $media_entity->getSource()->getSourceFieldValue($media_entity);
          $bg_file = File::load($file_id);
          $path = $bg_file->createFileUrl();
          $variables['bg_image'] = $path;
        }
      }
    }

The difference is after returning the media entity, I then needed an extra step to get the entity for the file, before returning the file URL. (Thanks to Akhilavnair's comment in the How to get image file uri from media entity id thread, in showing how to retrieve the File entity from the media entity)
As this is a page preprocess function the variable was not available for the html.html.twig template, and only for the page.html.twig template. This meant to get the background image to apply to the whole page I needed to wrap the ,  and  html elements in a
 and apply the style to that wrapper
.
To retrieve the path and apply the styling I added the following to my page.html.twig:
{% if bg_image is defined %}
  {% set bg_style = "background-image:url('" ~ bg_image ~ "'); background-size: cover;" %}
{% endif %}

    ...

    ...

    ...

The image I am retrieving from the media field can also be used within the manage display form as normal using any of the available image styles, or it can hidden (as in my case). And voila:


How do I implement "enable" or "disable feature" similar to Drupal Gardens?

Question: I'm interested in implementing something similar to the way Drupal gardens let you enable and disable features in the create-site interface. (I mean the term features figuratively, not necessarily the features module.) Is this just some sort of custom form that hooks into enabling and disabling modules?
Comment: It's a nicely themed and stripped-of-options version off the modules page, yes.
Answer: What you see on that page is a Drupal form where the form fields have been heavily themed to appear differently from how you would normally see that type of form field on a Drupal site.
Looking at the HTML source of that page, it is clear those selectors are simply checkboxes rendered with a custom theme function.

  <input type="checkbox" name="features[28711]" id="edit-features-28711" value="1"   class="gardens-feature-checkbox" />Follow us
Gain a following. Provide links to your (or your users') profile on Twitter, Facebook or other social networks.

There is also custom JavaScript code that changes the appearance of the form field.
When I turn off a feature, I see a CSS class being added to a tag, and another tag value being changed. The value associated with the checkbox is not changed; it is 1 when the feature is enabled, and it is still 1 when the feature is disabled.


Issues using ivy:publish task

Question: I'm trying to use ivy:publish to publish a jar that I've built to the .ivy repository, but I'm getting an error. I'm pretty sure I'm not using it correctly, so I was hoping someone could point me in the right direction.
The project structure is something like this:
root--|
      |--src
      |--build
      |      |
      |      |--someorganisation-commonlib-1.0.0.jar
      |
      |--ivy.xml
      |--build.xml

The build.xml looks something like this:
<target name="publish">
        <ivy-publish organisation="someorganisation" resolver="local" module="commonlib" revision="1.0.0">
               <artifacts pattern="build/[organisation]-[module](-[revision])(-[type]).[ext]" />
        </ivy-publish>
    </target>

ivy.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
    <ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">

        <info
            organisation="someorganisation"
            module="commonlib"
            status="integration">
        </info>

    <dependencies>
            <dependency org="com.thoughtworks.xstream" name="xstream" rev="1.3.1" transitive="false"/>
            <dependency org="org.slf4j" name="slf4j-api" rev="1.6.1" transitive="false"/>
            <dependency org="org.slf4j" name="slf4j-jdk14" rev="1.6.1" transitive="false"/>
            <dependency org="joda-time" name="joda-time" rev="1.6.2" transitive="false"/>
        </dependencies>

    </ivy-module>

When I run the build.xml, I get the following error:
 C:\workspaces\wkspc\someproject\build.xml:8: someorganization#commonlib;1.0.0: java.lang.IllegalStateException: ivy file not found in cache for someorganization#commonlib;1.0.0: please resolve dependencies before delivering (C:\Documents and Settings\someuser\.ivy2\cache\resolved-someorganization-commonlib-1.0.0.xml)

Answer: You've forgotten a publications section in your ivy file.
<ivy-module version="2.0">
    <info organisation="someorganisation" module="commonlib"/>

    <publications>
        <artifact name="commonlib" type="jar"/>
    </publications>

    <dependencies>
        <dependency org="com.thoughtworks.xstream" name="xstream" rev="1.3.1" transitive="false"/>
        <dependency org="org.slf4j" name="slf4j-api" rev="1.6.1" transitive="false"/>
        <dependency org="org.slf4j" name="slf4j-jdk14" rev="1.6.1" transitive="false"/>
        <dependency org="joda-time" name="joda-time" rev="1.6.2" transitive="false"/>
    </dependencies>
</ivy-module>

The status and revision (pubrevision) fields can be specified by the publish task as follows:
   <ivy:publish resolver="${publish.resolver}" pubrevision="${publish.revision}" status="${publish.status}">
        <artifacts pattern="${build.dir}/[organisation]-[artifact].[ext]"/>
    </ivy:publish>

Note 1:
It would be simpler to generate the jar file without the revision number in the name. Just let ivy's artifact pattern pick up the jar file.
Note 2:
You will require an ivy resolve at some stage in your build, otherwise the ivy file doesn't get processed.

Issues using ivy:publish task


How do I import a specific word from a .txt file into Python as a string variable?

Question: I am trying to use a .txt file as a local database for around 4000 different words. They are organized in the following format:
wordOne
wordTwo
wordThree
wordFour
...
wordFourThousand

Each word has it's own separate line. My goal is to be able to import a specific word from this text file based on a random variable. I put an example of what I have so far below. Ignore my crummy camelCase habit.
import random
wordName=random.randint(1,4000)
with open('wordList.txt') as wordList:
    #use the variable wordName to open the word on that particular line number in the .txt file and set it as a variable named wordString
print(wordString)

So if the variable wordName is equal to 32, it will open up the word on line 32 of the text file and print it to the console. I hope this isn't too easy of a question, I am a bit new to Python and trying to get some practice moving data from one source to another. I really appreciate the help!
Comment: The simplest solution would be loading the entire file into emory as a list of lines
Answer: You can do:
words = wordlist.readlines()

then can do:
words[wordName - 1]

to retrieve the word you want, also you won't have to reopen the text file if you save words as a global variable.
Answer: Reading 4k words into memory is peanuts, so I'd not optimize anything here. The simplest approach is using random.choice():
import random

with open('filename.txt') as fp:
    words = list(fp)

random_word = random.choice(words).strip()  # strip will remove the trailing \n

Answer: the easiest way to do what you have described is using the read lines methods.
Assuming the below is your text file
words.txt:
one
two
three
...

You would do the following:
with open("words.txt") as textFile:
    words = textFile.readlines()
    print(words[1])

output
two

Remember the list index start from zero, so if you wanted words[i] where i = 1 to return the first element you would do words[i + 1].
Comment: This is exactly what I was looking for! Thank you so much! I don't have enough reputation yet to upvote you but I really do appreciate it!


Coin flipping probability problem.

Question: You flip a fair coin until you see three tails in a row. What is the average number of heads
that you'll see until getting T T T? (3 tails in a row).
My math got me to about 21 heads before it happens, and I wanted to know if that is correct. Thanks!
Answer: So, we can approach this via markov chains and their corresponding stochastic and fundamental matrices.
The stochastic matrix with corresponding states from left to right as 3tails, 2tails, 1tail, 0tails is:
$$\begin{bmatrix}1&\frac{1}{2}&0&0\\0&0&\frac{1}{2}&0\\0&0&0&\frac{1}{2}\\0&\frac{1}{2}&\frac{1}{2}&\frac{1}{2}\end{bmatrix}$$
We turn our attention now to the fundamental matrix:
$(I-R)^{-1}=\left(\begin{bmatrix}1&0&0\\0&1&0\\0&0&1\end{bmatrix}-\begin{bmatrix}0&\frac{1}{2}&0\\0&0&\frac{1}{2}\\\frac{1}{2}&\frac{1}{2}&\frac{1}{2}\end{bmatrix}\right)^{-1}$
$=\begin{bmatrix}1&-\frac{1}{2}&0\\0&1&-\frac{1}{2}\\-\frac{1}{2}&-\frac{1}{2}&\frac{1}{2}\end{bmatrix} = \begin{bmatrix}2&2&2\\2&4&4\\4&6&8\end{bmatrix}$
We start in the state 0tails at the beginning of the game, so we focus our attention to the third column of the fundamental matrix.  By looking at the fundamental matrix, we can gain quite a bit of information.  In particular, the sum of the column corresponds to the number of flips on average until we reach an absorbing state (in this case 3 tails in a row).  There will be $2+4+8=14$ flips on average until you reach three tails in a row.
By looking at the entries of the matrix individually, you can tell how many times you are expected to be in each specific state.  In our specific case, we look to the bottom right entry which is an $8$ and this corresponds to the number of times we move to the state 0tails, which corresponds to one time at the very start and otherwise is equivalent to having flipped a head.
Thus there are a total expected number of $7$ heads.

tldr: $7$ heads are expected to have been seen by the time you have flipped three tails in a row.
Answer: The correct answer is that the expected number of heads (or tails) is $7$.
Not 8.
The expected length of sequence is indeed 14, as shown by @JMoravitz.  But at each epoch, ther is some probability distribution for each of the four possible states of last-two flips.  And given this distribution, the expected increase in number of heads rolled is exactly equal to the expected increase in the number of tails rolled.  So the answer is $14/2$.
Comment: Ah, I believe I see my mistake.  thanks for pointing it out.  Forgot that among the eight occurrences that the entry in the matrix refers to, one of them is the starting position.  I.e. it counted the start as a "head" in my initial wording.

Coin flipping probability problem.


what is the use of form[#special] in a drupal form?

Question: Now i'm working with forms and trying to add template in to it, I have form['#special'], but i don't know how to set it and what's the use of that and its usage.
Answer: You can embed anything in your form. Just add # at the beginning of the array index to indicate it's not a child element, and Form API will accept that even if it does not define or use it. Form API reference does not mention #special, so it is not an standard parameter. Instead, it's a parameter created by module's author for his own need.
For example, I usually add #machine_name to anything that can trigger AJAX, for easier handling of $form_state['triggering_element']. There are many uses.


Extending block configuration schema

Question: I'm using the Configuration Inspector module module, and I'm finding a missing schema error.
The configuration is for block.block.pminbox.settings.thread_count
The block itself is a plugin, created in my module. I've tried:

Adding the settings to the block annonation
Creating block.block.pminbox and adding settings as a mapping with thread_count as a property of that mapping
Creating block.block.pminbox.settings and adding thread_count in there
Adding the config to mymodule.schema.yml

Here is where I am at as of now.
Submit handler for class extending BlockBase:
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['thread_count'] = (int) $form_state->getValue('thread_count');
  }

mymodule.schema.yml:
block.settings.pminbox:
  type: block_settings
  label: 'Private message inbox block settings'
  mapping:
    thread_count:
      type: integer
      label: 'Thread count'

The rest of the schema in this file is being picked up, however, I'm still getting a 'schema undefined' error from the configuration inspector for this block.
Comment: The point of having schema is that you don't have to worry about casting, the config system will take care of that for you. And if you get schema undefined then it's not about having the wrong type. Note that the key after block.setings.pminbox is the plugin ID, not the block config entity ID (as you can have N arbitrary named config entities). Are you sure your block plugin id is correct? Also, I assume the schema file is in config/schema. would be helpful if you could post a bit more of the relevant code
Comment: I am definitely using the block plugin ID (pminbox). I've confirmed it in code, it's also the name of the exported file in my config directory, and what is listed on the configuration inspector page. I tried using the config entity ID after reading your post, just to confirm, and that throws an error. The config file is in config/schema, and the rest of the config in that file is properly being read. I'm happy to post some more code, but I'm not sure which would be relevant at this point.
Answer: It would really help to knowing how your data is saved (e.g. providing a snippet from your BlockBase::blockSubmit() implementation that shows this value), or what exactly you tried adding to your yml files.
However, in theory a working example that assumes, you are saving the value like this:
PmInboxBlock.php
/**
 * @Block(
 *   id = "pminbox",
 *   admin_label = @Translation("PmInbox"),
 *   category = @Translation("PmInbox"),
 * )
 */
class PmInboxBlock extends BlockBase {

  // ... Your Form definition here ...

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['thread_count'] = $form_state->getValue('thread_count');
  }

}

Then you provide the schema definition in a schema file named after your module:
mymodule.schema.yml
block.settings.pminbox:
  type: block_settings
  label: 'PmInbox Block'
  mapping:
    thread_count:
      type: string
      label: 'Thread count'

Comment: Thanks, I appreciate the reply. I've updated the original post, however I'm still seeing the error.
Comment: @Jaypan: I suppose, you cleared the caches after adding the schema file?
Comment: I did :) [more characters]
Comment: I just triedre-installing the module, but still seeing the same issue.
Comment: That's really strange. We support a lot of modules with custom blocks using the above approach. And of course also check the schema, as we're heavily making use of configuration management. It ALWAYS worked. Please let me know, if you found your issue.
Comment: Yeah, what you posted looks right, and I even found similar code within core after you posted it. I've been around every which way and it looks like it should be working... but it's not! I'll have to keep plugging at it.
Answer: I was on the right path, thanks to Mario's answer. The problem was I was looking at the wrong ID for the block. When looking at the config file for the block (block.block.pminbox), there are two IDs. The first is the block ID (pm_inbox), and the second is in the settings array (settings.id), which is the plugin ID of the block. The value for settings.id (the plugin ID for the block) is the value to be used here (pm_inbox_block):
block.settings.pm_inbox_block:
  type: block_settings
  label: 'Settings for the private message inbox block'
  mapping:
    thread_count:
      type: integer
      label: 'The number of threads shown when block is loaded'

Extending block configuration schema


Angular frequency - Cannot explain solution

Question: Hello I'm learning some electrical engineering today but cannot come to the solution.
$w = 2π*f$
How is:
$2π*295.4 kHz = 1.86 * 106 s^{-1}$
cannot figure out what $1.86 * 106 s^{-1}$ should be
Answer: Use:

$$\text{f}_{\left[\text{Hz}\right]}=\frac{1}{\text{t}_{\left[\text{s}\right]}}$$
$$\omega_{\left[\text{rad/s}\right]}=2\pi\cdot\text{f}_{\left[\text{Hz}\right]}=2\pi\cdot\frac{1}{\text{t}_{\left[\text{s}\right]}}=\frac{2\pi}{\text{t}_{\left[\text{s}\right]}}$$

So, when $\text{f}_{\left[\text{Hz}\right]}=295.4\cdot1000=295400\space\text{Hz}$, we get:

$$\omega_{\left[\text{rad/s}\right]}=2\pi\cdot295400=590800\pi\approx1856052.94\space\text{rad/s}$$
Comment: Thank you i know its a poor question! Thank you that helped me.
Comment: @raviolican You're welcome, I'm glad that I could help. I'm very interested in electronics so, nice question :)


query hangs oracle 10g

Question: I have this strange issue with our software.
Is is on production for 5 years and we had no such problems...
Problem:
We have a spring job (scheduler) which makes a query via hibernate, retrieves the objects and modifies them.
Well, this worked for several years but a month ago the query hangs 5-10 times a day (the query is invoked every 10 minutes). And when it hangs, we have to restart the service.
The following code does the query:
@SuppressWarnings("unchecked")
public List<Delivery> findScheduledForDelivery(final String inType, final int max, final String benefitType ) {

    //getHibernateTemplate().clear();

    return getHibernateTemplate().executeFind(new HibernateCallback() {
        public Object doInHibernate(Session session) throws SQLException {
            Criteria criteria = session.createCriteria(Delivery.class);

            criteria.createAlias("reward","r");
            criteria.createAlias("r.customer","c");
            criteria.createAlias("c.inNe","i");
            criteria.createAlias("r.promotion","p");
            criteria.createAlias("benefit","b");

            String sqlCustAlias = StringHelper.generateAlias("c", 2);

            criteria.add(Expression.disjunction()
                .add(Expression.eq("inStatus", INStatus.InterfaceFailure))
                .add(Expression.eq("inStatus",INStatus.Initial)));

            criteria.add(Expression.le("deliverAt", new Date()));

            String dateString = "2000/01/01";
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            Date startDate = new Date();
            try {
                startDate = dateFormat.parse(dateString);
                criteria.add(Expression.ge("deliverAt", startDate));
            }
            catch(ParseException e) {
                e.printStackTrace();
            }

            String sqlEqual = "decode(delivered,null,0,1) = 0";
            criteria.add(Expression.sql(sqlEqual));

            sqlEqual = "decode(" + sqlCustAlias + ".deleteDate,null,1,0) = 1";
            criteria.add(Expression.sql(sqlEqual));

            if(inType  != null ) {
                for(INType i : INType.values())
                    if(i.toString().equals(inType)) {
                        criteria.add(Expression.eq("i.inType", i));
                        break;
                    }
            }

            criteria.add(Expression.eq("p.active", true));

            if(benefitType != null) {
                if(benefitType.equals("FREECREDIT"))
                    criteria.add(Expression.disjunction()
                            .add(Expression.eq("b.type", BenefitType.FREE_CREDIT))
                            .add(Expression.eq("b.type", BenefitType.FREE_CREDIT_FTAM)));
                else if(benefitType.equals("NONFREECREDIT")) {
                    criteria.add(Expression.conjunction()
                            .add(Expression.ne("b.type", BenefitType.FREE_CREDIT))
                            .add(Expression.ne("b.type", BenefitType.OTHER))
                            .add(Expression.ne("b.type", BenefitType.VOUCHER)));
                    criteria.add(Expression.isNull("b.md3Profile"));
                }
                if(max != 0)
                    criteria.setMaxResults(max);
            }

            criteria.addOrder( Order.desc("p.priority") );
            criteria.addOrder( Order.asc("deliverAt") );

            return criteria.list(); <===== hangs here
        }
    });
}

Data source is defined as this (I know that this is not supposed to be on production but this is the only way it works - I tried to use oracle connection pool but then the query hangs more often..):
<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
    <beans>
      <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="connectionProperties">
         <props>
          <prop key="tcp.nodelay">yes</prop>
          <prop key="delayRowPrefetch">20</prop>
          <prop key="defaultBatchSize">5</prop>
         </props>
        </property>
      </bean>
    </beans>

Software used:

spring 1.2.7
hibernate 3.0.5
oracle 10.2.0.1 (RAC)
oracle jdbc 10.1.0.2
Red Hat 3 EL
Java 1.5_06

What I've tried so far:

use oracle connection pool as data
source -> failed with hanging
connections
used oracle jdbc 10.2.0.5 -> I thought I've solved it ... and after a few hours it hanged again :(

There are no database locks on oracle as far I can see...
What could be the problem?
UPDATE:
in oracle EM:
ADDM findings:
SQL statements consuming significant database time were found.
The query consumes significant database time. Impact 81%.
User I/O waits 97%.

Individual SQL statements responsible
for significant user I/O wait were
found.
Individual database segments
responsible for significant user I/O
wait were found.
The throughput of the I/O subsystem
was significantly lower than
expected.

UPDATE: (15.03.2011)
For now the service works for almost 48 hours without hanging.
I'm skeptical that this will solve the problem but I did some changes to the code:
Removed the decode(delivered,null,0,1) = 0 and decode(" + sqlCustAlias + ".deleteDate,null,1,0) = 1 functions in query and replaced them with is null statements.
The delivered field is indexed but indexing can't be used in decode functions.
Do you think that this is just coincidence?
UPDATE: (16.03.2011)
alert.log now shows many entries like this:
ORA-01555 caused by SQL statement below (SQL ID: affkpm4j7azc4, Query Duration=232624 sec, SCN: 0x0003.dca70559):
Tue Mar 15 17:43:06 2011
select * from ( select this_.id as id5_, this_.deliverAt as deliverAt68_5_, this_.delivered as delivered68_5_, this_.inDelivery as inDelivery68_5_, this_.lastDeliveryTry as lastDeli5_68_5_, this_.tries as tries68_5_, this_.sentAt as sentAt68_5_, this_.sent as sent68_5_, this_.retry as retry68_5_, this_.inStatus as inStatus68_5_, this_.errorMessage as errorMe11_68_5_, this_.inCvsDelivery as inCvsDe12_68_5_, this_.cvsDelivered as cvsDeli13_68_5_, this_.cvsLastDeliveryTry as cvsLast14_68_5_, this_.cvsTries as cvsTries68_5_, this_.collectedPoints as collect16_68_5_, this_.smsMessage as smsMessage68_5_, this_.inOldStatus as inOldSt18_68_5_, this_.replacedDate as replace19_68_5_, this_.oldMsisdn as oldMsisdn68_5_, this_.deletedDate as deleted21_68_5_, this_.addManualDate as addManu22_68_5_, this_.stornoPromiseDate as stornoP23_68_5_, this_.stornoINDate as stornoI24_68_5_, this_.activationCode as activat25_68_5_, this_.activationExpirationDate as activat26_68_5_, this_.rewardId as rewardId68_5_, this_.benefitId as b

It seems to be from sessions 3 days before.. 232624seconds!
Comment: +1 because you're obviously working on the weekend to solve a production issue. There's no overtime in our profession, but at least there's a couple rep :-)
Comment: My experience has been that if something was working, but now it isn't, it's only because something changed. This code hasn't changed, which means your data probably has. Now, I know about as much about hibernate as that rock over there, so I can't analyze the code to find the problem very well, but I would look at what might have changed with the data. Of course, you've been over that already I'm sure... but *shrug* just worth mentioning.
Comment: You say "the query" is executed every 10 minutes, but the method shown is capable of creating and executing a number of different queries.  Is it called every 10 minutes with the same parameters?  If so, what are they?  If it is called with different parameters, is there any relationship between the parameters passed and whether the query hangs?
Comment: @alesko - Did you get a resolution to this? A java app slowing down, then stopping is often indicative of it running out of memory. Do you have access to the heap usage or garbage collection stats?
Comment: @Alohci Memory is ok. gc.log shows only 200MB used. -Xmx is set to 2048M
Comment: @Dave Costa The parameter benefitType is either FREECREDIT or NONFREECREDIT. I can say for sure that the parameter will never be null. Hanging occures for both benefitsTypes. But also I noticed sometimes that only FREECREDIT hangs and and the other works but after a few hours also the query with the other benefitType hangs.
Comment: Out of curiousity, did you ever solve this? We recently had a hibernate query do basically the same thing, and I found this on Google. Then I saw the first comment and though 'wow that sounds like something I'd say!'... and, well, yeah...
Comment: We actually never found out. As far as I remember we restarted the cluster and since then it thankfully works...
Comment: thank you very much. Weekends are reserved for EMCYs :-)
Comment: Do you mean that you are restarting the Oracle service every time this query hangs?  Is it causing other sessions to hang?
Comment: When the query runs successfully how long does it take?
Comment: @Dave Costa No, just our java application/process. We have 8 java applications which are connected to oracle. And only this one is causing problems so we have to restart it...
Comment: @Alohci mostly about 200ms. When problems begin then the query takes from 10s to even 1 minute and then the hanging begins.
Answer: First thing, when this query hangs, check V$SESSION_WAIT to see what the session is waiting on.
Second observation:  The code you've shown above appears to ignore the max parameter unless the benefitType parameter is non-null.  Is this intentional?  Is it possible that the query is "hanging" only when the benefitType parameter is null?
Sorry, I assumed you had some way of identifying the correct session within Oracle.  Try a query like this:
select v2.sid,
       v2.module,
       substr(v1.sql_text,1,180) sql_text,
       v1.rows_processed,
       v2.event,
       v2.seq#
from v$sqlarea v1, v$session v2
where v1.users_executing > 0
  and v2.sql_address (+) = v1.address;

That will show all the SQL currently being executed, and if possible the related session ID and what event it is waiting on.  You should be able to use the SQL text to identify the session you are interested in.
Comment: "SQL*Net message from/to client" usually means the database session is idle.
Comment: I will check it as soon as it happens again. This shouldn't take long.
Comment: And to be clear, check a few times and see if the wait event changes or the sequence number changes.  Even if it's waiting on the same event but the sequence number changes, that means it's doing work, just very slowly.
Comment: The question is how to find out which session is the one which is hanging? There are 16+ sessions with event "SQL*Net message from/to client".
Comment: sorry can't find anything suspicious in session_wait. Maybe the client couldn't obtain a connection to oracle so we can't see it.

query hangs oracle 10g


EF 5 Inheritance Query Issue

Question: I'm currently experiencing an issue with Entity Framework 5 not returning a record that exists when that entity is derived from an entity that has the property I'm querying against.
These are my entities:
public class Person
{
    [Key]
    public int Id { get; set; }

    public string Email { get; set; }
}

public class User : Person
{
    public  DateTime LastLoginDate { get; set; }
}

My Data Context:
public class DataContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Person> Persons { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().Map(m => { m.ToTable("User"); });

        modelBuilder.Entity<Person>()
                    .Property(x => x.Id)
                    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}

Repository:
public class UserRepository
{
    private readonly DataContext _dataContext;

    public UserRepository(DataContext dataContext)
    {
        _dataContext = dataContext;
    }

    public User GetByEmailAddress(string emailAddress)
    {
        if (string.IsNullOrEmpty(emailAddress))
            throw new ArgumentException("The emailAddress parameter cannot be null or empty.", "emailAddress");

        //This query works
        var working = _dataContext.Persons
            .FirstOrDefault(x => x.Email.Equals(emailAddress, StringComparison.CurrentCultureIgnoreCase));

        //Where as this returns null
        var query = _dataContext.Users
                .FirstOrDefault(x => x.Email.Equals(emailAddress, StringComparison.CurrentCultureIgnoreCase));

        return query;
    }
}

If I attempt to query for a Person by email address I get the record I'm looking for; however, if I query for a User by email address I get a null result.
Any suggestions would be greatly appreciated.
Answer: How was the person you are looking for added?  Were they added to the Persons collection or the Users collection when saved?  Were they of type User or Person?  What are the contents of the two tables (User and Person in your database).
I have duplicated the code above, but when I added the test user I added like:
_dataContext.Users.Add(new User { Email = emailAddress, LastLoginDate = DateTime.Now });
_dataContext.SaveChanges();

And both queries work fine (they return that user).
And even if I add them as a User type but to the Person collection, still both queries come back.  The only time it doesn't work is if I add a Person type to the Person collection, then I get the results you outline above.
I would recommend marking the Person class "abstract" so that future developers are not tempted to create instances of that type.

EF 5 Inheritance Query Issue


Xbox Music RESTful API on Azure access problems

Question: The simple goal here is to access the Xbox Music RESTful API on Azure and I stumble on the first part of it which is getting the Access Token. By following this procedure: http://msdn.microsoft.com/en-us/library/dn546686.aspx it's simply not allowing me to get a token.
Thus far I have:

I have a datamarket registration
I registered an application, got a client_id and client_secret
Subscribed to the Xbox Music RESTful API

Then I simply try to get a token either through a POST using XMLHttpRequest or Advanced Rest Client for Chrome and thus far all I receive is this Json response:
<code>{
    "error":"invalid_client",
    "error_description":"ACS50012: Authentication failed.\r\nTrace ID: d2469189-d620-4725-98c6-544e3899d711\r\nCorrelation ID: 3726a6c7-de19-4873-a90c-b51c7ca447a7\r\nTimestamp: 2014-05-08 14:18:31Z"
}
</code>
I did some research for this error here: http://msdn.microsoft.com/en-us/library/gg429787.aspx but can't seem to pull an explanation for this.
The data explorer is also broken as I receive this:
<code>The request resulted in a backend time out or backend error. The team is investigating the issue. We are sorry for the inconvenience. (502)
</code>
In the end I assume something is bogus with my account but can't figure it out. Any help with this would be greatly appreciated.
Comment: Got it resolved. Recreating the application and getting a new client_secret fixed it.
Answer: See comment, recreate a new application and copy client secret properly.


jquery adding stripes to ul

Question: Hi I'm trying to make a function that will add a striped effect to an unordered list, I've got the following so far but cant work out how the selector should work.
    (function($) {
    $.fn.stripe = function(){
        this.$("li:even").css("background-color","#f00");
    };
    })(jQuery);

    $("list_id").stripe();

Answer: Lots of complicated answers using jQuery here. All you need is a small bit of CSS:
ul > li:nth-of-type(odd) {
    background-color: #f9f9f9 ;
}

Comment: Keep in mind this question was posted in 2009, and predates CSS3 selectors like `:nth-of-type` by two years.
Comment: Fair point, I just noticed that there were pretty recent answers too. Nevertheless, hopefully if somebody lands here from Google, as I just did, they'll at least have a good answer now.
Answer: $(this).children('li:even').css("background-color","#f00");

Comment: Also: $("list_id").stripe(); should be: $("#list_id").stripe();
Answer: As reko has said, the best way to implement this is using the pseudo odd and even. Try implementing it the same as the following:
JQuery
$(document).ready(function() {
    $("ul.formattedList li:odd").addClass("oddItem");
    $("ul.formattedList li:even").addClass("evenItem");
}

CSS
.formattedList .oddItem {
    background-color: Black;
    color: White;
}

.formattedList .evenItem {
    background-color: White;
    color: Black;
}

HTML

Item 1

Item 2

Item 3

Item 4

Item 5

Answer: You have the call the call the children of the unorderedlist
HTML

test

test

test

test

JQuery
(function($) {
$.fn.stripe = function(){
  $(this).children("li:even").css("background-color","#ccc");
};

$('ul').stripe();
})(jQuery);

Answer: I think the best way is to use nth-child CSS3 property
Something like:
.black-one {
 background: black;
}

Demo:
http://codepen.io/anon/pen/doWyKg

jquery adding stripes to ul


Open python program on system startup

Question: I need my program to launch on system startup or user login. I have played around a little with the scheduler, but I'm pretty new to that and I couldn't get it to work. Basically I need to save something in the code to the startup registry.
It might also be worth to note that I will be turning this into an exe with pyinstaller, but that shouldn't make too much of a difference I believe.
Comment: On what OS are you?
Comment: I'm on windows 10
Comment: Take a look [here](http://www.howtogeek.com/228467/how-to-make-a-program-run-at-startup-on-any-computer/)
Comment: @StamKaly nice answer
Comment: Thanks for the suggestion, but this requires me to manually put it into the startup registry. I need the program to automatically do this so that my friends who also installs it gets this as well. If it is possible to make the program do what the link suggest automatically I can look into that
Answer: you can use the old-good startup folder of windows, adding a bat file running your script or its exe version obtained  with pyinstaller.
Charlie
Answer: Windows 8 / 10 startup folder location
The Current Users Startup folder in Windows 8 and 10 is located at:
<code>C:\Users\Username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
</code>
These programs start up for the current logged in user only. To directly access this folder, open Run, type shell:startup and hit Enter.
Screenshot
Comment: I dont think it does for windows 8+
Comment: He is using windows 10
Comment: Yes, I need the program to automatically get put into that folder when you launch it :)
Comment: make a batch file and include this line "move c:\YourScript.py C:\Users\Username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"

Open python program on system startup


Generic way to create different pojo objects and persist in db

Question: I'm creating a project that uses spring data jpa for persistance. I'm receiving a json string as input that I transform to the corresponding pojo to save into the db. Currently I'm using if else to determine the pojo and the corresponding repository. Is there a way to handle this generically instead of using if else.
Please help. Thanks in advance.
here is my code:
                    if(designation.equals("Teacher"))
                    {
                        Teacher teacher= mapper.readValue(jsonString,Teacher.class);
                        teacherRepository.save(teacher);
                    }
                    else  if(designation.equals("Student"))
                    {
                        Student student= mapper.readValue(jsonString,Student.class);
                        studentRepository.save(student);
                    }
                    else  if(designation.equals("Staff"))
                    {
                        Staff staff= mapper.readValue(jsonString,Staff.class);
                        staffRepository.save(staff);
                    }

Answer: If you have resources which use different repositories maybe you should have different REST endpoints (or whatever you are using) and service classes right.
One simple way to get rid of your if-else blocks would be to use a Map
Map<String, Consumer<?>> map = new HashMap<>();
 map.put("Teacher", (e) -> teacherRepository.save(mapper.readValue(e,Teacher.class))
});

and you can use it like,
map.get("Teacher").accept(jsonString);


Not able to close a UiApp after it is invoked as a published service

Question: I have a published service on my script, the link to which I pass out to an email. Once the active account invokes the service a UiApp opens up for further processing. I do that using doGet(). Once the processing on the UiApp is complete I have a Submit button, linked to a server click handler, which is supposed to process the changes made through the UiApp forms. While I am able to change the values on the spreadsheet that I wish to change using this UiApp, I still have two issues which I encounter on clicking the Submit button:

The Ui App doesn't close on pressing the submit button
I am not able to call a browser msgBox to give a process complete verification message.

I have read a lot that on closing and returning the app the UiApp is supposed to get closed, but it isn't happening and I am assuming this is because that happens only if there is no serverClickHandler involved. I could be wrong.
Can someone help me with resolving Issue 1 and getting around Issue 2? A relevant version of my doGet and clickHandler functions are attached below.
<code>function doGet(e) //On invoking service in the mail.
{
  //Adding all other elements of the UiApp here
  /* …
     …  All other elements of the UiApp
     …
*/
  //Adding Submit button to the UiApp
  var button = app.createButton('Submit');
  var handler = app.createServerClickHandler('click').addCallbackElement(panel);
  button.addClickHandler(handler);
  panel.add(button);
  app.add(panel);
  return app;
}

 function click(eventInfo) {
   var app = UiApp.getActiveApplication();
 //Processing the actions that have to be performed on hitting the submit button
/* …
   … Processing the actions that have to be performed on hitting the submit button
   …
*/
   app.close();
   return app;
 }
</code>
Answer: Browser.messageBox are not available in published UiApps, you should use a label that is invisible until you make it visible at the end of the process.
The other issue is not an issue neither : The UiApp have no way to close your browser window, you could simply make the main panel of your UI invisible.
Combining both modifications will allow you to hide your form and to replace it by a 'completed, thanks for submitting' message.