text:
Q: Access Violation on FreeLibrary after calling DLL with Delphi XE7 FireMonkey FMX Form, possible GDI+ initialization/finalization issue I'm starting a FireMonkey application in Delphi XE7 that must call some DLL's which have themselves forms (also created in Delphi XE7).
I load the DLL and call my exported procedure (no parameters), and the form loads and works as expected (ShowModal). I close that form and the main application resumes and works perfectly, until the moment the user terminates the application and the FreeLibrary is called.
An Access Violation is then raised with the following message:

"First chance exception at $045B30E6. Exception class $C0000005 with message 'access violation at 0x045b30e6: read of address 0x00000008'. Process bpltesteVCL.exe (6708)"

I ran some tests with a basic test application and found out it only happens if the DLL has a FireMonkey TForm - VCL runs fine.
These are the combinations I tried in my testings with virtually the same code:
VCL App/VCL Dll = OK; VCL App/FMX Dll = Fail; FMX App/FMX Dll = Fail; FMX App/VCL Dll = OK.
These were only for testing purposes, since my goal is a full FMX application.
The code I used to load the library:
procedure TForm2.Button1Click(Sender: TObject);
type
  TFExecute = procedure; StdCall;
var
  Execute: TFExecute;
  Ext: HMODULE;
begin
  Ext := LoadLibrary(PChar(ExtractFilePath(ParamStr(0)) + 'dlltest.dll'));

  if Ext <> 0 then
  begin
    try
      @Execute := GetProcAddress(Ext, 'Execute');
      if Assigned(Execute) then
         Execute
      else
        ShowMessage('Function not found !');
    finally
      FreeLibrary(Ext);
    end;
  end
  else
    ShowMessage('DLL not found');
end;

And the Dll code for 'Execute':
procedure Execute; StdCall;
begin
     fMain := TfMain.Create(nil);
     fMain.ShowModal;
     fMain.Free;
end;

Exports
       Execute;

The DLL form has no component inside. Only the plain form. Also, no units were added to it that were not needed to load the form itself.
I have been searching and found some similar cases, and the problem seems to be the GDI+ initialization and finalization, but unfortunately, the answers there don't work for me:
FMX form in a DLL (firemonkey/delphi)
This couldn't help me, because in this method the dll is loaded in the initialization section of a unit, making it in fact similar to static loading, which I cannot use. Still I tried it for the sake of testing, and it crashed with an Access Violation in the same maner.
FireMonkey Form in a dll, loaded from a VCL Application
This was in fact the closest I got to a solution to my problem, but unfortunately, the solution given here seems to work for XE2, but not for later versions of Delphi, because one of the most important methods used here is GetMeasureBitmap, which only exists (by that name at least) in XE2.
I did search for an equivalent in XE7 so I could find the solution before posting the question, but couln't get anything of the sort.
Is there any way to load FMX forms in a dll in Delphi XE7?
EDIT:
Continuing the research for a solution, I tried the following:

*

*All the mentioned combinations with BPL instead of DLL

*Usage of ShareMem / FastShareMem

No change on the mentioned behaviour!


text:
Q: access select query between 2 date fields as criteria Trying to figure out how to select records in Access where there are 3 fields: Manuf_Date, Date_Opened  and Record ID. I want to find records where  Date_Opened  is 2 years greater than Manuf_Month_Year.
I entered this function as criteria in access under the Manuf_Month_Year field
<=DateAdd("yyyy",-2,[(dbo_TW_Parent_Child_All_Records.Date_Opened])

<=DateAdd("yyyy",-2,[(dbo_TW_Parent_Child_All_Records.Date_Opened])

A: Try with some syntax clean-up:
<=DateAdd("yyyy",-2,[dbo_TW_Parent_Child_All_Records].[Date_Opened])

redpajama_set_name: RedPajamaStackExchange


text:
Q: lessc command cannot find import inside another import I have an issue with running lessc command when there is hierarchical imports. My folder structure is like this:
(root)/
|--- website
     |--- styles
          |--- master.less
|--- library
          |--- testDir
               |--- child.less
          |--- test.less

The short version of master.less:
@import url('../../library/test.less');

The short version of test.less:
@import url('/testDir/child.less');

When I run lessc website/styles/master.less website/styles/master.css, I am given FileError: '/testDir/child.less' wasn't found. Tried - /testDir/child.less, etc.
Note: It is not viable for me to use --include-path=./library/testDir option, because I have many instances of these hierarchical imports in my less files.
Any other option that I am missing, or a workaround?


text:
Q: "ng generate module/component" doesn't work as expected I get the following error with "ng g c course":

Error: You provided an invalid object where a stream was expected. You can
     provide an Observable, Promise, Array, or Iterable.
     You provided an invalid object where a stream was expected. You can provide an
     Observable, Promise,
     Array, or Iterable.

How can I solve it?


text:
Q: How is springboot able to run on OpenJDK considering that OpenJDK only implements JavaSE I am planning to switch to OpenJDK to write my spring boot project but for a while, I have stalled because I read that OpenJDK only implements JavaSE and not EE. My view Changed after I read this post .
My question is how would spring boot work with OpenJDK when OpenJDK only implements JavaSE and not Java EE and Springboot is a web framework?


text:
Q: Authenticate google certificate by c# code? When I browse google.com I can ensure that it is google.com by clicking in the address bar :

But let's assume google is exposing  Service1, and I - using c# consume this service (wcf) -
How can my service be assure that he is connecting to google.com ?
I know there is a certificate involved here.
I already  know how to read local certificates from my store. but this certificate is not in my store.
Question :
So How do ( and in what stage) can I read google's certificate data and to assure i'm connecting to them?
Thank you.

A: ServicePointManager.ServerCertificateValidationCallback =
    (sender, certificate, chain, policyError) => {
        var subject = certificate.Subject;
        return subject == "CN=www.google.com, O=Google Inc, L=Mountain View, S=California, C=US";
    };


text:
Q: SQL Server 2008 R2: Update with condition Table: Dots
CREATE TABLE dots
(
    cola VARCHAR(50),
    NAME VARCHAR(10),
);

Insertion:
INSERT INTO dots VALUES('59.96.12.563','');
INSERT INTO dots VALUES('594.966.127.5683','');
INSERT INTO dots VALUES('5998.8896.4412.22563','');
INSERT INTO dots VALUES('791','');
INSERT INTO dots VALUES('891','');
INSERT INTO dots VALUES('691','');

Note: Now I want to update the NAME column in the table Dots to the value IP for those records who contains the 3 dots on it in column Cola. For example as shown below in the expected result.
Result:
Cola                    NAME
--------------------------------
59.96.12.563            IP
594.966.127.5683        IP
5998.8896.4412.22563    IP
791
891
691

A: Try the below code snippet -
UPDATE dots SET Name = 'IP'
WHERE (LEN(cola) - LEN(REPLACE(cola, '.', ''))) / LEN('.')  = 3

A: Try this:
UPDATE dots
  SET   NAME = 'IP'
  WHERE cola LIKE '%.%.%.%'

A: The correct way of checking would be using LIKE, this will check for exactly 3 dots:
WHERE
  cola like '%.%.%.%'
  and cola not like '%.%.%.%.%'

If you fancy the REPLACE method. This is the correct syntax:
 WHERE
   LEN(REPLACE(cola, '.', '.X')) - LEN(cola) = 3

The reason is that
LEN(cola) - LEN(REPLACE(cola, '.', '')) = 3

Will fail in case the text ends with space period.
Example:
SELECT LEN(REPLACE('.  .', '.', ''))

Returns 0 indication there are 4 dots in the text.
This may not be an issue since the spaces are probably not existing in your IP addresses.


text:
Q: unix nohup sqlplus not working Trying to run all of the sql scripts in one NOHUP command. Below is my code. But, it is not running in nohup mode based on the below.  There are no errors either.  How do I run all of the below in one NOHUP command??
nohup sqlplus -S /NOLOG << %EOF% > engine_error.log
WHENEVER SQLERROR EXIT 1;
@$Level2/passFile server05
@engine_check.sql $stroke1 $bore1
@engine_start.sql
%EOF% &

A: Try putting this in a script and then nohup the script. The nohup is probably getting confused because of the command.
#!/usr/bin/env
#query.sh
sqlplus -S /NOLOG << %EOF% > engine_error.log
WHENEVER SQLERROR EXIT 1;
@$Level2/passFile server05
@engine_check.sql $stroke1 $bore1
@engine_start.sql
EOF

Then in your shell try doing this
nohup query.sh &

A: When you have a script that must start some background jobs, make a script that starts functions with & and nohup your script.
When your script startit.sh looks like
function f1 {
   echo "f1 start"
   sleep 2
   echo "f1 end"
}

function f2 {
   echo "f2 start"
   sleep 1
   echo "f2 end"
}

function f3 {
   echo "f3 start"
   sleep 1
   cat <<END
f3 start here
more f3
f3 end here
END
   echo "f3 end"
}

f1 &
f2
f3 &

call nohup startit.sh.

A: Problem is "&" (or any sign) in same line with EndOfMessage-String.
"EOF &" is not equal to "EOF" -> "inline script" is still waiting for "EOF".
A line with only the defined string after "<<" can finalize the "inline script":


text:
Q: Avoid Blurry texts when having 150% of normal DPI (windows 8.1) (yes, it is a common problem but the found solutions are not acceptable for me)
I am using one screen 1920 x 1080 and 125% of normal DPI is even little for me and prefer to have 150% on windows 8.1.
When DPI = 150% texts in opera and chrome are blurry but not in Firefox

When DPI = 125% (default) text is cristal clear just they are small

I have tried solutions that allegedly solved my problem:

*

*a) turning on Let me choose one scaling level for all my displays - no effect on text sharpness (see the first image)

*b) Program's context menu > Compatibility tab > check Disable display scaling on High DPI settings - the program ignores 150% scaling and shows like on 125% scaling. This means Text size is small:

Note that even device manager (native Windows program) is blurry on 150% DPI.

So, I am searching for a method to get clear and big size text in all programs (e.g. opera, chrome) on windows 8.1

A: Chrome has been lacking support for DirectWrite to render fonts on Windows. The issue you are describing is what happens not only on high DPI settings but also on normal (100%) settings.
There is a long and old thread on the Chromium issues website: https://code.google.com/p/chromium/issues/detail?id=25541
The developers said they already enable it on Chrome Canary builds but there is no timetable on when the regular version of Chrome will support it.
You can enable DirectWrite launching the latest Chrome Canary build with the following parameters:
# To enable DirectWrite:
--enable-direct-write --no-sandbox

# To enable DirectWrite and sub-pixel font scaling:
--enable-direct-write --no-sandbox --enable-experimental-web-platform-features

The above parameters were listed by one of the developers in the same thread. The post link is https://code.google.com/p/chromium/issues/detail?id=25541#c61
Be warned the by disabling the sandbox feature you are compromising one of Chrome's security features.
Opera, which uses Webkit, has the same problem as Chrome.

A: I am using also 1920 x 1080. In Chrome Beta Version 37 (I do not know if it is yet available in stable Chrome) you can go into flags (chrome://flags) and enable distance field text. Now the text is much clearer when I zoom (but not all sites).

A: I have Win 7 64bit and I solved the problem by checking the compatibility with Win XP (SP 2).
So right click on Chrome->Compatibility->Check: Run this program in compatibility with->Select: Windows XP (Service Pack 2).
Before, I had it checked and selected for Win 7, or not checked at all.

A: Windows Registry editing fixed the font thickness issue for me completely, we can tune the font thickness/darkness by calibrating  FONTSMOOTHINGGAMMA  value to between 150 and 190 hexadecimal( 336 to 400 decimal )
-     START  ->  RUN  ->  REGEDIT
-     search for  FONTSMOOTHINGGAMMA   by  keying  " Ctrl F "  ( will automatically take us to  CurrentUser\ControlPanel\Desktop  path)
-     double-click mouse on  FONTSMOOTHINGGAMMA   enter anything between 150 and 190 hexadecimal.(the Lower the value, the thicker the fonts.)
-     close the REGEDIT tool
-     LOGOFF and then LOGON

Now all the fonts are very thick & very dark in Chrome Browser.
But we must make sure that ClearType smoothing is enabled in Windows( controlPanel  ->  personalization  ->  appearance  ->   Effects   ->      ClearType smooth check (ticked box) )
                     OR  alternately in RegEdit ...

         FONTSMOOTHING=2
         FONTSMOOTHINGTYPE=2
         FONTSMOOTHINGORIENTATION=1  for LCD-screen,  0 for CRT-screen


text:
Q: Combine Two hash in Puppet i have 2 hash, and need to "combine" them to make a new ssh_authorized_key resource:
First hash contains all ssh keys
$ssh_keys = {
 'user1@192.168.14.47' => {
    type => 'ssh-rsa',
    key  => 'Key1',
 },
 'user2@192.168.18.10' => {
    type => 'ssh-rsa',
    key  => 'Key2',
  }
}

second hash contains the "deploys" of the keys and users
$deploys = {
    'user1@192.168.14.47' => { user => ["user3","user4"]},
    'user2@192.168.18.10' => { user => ["user3"]}
}

I want to "merge" this hashes so i can use create_resources
$newhash ={
    'user1@192.168.14.47' => {
    type => 'ssh-rsa',
    key  => 'Key1',
    user => ["user3","user4"]
 },
 'user2@192.168.18.10' => {
    type => 'ssh-rsa',
    key  => 'Key2',
    user => ["user3"]
  }
}

create_resources('ssh_authorized_key',$newhash)

how can i create the newhash? puppet do not have iteration which make this way to difficult
The data of the hashes eventually comes from foreman smart classes/variables
Edit:
This is on foreman 1.11.1 with puppet 3.8.7 in ubuntu 14.04

A: I'm not aware of a function for merging hashes built into the puppet language, but you can always use a custom parser function instead -- which would allow you to combine two or more hashes however you like, using pure ruby -- and it's really not as scary as it sounds.
Fortunately, one of these already exists in the puppetlabs/stdlib module. Unfortunately, the function you need for this particular case is not documented in the README. Called deep_merge, it will merge nested hashes and you can find documentation in the source of the function itself.
I don't use foreman, so it's unclear to me if you'll need to install the puppetlabs/stdlib module, or if it's accessible with the default install. It's a common dependency for a large number of forge modules, so you might have it already. If not, the foreman docs explain how to install and add a puppet module to a node (I presume you'd just replace saz/ntp with puppetlabs/stdlib where referenced).
You can then deep_merge to your heart's content, as in ...
$ssh_keys = {
 'user1@192.168.14.47' => {
    type => 'ssh-rsa',
    key  => 'Key1',
 },
 'user2@192.168.18.10' => {
    type => 'ssh-rsa',
    key  => 'Key2',
  }
}

$deploys = {
    'user1@192.168.14.47' => { user => ["user3","user4"]},
    'user2@192.168.18.10' => { user => ["user3"]}
}

$merged = deep_merge($ssh_keys, $deploys)

notify { $merged: }

... which results in ...
Notice: { \
  "user1@192.168.14.47"=>{"type"=>"ssh-rsa","key"=>"Key1", "user"=>["user3", "user4"]}, \
  "user2@192.168.18.10"=>{"type"=>"ssh-rsa", "key"=>"Key2","user"=>["user3"]}}


text:
Q: How to detect if current window is behind another application, using Javascript Same like facebook on web browser. If you open another application like going to computer dashboard or any app, the video on Facebook will pause, when you switch back to browser the video will resume.
Page Visibility API, onFocus, hasFocus and onBlur are working only if the user switches between the browser tabs.
I want to listen when the user switches away from browser to another application while browser still open on background. Be able to tell full visibility of current page.
It should be possible, same feature is working on facebook Web from the browser.


text:
Q: url redirection from http to https in IBM Web server I have installed SSL certificates in my WAS 7.0 and pointed to IBM Http Server under httd.conf file. I have implemented the below rewrite mechanism also.But still unable to redirect from http request to https for specific context root applications.
Please suggest me.
implemented below lines under httpd.conf file.
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule ibm_ssl_module modules/mod_ibm_ssl.so
<IfModule mod_ibm_ssl.c>
Listen 443
<VirtualHost *:443>
SSLEnable
SSLProtocolDisable SSLv2
ErrorLog logs/error_log
CustomLog logs/access_log common
RewriteEngine On
RewriteOptions Inherit
</VirtualHost>
</IfModule>
KeyFile "/IBM/HTTPServer/testSSL/testkey.kdb"
SSLStashFile "/IBM/HTTPServer/testSSL/testkey.sth"
RewriteEngine on
RewriteRule ^/testPOC/(.*)$ https://localhost/testPOC/$1

A: Config look OK. Perhaps you have an explicit *:80 virtualhost defined somewhere, in which case you need to put the mod_rewrite directives there instead.

A: Like Eric stated the most likely answer is a VH for *:80 needing the RewriteRule.  Another outside possibility would be the use of localhost for the host name.  Make sure you haven't done something that causes the loopback to not be handled properly.  You can always try the real host name or IP to make sure using localhost does not cause problems (hosts file,  A load balancer using the loopback, etc).
Use RewriteLog to verify rewrite was done.  Also make sure plugin-cfg.xml is set up to recognize port 443.  It might have an explicit host name:443 for a VH as opposed to *:443.   Using localhost would not match in that case.  If you have a Load Balancer in front of IHS,  it might be doing SSL offloading and SSL never makes it to IHS for the problem context roots.


text:
Q: Watchkit and Firebase I can return snapshot.value for the first time to Apple Watch...
How to return snapshot.value for the second time (e.g. someone else updated the database with new data) firebase1 observeEventType:FEventTypeChildAdded being triggered?
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply {

    [firebase1 observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot){
        reply(snapshot.value);
    }]
}


text:
Q: C# Winform - OracleDataAdapter not persisting the records immediately I am making changes in an old C# WinForm application.
In the code below, when the DoWork() function is invoked. It calls the two functions PerformOperation1 and PerformOperation2. Both functions have a very similar body. The only difference is that they both update different fields of the same database table.
Finally, when they both have performed their job, we fetch the records using an OracleDataAdapter.
The count of the rows returned is 0 in the code. However, if I execute the query on the database straight away, it returns some rows. This means somehow the records updated by the PerformOperation2 are not pushed to the database at the time when we call the Fill on the DataAapter.
public void DoWork()
{
    PerformOperation1();
    PerformOperation2();

    var sql = "select * from results where result_id = 1 and is_valid = 'Y'";
    var table =  new DataTable();
    var data = new OracleDataAdapter(new OracleCommand(sql, base.Connection));
    data.Fill(table);
    var count = data.Rows.Count; //It returns 0 But when execute the same query on database, it returns rows.
}

    public void PerformOperation1()
    {
        string sql = "select seq_1, product, count_1, count_2 from results where result_id = 1";
        string updateSQL = "update results set count_1 = :count_1, count_2 = :count_2 WHERE seq_1 = :seq_1";

        var selectCmd = new OracleCommand(sql, base.Connection);
        selectCmd.CommandType = CommandType.Text;
        var adapter = new OracleDataAdapter(lCmd);

        adapter.UpdateCommand = new OracleCommand(updateSQL, base.Connection);
        adapter.UpdateCommand.CommandType = CommandType.Text;

        AddCommandParameter(adapter.UpdateCommand, ":count_1", DbType.Double, 11, "count_1");
        AddCommandParameter(adapter.UpdateCommand, ":count_2", DbType.Double, 11, "count_2");

        var data = new DataSet();
        adapter.Fill(data);

        foreach (var row in data.Tables[0].Rows)
        {
            row["count_1"] = GetCount1(row["seq1"]); //Returns Count1
            row["count_2"] = GetCount2(row["seq1"]); //Returns Count2

            //Forces an immediate garbage collection of all generations
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

        adapter.Update(data);
        data.AcceptChanges();
    }

    public void PerformOperation2()
    {
        string sql = "select seq_1, product, is_valid from results where result_id = 1";
        string updateSQL = "update results set is_valid = :is_valid WHERE seq_1 = :seq_1";
        //Does exactly the samething like PerformOperation1 function above.
        //100% same code.
        //Only difference is that it updates different column named is_valid (with value 'Y' or 'N')
    }

    public void AddCommandParameter(DbCommand aoCommand, string asParamName, DbType aoDataType, int aiSize, string asColName)
    {
        if (aoCommand is OracleCommand)
        {
            OracleCommand loCommand = (OracleCommand)aoCommand;
            OracleType loOraDataType = ConvertToOracleType(aoDataType);
            loCommand.Parameters.Add(asParamName, loOraDataType, aiSize, asColName);
        }
    }

Any idea why this is happening, please?

A: I figured it out. It was not a coding issue. It was some underlying database view problem.


text:
Q: Is $z^3 cot(z)$ analytic inside the unit circle ($z \in C$)? I'd like to prove that $f(z)=z^3 \cot(z)$ is analytic in $0$. I know that $\cot(z)$ is not analytic in $\pm n \pi$ (and so in $0$), but this doesn't imply $z^3 \cot(z)$ being not analytic in $0$.
Everything I tried resulted in a very complicated combination of trigonometric and hyperbolic functions. I tried to show that $f(z)$ is continuous in $0$, that is differentiable in $0$, that the Cauchy-Reimann equation applies and that the partial derivatives of the real and imaginary part are continuous in $0$.
How to do that in a doable way?
From "Advanced engineering mathematics 10th edition - Kreyszig", "Problem Set 14.2", exercise 19, page 659. The answer is "yes", that is the Cauchy's integral theorem applies inside the unit circle, that is $f(z)$ is analytic there, and so the line integral around the unit circle is $0$.
Thanks,
Luca

A: From the Bernoulli numbers generating function :
$$ \frac{z}{e^z -1} = \sum_{n=0}^\infty \frac{B_n}{n!} \, z^n \text{ valid for } \vert z\vert <2\pi $$
It follows that for $\vert z\vert < \pi$
$$ z\cot z =  \sum_{n=0}^\infty \frac{(-1)^{n} 2^{2n}B_{2n}}{(2n)!}\,z^{2n} $$
Then your function $z\mapsto z^3\cot z$ has a convergent Taylor series inside the open disk $D(0,\pi)$ , thus it's analytic inside the unit circle.


text:
Q: How to build map file for kernel modules I need to load 2 instances of a driver for 2 physical devices of the same kind on my platform. I have renamed all the conflicting function exports and I am able to load both the drivers corresponding to each of those 2 physical devices.
But, I am worried that there might be some sort of a conflict with regard to data structure between them at some point of time. In order for me to make sure that this doesn't happen, I need to see all the data being shared between them. I thought the best way is to generate a MAP file for each of the kernel modules.
Can somebody please tell me how to generate MAP files for kernel modules?
Thanks,
Pradeep.


text:
Q: Symfony schema:update error I have an error which i can't fix cause i can't find the problem.
The error in the console says:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Parse error: syntax error, unexpected 'public' (T_PUBLIC), expecting ',' or ';'

when trying to use:
php bin/console doctrine:schema:update --dump-sql

I'm trying to make an assignment for my study but i can't find the problem.
The command didn't work after adding the next fields in the entity "client_order.php":
/**
 * @ORM\ManyToOne(targetEntity="order_line")
 * @ORM\JoinColumn(name="order_line_id", referencedColumnName="id")
 */
private $order_line;

/**
 * @ORM\ManyToOne(targetEntity="user")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
private $user;

/**
 * @ORM\ManyToOne(targetEntity="Product")
 * @ORM\JoinColumn(name="Product_id", referencedColumnName="id")
 */
private $Product;

After i added the new fields in symfony i used the command:
php bin/console doctrine:generate:entities TuinadviesBundle:client_order

Here is the full document:

namespace TuinadviesBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* client_order
*
* @ORM\Table(name="client_order")
* @ORM\Entity(repositoryClass="TuinadviesBundle\Repository\client_orderRepository")
*/
class client_order
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="date", type="date")
 */
private $date;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="expiration_date", type="date")
 */
private $expirationDate;

/**
 * @ORM\ManyToOne(targetEntity="order_line")
 * @ORM\JoinColumn(name="order_line_id", referencedColumnName="id")
 */
private $order_line;

/**
 * @ORM\ManyToOne(targetEntity="user")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
private $user;

/**
 * @ORM\ManyToOne(targetEntity="Product")
 * @ORM\JoinColumn(name="Product_id", referencedColumnName="id")
 */
private $Product;

/**
 * Get id
 *
 * @return int
 */
public function getId()
{
    return $this->id;
}

/**
 * Set date
 *
 * @param \DateTime $date
 *
 * @return client_order
 */
public function setDate($date)
{
    $this->date = $date;

    return $this;
}

/**
 * Get date
 *
 * @return \DateTime
 */
public function getDate()
{
    return $this->date;
}

/**
 * Set expirationDate
 *
 * @param \DateTime $expirationDate
 *
 * @return client_order
 */
public function setExpirationDate($expirationDate)
{
    $this->expirationDate = $expirationDate;

    return $this;
}

/**
 * Get expirationDate
 *
 * @return \DateTime
 */
public function getExpirationDate()
{
    return $this->expirationDate;
}

/**
 * Set orderLine
 *
 * @param \TuinadviesBundle\Entity\order_line $orderLine
 *
 * @return client_order
 */
public function setOrderLine(\TuinadviesBundle\Entity\order_line $orderLine = null)
{
    $this->order_line = $orderLine;

    return $this;
}

/**
 * Get orderLine
 *
 * @return \TuinadviesBundle\Entity\order_line
 */
public function getOrderLine()
{
    return $this->order_line;
}

/**
 * Set user
 *
 * @param \TuinadviesBundle\Entity\user $user
 *
 * @return client_order
 */
public function setUser(\TuinadviesBundle\Entity\user $user = null)
{
    $this->user = $user;

    return $this;
}

/**
 * Get user
 *
 * @return \TuinadviesBundle\Entity\user
 */
public function getUser()
{
    return $this->user;
}

/**
 * Set product
 *
 * @param \TuinadviesBundle\Entity\Product $product
 *
 * @return client_order
 */
public function setProduct(\TuinadviesBundle\Entity\Product $product = null)
{
    $this->Product = $product;

    return $this;
}

/**
 * Get product
 *
 * @return \TuinadviesBundle\Entity\Product
 */
public function getProduct()
{
    return $this->Product;
}
}

All the classes i added are correct (even the Product wit a capital P (did that by mistake)).
Can anyone please tell me what i did wrong?
Thanks in advance :)

A: Jep it was in user.php i forgot a ";" but i could swear i did not edit that one.. oh well thanks anyway :)
    C:\xampp\htdocs\tuinadvies>php bin/console doctrine:schema:update --dump-sql
    -vvv
    21:50:41 INFO      [php] User Deprecated: The
    "Symfony\Component\Console\Event\ConsoleExceptionEvent" class is deprecated
    since version 3.3 and will be removed in 4.0. Use the ConsoleErrorEvent
    instead.
    [
    "exception" => Symfony\Component\Debug\Exception\ContextErrorException {
    -context: [
      "class" => "Symfony\Component\Console\Event\ConsoleExceptionEvent",
      "file" =>

 "C:\xampp\htdocs\tuinadvies\vendor\composer/../symfony/symfony/src/Symfony/Component\Console\Event\ConsoleExceptionEvent.php"
    ],
    #message: "User Deprecated: The
    "Symfony\Component\Console\Event\ConsoleExceptionEvent" class is deprecated since version 3.3 and will be removed in 4.0. Use the ConsoleErrorEvent instead.",
    #code: 0,
    #file: "C:\xampp\htdocs\tuinadvies\vendor\symfony\symfony\src\Symfony\Component\Console\Event\ConsoleExceptionEvent.php",
    #line: 14,
    #severity: E_USER_DEPRECATED,
    trace: {
      C:\xampp\htdocs\tuinadvies\vendor\symfony\symfony\src\Symfony\Component\Console\Event\ConsoleExceptionEvent.php:14: {
        : ,
        : @trigger_error(sprintf('The "%s" class is deprecated since version 3.3 and will be removed in 4.0. Use the ConsoleErrorEvent instead.', ConsoleExceptionEvent::class), E_USER_DEPRECATED);,
        :
      },
      C:\xampp\htdocs\tuinadvies\vendor\symfony\symfony\src\Symfony\Component\Debug\DebugClassLoader.php:144: {
        : if ($file = $this->classLoader[0]->findFile($class)) {,
        :     require_once $file;,
        : },
        arguments: {
          "C:\xampp\htdocs\tuinadvies\vendor\symfony\symfony\src\Symfony\Component\Console\Event\ConsoleExceptionEvent.php"
        }
      },
      Symfony\Component\Debug\DebugClassLoader->loadClass(): {},
      C:\xampp\htdocs\tuinadvies\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:897: {
        : $x = $e instanceof \Exception ? $e : new FatalThrowableError($e);,
        : $event = new ConsoleExceptionEvent($command, $input, $output, $x, $x->getCode());,
        : $this->dispatcher->dispatch(ConsoleEvents::EXCEPTION, $event);,
        arguments: {
          $class_name: "Symfony\Component\Console\Event\ConsoleExceptionEvent"
        }
      },
      C:\xampp\htdocs\tuinadvies\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:223: {
        : $this->runningCommand = $command;,
        : $exitCode = $this->doRunCommand($command, $input, $output);,
        : $this->runningCommand = null;,
        arguments: {
          $command: Doctrine\Bundle\DoctrineBundle\Command\Proxy\UpdateSchemaDoctrineCommand { …},
          $input: Symfony\Component\Console\Input\ArgvInput {#1 …},
          $output: Symfony\Component\Console\Output\ConsoleOutput {#2 …}
        }
      },
      C:\xampp\htdocs\tuinadvies\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php:81: {
        : ,
        :     return parent::doRun($input, $output);,
        : },
        arguments: {
          $input: Symfony\Component\Console\Input\ArgvInput {#1 …},
          $output: Symfony\Component\Console\Output\ConsoleOutput {#2 …}
        }
      },
      C:\xampp\htdocs\tuinadvies\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:130: {
        :     $e = null;,
        :     $exitCode = $this->doRun($input, $output);,
        : } catch (\Exception $x) {,
        arguments: {
          $input: Symfony\Component\Console\Input\ArgvInput {#1 …},
          $output: Symfony\Component\Console\Output\ConsoleOutput {#2 …}
        }
      },
      C:\xampp\htdocs\tuinadvies\bin\console:28: {
        : $application = new Application($kernel);,
        : $application->run($input);,
        : ,
        arguments: {
          $input: Symfony\Component\Console\Input\ArgvInput {#1 …}
        }
      }
    }
  }
]
[]

  [Symfony\Component\Debug\Exception\FatalThrowableError]
  Parse error: syntax error, unexpected 'public' (T_PUBLIC), expecting ',' or ';'

Exception trace:
 () at C:\xampp\htdocs\tuinadvies\src\TuinadviesBundle\Entity\user.php:108
 Doctrine\Common\Persistence\Mapping\Driver\AnnotationDriver->getAllClassNames() at C:\xampp\htdocs\tuinadvies\vendor\doctrine\common\lib\Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain.php:128
 Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain->getAllClassNames() at C:\xampp\htdocs\tuinadvies\vendor\doctrine\common\lib\Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory.php:114
 Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getAllMetadata() at C:\xampp\htdocs\tuinadvies\vendor\doctrine\orm\lib\Doctrine\ORM\Tools\Console\Command\SchemaTool\AbstractCommand.php:59
 Doctrine\ORM\Tools\Console\Command\SchemaTool\AbstractCommand->execute() at C:\xampp\htdocs\tuinadvies\vendor\doctrine\doctrine-bundle\Command\Proxy\UpdateSchemaDoctrineCommand.php:50
 Doctrine\Bundle\DoctrineBundle\Command\Proxy\UpdateSchemaDoctrineCommand->execute() at C:\xampp\htdocs\tuinadvies\vendor\symfony\symfony\src\Symfony\Component\Console\Command\Command.php:264
 Symfony\Component\Console\Command\Command->run() at C:\xampp\htdocs\tuinadvies\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:887
 Symfony\Component\Console\Application->doRunCommand() at C:\xampp\htdocs\tuinadvies\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:223
 Symfony\Component\Console\Application->doRun() at C:\xampp\htdocs\tuinadvies\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php:81
 Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at C:\xampp\htdocs\tuinadvies\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:130
 Symfony\Component\Console\Application->run() at C:\xampp\htdocs\tuinadvies\bin\console:28

doctrine:schema:update [--complete] [--dump-sql] [-f|--force] [--em [EM]] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command>


text:
Q: JBOSS fuse proxying the schema I tried to create router with JBoss Fuse/Camel and deployed in successfully.
<camelContext id="blueprintContext"
                trace="false"
                xmlns="http://camel.apache.org/schema/blueprint">
    <route id="httpBridge">
      <from uri="jetty:http://mysystem:8282/CreateAccountService?matchOnUriPrefix=true"/>
      <to uri="jetty:http://mysystem:8080/service/services/CreateAccountService?bridgeEndpoint=true&throwExceptionOnFailure=false"/>
    </route>
  </camelContext>

Able to access the service using proxy.
I have used xsd for data types in wsdl.
<wsdl:types>
<xsd:schema xmlns:fault="http://www.sample.project.com.au/common/message/FaultMessage/v1" xmlns:pref="http://www.sample.project.com.au/services/account/CreateAccount/CreateAccountRequest/v1" xmlns:pref1="http://www.sample.project.com.au/services/account/CreateAccount/CreateAccountResponse/v1" xmlns:pref2="http://www.sample.project.com.au/common/message/TechnicalException/v1" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.sample.project.com.au/services/account/CreateAccount/v1" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.sample.project.com.au/services/account/CreateAccount/v1">
<xsd:import namespace="http://www.sample.project.com.au/services/account/CreateAccount/CreateAccountRequest/v1" schemaLocation="http://mysystem:8080/service/services/CreateAccountService?xsd=CreateAccountRequest.xsd"></xsd:import>
<xsd:import namespace="http://www.sample.project.com.au/services/account/CreateAccount/CreateAccountResponse/v1" schemaLocation="http://mysystem:8080/service/services/CreateAccountService?xsd=CreateAccountResponse.xsd"></xsd:import>
</xsd:schema>
</wsdl:types>

http://mysystem:8282/CreateAccountService?wsdl (Proxy)
But, I can see all the xsd details in wsdl with
<xsd:import namespace="http://www.sample.project.com.au/services/account/CreateAccount/CreateAccountRequest/v1" schemaLocation="http://mysystem:8080/service/services/CreateAccountService?xsd=CreateAccountRequest.xsd"></xsd:import>

which is original url of the schema.
http://mysystem:8080/service/services/CreateAccountService?xsd=CreateAccountRequest.xsd

I want to hide this details also.
But, I was able to see all the schema with actual url details.
How can I create the proxy for all the contents in the URI.
If I am not clear with my question, please let me know.

A: 1)
You need to process the reply message (using message translator eip  http://camel.apache.org/message-translator.html) before returning it to the client, so you can replace the url in the message body from the actual url, to the proxy url
For example you can use a bean with a single method that does the search/replace
public String transformTheMessage(String body) {
  ...
  ... search for the url you want to replace
}

And then define a bean in the xml file and use it in the Camel route
<route id="httpBridge">
      <from uri="jetty:http://mysystem:8282/CreateAccountService?matchOnUriPrefix=true"/>
      <to uri="jetty:http://mysystem:8080/service/services/CreateAccountService?bridgeEndpoint=true&throwExceptionOnFailure=false"/>
      <to uri="bean:myBean"/>
    </route>

2)
Or check if the request is for the WSDL and do a content based router, and return the content from a file which you have on the proxy server - and the file has the proxy urls hardcoded etc.
http://camel.apache.org/content-based-router.html
3)
Or check out this example

*

*https://camel.apache.org/cxf-proxy-example.html


text:
Q: How to sort a timeseries GridDB table according to timestamps? I'm using JavaScript (NodeJS) to run GridDB NodeJS client on my Ubuntu machine. I have stored my time series database in a griddb container. I need to find a way to select a table and sort it by the timestamps. It returns the table with the sorted rows where the timestamps are sorted in a descending order, or the most recent time comes last. Do you think there's a way to do that?
Below is a code snippet for a sample time series database as I stored mine in the GridDB container:
// preliminary codes have been deleted
let time_series;
        store.putContainer(timeConInfo, false)
            .then(ts => {
                time_series = ts;
                return ts.put([new Date(), 60, 'resting']);
            })
            .then(() => {
                query = time_series.query(" "); // the query goes here
                return query.fetch();
            })
            .then(rowset => {
                while (rowset.hasNext()) {
                    var row = rowset.next();
                    console.log("Time =", row[0], "Value =", row[1].toString());
                }
            })
    // catch the exception
            .catch(err => {
                if (err.constructor.name == "GSException") {
                    for (var i = 0; i < err.getErrorStackSize(); i++) {
                        console.log("[", i, "]");
                        console.log(err.getErrorCode(i));
                        console.log(err.getMessage(i));
                    }
                } else {
                    console.log(err);
                }
            });


text:
Q: In Oracle SQL, How to replicate rows based on the binary value in a column? Problem:
+------+--------+
| NAME | BINARY |
+------+--------+
| A    |   1101 |
| B    |   0011 |
+------+--------+

I have table with NAME and BINARY values.
I have to replicate rows, including a column for ID by considering their respective BINARY values.
In the given example, name A has BINARY value of 1101, which means it should have 3 rows with their IDs being A-01, A-02, A-04 and no row should be added for A-03 as it is 0 in Binary value (11'0'1).
How to do this in Oracle SQL query? I use 11g.
Expected Output:
+------+--------+------+
| NAME | BINARY |  ID  |
+------+--------+------+
| A    |   1101 | A-01 |
| A    |   1101 | A-02 |
| A    |   1101 | A-04 |
| B    |   0011 | B-03 |
| B    |   0011 | B-04 |
+------+--------+------+

A: You could use a query from dual with a connect by level clause to generate a series of numbers from 1 to 4, and then (anti)join it on the table and check if the character in that position in binary is a 0 or a 1:
SELECT name, bin, name || '-0' || lev AS id
FROM   mytable
JOIN   (SELECT     LEVEL AS lev
        FROM       dual
        CONNECT BY LEVEL <= 4) ON SUBSTR(bin, lev, 1) != '0'

Assumptions for this query:

*

*I called the column bin instead of binary since that's a reserved word. You could use binary and surround it by quotes if you need to.

*I assumed the bin column is a varchar. If it isn't, just use to_char to convert it to a string in the query

SQLFiddle


text:
Q: Sublime Text through command line: Don't open more than 1 window/instance, add to working project instead It's pretty unclear the philosophy of Sublime Text (3 in my case) concerning opening program from command line.
With version 2, if I wanted to open Sublime with the current working directory I would type subl . &.
With version 3, the & has become optional, the instance is automatically sent to the background.
That's good, but if there already was an instance of sublime to be restored, both window become open.

What I'd expect by running subl .

*

*If an instance is already stored, it opens and adds . (working directory) to the left panel (they call it Add to the project)

*Else do the current behavior

Is there any chance I can achieve that?
Maybe I should use what they call project, but that's pretty unnatural to me: sublime should open and close files, so only 1 window, with many folders in the left panel I can manage is the best.

A: Cool, I found it:
subl --add .
From subl --help.
I've aliased it: alias subl="subl --add"


text:
Q: How do I select a record by matching an index based on a partial string that contains '-' characters? I'm using YDN-DB (an abstraction on top of IndexedDB) as a local database. I have an object store called 'conversations', and in that store, there's an index called 'participants' where there is a string containing id's for different users in the conversation. For example:
Example Conversation #1:
id: 1234343434353456,
participants: '171e66ca-207f-4ba9-8197-d1dac32499db,82be80e2-2831-4f7d-a8d7-9223a2d4d511'

Example Conversation #2:
id: 4321343434356543,
participants: 'd7fa26b3-4ecc-4f84-9271-e15843fcc83f,171e66ca-207f-4ba9-8197-d1dac32499db'

To try to perform a partial match on an index, I tried using ydn-db-fulltext as a solution. The full text catalog looks like this:
  {
    name: 'participants',
    lang: 'en',
    sources: [
      {
        storeName: 'conversations',
        keyPath: 'participants',
        weight: 1
      }
    ]
  }

I see that the catalog is generated, but there seems to be a problem doing exact matches. For example, if I query using only part of the key in the participants index, I get back a primary key from the catalog:
db.search('participants', 'd7fa26b3').done(function(results) {
  if(results.length == 0) console.debug('No results found...');
  console.debug(results);                  // there is 1 object here!
  var primaryKey = results[0].primaryKey;  // primaryKey exists!
});

However, when using any value past the '-', the search request returns 0 results:
db.search('participants', 'd7fa26b3-4ecc-4f84-9271-e15843fcc83f').done(function(results) {
  if(results.length == 0) console.debug('No results found...');
  console.debug(results);                  // there are 0 objects in the array
  var primaryKey = results[0].primaryKey;  // primaryKey throws undefined since there are 0 results!
});

This makes sense, when reading the documentation, in that '-' and '*' are reserved characters that remove a phrase and match a prefix respectively:

Query format is free text, in which implicit and/or/near logic operator apply for each token. Use double quote for exact match, - to subtract from the result and * for prefix search.

I tried putting double quotes inside the single quotes, using only double quotes, and also escaping all of the '-' characters with a backslash, but none of these seem to work.
So the question is how does one perform a match in an index where the string contains '-' characters?

A: Have you try db.search('participants', '"d7fa26b3"').
BTW, you are using full text search that is not suppose to do. You have to tokenize your string and index them manually.

A: If you store the participants field of your object as an array, then you can use the multi-entry flag to the createIndex method called on the participants field, and probably do what you want.
The number of items in the participants property of the object is mutable. When you update an object in the store and it has a different number of items in the partic property, then the index is automatically updated as a result (just like any other index). If you add an item to the prop, then restore (put/override/cursor.update) the object in the store, the index updates.
It helps to review the basics of how a multi-entry index works. You can do this with vanilla js, without a framework, and certainly without full-text searching.


text:
Q: Electron Angular playing static audio files I try to develop a native app using electron and angular2.
Its purpose is to conduct Psychology experiments connected with sound perception.
In order to do this, I want to play sounds that will be stored in some assets directory in my app directories. But I find difficulties with accessing those audio files from angular in order to play it. And the internet seems to be pretty unhelpful after half day of searching I did not find and supporting articles.
What is the best way to do it?
Should I add to my app some server application, with angular proxying api requests to it? That solution will most likely work accordingly to what I found.
But is there any simple solution? Like some Electron library that allows offline access from Angular level to file system and files that are in app directory?
Thanks in advance
Tomasz

A: You could try using howler.js
You can install it to your project with npm install --save howler and play a sound with
var sound = new Howl({
  src: ['sound.mp3']
});

sound.play();

You would also probably want to install @types/howler via npm to work with typescript


text:
Q: How to print the position and value of a nested array using recursion in Javascript I have a simple question
have a nested list using recursion I have to print all the nested array as well as the value of main array  .
In-put
var list = ['a', ['a','b','c',['a','b','c']],'b', 'c'];
printList('foo',list);

Out-put
foo.0.a
foo.1.0.a
foo.1.1.b
foo.1.2.c
foo.1.3.0.a
foo.1.3.1.b
foo.2.b
foo.3.c

But I am able to print only till one level deep

var list = ['a', ['a','b','c',['a','b','c']],'b', 'c'];
   var printList = function(name,list){

     for(var i=0;i< list.length;i++){

         if(Array.isArray(list[i]))
             {
               printList(name+'.'+i,list[i]);

             }
             else{

                 document.write(name+'.'+i+'.'+list[i]+'
');

             }

     }
   }

   printList('foo',list);

I have added the code snippet have a look
Thanks

A: This is because the i in the for loop became a global variable, making it loose its value once in the recursion.
add var i; declaration before for loop in the function and the issue should be solved.
var list = ['a', ['a','b','c',['a','b','c']],'b', 'c'];
    var printList = function(name,list){
        var i;
        for(i=0;i< list.length;i++) {
            if(Array.isArray(list[i])) {
                printList(name+'.'+i,list[i]);
            } else {
                  document.write(name+'.'+i+'.'+list[i]+'
');
            }
        }
    }

    printList('foo',list);


text:
Q: How to connect Entity Framework with Azure user assigned identity? Instead of using connection string Microsoft has given documentation on how to connect through managed identity. it's okay for Azure AD user but I want to use User assigned identity which I've created in Azure portal.
var conn = (System.Data.SqlClient.SqlConnection)Database.Connection;
var credential = new Azure.Identity.DefaultAzureCredential();
var token = credential.GetToken(new Azure.Core.TokenRequestContext(new[] { "https://database.windows.net/.default" }));
conn.AccessToken = token.Token;

Code provided by Microsoft for creating connection with default Azure credential.
It was working with system assigned identity. Getting error while making connection for user assigned identity.

A: When connecting to an SQL server you basically have 2 options:

*

*Connect based on the identity of the calling process

*Connect based on the information in a connection string

It looks like what you want to do is:

*

*Connect using a user assigned identity

*Do not place user name and password in the connection string

To do this you must:

*

*Grant the user assigned identity access to SQL Server

*Change the identity of the process running your code to the user assigned identity


text:
Q: Why doesn't this two way data binding work? I have this controller. Whenever I try to bind my $scope.things to my received JSON from the server, my View wont update. In fact, if I left my push(newThing) and uncomment my calls to getAllThings(), my view will display the data and, in less than a second, will remove it.
The problem is: in the server side (Morgan running with Node and MongoDB), I'm printing out the json object before it is passed to my client and the object is correct, it DOES have the latest created object.
I'm willing to use push instead of making another request to server to fetch data, but I'm really upset about this topic. Another interesting thing it that my second, third and consequent calls to insertThing() will properly update my view. It made feel kind of clueless. I can provide more code if needed.
Controller:
$scope.insertThing= function(newThing){
    $scope.things.push(newThing);
    $http.post('http://localhost:8080/things', newThing)
    .then(function(res){
        //$scope.getAllThings();
        delete $scope.newThing;
    }, function(res){

    });
    //$scope.getAllThings();
};

$scope.getAllThings = function(userDpt){
    $http.post('http://localhost:1234/things/dpt/', {userDpt: userDpt})
    .then(function(res){
        $scope.things = res.data;
    }, function(res){

    });
};

Node Server with Mongoose:
app.post('/things/dpt', function(req, res){
var department = req.body.dpt;
var things= {};
TicketModel.find({ fromDpt: department},
    function(err,obj){
        res.json(obj);
    });
});

Markup:

   {{ thing.toDpt}}
   {{ thing.status }}
   {{ thing.deadline }}
  <button class="btn close" data-ng-click="deleteThing(thing._id)">×</button>

A: Well, this was long time ago.
All this code was fully refactored. The problem was with the assyncronous behavior of JavaScript. Sometimes, the getAllThings() function would finish before the delete line and the new fetched data would just vanish after being received.
The way around this problem is to add another callback after the http request.


text:
Q: Error in extracting json content from an API request: Error: parse error: premature EOF? I'm trying to retrive data from an API, the request I get back is of type "application/json", however when I try to extract the content as text I get an empty string and, therefore, also the fromJSON command fails. The following code worked until yesterday, but now there must have been some changes in the API and I can't work my way around it.
Here's a snippet of how the raw req$content looks like:
[1] fe ff 00 7b 00 0d 00 0a 00 20 00 20 00 22 00 40 00 6f 00 64 00 61 00 74 00 61 00 2e 00 63 00 6f 00 6e 00 74 00 65 00 78
  [41] 00 74 00 22 00 3a 00 22 00 68 00 74 00 74 00 70 00 73 00 3a 00 2f 00 2f 00 73 00 65 00 72 00 76 00 69 00 63 00 65 00 73
  [81] 00 2d 00 61 00 70 00 69 00 2e 00 6c 00 65 00 78 00 69 00 73 00 6e 00 65 00 78 00 69 00 73 00 2e 00 63 00 6f 00 6d 00 2f
 [121] 00 76 00 31 00 2f 00 24 00 6d 00 65 00 74 00 61 00 64 00 61 00 74 00 61 00 23 00 4e 00 65 00 77 00 73 00 22 00 2c 00 22

This is the code that worked until yesterday and that I'm trying to use:
content = jsonlite::fromJSON(content(req, "text"),
       simplifyVector = FALSE)

Error: parse error: premature EOF
                      (right here) ------^

I've also tried the following with no success:
dta <- req$content
dtan <- dta[!dta=='00']
dtanc <- rawToChar(dtan)
content = jsonlite::fromJSON(dtanc, simplifyVector = FALSE)

Error: lexical error: invalid char in json text.
                                       <fe><ff>{    "@odata.context":"
                     (right here) ------^


text:
Q: Angular: ng-click with a parameter not working I've got the following HTML:

And the following functions in my controller's $scope:
$scope.addName = function() {
    $scope.names.push($scope.newName);
    $scope.newName = '';
};
$scope.delName = function(i) {
    $scope.names.splice(i, 1);
};

The addName() works fine but the delName() is never called. Is it impossible to bind an ng-clik to a function with an argument?

A: The error was in the html, the ng-repeat $index should not be evaluated beforehand:
This is the valid HTML:

A: The code seems fine to me, can you isolate your problem in a jsFiddle?
EDIT:
Removed incorrect answer about splice not modifying to array.

A: You can do as follows

In css
[ng-click],
[data-ng-click],
[x-ng-click] {
    cursor: pointer;
}


text:
Q: Need Help in Configuring Links React Native Navigation I am trying to configure links of the below nested navigation. I wanted to navigate user to bdetails or adetails or alist or blist views based on data that comes from firebase notification.
const AStack = () => <Stack.Navigator>
<Stack.Screen name="adetails" component={ADetails} />
<Stack.Screen name="alist" component={AList} />
</Stack.Navigator>

const BStack = () => <Stack.Navigator>
<Stack.Screen name="bdetails" component={BDetails} />
<Stack.Screen name="blist" component={BList} />
</Stack.Navigator>

const TabNavigation = () => <Tab.Navigator>
<Tab.Screen name="A" component={AStack} />
<Tab.Screen name="B" component={BStack} />
</Tab.Navigator>

const TabNavContainer = () => <Stack.Navigator>
<Stack.Screen name="app" component={TabNavigation} />
</ Stack.Navigator>

const RootNav = () => <Drawer.Navigator>
<Drawer.Screen name="tabnav" component={TabNavContainer} />
</Drawer.Navigator>

const linking = {
    prefixes: ['cdpharmacy://'],
    config: {
      screens: {
        RootNav: {
          path: 'root',
          screens: {
            tabnav: {
              path: 'nav',
              screens: {
                app: {
                  path: 'app',
                  screens: {
                    A: {
                      path: 'a',
                      screens: {
                        alist: 'list/:param1',
                        adetails: 'details/:param1/:param2'
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  };

<NavigationContainer>
      <Stack.Navigator>
          <Stack.Screen name="AuthNav" />
          <Stack.Screen name="RootNav"/>
      </Stack.Navigator>
</NavigationContainer>

The below link is not working in the app.
linkTo('/root/nav/app/a/details/param1/param2')

A: You dont need to use deeplinking for that simply check notification data in App.js when recieved in setBackgroundMessageHandler() if data equal to something navigate to that page.
See in this e.g. if my data.action== "open_map" im navigating user to RouteMap page.
e.g.
messaging().setBackgroundMessageHandler(async remoteMessage => {
    const {data} = remoteMessage;
    if (data.action == 'open_map') {
      navigate('RouteMap', {data: data.eventsteamID});
    } else if (data.action == 'open_home') {
      navigate('Home');
    } else {
      console.log('Something went wrong.');
    }
    console.log('Message handled in the background!', remoteMessage);
  });


text:
Q: Embedly.oembed not adhering to the maxwidth parameter I am trying to use Embedly to generate a thumbnail for a given url. I need the thumbnail to be smaller than a maximum size, so I call the api like so:
url = "http://embed.ly"
embedly_api = Embedly::API.new(key: ENV['EMBEDLY_KEY'])
obj = embedly_api.oembed(url: url, maxwidth: 50, type: 'photo').first

json_obj = JSON.pretty_generate(obj.marshal_dump)

or
http://api.embed.ly/1/oembed?key=[KEY_VALUE]&url=http://embed.ly&maxwidth=50&type=photo

In either case the result is:
{
  provider_url: "http://embed.ly",
  description: "Embedly delivers the ultra-fast,...",
  title: "Embedly makes your content more engaging and easier...",
  mean_alpha: 32.7480314961,
  thumbnail_width: 399,
  url: "http://embed.ly",
  thumbnail_url: "http://embed.ly/static/images/logos/logo_color.png?v=4b245",
  version: "1.0",
  provider_name: "Embedly",
  type: "link",
  thumbnail_height: 127
}

Notice that thumbnail_width is 399 (which is larger than what I passed in for the maxwidth parameter). Am I missing something obvious here?

A: maxwidth only applies to the html, images can be of any width.
Embedly does allow you to set an image_width though. Try:
embedly_api.oembed(url: url, maxwidth: 50, type: 'photo', image_width: 50)

http://embed.ly/docs/api/display/integration


text:
Q: Unauthorized error on GetProvisioningTemplate I have Provider Hosted Add-In and everything is working as expected but fails on 'web.GetProvisioningTemplate(creationInfo)'.
it gives me below error

The remote server returned an error: (401) Unauthorized

Below is the complete code,
    var siteUrl = "<siteurl>"; //This is not the same url from where add in is running
var tenantAdminUrl = "";
var appId = "";
var appSecret = "";

    using (ClientContext ctx = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(tenantAdminUrl, appId, appSecret))
    {
        Tenant tenant = new Tenant(ctx);
        ctx.Load(tenant);
        ctx.ExecuteQuery();

        var site = tenant.GetSiteByUrl(siteUrl);
        var web = site.RootWeb;

        ctx.Load(site);
        ctx.Load(web);
        ctx.ExecuteQuery();

        var sourcelist = web.GetList(listUrl);
        ctx.Load(sourcelist);
        ctx.ExecuteQuery();

        ProvisioningTemplateCreationInformation creationInfo = new ProvisioningTemplateCreationInformation(web);

        var provisioningTemplate = web.GetProvisioningTemplate(creationInfo);

    }


text:
Q: With vagrant-berkshelf deprecated, will it be possible to drive builds from Vagrant, with Chef solely as a provisioner? I have had a number of issues recently with vagrant-berkshelf not syncing Chef cookbooks on an existing machine reliably.  And, basically, when doing research on workarounds, I see something like:
vagrant-berkshelf is deprecated, use Test Kitchen instead.
My use case is that I have Vagrantfiles, used to build VMs and DigitalOcean droplets, that are hand-written and only use Chef to provision the VMs.  I am most definitely approaching Chef as a user, not an author or tester of cookbooks.
So, I am in a case of Vagrant -> Chef, not Chef -> Vagrant.
When looking at Kitche-Vagrant, I see that:
The kitchen-vagrant driver for Kitchen generates a single Vagrantfile for each instance of Kitchen in a sandboxed directory..
My question is:  if my workflow relies on hand-written, complex, Vagrantfiles, can I continue to use Chef as a provisioner without having to rely on vagrant-berkshelf?
Some of the possible alternatives I see are:

*

*mangle Test Kitchen configuration to work with my exiting Vagrantfile.  I fear that this is not the intent of this tool and will not end well.

*use chef.cookbooks_path attribute in vagrant and let it take the place of vagrant-berkshelf.

*switch out provisioners and use say Vagrant->Ansible.
The Vagrantfile below is somewhat simplified, but the gist is that the Vagrantfile is in charge and Chef is just used to provision.
# -*- mode: ruby -*-
# vi: set ft=ruby :

#...grab some variables from my host environment...
DJANGO_SECRET_KEY = ENV['BUILD_DJANGO_SECRET_KEY']

Vagrant.configure('2') do |config|

  config.vm.define "myserver" do |config|
      config.vm.provider :digital_ocean do |provider, override|
        override.ssh.private_key_path = digoconf.private_key_path
        override.vm.box_url = "https://github.com/devopsgroup-io/vagrant-digitalocean/raw/master/box/digital_ocean.box"
        provider.token = digoconf.TOKEN
        ...
      end

      #had chef_client before, that worked too.
      config.vm.provision "chef_zero" do |chef|

        chef.log_level = "info"

        #I haven't tested these out
        #chef.cookbooks_path = ["../community/cookbooks","../.berkshelf/cookbooks"]

        env_for_chef = " DJANGO_SECRET_KEY='#{DJANGO_SECRET_KEY}'"
        chef.binary_env = env_for_chef

        chef.environment = "digitalocean"
        chef.add_recipe "base::install"
      end
  end
end

A: It isn't deprecated per se, but it does no longer have a maintainer and does highly recommend against its use. There is no replacement for the workflow you describe. Sorry. If you are interested in taking over as maintainer, I can put you in contact with the team.


text:
Q: ExtJS Theme Centralization I have multiple ExtJS apps based on a custom theme say "my-ux-theme" (extension of "ext-theme-crisp").
I have bunch of .SCSS files repeated in each one of the apps. Every time I make any change to the theme, I have to make change in each of the SCSS files across the apps.
I want to centralize my theme
I am planning to attach "my-ux-theme" to the KitchenSink application and then I am building the entire KitchenSink which produces the .CSS files I need. I then deploy this CSS to my CDN and linking all my apps to this theme (CSS files). Is this a good approach?
Is this a safe assumption that KitchenSink is a big app covering all the components in ExtJS and is generating all the CSS I would ever need?
Can you all please suggest?
The basic question is when we do Sencha Command on an ExtJS application (sencha app build) then the generated CSS files by the theme covers only those components which are used/present in the application? Or it doesn't matter?

A: Using Kitchen Sink does not feel right to me, Here is what you can do.

*

*Create a Sencha Work Space

*Create a Theme Package

*Build the Theme Package using "sencha package build"

*It will generate one single CSS file for your theme in build/resource/theme-name-all.css

Here are commands for it
sencha -sdk {path/to/Ext-JS-5-SDK} generate workspace my-workspace
sencha generate package -type theme my-custom-theme
sencha package build


text:
Q: What is the latest working version of videojs-transcript? The "working sample" for videojs-transcript, whose link is on the author's Github page uses an old version, 0.7.1, from 2014. The master branch is 3 versions ahead at 0.8.1, from 2017. When I attempt to run 0.8.1, it fails:
"Uncaught TypeError: my._options is undefined" in videojs-transcript.js:379:5"
The only way that I could get something working was to download the files used by the sample from the author's github.io page.
The author did not create an npm package. But I noticed that there are two npm packages for this component:

*

*https://www.npmjs.com/package/videojs-transcript-ac

*https://www.npmjs.com/package/@packt/videojs-transcript
I couldn't find a corresponding code repository for videojs-transcript-acvideojs-transcript-ac. But there is a bitbucket repo for @packt/videojs-transcript.
The original author's (walsh9) working sample is from 2014. I noticed that there are much more recent stackoverflow Q&A for videojs-transcript, even a couple from this year.
What and where is the latest working version for this package? Is there a fix to the author's latest 0.8.1 version available? (There hasn't been any activity on https://github.com/walsh9/videojs-transcript since 2017)


text:
Q: Yii: custom error handling forwarding I'm looking for a way to forward the error handling in my Yii 1.1.14 app. The scenario comes as follows:
Assuming I have two modules: ClientModule at /client/, AdminModule at /admin/. If an url is resolved to belong to any controller in that module, the controller is loaded, and the errorHandler is reassigned to a module-level error handler like this:
public function beforeControllerAction($controller, $action)
{
    Yii::app()->errorHandler->errorAction='admin/error';
    return parent::beforeControllerAction($controller, $action);
}

In this way, an action exists at 'admin/admin/error' (which in turn is manually specified to be resolved to 'admin/error'), which will handle the error with a boilerplate like:
public function actionError() {
    if($error=Yii::app()->errorHandler->error)
    {
        if(Yii::app()->request->isAjaxRequest)
            echo $error['message'];
        else
            $this->render('application.views.error.index', $error);
    }
}

Meanwhile, the analogous code (for both functions) exist in the other module (There's also a ClientModule and a ClientController with an actionError mapped automatically to 'client/client/error', remapped to 'client/error').
I have no trouble at all with these code chunks. My issue starts now:
If I input an url which cannot be resolved, even when the prefix is a module prefix (e.g. 'client/invalid/url' or 'client/client/invalid'), the controller will not be created (since it does not exist - or, as in the second example, the controller exists but not the action), and so beforeController will not be called, and so the custom error handler (in this example: the corresponding to ClientModule which sets $aClientController->actionError) will not be assigned. Result: the default ErrorController handling the unresolved url error.
So, questions:

*

*Is there any way I could map an unresolved url (404) error to certain module, depending on the prefix? (it is safe, in my case, to assume prefixes, since I have not set any module as default).

*Alternatively: is there a way to, being in the ErrorController->actionIndex(), forward the error handling to one of those controllers (i.e. moving to admin/admin/error and client/client/error while keeping the Yii::app()->errorHandler->error state)?
Edit - Footnote: Why should I use another controller if the error handling code is the same? Because I have additional data provided by those controllers which is used in the layout (e.g. menu, head menu).

A: Found the answer, again (my juniority has no limits - and the method name I needed had the exact name: forward!!).
Using the CController->forward('module/controller/action') inside the ErrorController->actionError method I could dispatch everywhere. I also changed another business logic condition and have not the custom error handler assignment in the modules constructors anymore, but I still use those controllers as forward targets of 'error/index' depending on the logged user type (i.e. an error occurred and the user was a client => forward to client/client/error, while being admin led to admin/admin/error, and being no logged user performed the error handling with error/index as usual).
public function actionIndex() {
    if (Yii::app()->user->getState('client'))
    {
        $this->forward('client/client/error');
    }
    if (Yii::app()->user->getState('staff'))
    {
        $this->forward('admin/admin/error');
    }

    //usual boilerplate here
    if($error=Yii::app()->errorHandler->error)
    {
        if(Yii::app()->request->isAjaxRequest)
            echo $error['message'];
        else
            $this->render('index', $error);
    }
}


text:
Q: Enable requests to .git/HEAD in IIS With the very clear understanding that you should never, ever (ever) do this in your production environment, how do you enable IIS to serve requests to ".git/HEAD"? I wasn't sure if it was being blocked by request filtering or because of a missing MIME type but I can't get it to be served either by adding an allowable file extension in request filtering or by adding a MIME map.
Any ideas?
For context, this is part of project that demonstrates remotely exploitable risks, one of which is VCS repos accessible over HTTP. Unfortunately IIS does too good a job of looking after this by default!

A: Add a MIME Type mapping for '.' to 'application/octet-stream'. This will let IIS serve extension-less static files.
This works for me on IIS 10.0 (Windows 10).


text:
Q: Is there a way to install Chrome/Chromium in a sandboxed environment from Firefox? I'm convinced that when Firefox and Chrome/Chromium are installed together on the same Ubuntu system, that Chrome/Chromium does something to make Firefox slower and less reliable.
Whenever I install Chrome/Chromium on an Ubuntu system, the system always gets really slow about a month later. I have a lot of Ubuntu systems and this happens all the time, for the past two years at least, literally.
When I install both Firefox and Chrome/Chromium, the most annoying things happen. It works for a few days, then Firefox is ridiculously slow to start. One of my machines it took almost 10 minutes just to load Firefox, whereas with Chrome/Chromium it was instantaneous.
I really prefer Firefox because it doesn't have any of this sketchy BS added to it. But I need Chrome/Chromium to be able to debug a webview inside my android application. So, is there a way to install Chrome/Chromium inside a sandboxed environment, which can still use USB, without breaking Firefox?
(Are there any alternative softwares to Google's browsers for debugging Android webviews, that don't force me to reinstall Ubuntu 16.04 a month after installing them?)

A: In my case I had an extra, very old, Ubuntu laptop that I was already using to play some DRM content using Chrome. I decided to set this up as a permanent android test device that I could access even remotely.
In another situation, one might create a docker image with Chrome involved. This blog post goes over the details, but here's a brief outline.

*

*Install dependencies from the docker community edition: sudo apt-get install docker-ce -y; mkdir chrome-local; cd chrome-local;

*Inside a file named: "Dockerfile", put:
FROM ubuntu:trusty

RUN apt-get update; apt-get clean

# Add a user for running applications.
RUN useradd apps
RUN mkdir -p /home/apps && chown apps:apps /home/apps

# Install x11vnc.
RUN apt-get install -y x11vnc

# Install xvfb.
RUN apt-get install -y xvfb

# Install fluxbox.
RUN apt-get install -y fluxbox

# Install wget.
RUN apt-get install -y wget

# Install wmctrl.
RUN apt-get install -y wmctrl

# Set the Chrome repo.
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list

# Install Chrome.
RUN apt-get update && apt-get -y install google-chrome-stable

COPY bootstrap.sh /

CMD '/bootstrap.sh'

*Inside a file named bootstrap.sh, put:
#!/bin/bash

# Based on: http://www.richud.com/wiki/Ubuntu_Fluxbox_GUI_with_x11vnc_and_Xvfb

readonly G_LOG_I='[INFO]'
readonly G_LOG_W='[WARN]'
readonly G_LOG_E='[ERROR]'

main() {
    launch_xvfb
    launch_window_manager
    run_vnc_server
}

launch_xvfb() {
    # Set defaults if the user did not specify envs.
    export DISPLAY=${XVFB_DISPLAY:-:1}
    local screen=${XVFB_SCREEN:-0}
    local resolution=${XVFB_RESOLUTION:-1280x1024x24}
    local timeout=${XVFB_TIMEOUT:-5}

    # Start and wait for either Xvfb to be fully up or we hit the timeout.
    Xvfb ${DISPLAY} -screen ${screen} ${resolution} &
    local loopCount=0
    until xdpyinfo -display ${DISPLAY} > /dev/null 2>&1
    do
        loopCount=$((loopCount+1))
        sleep 1
        if [ ${loopCount} -gt ${timeout} ]
        then
            echo "${G_LOG_E} xvfb failed to start."
            exit 1
        fi
    done
}

launch_window_manager() {
    local timeout=${XVFB_TIMEOUT:-5}

    # Start and wait for either fluxbox to be fully up or we hit the timeout.
    fluxbox &
    local loopCount=0
    until wmctrl -m > /dev/null 2>&1
    do
        loopCount=$((loopCount+1))
        sleep 1
        if [ ${loopCount} -gt ${timeout} ]
        then
            echo "${G_LOG_E} fluxbox failed to start."
            exit 1
        fi
    done
}

run_vnc_server() {
    local passwordArgument='-nopw'

    if [ -n "${VNC_SERVER_PASSWORD}" ]
    then
        local passwordFilePath="${HOME}/x11vnc.pass"
        if ! x11vnc -storepasswd "${VNC_SERVER_PASSWORD}" "${passwordFilePath}"
        then
            echo "${G_LOG_E} Failed to store x11vnc password."
            exit 1
        fi
        passwordArgument=-"-rfbauth ${passwordFilePath}"
        echo "${G_LOG_I} The VNC server will ask for a password."
    else
        echo "${G_LOG_W} The VNC server will NOT ask for a password."
    fi

    x11vnc -display ${DISPLAY} -forever ${passwordArgument} &
    wait $!
}

control_c() {
    echo ""
    exit
}

trap control_c SIGINT SIGTERM SIGHUP

main

exit

*Build the docker image: chmod +x boostrap.sh; docker build -t local/chrome:0.0.1 . - Note the trailing .! This builds the image in the Dockerfile above and gives it a name called local/chrome:0.0.1.

*Run the docker image with: docker run -p 5900:5900 -e VNC_SERVER_PASSWORD=password --user apps --privileged local/chrome:0.0.1

*Use a VNC client to connect to port 5900 which holds your docker image


text: Q: How to design the leaf node if I want to fix the node size with variable length kv pair in B tree How to design the leaf node if I want to fix the node size with variable length kv pair in B+ tree? Say if I want to fix the leaf node size with 4KB and insert as much kv pairs as it can hold. I found that many of implementation of the B+ tree are using array and fix the size of array, but It can not be work for the variable length key or value. I wonder if it could be possible by any chance?


text:
Q: how to listen for new tweets for an @mention using tweepy? I am new to tweepy. And tried to implement an api which can listen the new tweets for a @mention or screen name.
tweets = api.user_timeline(screen_name=username)

But it is not listening the new tweets. Could you please help me to understand how it can be implemented so that whenever a tweet comes with '@mention'. the api should listen immediately

A: Creating a StreamListener
The on_data method of Tweepy's StreamListener conveniently passes data from statuses to the on_status method.
Create class MyStreamListener inheriting from StreamListener and overriding on_status.
import tweepy

override tweepy.StreamListener to add logic to on_status
class MyStreamListener(tweepy.StreamListener):

    def on_status(self, status):
        print(status.text)

Creating a Stream
Need an API to stream with the right credentials for authentications. Once we have an API and a status listener we can create our stream object.
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener)

start stream
myStream.filter(track=['python'])

myStream.filter(follow=["2211149702"])

Async stream
myStream.filter(track=['python'], is_async=True)

handling errors
class MyStreamListener(tweepy.StreamListener):

    def on_error(self, status_code):
        if status_code == 420:
            #returning False in on_error disconnects the stream
            return False

        # returning non-False reconnects the stream, with backoff.

A: Firstly, get their twitter user id using this.
Then, use this:
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy import StreamListener

listener = StreamListener()
auth = OAuthHandler(config.API_KEY, config.API_SECRET)
auth.set_access_token(config.ACCESS_TOKEN, config.ACCESS_TOKEN_SECRET)
stream = Stream(auth, listener)
stream.filter(follow=['1102105048253849600']) # user ID for random account

A: def on_data( self, status ):
    print("Entered on_data()")
    print(status.text, flush = True)
    return True
...
user = api.verify_credentials()
# this is just for getting user. without this also connection can be established
if user:
    print(user.id)
    print('started')
twitter_stream=Stream(auth,StdOutListener())
print('Stream created...')
twitter_stream.filter(follow=[user.id_str], is_async=True)


text:
Q: Convert the any locale date format to US date format in Javascript lightning I have been struggling to change the date format to US locale time.
I tried so many methods but if fails at some or other scenario.
The issue is I cannot say which Locale the client will be using.
If anybody can help me it will be great.
I have tried the $A.localizationService.formatDate(sDate, "yyyy-MM-dd") but when the date comes like this '31.3.2018' it throws error.
Even tried this as well new Date(sDate). it throws Invalid Date Error for date '31.3.2018' but it works if the date is less or equals to 12 suppose '10.2.2018' or '2.10.2018'.
So I tried to write a method which converts the date to "yyyy-MM-dd" format.   So far what I have tried.
formatDate : function(date) {
    if(typeof(date) != 'string') {
        return $A.localizationService.formatDate(date, "yyyy-MM-dd");
    }

    if(date != null && date.search("-") > -1){
        return date;
    }

    var regex = /[^a-zA-Z0-9]/g;
    var specialcharacter = '-';

    date = date.replace(regex, specialcharacter);
    var dateparts = date.split(specialcharacter);

    if(dateparts == null || dateparts.length <= 1) {
        return $A.localizationService.formatDate(new Date(), "yyyy-MM-dd");
    }
    if(dateparts[0].length == 4){
        date = new Date(parseInt(dateparts[0]), parseInt(dateparts[1] - 1), parseInt(dateparts[2]));
    }
    else{
        date = new Date(parseInt(dateparts[2]), parseInt(dateparts[1] - 1), parseInt(dateparts[0]));
    }
    return $A.localizationService.formatDate(date, "yyyy-MM-dd");
}

anywhere in my controller.js I have passing date to the above function which converts the date to "yyyy-MM-dd" format.
I tried with Finnish locale in Dev org it is working as expected but when we installed this on sandbox it was giving us the error.
Let me know if something else is required from my side.

A: Where is the date that you're trying to process coming from? From user input? Is there any constraint on its format?
I would never consider writing a date parser (or anything remotely like one) myself. If you start throwing regexes at a string that might be a date, you're going to be in for an endless world of pain as funny strings trip you up.
I'd split the problem into two steps:

*

*Take untrusted/unpredictable input and turn it into a JS Date object

*Output the JS Date in user's locale

Part (2) is easy. As in your code, you just use $A.localizationService.formatDate. Or maybe the <lightning:formattedDateTime> component.
Part (1) is where I would just go straight to using moment.js (https://momentjs.com/). If you know what format to expect, you can parse it like this:
var parsed = moment('31.3.2018', 'DD.MM.YYYY')

Standard ISO formats are simply like this:
var parsed = moment('2018-3-31')

A: Some how I found the workaround for this solution.. This is not a full proof solution but it may be work as workaround.
<aura:attribute name="dateFormat" type="String" default="{!$Locale.dateFormat}"/>

This gives me the user's current locale date format.
So I will try to parse the date using format.
formatDate : function(component, date) {
    if(typeof(date) != 'string') {
        return $A.localizationService.formatDate(date, "yyyy-MM-dd");
    }

    var regex = /[^a-zA-Z0-9]/g;
    var specialcharacter = '-';

    date = date.replace(regex, specialcharacter);
    var dateparts = date.split(specialcharacter);

    var dateFormat = component.get('v.dateFormat');
    dateFormat = dateFormat.replace(regex, specialcharacter);
    var dateFormatParts = dateFormat.split(specialcharacter);

    var dayIndex = 0;
    var monthIndex = 0;
    var yearIndex = 0;
    for(var i=0; i<dateFormatParts.length; i++) {
        if(dateFormatParts[i].includes('d') || dateFormatParts[i].includes('D')) {
            dayIndex = i;
        }
        if(dateFormatParts[i].includes('m') || dateFormatParts[i].includes('M')) {
            monthIndex = i;
        }
        if(dateFormatParts[i].includes('y') || dateFormatParts[i].includes('Y')) {
            yearIndex = i;
        }
    }
    date = date.replace(regex, specialcharacter);
    var dateparts = date.split(specialcharacter);

    date = new Date(parseInt(dateparts[yearIndex]), parseInt(dateparts[monthIndex] - 1), parseInt(dateparts[dayIndex]));
    return $A.localizationService.formatDate(date, "yyyy-MM-dd");
}

user can call this function by passing the Component and Date. and it will change the date to "yyyy-MM-dd". User can change to other format as well. I wanted "yyyy-MM-dd" way.
Hope this may help someone.


text:
Q: My player is glitching back and fourth and I don't know why I have a 2d game where the enemy sprite is following the player on the x axis. The enemy faces to the right and follows the player to the right if the player is on the right of it and the opposite if the player is on the left. But sometimes if I stop moving the player and let the enemy get up to it it's supposed to stop, face left, and have my player take damage but sometimes it just starts facing to the right and left at the same time super fast. Why?
Here is my code
# Import Libraries here...
import random
import pygame
from sys import exit
import random
from random import randrange
from time import sleep

pygame.init()
clock = pygame.time.Clock()

# Background Music
bg_music = pygame.mixer.Sound('music_zapsplat_astro_race.mp3')
bg_music.play(loops=-1)
bg_music.set_volume(0.3)

# Screen/background
screen = pygame.display.set_mode((1200, 535))
background = pygame.image.load("background1.jpg")
background = pygame.transform.rotozoom(background, 0, 2)

# Player
player_surf = pygame.image.load("player_sprites/player_right.png").convert_alpha()
player_rect = player_surf.get_rect(bottomright = (575, 470))
player_surf = pygame.transform.rotozoom(player_surf, 0, 2.5).convert_alpha()

# Health...
health = 50
health_font = pygame.font.Font('Pixeltype.ttf', 50)
health_display = health_font.render(f"Health {health}", True, (0, 0, 0))

# Enemy #1
enemy1_hp = 10
enemyx_position = randrange(1200, 1500)
enemy1_surf = pygame.image.load("enemy1sprites/enemy1_right.png").convert_alpha()
enemy1_rect = enemy1_surf.get_rect(bottomleft = ((enemyx_position), 462))
enemy1_surf = pygame.transform.rotozoom(enemy1_surf, 0, 2.5).convert_alpha()

# Game Loop
level_one = True
while level_one:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    # Draw Images on the screen
    screen.blit(background, (0, 0))
    screen.blit(enemy1_surf, enemy1_rect)
    screen.blit(player_surf, player_rect)
    screen.blit(health_display, (550, 75))

    # Player Movement
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            player_surf = pygame.image.load("player_sprites/player_left.png")
            player_surf = pygame.transform.rotozoom(player_surf, 0, 2.5)
            player_rect.x -= 4

        if event.key == pygame.K_RIGHT:
            player_surf = pygame.image.load("player_sprites/player_right.png")
            player_surf = pygame.transform.rotozoom(player_surf, 0, 2.5)
            player_rect.x += 4

        # Window Edge
        if player_rect.x >= 1075:
            player_rect.x = 1075
        elif player_rect.x <= 0:
            player_rect.x = 0

    # Enemy 1 AI
    if player_rect.x != enemy1_rect.x:
        if player_rect.x > enemy1_rect.x:
            enemy1_surf = pygame.image.load("enemy1sprites/enemy1_right.png")
            enemy1_surf = pygame.transform.rotozoom(enemy1_surf, 0, 2.5)
            enemy1_rect.x += 2
        elif player_rect.x < enemy1_rect.x:
            enemy1_surf = pygame.image.load("enemy1sprites/enemy1_left.png")
            enemy1_surf = pygame.transform.rotozoom(enemy1_surf, 0, 2.5)
            enemy1_rect.x -= 2

    # Collision with enemy
    if player_rect.x == enemy1_rect.x:
        enemy1_surf = pygame.image.load("enemy1sprites/enemy1_left.png")
        enemy1_surf = pygame.transform.rotozoom(enemy1_surf, 0, 2.5)
        health -= 0.03
        print(int(health))
        health_display = health_font.render(f"Health {int(health)}", True, (0, 0, 0))
        pygame.display.update()

    # Player Attacking
    if player_rect.x >= enemy1_rect.x + 200:
        print("test")

    elif player_rect.x <= enemy1_rect.x - 200:
        print('test')

    # Attacking
    else:
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                enemy1_hp -= 1

    pygame.display.update()
    clock.tick(60)

I was expecting to see it work all the time but sometimes it works and about 25%-50% of the time it doesn't...

A: The enemy always moves by 2, so you must stop moving the enemy if the distance to the target is less than 2. Therefore, move the enemy only when the distance to the player is greater than or equal to 2:
if player_rect.x != enemy1_rect.x:
if abs(player_rect.x - enemy1_rect.x) >= 2:


text:
Q: jsonschemavalidator.net is failing to match dateTime pattern I am trying to validate JSON file against this schema including dateTime regex pattern:
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://example.com/product.schema.json",
  "title": "title",
  "type": "object",
  "properties": {
    "entries": {
      "description": "date time entries",
      "type": "array",
      "contains": {
        "type": "object"
      },
      "items": {
        "type": "object",
        "properties": {
          "dateTime": {
            "description": "UTC timestamp in format \"YYYY-MM-DDThh:mm:ssTZD\" according to ISO 8601",
            "type": "string",
            "pattern": "^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]{3})?(?:Z|[+-][01][0-9]:[0-5][0-9])?$"
          }
        }
      }
    }
  }
}

When I try to validate this JSON file:
{
  "description": "date time entries",
  "entries": [
    {
      "dateTime": "2020-10-09T08:48:41.348+02:00"
    },
    {
      "dateTime": "2020-10-09T08:48:52.240+02:00"
    }
  ]
}

I get the following error regarding second entry in the array:
String '2020-10-09T06:48:52.24+00:00' does not match regex pattern '^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]{3})?(?:Z|[+-][01][0-9]:[0-5][0-9])?$'.
Please note, that the validator correctly validated 1st entry: "2020-10-09T08:48:41.348+02:00".
What I noticed is that the problem is with entries containing milliseconds with "0" at the end, like: ".240"


text:
Q: How to exclude worksheets with "- Matrix" at the end of their name? I have a code which I want to apply on multiple worksheets.
I want to exclude "Data" and all the worksheets containing "- Matrix".
I used * wildcard to select these worksheets though it doesn't work.
Sub DoForSheets()
    Dim xwks As Worksheet
    Application.ScreenUpdating = False
    For Each xwks In Worksheets
        If xwks.Name <> "Data" And xwks.Name <> "* - Matrix" Then
           Debug.Print xwks.Name
        End If
    Next
    Application.ScreenUpdating = True
End Sub

A: Instr will do the Job for you.
Try:
Sub DoForSheets()

    Dim xwks As Worksheet
    Application.ScreenUpdating = False
    For Each xwks In Worksheets
        If xwks.Name <> "Data" And Not InStr(1, xwks.Name, "- Matrix") > 0 Then
           Debug.Print xwks.Name
        End If
    Next
    Application.ScreenUpdating = True

End Sub

Doesn't Matter where the - Matrix is in the Name. This will not Fail

A: Use the Right function:
 Right(xwks.Name, 6) = "Matrix" 'returns True if right hand side of the string is "Matrix"

There is also Left and  Mid


text:
Q: Return lexicographically maximum possible proper string Obtain a proper string that is lexicographically maximum. In one operation, you can swap a character It is given that a string is called a proper string if it has equal counts of 'a','b','c','d'. You can swap a character of the string with any of 'a','b','c','d'.
    import java.util.*;
class Main
{
static int MAX = 26;
static String smallestStr(char []str, int n)
{
    int i, j = 0;
    int []chk = new int[MAX];
    for (i = 0; i < MAX; i++)
        chk[i] = -1;
    for (i = 0; i < n; i++)
    {
        if (chk[str[i] - 'a'] == -1)
            chk[str[i] - 'a'] = i;
    }
    for (i = 0; i < n; i++)
    {
        boolean flag = false;
        for (j = 0; j < str[i] - 'a'; j++)
        {
            if (chk[j] > chk[str[i] - 'a'])
            {
                flag = true;
                break;
            }
        }
        if (flag)
            break;
    }
    if (i < n)
    {
        char ch1 = str[i];
        char ch2 = (char) (j + 'a');
        for (i = 0; i < n; i++)
        {
            if (str[i] == ch1)
                str[i] = ch2;

            else if (str[i] == ch2)
                str[i] = ch1;
        }
    }

    return String.valueOf(str);
}

public static void main(String[] args)
{
    String str = "aacacbbc";
    int n = str.length();
    System.out.println(smallestStr(
                    str.toCharArray(), n));
}
}

The output is supposed to be  dadacbbc
but my output is aababccb


text:
Q: Insert copy of a row multiple times with 1 column changed I have the table
+---------------------+
| ID | Code | Amount  |
+---------------------+
| 1  | 101  | 1.2     |
| 2  | 101  | 1.3     |
| 3  | 101  | 1.3     |
| 4  | 101  | 1.4     |
| 5  | 101  | 1.2     |
| 6  | 101  | 1.5     |
| 7  | 101  | 1.4     |
| 8  | 101  | 1.3     |
| 9  | 101  | 1.1     |
| 10 | 101  | 1.0     |
+---------------------+

I am trying to copy each row with a unique ID around 20 times and changing
So my output should be like this.
+---------------------+
| ID | Code | Amount -|
+---------------------+
| 1  | 101  | 1.2     |
| 1  | 102  | 1.2     |
| 1  | 103  | 1.2     |
| 1  | 104  | 1.2     |
| 1  | 105  | 1.2     |
| 1  | 106  | 1.2     |
| 1  | 107  | 1.2     |
| 1  | 108  | 1.2     |
| 1  | 109  | 1.2     |
| 1  | 110  | 1.2     |
| 1  | 115  | 1.2     |
| 1  | 118  | 1.2     |
| 1  | 121  | 1.2     |
| 1  | 119  | 1.2     |
| 2  | 101  | 1.3     |
| 2  | 102  | 1.3     |
| 2  | 103  | 1.3     |
| 2  | 104  | 1.3     |
+---------------------+

And so on for the table. The codes are going to be the same for each ID. They are not in an order like my example table above so I will need to hard code them in somewhere. There is 20 more codes I need to add for each ID. The amount will be the same. The ID will be the same. But the code is always going to be different.
I need to update this table to reflect this.
I am having trouble doing it. I can copy the row once. And then change the code. But I can only do that for the first ID and I cannot do any more. Help is very much apreciated.
Thanks,

A: Create a simple 1-column table with the additional codes.
CREATE TABLE AdditionalCodes (Code int)

INSERT INTO AdditionalCodes VALUES (102), (103), (104), (105)

Now all you have to do is join this table with the original table, and insert the result.
INSERT INTO MyTable (ID, Code, Amount)
SELECT t.ID, c.Code, t.Amount
FROM MyTable t, AdditionalCodes c

A: You can use a CTE or subquery to define the codes.  Here is a method using VALUES():
select t.id, c.code, t.amount
from thetable t cross join
     (values(101), (102), (103), . . . ) codes(code);


text:
Q: root user can't create a file in /usr/lib I am trying to follow this advice from stackoverflow and copy some library files from /usr/local/Cellar/openssl/1.0.1c to /usr/lib/.
I have tried cp, ln -s and even touch, but they all fail. I am using the root credentials:
joyce# whoami
root

In the right directory:
joyce# pwd
/usr/lib

But no write operation is permitted:
joyce# cp /usr/local/Cellar/openssl/1.0.2e_1/lib/libssl.1.0.0.dylib .
cp: ./libssl.1.0.0.dylib: Operation not permitted
joyce# ln -s /usr/local/Cellar/openssl/1.0.2e_1/lib/libssl.1.0.0.dylib .
ln: ./libssl.1.0.0.dylib: Operation not permitted
joyce# touch blah
touch: blah: Operation not permitted

Any idea how can I write to /usr/lib as root?

A: /usr/lib is protected by SIP. Even if this wouldn't be the case, it's not the best idea to put your own stuff there as any system upgrade can wipe it.
The better place to store such stuff (or link to it) is /usr/local/lib. You may need to pass appropriate flags to the linker then (or you point it directly to the Cellar folder).


text:
Q: Newbie Neo4j issue about Match/with clause So Imagine that in my you have a relationship [event] --> [person]
and this event can have many relationships to the same person. For example:
   /-----------\
  /---------v   v
event----->[person]
  \---------^

In this case we have an event have 3 relations with this [person] node.
(There may be many occurrences of this)
My problem is only selecting the ones with more then x of the same relationship.
Right now I have the query.
MATCH (e:Event)-[r:FOLLOWS]->(f:Follows { name: "ExamplePerson"})
with e, count(r) as alias
where alias > 3
return e, alias

But this is returns total relationships for example:
   /------------- \
  /------------v   v
event----->[person1]
  \---------^
   \---------->[person2]

= 4 instead of 3.
 I have also tried the following:
MATCH (e:Event)-[r:FOLLOWS]->(f:Follows { name: "ExamplePerson"})
with e, count((e:Event)-[r:FOLLOWS]->(f:Follows { name: "ExamplePerson"})) as alias
where alias > 3
return e, alias

Without success what  am I doing wrong?

A: Try grouping for the same person, such as this change into your 1st attempt:
MATCH (e:Event)-[r:FOLLOWS]->(f:Follows { name: "ExamplePerson"})
with e, f, count(r) as alias
where alias > 3
return e, f, alias


text:
Q: Google map displaying in jquery pop up window I use jQuery 1.7 my web site, i need to show a google Map in a lightbox.
for example : http://dev.visualdrugs.net/mootools/gmapsoverlay/
Can you help me to do the same with jQuery.
Thanks

A: Here is a link to some instructions on one way to do this using jQuery Colorbox:
http://www.primecut.gr/2011/06/colorbox-with-google-maps/
Here is some simple code to this. This requires jQuery and the Colorbox plugin (JavaScript and CSS).
HTML
<a class="googleMapPopUp" href="https://maps.google.com.au/maps?q=south+australia" target="_blank">
    View location map
</a>

JavaScript
$('.googleMapPopUp').each(function() {
    var thisPopup = $(this);
    thisPopup.colorbox({
        iframe: true,
        innerWidth: 400,
        innerHeight: 300,
        opacity: 0.7,
        href: thisPopup.attr('href') + '&ie=UTF8&t=h&output=embed'
    });
});

Demo


text:
Q: C/C++: How does this inline if get parsed? Consider this code:
int main()
{
    cout << true ? "Yes" : "No";
    return 0;
}

Its output will be 1 , not Yes or No. Why is it that true is sent to the output stream instead of the Yes or No strings? How does the rest of the inline if get parsed?

A: It has to do with order of operations.  It's the same as:
  (cout << true) ? "Yes" : "No";

cout << true returns an ostream&, which must have a conversion to bool or an equivalent.  The result of ?: is thrown away.
If this seems odd (why this precedence?), just remember that ostream's operator<< is an overload introduced in C++ code, which doesn't allow precedence changing.  The precedence of << is designed for what makes sense for bit-shifting.  Its use as a streaming operator came much later.
Edit: Probably converting to (void*) using this:  http://www.cplusplus.com/reference/iostream/ios/operator_voidpt/


text:
Q: Does GPIO.IN need to be linked to GPIO.OUT in RPi.GPIO in order for it to work properly? I was writing code on an raspbian emulator with GPIO. I am able to get it to work, but for some reason when I change the order of GPIO.HIGH and the print statement in the conditionals, it does not run properly and stops after the first click. Anyone know if this is an issue with the emulator or just a property of raspberry pi and hooking it up to hardware? It also does not work at all if I do not link the GPIO.IN with a GPIO.OUT.
this gif shows what happens when I change order or remove - It turns on the first time, but it does not turn off or on again after that. It for some reason breaks it out of the while loop.

Here is the code I am using:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
import time
#initialise a previous input variable to 0 (assume button not pressed last)
prev_input = 0
prev_input1 = 0

inputs = [11, 13, 15]
outputs = [3, 5, 7]
GPIO.setup(inputs, GPIO.IN)
GPIO.setup(outputs, GPIO.OUT)

secs = 0

def main():
  while True:
    button_press(15, 7)
    timer = add_secs(11, 5, 2)
    #print(timer)

def button_press(button1, button2):
  #take a reading
  global prev_input
  inputa = GPIO.input(button1)
  #if the last reading was low and this one high, print
  if ((not prev_input) and inputa):
    print("Light on")
    GPIO.output(button2, GPIO.HIGH)   #code does not work if I remove/reorder this statement
  if((not inputa) and prev_input):
    print("Light off")
    GPIO.output(button2, GPIO.LOW)      #code does not work if I remove/reorder this statement
  #update previous input
  prev_input = inputa
  #slight pause to debounce
  time.sleep(0.05)

def add_secs(button1, button2, num):
  global prev_input1
  secs = 0
  inputa = GPIO.input(button1)
  if((not prev_input1) and inputa):
    secs = num
    print(secs)
    GPIO.output(button2, GPIO.LOW)      #code does not work if I remove/reorder this statement
  prev_input1 = inputa
  time.sleep(0.05)
  return secs

main()

A: I contacted the developer of the emulator and he let me know there was an issue with the emulator that is now resolved.
The code runs properly after clearing the browsing data in chrome and re-running the program.