Q: Apache Wicket replace fragements of the RIA application (web-site :)) without page refresh we are currently in the process of analyzing different JS and web-frameworks.
We would like to build a DHTML application where you can replace / load content into the website at runtime.
For example:
There is only a "main.html" (or at least one that looks like being a single HTML file for externals) and inside that file I would like to load a login form at runtime.
But WITHOUT page refresh.
I would like to load the HTML into the website dynamically.
http://api.jquery.com/load/ seems to be perfect for that.
However we are also considering using Apache Wicket.
Does Wicket provide a similar mechanism? For me it seems like Wicket can define "static" parts in the website but it does heavily rely on page-refresh to update the website.
Also as a Wicket "newbe" I wonder why there are quite only a few UI components documentated on the Wicket website compared to other UI frameworks.
For me it seems like most people use Wicket + jQuery but never Wicket standalone.
As we already have a REST interface available I wonder what Wicket would offer us at all compared to for example Apache Velocity.
Thanks!
Sebastian

A: It is quite common in Wicket to replace only portions of a page using Ajax.  See these examples.
Wicket is also easily used in combination with jQuery and other JavaScript frameworks.

A: So called single page applications (a single page who's components get constantly replaced and/or updated via ajax) are the way almost every Wicket Apllication I wrote up till now turned out. Most of the Wicket Applications I saw out there relied on a very small number of (or just one) page(s).
The real big advantage of Wicket above jQuery in these use cases is the way in which Wicket offers a non-javascript fallback (then relying on page refreshes) with very little additional work (replacing AjaxLinks by AjaxFallbackLinks and adding an if-statement to check which refresh was triggered.


Q: Error in lines.etm(x[[i]], tr.choice = tr.choice[j], col = col[j + (i - : Argument 'tr.choice' and possible transitions must match When trying to plot cif data in R :
plot(cif.kweet) this error pops up:
    "Error in lines.etm(x[[i]], tr.choice = tr.choice[j], col = col[j + (i -  :
  Argument 'tr.choice' and possible transitions must match", what does this mean, how to solve it?
Additional information:
cif.kweet <-etmCIF(Surv(entry, exit, cause !=0) ~ group, data, etype=data$cause, failcode=3)


Q: Cancel IO for pipe I 'm using the CreatePipe to redirect stdin/out from a process to my process.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365152(v=vs.85).aspx
This works ok so far. The problem is when I want to terminate the thread that waits for the client process to write something.
I can use CancelIoEx() but this only works in Vista+, and I also want an XP solution. Without CancelIoEx(), ReadFile() in the other thread never returns.
I cannot also use OVERLAPPED ReadFile, for pipes created with CreatePipe do not support it.
Any options?

A: Save a handle to the write end of the stdout pipe when creating the child process. You can then write a character to this to unblock the thread that has called ReadFile (that is reading from the read end of the stdout pipe). In order not to interpret this as data, create an Event (CreateEvent) that is set (SetEvent) in the thread that writes the dummy character, and is checked after ReadFile returns. A bit messy, but seems to work.
/* Init */

stdout_closed_event = CreateEvent(NULL, TRUE, FALSE, NULL);

/* Read thread */

read_result = ReadFile(stdout_read, data, buf_len, &bytes_read, NULL);
if (!read_result)
    ret = -1;
else
    ret = bytes_read;
if ((bytes_read > 0) && (WAIT_OBJECT_0 == WaitForSingleObject(stdout_closed_event, 0))) {
    if (data[bytes_read-1] == eot) {
        if (bytes_read > 1) {
            /* Discard eot character, but return the rest of the read data that should be valid. */
            ret--;
        } else {
            /* No data. */
            ret = -1;
        }
    }
}

/* Cancel thread */

HMODULE mod = LoadLibrary (L"Kernel32.dll");
BOOL WINAPI (*cancel_io_ex) (HANDLE, LPOVERLAPPED) = NULL;
if (mod != NULL) {
    cancel_io_ex = (BOOL WINAPI (*) (HANDLE, LPOVERLAPPED)) GetProcAddress (mod, "CancelIoEx");
}
if (cancel_io_ex != NULL) {
    cancel_io_ex(stdout_write_pipe, NULL);
} else {
    SetEvent(stdout_closed_event);
    WriteFile(stdout_write_pipe, &eot, 1, &written, NULL);
}


Q: Run GitHub Actions workflows Jobs on 2 runners parallelly at a time I'm using GitHub actions to copy the artifact to the runner/VM, here I added my VM as a self-hosted runner and ran the workflow directly on the runner. I'm downloading the artifact from artifactory and copying it to the deployment location, Now, I Need to do the same thing on another runner/VM as I have an identical deployment VM for the application.
To achieve this, I have copied the same job and changed the 'runs-on' value with a different runner name which is my second VM. below is my workflow code snippet.
My question is, Instead of 2 jobs, how can we run using a single job for all VMs related to dev? let's say, Assume that I have 4 VMs for the Dev environment and 3 VMs for QA, and 5 VMs for Production
can someone help with this or do we need to continue with the same approach as whatever I'm doing right now?
I have tried matrix but looking to see if there is any other solution
name: Deployment_workflow

on:
  workflow_dispatch:
    inputs:
      dev:
        type: boolean
        required: false
        default: false
      qa:
        type: boolean
        required: false
        default: false
jobs:
    dev_deploy_1:
      if: github.event.inputs.dev =='true'
      runs-on: dev-vm-1
      steps:
        - name: Download the artifact from artifactory
          run: |
            cd /tmp
            curl -u ${ARTIFACTORY_USER}:${ARTIFACTORY_ENCRYPT} -T dep-deploy-1.war "$(ARTIFACTORY_URL)/artifactory/general-artifacts/dep-deploy-1.war"
        - name: copy the file from /tmp to deployment location
          run: |
            cp /tmp/dep-deploy-1.war /var/lib/app_deploy_dir

    dev_deploy_2:
      if: github.event.inputs.dev =='true'
      runs-on: dev-vm-2
      steps:
        - name: Download the artifact from artifactory
          run: |
            cd /tmp
            curl -u ${ARTIFACTORY_USER}:${ARTIFACTORY_ENCRYPT} -T dep-deploy-2.war "$(ARTIFACTORY_URL)/artifactory/general-artifacts/dep-deploy-2.war"
        - name: copy the file from /tmp to deployment location
          run: |
            cp /tmp/dep-deploy-1.bar /var/lib/app_deploy_dir


Q: Read a PEM file with Flutter API encrypt import 'package:encrypt/encrypt.dart';
import 'package:encrypt/encrypt_io.dart';
import 'dart:io';
import 'package:pointycastle/asymmetric/api.dart';
import 'dart:async';
import 'package:flutter/services.dart' show rootBundle;

class Encrypt {
  Future<String> loadPrivateKey() async {
    return await rootBundle.loadString('assets/private_key.pem');
  }

  Future<String> loadPublicKey() async {
    return await rootBundle.loadString('assets/public_key.pem');
  }

  encryptString() async {
    print(loadPublicKey().toString());
    final publicKey =
        await parseKeyFromFile<RSAPublicKey>('${loadPublicKey()}');
    final privateKey =
        await parseKeyFromFile<RSAPrivateKey>('${loadPrivateKey()}');

    final plainText = 'James Bond';
    final encrypter =
        Encrypter(RSA(publicKey: publicKey, privateKey: privateKey));

    final encrypted = encrypter.encrypt(plainText);
    final decrypted = encrypter.decrypt(encrypted);

    print(decrypted);
    print(encrypted.base64);
  }
}

ERROR:
Performing hot reload...
Syncing files to device AOSP on IA Emulator...
Reloaded 8 of 707 libraries in 1,021ms.
I/flutter ( 7395): Instance of 'Future'
E/flutter ( 7395): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Cannot open file, path = 'Instance of 'Future'' (OS Error: No such file or directory, errno = 2)
I did add assets in yaml file as:
flutter:
  assets:
    - assets/

A: parseKeyFromFile is a convenience function that reads a file and parses the contents. You don't have a file, you have an asset that you are already doing the work of reading into a string. Having read the file, it just parses it - and that's what you need.
This should work:
final publicPem = await rootBundle.loadString('assets/public_key.pem');
final publicKey = RSAKeyParser().parse(publicPem) as RSAPublicKey;

and similar for the private key.


Q: Using Vagrant to manage AWS instances For some time I am managing EC2 (Windows Boxes), RDS and S3 on AWS.
I do know manual steps that must be made in order to set up lets say a normal box (DB, Storage and Server. I heard about Vagrand, but everywhere I looked it mainly talks about Linux boxes on AWS.
My main question is: Is Vagrand a tool that will save me time for deyploment (windows), or should I not use it at all (in Windows scenario).

A: Vagrant plays nicely with AWS (via vagrant-aws plugin).
Vagrant seems to play nicely with Windows as well since version 1.6 and the introduction of WinRM support (ssh alternative for Windows).
However AWS plugin doesn't support WinRM communicator yet. So you'll need to pre-bake your Windows AMIs with SSH service pre installed, if you want vagrant to provision it.
Update (29/03/2016): Thanks to Rafael Goodman for pointing to vagrant-aws-winrm plugin as a possible workaround.


Q: Entity Framework - Challenging setup includes multiple primary keys, and multiple associations to foreign table I'm trying to map a couple of legacy tables using Entity Framework. The classes look like this...
public class Customer
{
    [Key, Required]
    public string Code { get; set; }

    public string Domain { get; set; }

    public virtual Address BillToAddress { get; set; }

    public virtual ICollection<Address> ShipToAddresses { get; set; }
}

public class Address
{
    [Column(Order = 0), Key, Required]
    public string Code { get; set; }

    [Column(Order = 1), Key, Required]
    public string Domain { get; set; }

    public string Type { get; set; }

    public string CustomerReferenceCode { get; set; }
}

Each Customer has one "BillToAddress" that corresponds with an Address whose CustomerReferenceCode contains the Customer's Code and where the Type field contains the text "Customer"
Each Customer has zero or more "ShipToAddresses" that correspond to Addresses whose CustomerReferenceCode contains the Customer's Code and whose where the Type fields contain the text "Ship-To"
I'm able to reference the BillToAddress by adding
[Key, Required]
[ForeignKey("BillToAddress"), Column(Order = 1)]
public string Code { get; set; }

[ForeignKey("BillToAddress"), Column(Order = 2)]
public string Domain { get; set; }

But I've not been able to figure out how to reference the collection of ShipToAddresses for the customer.

A: See this example (note it is separate classes): Fluent NHibernate automap inheritance with subclass relationship
One easy approach might be:
public class Customer
{
[Key, Required]
public string Code { get; set; }

public string Domain { get; set; }

public virtual ICollection<Address> Addresses{ get; set; }

public virtual Address BillToAddress { get { Addresses.Where(n=>n.Type = Address.BillingAddress)).Single(); }

public virtual ICollection<Address> ShipToAddresses { get { Addresses.Where(n=>n.Type = Address.ShipToAddress)); }
}

One additional comment - this is not implicitly forcing your one Billing address business logic as the example you start with does, so you either need to enforce that elsewhere with the above approach. Also, creating two classes and using TPH as described in the example I link to is the approach I would likely take anyway - which would meet your described goal above directly. Also, in between the two, this may work, using the discriminator in the getter of each property directly.


Q: Python Regex Capturing Multiple Matches in separate observations I am trying to create variables location; contract items; contract code; federal aid using regex on the following text:
    PAGE    1

                BID OPENING DATE    07/25/18    FROM 0.2 MILES WEST OF ICE HOUSE        07/26/18 CONTRACT NUMBER    03-2F1304   ROAD TO 0.015 MILES WEST OF CONTRACT CODE 'A '

            LOCATION    03-ED-50-39.5/48.7  DIVISION HIGHWAY ROAD   44 CONTRACT ITEMS

        INSTALL SANDTRAPS AND PULLOUTS  FEDERAL AID ACNH-P050-(146)E

PAGE    1

                    BID OPENING DATE    07/25/18    IN EL DORADO COUNTY AT VARIOUS          07/26/18 CONTRACT NUMBER     03-2H6804  LOCATIONS ALONG ROUTES 49 AND 193   CONTRACT CODE 'C ' LOCATION 03-ED-0999-VAR          13 CONTRACT ITEMS

        TREE REMOVAL    FEDERAL AID NONE

PAGE    1

                BID OPENING DATE    07/25/18    IN LOS ANGELES, INGLEWOOD AND       07/26/18 CONTRACT NUMBER    07-296304   CULVER CITY, FROM I-105 TO PORT CONTRACT CODE 'B '

            LOCATION    07-LA-405-R21.5/26.3    ROAD UNDERCROSSING  55 CONTRACT ITEMS

        ROADWAY SAFETY IMPROVEMENT  FEDERAL AID ACIM-405-3(056)E

This text is from one word file; I'll be looping my code on multiple doc files. In the text above are three location; contract items; contract code; federal aid pairs. But when I use regex to create variables, only the first instance of each pair is included.
The code I have right now is:
# imports
import os
import pandas as pd
import re
import docx2txt
import textract
import antiword

all_bod = []
all_cn = []
all_location = []
all_fedaid = []
all_contractcode = []
all_contractitems = []
all_file = []

text = '    PAGE    1

            BID OPENING DATE    07/25/18    FROM 0.2 MILES WEST OF ICE HOUSE        07/26/18 CONTRACT NUMBER    03-2F1304   ROAD TO 0.015 MILES WEST OF CONTRACT CODE 'A '

        LOCATION    03-ED-50-39.5/48.7  DIVISION HIGHWAY ROAD   44 CONTRACT ITEMS

    INSTALL SANDTRAPS AND PULLOUTS  FEDERAL AID ACNH-P050-(146)E

PAGE    1

                BID OPENING DATE    07/25/18    IN EL DORADO COUNTY AT VARIOUS          07/26/18 CONTRACT NUMBER     03-2H6804  LOCATIONS ALONG ROUTES 49 AND 193   CONTRACT CODE 'C ' LOCATION 03-ED-0999-VAR          13 CONTRACT ITEMS

    TREE REMOVAL    FEDERAL AID NONE

    PAGE    1

            BID OPENING DATE    07/25/18    IN LOS ANGELES, INGLEWOOD AND       07/26/18 CONTRACT NUMBER    07-296304   CULVER CITY, FROM I-105 TO PORT CONTRACT CODE 'B '

        LOCATION    07-LA-405-R21.5/26.3    ROAD UNDERCROSSING  55 CONTRACT ITEMS

    ROADWAY SAFETY IMPROVEMENT  FEDERAL AID ACIM-405-3(056)E'

bod1 = re.search('BID OPENING DATE \s+ (\d+\/\d+\/\d+)', text)
bod2 = re.search('BID OPENING DATE\n\n(\d+\/\d+\/\d+)', text)

if not(bod1 is None):
    bod = bod1.group(1)
elif not(bod2 is None):
    bod = bod2.group(1)
else:
    bod = 'NA'

all_bod.append(bod)

# creating contract number
cn1 = re.search('CONTRACT NUMBER\n+(.*)', text)
cn2 = re.search('CONTRACT NUMBER\s+(.........)', text)

if not(cn1 is None):
   cn = cn1.group(1)
elif not(cn2 is None):
   cn = cn2.group(1)
else:
   cn = 'NA'

all_cn.append(cn)

# location

location1 = re.search('LOCATION \s+\S+', text)
location2 = re.search('LOCATION \n+\S+', text)

if not(location1 is None):
    location = location1.group(0)
elif not(location2 is None):
    location = location2.group(0)
else:
    location = 'NA'

all_location.append(location)

# federal aid

fedaid = re.search('FEDERAL AID\s+\S+', text)
fedaid = fedaid.group(0)

all_fedaid.append(fedaid)

# contract code

contractcode = re.search('CONTRACT CODE\s+\S+', text)
contractcode = contractcode.group(0)

all_contractcode.append(contractcode)

# contract items

contractitems = re.search('\d+ CONTRACT ITEMS', text)
contractitems = contractitems.group(0)

all_contractitems.append(contractitems)

This code parses the only first instance of these variables in the text.

contract-number
location
contract-items
contract-code
federal-aid

03-2F1304
03-ED-50-39.5/48.7
44
A
ACNH-P050-(146)E

But, I am trying to figure out a way to get all possible instances in different observations.

contract-number
location
contract-items
contract-code
federal-aid

03-2F1304
03-ED-50-39.5/48.7
44
A
ACNH-P050-(146)E

03-2H6804
03-ED-0999-VAR
13
C
NONE

07-296304
07-LA-405-R21.5/26.3
55
B
ACIM-405-3(056)E

The all_variables in the code are for looping over multiple word files - we can ignore that if we want :).
Any leads would be super helpful. Thanks so much!

A: import re
data = []
df = pd.DataFrame()

regex_contract_number =r"(?:CONTRACT NUMBER\s+(?P<contract_number>\S+?)\s)"
regex_location = r"(?:LOCATION\s+(?P<location>\S+))"
regex_contract_items = r"(?:(?P<contract_items>\d+)\sCONTRACT ITEMS)"
regex_federal_aid =r"(?:FEDERAL AID\s+(?P<federal_aid>\S+?)\s)"
regex_contract_code =r"(?:CONTRACT CODE\s+\'(?P<contract_code>\S+?)\s)"
regexes = [regex_contract_number,regex_location,regex_contract_items,regex_federal_aid,regex_contract_code]

for regex in regexes:
    for match in re.finditer(regex, text):
        data.append(match.groupdict())
    df = pd.concat([df, pd.DataFrame(data)], axis=1)
    data = []

df


Q: OpenLayers.js which files to use? As i red from the readme file, openlayers.js has multiple choices for including files and themes.
What i would like is to use the lightest solution of openlayers.js files.
I included the openlayers.light.js in my app, and it creates maps but do not show them, check this:

do i forgot to include some other file?
my structure structure is this:
/vendor
   /js
     openlayers.light.js
     /img
     /theme

how to show maps layers?
Also does the openlayers.light.js will work on mobile devices (once fixed this problem :P )? or i'll need to include openlayers.mobile.js too?
This is the code not working with openlayers.light.js but working with openlayers.js (740kb) :
var _element = "#map";
 var map = new OpenLayers.Map (_element, {
    controls: [
    new OpenLayers.Control.Navigation({
      dragPanOptions: {
        enableKinetic: true
      }
    }),
    new OpenLayers.Control.Zoom()
    ],
    projection: new OpenLayers.Projection("EPSG:900913"),
    displayProjection: new OpenLayers.Projection("EPSG:4326")
  });

  var lonLat = new OpenLayers.LonLat(_lon, _lat).transform (
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
// map.getProjectionObject() doesn't work for unknown reason
);
  var markers = new OpenLayers.Layer.Markers( "Markers" );
  map.addLayer(markers);

  var size = new OpenLayers.Size(21,25);
  var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
  var icon = new OpenLayers.Icon(_img_map_marker, size, offset);
  markers.addMarker(new OpenLayers.Marker(lonLat, icon.clone()));

  var mapnik = new OpenLayers.Layer.OSM("Test");
  map.addLayer(mapnik);

  map.setCenter (lonLat,3);

PS: my openlayers map js init method is ok, it works using the huge openlayers.js (740KB), but not working with openlayers.light.js as i showed above
html

css
img{max-width:none;}
#map{
width:300px;
height:300px;
}

A: if you want to use mobile properties with openlayers as panning or zooming with hand you have to use openlayers.mobile.js.
you can use openlayers.light.js with mobile devices but not mobile functions.
i think your structure should be :
myProject
   /js
      openlayers.light.js
   /img
   /theme

and i have tried openlayers.light.js in http://jsfiddle.net/aragon/ZecJj/ and there is no problem with it.
My code:
var map = new OpenLayers.Map({
    div: "map",
    minResolution: "auto",
    maxResolution: "auto",
});

var osm = new OpenLayers.Layer.OSM();
var toMercator = OpenLayers.Projection.transforms['EPSG:4326']['EPSG:3857'];
var center = toMercator({x:-0.05,y:51.5});
map.addLayers([osm]);

map.setCenter(new OpenLayers.LonLat(center.x,center.y), 13);

and try to read Deploying (Shipping OpenLayers in your Application).

OpenLayers comes with pre-configured examples out of the box: simply
  download a release of OpenLayers, and you get a full set of easy to
  use examples. However, these examples are designed to be used for
  development. When you’re ready to deploy your application, you want a
  highly optimized OpenLayers distribution, to limit bandwidth and
  loading time.

you can change src file with this link and can see it still works.

to

i hope it helps you...


Q: Need to sort complex objects, like dominoe Here is a situation. For example I have a structure like this (code is simplified):
class Dominoe
{
    ctor Dominoe(left, right)

    string LeftSide;
    string RightSide;
}

And I have data, somewhat like this:
Dominoe("2", "3"), Dominoe("1", "2"), Dominoe("4", "5"), Dominoe("3", "4")

I know that there won't be any gaps in dominoes, nor repeats.
I need to order this collection, so every RightSide would be connected to appropriate LeftSide. Like so:
Dominoe("1", "2"), Dominoe("2", "3"), Dominoe("3", "4"), Dominoe("4", "5")

Values - not numbers. Just need a clue.
Right now I've done this task in 2 steps. Primary - i'm looking for the entry point. The dominoe which have LeftSide not presented in any other Dominoe RightSide. After that i switch it with 0 index item. Secondly - i'm looking for next dominoe which have LeftSide same as RightSide of my entry dominoe and so on in cycle.
I'm doing this in C#, but this really doesn't matter.
The problem is - i don't think it's best algorithm. Any ideas will be great. Thx.
EDITED !
Was my bad to talk about numbers.
Let's change Dominoe for trevel cards.
So it'll be like:
TravelCard ("Dublin", "New York"), TravelCard ("Moscow", "Dublin"), TravelCard ("New York", "Habana")

A: Unless you have huge amount of your cards your solution will work. Otherwise you can consider 2 dictionaries to make searches constants and keep O(N) complexity:
namespace ConsoleApplication
{
    public class Dominoe
    {
        public Dominoe(int left, int right)
        {
            LeftSide = left;
            RightSide = right;
        }

        public int LeftSide;
        public int RightSide;
    }

    class Program
    {
        static void Main(string[] args)
        {
            var input = new List<Dominoe>()
            {
                new Dominoe(2, 3),
                new Dominoe(1, 2),
                new Dominoe(4, 5),
                new Dominoe(3, 4)
            };

            var dicLeft = new Dictionary<int, Dominoe>();
            var dicRigth = new Dictionary<int, Dominoe>();

            foreach (var item in input)
            {
                dicLeft.Add(item.LeftSide, item);
                dicRigth.Add(item.RightSide, item);
            }

            Dominoe first = null;

            foreach(var item in input)
            {
                if (!dicRigth.ContainsKey(item.LeftSide))
                {
                    first = item;
                    break;
                }
            }

            Console.WriteLine(string.Format("{0} - {1}", first.LeftSide, first.RightSide));

            for(int i = 0; i < input.Count - 1; i++)
            {
                first = dicLeft[first.RightSide];
                Console.WriteLine(string.Format("{0} - {1}", first.LeftSide, first.RightSide));
            }

            Console.ReadLine();
        }
    }
}


Q: How to cache a small piece of information in Django I have a website that delivers a list of questions to users. This set of questions is the same for all users. I have these questions stored in a text file. The content of this file will not change while the server is running.
I cannot use a static page to display these questions because I have some logic to decide when to show which question.
I would like to cache these questions in memory (instead of reading the file off the hard drive every time a user connects). I am using Django 1.7.
I did read about caching from Django's website, I think the suggested methods (like memcached and database) are too heavy for my need. What would be a good solution for my situation? use a global variable?
Thanks!

A: There are so many caching back-ends you can use as listed in https://docs.djangoproject.com/en/1.7/topics/cache/
I haven't tried the file system or local memory caching myself, I always needed memcached, but looks like they're available, and the rest is a piece of cake!
from django.core import cache

cache_key = 'questions'
questions = cache.cache.get(cache_key) # to get
if questions:
  # use questions you fetched from cache
else:
  questions = { 'question1': 'How are you?'} #Something serializable that has your questions
  cache.cache.set(cache_key, questions)


Q: XAMPP 7.0.0 php session causing whole page not to load Before upgrading to XAMPP 7, everything used to work fine.
Then after the update, everything except php sessions is working.
Any page with session_start() does not load in the browser and nothing is logged into php.log file concerning the error.
I've looked everywhere for such, and I found one here on Stackoverflow that had a similar problem, but the issue had been using MySQL.
Now, at the very basic level, this won't load:
<?php
   session_start();
?>

I've tried changing the session.save_path in php.ini file without any success. Any help?


Q: Automatically sync 2 writable git repositories I am working in a small office, where we are using git with a central repository at a windows share, where we can PUSH to and PULL from.
To be able to work from home, travel etc, we want to have a possibility to reach a central repo from "the outside world". Our internet connection is very, very slow, so it is no possibility to have just one central repository "inside" or "outside".
My simple attempt was the following:

*

*Make a central repository at the internal WIN network share: git init --bare

*Make one "outside" (e.g. github or an external WIN share or anything else)

*At the internal repo call git remote add EXTERNALREPO <pathToIt>

*and make a batch running every x minutes/hours, saying git fetch --tags EXTERNALREPO, git push --tags EXTERNALREPO
When working "inside", clone/push/pull the internal repo, when on the road, use the external repo for that.
Question: Is this the way to go, is there a better way, or am I completely wrong?
Related:

*

*Two-way git mirror –
I do not think that wee need locking as we are not so many people.

*Safe master-master setup with git? (writable git mirror)

*How to keep 2 git repositories in sync automatically – As far as I know, a push lasts as long as it take to run all the hooks, AND since using a windows share, the CLIENT has to run it, so it wouldn't be a solution.

Update 1: I now came up with a slightly adjusted configuration.

*

*INTERNAL repo on an internal Windows Share: git init --bare

*EXTERNAL repo on an external Windows Share: git init --bare

*Both repos:
git config receive.denyNonFastForwards 1
git config receive.denyDeletes 1
git remote add {INTERNAL|EXTERNAL} file:///...

*Every x seconds/minutes/hours, call git push --all {INTERNAL|EXTERNAL} and git push --tags {INTERNAL|EXTERNAL}, at first at the internal, then at the external repository.

A: *

*"repository at a windows share" is The Bad&Ugly Idea (tm)

*Use post-* hook in INTERNAL for pushing to EXTERNAL as it happens

*Pseudo-CVCS in DVCS is ugly (everybody can bring local travel-repo to workplace and sync from it)


Q: Google Cloud Shell - How to resolve CERTIFICATE_VERIFY_FAILED error? I have simple dataflow pipeline and trying to execute from cloud shell,
Code:
from __future__ import print_function
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
with beam.Pipeline(options=PipelineOptions()) as p:
    lines = p | 'Read' >> beam.io.ReadFromText('test.csv')
    lines | 'Write' >> beam.io.WriteToText('gs://bucket/output_20193003', file_name_suffix='.csv')
    result = p.run()
    result.wait_until_finish()

Command used to execute:
python -m simple_pipeline --runner DataflowRunner --project myproject --staging_location gs://bucket/staging --temp_location gs://bucket/temp

Observations:
When executed from Cloud shell I encounter below error,
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/runners/portability/fn_api_runner.py", line 859, in run_stages
    pcoll_buffers, safe_coders).process_bundle.metrics
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/runners/portability/fn_api_runner.py", line 970, in run_stage
    self._progress_frequency).process_bundle(data_input, data_output)
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/runners/portability/fn_api_runner.py", line 1174, in process_bundle
    result_future = self._controller.control_handler.push(process_bundle)
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/runners/portability/fn_api_runner.py", line 1054, in push
    response = self.worker.do_instruction(request)
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/runners/worker/sdk_worker.py", line 208, in do_instruction
    request.instruction_id)
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/runners/worker/sdk_worker.py", line 230, in process_bundle
    processor.process_bundle(instruction_id)
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/runners/worker/bundle_processor.py", line 301, in process_bundle
    op.finish()
  File "apache_beam/runners/worker/operations.py", line 398, in apache_beam.runners.worker.operations.DoOperation.finish
  File "apache_beam/runners/worker/operations.py", line 399, in apache_beam.runners.worker.operations.DoOperation.finish
  File "apache_beam/runners/worker/operations.py", line 400, in apache_beam.runners.worker.operations.DoOperation.finish
  File "apache_beam/runners/common.py", line 598, in apache_beam.runners.common.DoFnRunner.finish
  File "apache_beam/runners/common.py", line 589, in apache_beam.runners.common.DoFnRunner._invoke_bundle_method
  File "apache_beam/runners/common.py", line 618, in apache_beam.runners.common.DoFnRunner._reraise_augmented
  File "apache_beam/runners/common.py", line 587, in apache_beam.runners.common.DoFnRunner._invoke_bundle_method
  File "apache_beam/runners/common.py", line 299, in apache_beam.runners.common.DoFnInvoker.invoke_finish_bundle
  File "apache_beam/runners/common.py", line 302, in apache_beam.runners.common.DoFnInvoker.invoke_finish_bundle
  File "apache_beam/runners/common.py", line 693, in apache_beam.runners.common._OutputProcessor.finish_bundle_outputs
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/io/iobase.py", line 1005, in finish_bundle
    yield WindowedValue(self.writer.close(), window.MAX_TIMESTAMP,
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/io/filebasedsink.py", line 388, in close
    self.sink.close(self.temp_handle)
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/io/filebasedsink.py", line 148, in close
    file_handle.close()
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/io/filesystemio.py", line 201, in close
    self._uploader.finish()
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/io/gcp/gcsio.py", line 553, in finish
    raise self._upload_thread.last_error  # pylint: disable=raising-bad-type
RuntimeError: SSLHandshakeError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661) [while running 'Write/Write/WriteImpl/WriteBundles']

Note: I see this error only from Cloud Shell and the same code and commands works fine when executed from local machine - Using SDK or PyCharm IDE.
What is the problem with my cloud shell? How to fix it? Please suggest.

A: Or try this in cloud shell?
virtualenv --python=/usr/bin/python2 run_pipeline
. ./run_pipeline/bin/activate
pip install apache-beam[gcp]
python -m simple_pipeline --runner DataflowRunner --project myproject --staging_location gs://bucket/staging --temp_location gs://bucket/temp

A: I am able to launch dataflow jobs after upgrading to latest version.
pip install apache-beam[gcp]


Q: PHP duplicating query results? For some reason,when I run this query through PHP, it returns 8 rows, when in reality i only have 2 rows in my database, and when i run it through phpmyadmin it returns 2 obviously.
 $sql = "SELECT url FROM bookmarks,users WHERE bookmarks.user_id = {$session->user_id}";
 $resultado = $db->query($sql);

 echo mysql_num_rows($resultado);

I'm breaking my head!

A: your query produces cartesian product because you have not supplied the relationship between the two tables: bookmarks and users,
SELECT url
FROM   bookmarks
       INNER JOIN users
          ON bookmarks.COLNAME = users.COLNAME
WHERE  bookmarks.user_id = '$session->user_id'

where COLNAME is the column that defines how the table are related with each other, or how the tables should be linked.
To further gain more knowledge about joins, kindly visit the link below:

*

*Visual Representation of SQL Joins
As a sidenote, the query is vulnerable with SQL Injection if the value(s)  of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

*

*How to prevent SQL injection in PHP?

A: As JW pointed out, you are producing a Cartesian Product -- you aren't joining bookmarks against users.  That's why you're duplicating rows.
With that said, you don't need to join users at all in your above query:
"SELECT url FROM bookmarks WHERE bookmarks.user_id = {$session->user_id}"

Good luck.


Q: Intemittent Cannot create ActiveX component Everything was working fine, and then our code starts throwing:
Cannot create ActiveX component when we try to create a com object.
We reboot the server a couple of times and it goes away
Then after a while it comes back
This is driving us nuts.  Any help appreciated.

A: I apologize that the question was vague.  However we had no clue what was causing the problem so what facts would have been relevant?
At any rate it turns out we have two web apps running under IIS, both are trying to create ActiveX components.  As soon as we turn one of the web apps off the problem goes away.
After we verified this behavior, we tried calling some simple ActiveX components (like excel).  Lo and behold exactly the same behavior as long as there are more than two web apps running.
Our solution for now is to host the second web app elsewhere.


Q: Alternative to Cookie Session for different applications within same domain I have 2 different ASP.NET applications on the same domain, different app pools on IIS. Application 1 opens Application 2 using window.open(url). At this stage the cookie is shared among both applications.
Application 2 runs the following code after login:
Context.Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
Context.Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);

The purpose of this code is to prevent Session Fixation vulnerability whereby an attacker could steal the session id pre-login, and use it post-login to authenticate themselves as a legitimate user.
However, this also changes the session id on Application 1, effectively login the user out of the application.
How can I prevent this from happening? and what other approaches could I follow?

A: You could try use JSON web tokens instead
https://www.red-gate.com/simple-talk/dotnet/net-development/jwt-authentication-microservices-net/
https://jwt.io/


Q: Crash with UITabBarController Sometimes I have strange crash when I switch from one tab to another:
0   libobjc.A.dylib                     0x3857e636 objc_msgSend + 22
1   UIKit                               0x3024ca89 -[UIResponder(Internal) _canBecomeFirstResponder] + 21
2   UIKit                               0x3024c7a3 -[UIResponder becomeFirstResponder] + 207
3   UIKit                               0x3024caff -[UIView(Hierarchy) becomeFirstResponder] + 107
4   UIKit                               0x302c946b -[UITextField becomeFirstResponder] + 47
5   UIKit                               0x302ca345 -[UIView(Hierarchy) deferredBecomeFirstResponder] + 57
6   UIKit                               0x301cd441 __45-[UIView(Hierarchy) _postMovedFromSuperview:]_block_invoke + 165
7   Foundation                          0x2e304d33 -[NSISEngine withBehaviors:performModifications:] + 211
8   UIKit                               0x301cd291 -[UIView(Hierarchy) _postMovedFromSuperview:] + 297
9   UIKit                               0x301da01d -[UIView(Internal) _addSubview:positioned:relativeTo:] + 1413
10  UIKit                               0x301d9a93 -[UIView(Hierarchy) addSubview:] + 31
11  UIKit                               0x302bb563 -[UITransitionView transition:fromView:toView:removeFromView:] + 979
12  UIKit                               0x302fb783 -[UITransitionView transition:fromView:toView:] + 31
13  UIKit                               0x302fb759 -[UITransitionView transition:toView:] + 105
14  UIKit                               0x302fa87b -[UITabBarController transitionFromViewController:toViewController:transition:shouldSetSelected:] + 1107
15  UIKit                               0x302fa41f -[UITabBarController transitionFromViewController:toViewController:] + 39
16  UIKit                               0x302fa2f7 -[UITabBarController _setSelectedViewController:] + 259
17  UIKit                               0x303c45c9 -[UITabBarController _tabBarItemClicked:] + 273
18  UIKit                               0x302036c7 -[UIApplication sendAction:to:from:forEvent:] + 91
19  UIKit                               0x30203663 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 39
20  UIKit                               0x303c447f -[UITabBar _sendAction:withEvent:] + 371
21  UIKit                               0x302036c7 -[UIApplication sendAction:to:from:forEvent:] + 91
22  UIKit                               0x30203663 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 39
23  UIKit                               0x30203633 -[UIControl sendAction:to:forEvent:] + 47
24  UIKit                               0x301eed7b -[UIControl _sendActionsForEvents:withEvent:] + 375
25  UIKit                               0x303c41a7 -[UITabBar(Static) _buttonUp:] + 119
26  UIKit                               0x302036c7 -[UIApplication sendAction:to:from:forEvent:] + 91
27  UIKit                               0x30203663 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 39
28  UIKit                               0x30203633 -[UIControl sendAction:to:forEvent:] + 47
29  UIKit                               0x301eed7b -[UIControl _sendActionsForEvents:withEvent:] + 375
30  UIKit                               0x3020307b -[UIControl touchesEnded:withEvent:] + 595
31  UIKit                               0x30202d4d -[UIWindow _sendTouchesForEvent:] + 529
32  UIKit                               0x301fdca7 -[UIWindow sendEvent:] + 759
33  UIKit                               0x301d2e75 -[UIApplication sendEvent:] + 197
34  UIKit                               0x301d1541 _UIApplicationHandleEventQueue + 7121

Maybe for someone this will look familiar and he could help to understand root of problem.

A: I got the same crash log.And my reason is  the view controller is released but the UITextField.delegate is not setting nil. So you can set UITextField.delegate = nil in dealloc of the view controller.


Q: Asking the user about the radius of the circle and will solve the area and the circumference I am making a class similar code to this but I don't know how I will make it into a input function.
How would I ask the user to input a radius of a circle?
class Circle:
    def __init__(self, r):
        self.radius = r
    def area(self):
        return 3.14 * (self.radius ** 2)
    def perimeter(self):
        return 2*3.14*self.radius
obj = Circle(3)
print("Area of circle:",obj.area())
print("Perimeter of circle:",obj.perimeter())

A: You just have to replace the argument to an input function to take input from the user. So the code will be changed from
obj = Circle(3)

to
obj = Circle(int(input("Please Enter Radius:")))

The int() before the input function is to convert the input from string to an integer.
To know more about taking input from user, please check out here.

A: class Circle:
    def __init__(self, r):
        self.radius = r
    def area(self):
        return 3.14 * (self.radius ** 2)
    def perimeter(self):
        return 2*3.14*self.radius
obj = Circle(int(input("Enter Radius:")))
#obj = Circle()
print("Area of circle:",obj.area())
print("Perimeter of circle:",obj.perimeter())


Q: Where to place a data array in zf2 I want to create the following static data array in my zf2 project so that routing and others methods can be done based on department codes, and then view helpers and form select elements in different modules look up the department titles for the user interface.
    $deptList = array(
        '01'  => 'Human Resources',
        '02'  => 'Sales',
        '03'  => 'Marketing',
        '04'  => 'Accounting',
           // ...
    );

In the zf2 directory structure, where should I put this?  Does it need it's own class?
Also, it might be convenient to record this data in a database table instead of hard-coding it.  But I question whether this would affect performance.

A: As there is no registry singleton like in ZF1 creating a service and injecting it where needed is appropriate. You can then place it according to your autoloader configuration in the filesystem.  As well inside that class you could do anything you like to build the array, e.g. using a database for it.
Nevertheless you can as well use your config for it if it is static information - e.g. like this:
Module.php
class Module
{
    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }
}

module.config.php
return [
    'deptList' => [
        '01' => 'Human Resources',
        '02' => 'Sales',
        '03' => 'Marketing',
        '04' => 'Accounting',
        // ...
    ],
];

MyController.php
class MyController extends \Zend\Mvc\Controller\AbstractActionController
{

    public function myAction()
    {
        $config   = $this->getServiceLocator()->get('config');
        $deptList = $config['deptList'];
    }

}


Q: Facebook API Send Message : How to send link I send messages with facebook application, the messages are texts
I want to send link in the message.
This is my code :
$message_to_reply = 'hello';

$ch = curl_init($url);
$jsonData = '{
    "recipient":{
        "id":"' . $sender . '"
    },
    "message":{
        "text":"' . $message_to_reply . '"
    }
}';

$jsonDataEncoded = $jsonData;

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

But it doesnt work.


Q: qTranslate plugin switching language in the same page I have a serious problem with a qTranslate buttons.
Right now the web structure is: http://www.site.com/news/?lang=en
When I stay in the home page and I try to change the language, the botton opens the first post (maybe because I'm using permalink):
<?php if(qtrans_getLanguage()=='it'): ?>

<a href="<?php echo qtrans_convertURL(get_permalink(), 'en'); ?>" >eng

ita

<?php endif; ?>
<?php if(qtrans_getLanguage()=='en'): ?>

eng

<a href="<?php echo qtrans_convertURL(get_permalink(), 'it'); ?>" >ita

<?php endif; ?>

How to solve this without open the last post or come back at the home page, but only switching language in the same page?

A: I'm using qTranslate on my project and I do not do any of that stuff you do in your code above and have no problem switching between languages.
All I do is call qts_language_menu() function that creates language menu, nothing else. This will create necessary links which ables you to switch between languages but stay on the same page.

A: You don't need to use get_permalink()
you can just pass an empty string as url and the language as 2nd param
and the function will do rest !
just like:
$my_translated_content_url = qtrans_convertURL("", "en");

infact if you see at the function definition:
function qtrans_convertURL($url='', $lang='', $forceadmin = false) {
  global $q_config;

  // invalid language
  if($url=='') $url = esc_url($q_config['url_info']['url']); // <-You don't need the url
  if($lang=='') $lang = $q_config['language'];
      [... the function continue...]

A: The links are stored in the $qTranslate_slug object. I made a function to make it easy to get the link for the current page in the desired language:
function getUrlInTargetLanguage($targetLang){
    global $qtranslate_slug;
    return $qtranslate_slug->get_current_url($targetLang);
}

So for example, if you wanted to get the english link, you should write:
getUrlInTargetLanguage("en");

A: May be this late but following good functions to easy call check current language or auto generate any language URL for qTranslate:
// check language
function check_lang() {
    return qtranxf_getLanguage();
}

// Generate language convert URL
function get_lan_url($lang){
    echo qtranxf_convertURL('', $lang);
}

// generate inline translate short code
add_shortcode( 'translate_now', 'get_translate' );
function get_translate( $atts, $content = null ) {
    extract( shortcode_atts(
            array(
                'ar' => '',
                'en' => '',
                'es' => '',
                'fr' => '',
            ), $atts )
    );
    if ( check_lang() == 'ar' ) {
        echo $atts['ar'];
    }
    if ( check_lang() == 'en' ) {
        echo $atts['en'];
    }
    if ( check_lang() == 'es' ) {
        echo $atts['ar'];
    }
    if ( check_lang() == 'fr' ) {
        echo $atts['ar'];
    }
}

function translate_now($ar,$en,$es,$fr){
    $content = '[translate_now ar="'.$ar.'" en="'.$en.'" es="'.$es.'" fr="'.$fr.'"]';
    echo do_shortcode($content);
}

So now you can check current language using check_lang() function for example:
<?php if(check_lang() == 'ar'): echo 'مرحبا'; endif;?>
<?php if(check_lang() == 'en'): echo 'Hello'; endif;?>
<?php if(check_lang() == 'es'): echo 'Hola'; endif;?>
<?php if(check_lang() == 'fr'): echo 'Bonjour'; endif;?>

Also you can use function translate_now()to translate inline by passing values:
<?php
translate_now(
    'مرحبا', // ar
    'Hello', //en
    'Hola', //es
    'Bonjour' //fr
);
?>

Also to generate any langauge convert URL use function get_lan_url() passing requested language:
<a href="<?php get_lan_url('ar');?>">العربية
<a href="<?php get_lan_url('en');?>">English
<a href="<?php get_lan_url('es');?>">España
<a href="<?php get_lan_url('fr');?>">Français


Q: Can anyone explain ![]/[] == true statement in js? console.log(true == []); // -> false
console.log(true == ![]); // -> false

Why they are always false?

A: true == [] is false simply because true is not equal to [].
![] evaluates to false, so true == ![] is false.
Also, true == !![] is true.


Q: code/website to generate stacked bar graph in jsp hi all
can any one provide me the code/website name from where i can get jsp source code to generate stacked bar graph and other graphs.it will be good if code is in jsp .
Thanks
Yugal

A: Here's one on RoseIndia's site that shows how to create area chart in JSP  http://www.roseindia.net/chartgraphs/areachart-jsppage.shtml
Now, just replace the charting code with the one for making bar charts and you are done: http://www.geodaq.com/jfreechart-sample/bar_chart_code.jsp


Q: How to cast GETDATE() to be only time ignore day,month and year I have a table for store takt-time. It's compound with "day_shift(1)" and "night_shift(0)" like below.

If I put current time(by using GETDATE() function ).
I need to know this current time is "day(1)" or "night(0)". my query like this.
SELECT [day_shift_flag]
FROM  [company_working_time]
WHERE   GETDATE() BETWEEN [start_time] AND[end_time]

But it can't found because a date received from GETDATE() isn't '1900-01-01'
How to compare a only time and ignore day,month,year.
What should I do?

A: You can cast a DateTime as a Time data type. For example:
SELECT
    [day_shift_flag]
FROM  [company_working_time]
WHERE
CAST(GETDATE() AS TIME) BETWEEN CAST([start_time] AS TIME) AND CAST([end_time] AS TIME)

A: By Following Way You can Ignore the  day,month,year
       SELECT [day_shift_flag]
        FROM  [company_working_time]
        WHERE   DatePart(HH,GETDATE()) BETWEEN DatePart(HH,[start_time]) AND DatePart(HH,[end_time])


Q: MVC3 - How to insert a ValidationMessageFor with a line break  at the end? I'm validating about 10 input fileds in a form. The ValidationMessageFor-tags should be at the top of the page, so I'm writing every one like:
@Html.ValidationMessageFor(model => model.Customer.ADDRESS.NAME)
@Html.ValidationMessageFor(model => model.Customer.ADDRESS.CITY)

and so on.
My Models look like this:
[Required(ErrorMessage = Constants.ErrorMsgNameMissing)]
public string NAME { get; set; }
[Required(ErrorMessage = Constants.ErrorMsgCityMissing)]
public string CITY { get; set; }

The constants are Strings.
Now, if more than one ValidationMessageFor is shown, they are all in one line.
How can I insert a line break like
 at the end of every message?
This is NOT the right way:
@Html.ValidationMessageFor(model => model.Customer.ADDRESS.NAME)

@Html.ValidationMessageFor(model => model.Customer.ADDRESS.CITY)

since the
 is shown even if there is no error...;)
Thanks in advance.
PS: Displaying them as a list would also be great.

A: I think what you're actually looking for is:
@Html.ValidationSummary()

A: I would go with @Html.ValidationSummary() if possible

A: Check out Custom ValidationSummary template Asp.net MVC 3.  I think it would be best for your situation if you had complete control over how the validation is rendered.  You could easily write an extension method for ValidationMessageFor.

A: Actually, at the top should be:
@Html.ValidationSummary(/*...*/)

The field validations should be with their respective fields.
However, if you absolutely insist on putting @Html.ValidationMessageFor(/*...*/) at the top then adjust their layout behavior in your CSS and forget about the
's

A: I'm not sure if there's a built in way, but you could easily make another Extension method:
public static MvcHtmlString ValidationMessageLineFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) {
    return helper.ValidationMessageFor(expression) + "
";
}

Something like that?


Q: return extra columns based on group and count results Source data:
+-----+-------------+--------+---------+
| ID  | CandidateID | Rating |  Name   |
+-----+-------------+--------+---------+
| 777 |         119 |      5 | Fred    |
| 777 |         120 |      5 | Tony    |
| 777 |         121 |      3 | Ben     |
| 888 |         131 |      4 | Joe     |
| 888 |         132 |      4 | Matt    |
| 888 |         133 |      1 | Russell |
+-----+-------------+--------+---------+

I need to find duplicates (where ID and Rating are the same), but also somehow keep a reference to them (CandidateID) to present their names in the resulting table.
Desired output (only shows rows where ID AND Rating are the same):
+-----+-------------+--------+------+
| ID  | CandidateID | Rating | Name |
+-----+-------------+--------+------+
| 777 |         119 |      5 | Fred |
| 777 |         120 |      5 | Tony |
| 888 |         131 |      4 | Joe  |
| 888 |         132 |      4 | Matt |
+-----+-------------+--------+------+

My initial approach was to GROUP by ID and Rating, producing COUNT, then do HAVING COUNT(*) >= 2, and then listing all rows where ID from that result is present. Sadly, that also returns non-duplicate rows. Is there a better solution?

A: One simple way uses exists:
select t.*
from t
where exists (select 1
              from t t2
              where t2.id = t.id and t2.rating = t.rating and
                    t2.candidateid <> t.candidateid
             );

A: You can use analytics function for this as well
SELECT ID,CANDIDATEID,RATING,NAME
FROM T
QUALIFY COUNT(*)OVER(PARTITION BY ID,RATING)>=2

based on your database, you can change syntax for count(*) over. This syntax works in teradata.


Q: Howto merge two arrays with values from array2 that are in 1? I have an array with allowed values and an array with given values.
Howto merge two arrays with values from array2 that are in 1?
allowed_values => ["one", "two", "three"]
given_values => ["", "one", "five", "three", "seven"]

...

expected_values => ["one", "three"]

A: You want the array intersection, and you can obtain it via the & operator:

Set Intersection—Returns a new array containing elements common to the two arrays, with no duplicates.

[ 1, 1, 3, 5 ] & [ 1, 2, 3 ]   #=> [ 1, 3 ]


Q: ERROR: could not get unknown property 'plugin' for root project I am trying to build LineageOS' trebuchet launcher. After updating protobuf plugin I managed to get rid of some errors. But after several tries I can not handle this error:

Could not get unknown property 'plugin' for root project
'android_packages_apps_Trebuchet-lineage-16.0' of type
org.gradle.api.Project.

This is my first time editing code from Github. Please help.
buildscript {

    repositories {
        mavenCentral()
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.2'
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.13'
    }
}
apply plugin 'com.android.application'
apply plugin 'com.google.protobuf' version '0.8.13'

final String SUPPORT_LIBS_VERSION = '28.0.0'

android {

    defaultConfig {
        compileSdkVersion 28
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        debug {
            minifyEnabled false
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

There is a lot more code after this, didn't seem important so didn't add. Let me know if it's needed

A: It should be:
apply plugin: 'com.android.application'

with a colon.


Q: Crash Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE), Xamarin Forms I'm using Xamarin Forms framework for android and iOS mobile platform, on iOS devices it work's well but in Android when going on a specific page app shut down.
I got this error : Explicit concurrent copying GC freed 7041(512KB) AllocSpace objects
Using breakpoint I noticed crash arrived executing this
var content = JsonConvert.SerializeObject(
                            newStorageUsers,
                            Formatting.None,
                            new JsonSerializerSettings()
                            {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            });

I show you entire demo code
Page in which I got error
private readonly IStorageUserService _storageService
public MyPage(User user)
{
   InitializeComponent();
   ...
   _storageService = new StorageUserServiceImpl();
   _storageService.StoreUser(user);
   ...
}

Service Interface
public interface IStorageUserService
{
    void StoreUser(User user);
}

Service Implementation
public class StorageUserServiceImpl : IStorageUserService
{
    private string _usersPathFile = Path.Combine(App.GetPackagePath(), "users.txt");
    public StorageUserServiceImpl()
    {
        if (!File.Exists(_usersPathFile))
        {
            _createUsersFile();
        }
    }

    private void _createUsersFile()
    {
        var file = File.Create(_usersPathFile);
        file.Close();
    }

    public void StoreUser(User user)
    {
        var currentStorage = GetStorageUsers();
        List<StorageUser> newStorageUsers = new List<StorageUser>() { };
        if (currentStorage != "" && currentStorage != "[]")
        {
            newStorageUsers = JsonConvert.DeserializeObject<List<StorageUser>>(currentStorage);
        }
        var storageUser = new StorageUser()
        {
            Infos = user,
            CreationDate = Helper.DateFormatter.NowDateTime()
            ...
        };
        newStorageUsers.Add(storageUser);

        var content = JsonConvert.SerializeObject(
                            newStorageUsers,
                            Formatting.None,
                            new JsonSerializerSettings()
                            {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            });

        _store(newStorageUsers, content);
    }

    private void _store(List<StorageUser> newStorageUser, string content)
    {
        // breakpoint can't be triggered there because app shut down with logs
        File.WriteAllText(_usersPathFile, content);
    }
 }

This service is used on several pages but I got this bug in only one page
After this message on logs :

Explicit concurrent copying GC freed 7041(512KB) AllocSpace objects, 2(264KB) LOS objects, 49% free, 4343KB/8687KB, paused 187us total 28.412ms

I got

Pending exception java.lang.StackOverflowError: stack size 8192KB ...

JNI DETECTED ERROR IN APPLICATION: JNI IsInstanceOf called with pending exception java.lang.StackOverflowError: stack size 8192KB ...

Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 8815 (om.myapp.app), pid 8815

I've no more details of what happened, how can I fix this please?


Q: csv file extension hidden while downloading I have written a nodeJS + express server backend which creates reports and then uses fs.createWriteStream to write data separated by "," like below:
let writeStream = fs.createWriteStream(someFilename);
writeStream.write("header1, header2, header3");
writeStream.write("\n1, 2, 3");
writeStream.write("\n1, 2, 3");
writeStream.end();

Then I send the name of the file on server as a response to this request - so that user can do a post to request this file from server - like an "export to excel" functionality.
All this is working fine - but when the user downloads the csv file - in windows - it always hides the extension of the csv file. It downloads as a generic common file - when I open it in an explorer window - it doesn't have an extension - so I have to manually rename it and then open it. In mac it works perfectly.
I have unchecked the "hide extension for known file types" checkbox in Folder options.
How do I fix this - make the browser respect the extension of the file or download it with the extension - ONLY on Windows.


Q: do a sum when clicking on the datagridview checkbox private void grid_games_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    int total = 0;
    for (int i = 0; i <= grid_games.RowCount - 1; i++)
    {
        Boolean chek = Convert.ToBoolean(grid_games.Rows[i].Cells[0].Value);
        if (chek)
        {
            total += 1;
        }
    }
    total *= 50;
    txt_total.Text = total.ToString();
}

I need to do a sum for each row selected from the datagridview selection box. each line is worth 50. it is working, but it has a delay, so when I click on 2 check, it only shows me 50... and the same delay occurs when I uncheck a box. how can i instantly get the total by clicking on that checkbox?

A: The CheckBox column of the DataGridView control is implemented by the DataGridViewCheckBoxCell class, and this class has a delay function, that is, when the user selects a CheckBox in the DataGridView, it will delay updating it to the data source for a period of time.
You just need to add an event about CurrentCellDirtyStateChanged to get the state immediately
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (this.dataGridView1.IsCurrentCellDirty)
            {
                this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

Best used with CellValueChanged:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int total = 0;
            for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
            {
                Boolean chek = Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value);
                if (chek)
                {
                    total += 1;
        }
    }
            total *= 50;
            textBox1.Text = total.ToString();
        }


Q: UIWebView stuck at the second time I am working on an iOS app that user can pick an email from inbox list, and view it on the next page (there's a UIWebView to serve the content).
Here's what I am observing: The first time I pick the email and it shows up on the second page pretty fast. However, if I navigate back and choose to view the email again, it takes a very long time to get webViewDidFinishLoad: called on the second page.
I saw the following message in console:
void SendDelegateMessage(NSInvocation *):
delegate (webView:didFinishLoadForFrame:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode

As soon as this message is printed, the content is rendered on WebView.
What I don't understand is, this always happen at the second time of using webview to show HTML content. There's no local cache for files/resources, and there's no network issues.
Please point me where I should look at for this issue. Thanks!
---- Update ----
During my random attempts, I found removing this line:
self.webView.delegate = self;
will make the issue gone. This makes me feel even more confusing. Why making self to be the delegate could cause such issue?
---- Update 2 ----
I found the culprit is a flatten html method I called after webview loaded the html. If I remove the NSHTMLTextDocumentType it's all good, but I don't understand why:
+ (NSString *) stripHtmlSchema: (NSString *)htmlString
{
    NSString *flatString = [[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
                                                            options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                      NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
                                                 documentAttributes:nil
                                                              error:nil] string];
    return flatString;
}

---- Final Update ----
Figured out the issue. [NSAttributedString alloc] initWithData was taking too long to execute, so blocked everything.

A: Figured out the issue. [NSAttributedString alloc] initWithData was taking too long to execute, so blocked everything.


Q: Swing layout issue on migration to java 8 My swing application in java 5 which had a display like

After migrating to java 8, zoomed up and displays only a part of it like

I saw this and tried setting J2D_D3D as environment variable and also tried passing it as a vm parameter. But didn't solved the issue. Any idea what this could be?

A: For reference, here's an example the doesn't have the problem. It uses a GridLayout(0, 1) with congruent gaps and border. Resize the enclosing frame to see the effect. Experiment with Box(BoxLayout.Y_AXIS) as an alternative.
I suspect the original code (mis-)uses some combination of setXxxSize() or setBounds(), which will display the effect shown if the chosen Look & Feel has different geometry specified by the buttons' UI delegate.

import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see https://stackoverflow.com/a/31078625/230513 */
public class Buttons {

    private void display() {
        JFrame f = new JFrame("Buttons");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel p = new JPanel(new GridLayout(0, 1, 10, 10));
        p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        for (int i = 0; i < 3; i++) {
            p.add(new JButton("Button " + (i + 1)));
        }
        f.add(p);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Buttons()::display);
    }
}


Q: VBA - Check if recordset has been deleted before updating DB I'm experimenting with VBA and i made the following thingy.
Dim rs1 As Recordset
Set rs1 = CurrentDb.OpenRecordset("TBL_Registratie")

With rs1
.AddNew
!leerling_Id = Me.leerling_Id
datum = DateValue(!datum_tijd)
tijd = TimeValue(!datum_tijd)
weekDag = Weekday(datum, vbMonday)

Select Case weekDag
    Case 1, 2, 4
        Select Case tijd
            Case "07:00:00" To "08:00:00"
                !score = !score + 1
            Case "16:00" To "16:30"
                !score = !score + 1
            Case "16:31" To "17:00"
                !score = !score + 2
            Case "17:01" To "22:00"
                !score = !score + 3
            Case Else
                Me.txt_resultaat.Caption = "Het is geen opvang"
                Me.txt_resultaat.Visible = True
                ( rs1.close ? )
        End Select

other cases
 .Update
 .Close

QUESTION: How can i check if my last record in there recordset has a score added or not? if not, i want to delete it and close Else Update & Close

A: A much easier way: Calculate the score before adding the record, save all needed data in variables instead of recordset fields.
Then only if score > 0 do the rs1.AddNew etc.


Q: How to change back.color of WindowsForm using a picture box on a mouseClick event? I have a simple windows form and I have added a picturebox that I want to act as a dark mode on/off switch for my application. I have created an event for mouse click, but it only works one way:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WeatherApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // The below two lines are used to move my WindowsForm window
        private bool mouseDown;
        private Point lastlocation;

        public void picDarkMode_MouseClick(object sender, MouseEventArgs e)
        {
            //var frmForm1 = new Form1();
            //frmForm1.BackColor = Color.Black;
            //var darkTheme = this.BackColor = System.Drawing.Color.DarkGray;

            this.BackColor = System.Drawing.Color.DarkGray;

            if (System.Drawing.Color.DarkGray == System.Drawing.Color.DarkGray)
            {
                this.BackColor = System.Drawing.Color.LightYellow;
            }
            else
            {
                this.BackColor = System.Drawing.Color.DarkGray;
            }

            //this.BackColor = System.Drawing.Color.LightYellow;
        }

I tried to play with if statements, but cannot understand why it is not working...

A: You are making two mistakes. You are setting the backcolor to DarkGray before the if statement, so it will always give the same result, and you are comparing DarkGray to DarkGray instead of the forms backcolor to DarkGray. So...
Get rid of this line:
this.BackColor = System.Drawing.Color.DarkGray;

And change this:
if (System.Drawing.Color.DarkGray == System.Drawing.Color.DarkGray)

To this:
if (this.BackColor == System.Drawing.Color.DarkGray)

This is the whole click event:
public void picDarkMode_MouseClick(object sender, MouseEventArgs e)
{
    if (this.BackColor == System.Drawing.Color.DarkGray)
    {
        this.BackColor = System.Drawing.Color.LightYellow;
    }
    else
    {
        this.BackColor = System.Drawing.Color.DarkGray;
    }
}


Q: Simple approach to check and store which states that has changed from initial value This component checks if the fields have been changed from the initial value and display the number of changed fields. There's a useEffect for each field. It would be better with something more DRY, but haven't figured out how.
Is there a way to do this faster and better?
States
    const [unsavedChanges, setUnsavedChanges] = useState<Array<string>>([]);
    const [customField1, setCustomField1] = useState<string | null | undefined>(
        Data.field1
    );
    const [customField2, setCustomField2] = useState<string | null | undefined>(
        Data.field2
    );

Set unsavedChanges state
//Field 1
    useEffect(() => {
        if (
            (customField1 === Data.field1 ||
                customField1 === null) &&
            unsavedChanges?.includes('customfield1')
        ) {
            let filtered = unsavedChanges.filter(
                (item) => item !== 'customfield1'
            );
            setUnsavedChanges(filtered);
        } else if (
            customField1 === Data.field1 ||
            unsavedChanges?.includes('customfield1')
        ) {
            return;
        } else {
            setUnsavedChanges([...unsavedChanges, 'customfield1']);
        }
    }, [customField1]);

//Field 2
    useEffect(() => {
        if (
            (customField2 === Data.field2 ||
                customField2 === null) &&
            unsavedChanges?.includes('customfield2')
        ) {
            let filtered = unsavedChanges.filter(
                (item) => item !== 'customfield2'
            );
            setUnsavedChanges(filtered);
        } else if (
            customField2 === Data.field2 ||
            unsavedChanges?.includes('customfield2')
        ) {
            return;
        } else {
            setUnsavedChanges([...unsavedChanges, 'customfield2']);
        }
    }, [customField2]);

Return
        <>
            <Input value={customField1} onChange={setCustomField1(e.target.value}/>
            <Input value={customField2} onChange={setCustomField2(e.target.value}/>

{unsavedChanges.length} # of unsaved changes.

            <Button disabled={unsavedChanges.length > 0 ? false : true} label='Submit'/>
        </>

A: i created an example of how to make it simple (in my opinion).
I merged the three states into one. this way i can get each one in more dynamic way. then i created on change handler that handles the changes and doing the all if statements (with less code).
each input is firing the change handler on change. and it sets the state according to the if statements.
this way we can create as many inputs as we want, we just need to pass the right arguments to the change handler and it will take care of the rest for us (and to make sure to include one more key value pair to the state)
this is the dummy data for Data:
 const Data = { field1: "abc", field2: "efg" };

the state:
  const [generalState, setGeneralState] = useState({
     unsavedChanges: [],
     customField1: "",
     customField2: ""
  });

the handler:
const changeTheState = (type, value, field, customField) => {
    //setting the values to the state. so we can fetch the values for the inputs and for later use
    setGeneralState((prev) => ({ ...prev, [type]: value }));

    // i narrowed down the if statements. now its only two.
    if (
      value === Data[field] &&
      generalState.unsavedChanges?.includes(customField)
    ) {
      return setGeneralState((prev) => {
        let filtered = prev.unsavedChanges.filter(
          (item) => item !== customField
        );
        return { ...prev, unsavedChanges: filtered };
      });
    }

    if (!generalState.unsavedChanges?.includes(customField)) {
      setGeneralState((prev) => ({
        ...prev,
        unsavedChanges: [...prev.unsavedChanges, customField]
      }));
    }
  };

and the jsx:

      <input
        value={generalState.customField1}
        onChange={(e) => {
          changeTheState(
            "customField1",
            e.target.value,
            "field1",
            "customField1"
          );
        }}
      />
      <input
        value={generalState.customField2}
        onChange={(e) => {
          changeTheState(
            "customField2",
            e.target.value,
            "field2",
            "customField2"
          );
        }}
      />

{generalState.unsavedChanges.length} # of unsaved changes.

      <button disabled={generalState.unsavedChanges.length > 0 ? false : true}>
        Submit
      </button>

here is the example : codesandbox example
One more thing you can do , is to create a reusable component for the input. create array of objects to represent each input. loop through the array and generate as many inputs you want.
if you need extra explaination let me know.


Q: Delphi XE2 Rounding with DecimalRounding_JH1 Because of a documented rounding issue in Delphi XE2, we are using a special rounding unit available on the Embarcadero site named DecimalRounding_JH1 to achieve true bankers rounding.  A link to the unit can be found here:
DecimalRounding_JH1
Using this unit's DecimalRound function with numbers containing a large number of decimal place we
This is the rounding routine from the DecimalRounding_JH1 unit.  In our example we call this DecimalRound function with the following parameters (166426800, 12, MaxRelErrDbl, drHalfEven) where maxRelErrDbl = 2.2204460493e-16 * 1.234375 * 2
Function DecimalRound(Value: extended; NDFD: integer; MaxRelErr: double;
                         Ctrl: tDecimalRoundingCtrl = drHalfEven): extended;
{ The DecimalRounding function is for doing the best possible job of rounding
  floating binary point numbers to the specified (NDFD) number of decimal
  fraction digits.  MaxRelErr is the maximum relative error that will allowed
  when determining when to apply the rounding rule.  }
var i64, j64: Int64; k: integer; m, ScaledVal, ScaledErr: extended;
begin

  If IsNaN(Value) or (Ctrl = drNone)
    then begin Result := Value; EXIT end;

  Assert(MaxRelErr > 0,
      'MaxRelErr param in call to DecimalRound() must be greater than zero.');

{ Compute 10^NDFD and scale the Value and MaxError: }
  m := 1; For k := 1 to abs(NDFD) do m := m*10;
  If NDFD >= 0
    then begin
      ScaledVal := Value * m;
      ScaledErr := abs(MaxRelErr*Value) * m;
      end
    else begin
      ScaledVal := Value / m;
      ScaledErr := abs(MaxRelErr*Value) / m;
      end;

{ Do the diferent basic types separately: }
  Case Ctrl of
    drHalfEven: begin
      **i64 := round((ScaledVal - ScaledErr));**

The last line is where we get a floating point error.
Any thoughts on why this error is occurring?

A: If you get an exception, that means you cannot represent your value as an double within specified error range.
In other words, the maxRelErrDbl is too small.
Try with maxRelErrDbl = 0,0000000001 or something to test if I am right.


Q: Add timestamp to sdterr? I've a application launched by bash script. I redirected stderr and stdout to different files:
./app >> /home/user/logs/debug.log 2>>/home/user/logs/debug.err &

And I need to add a timestamp for stderr lines.
How I can do it?

A: check this out
./app >> /home/user/logs/debug.log 2> >( while read line; do echo "$(date): ${line}"; done > /home/user/logs/debug.err )


Q: AJAX: download new content every X seconds using jQuery I have page with posts. Initially posts was added by server-side code.
I need every 60 seconds download and show new posts from server.
Server can return 0 to N posts. Page returned by server have this format for two posts (most recent on top):

...

...

There is my code:

...

...

...

Can you please recommend me any good jQuery timer plugin?
I see at JS console every 10s:
null "lastPostID"

Where I have an error?

Update:
If I use:

Output is OK:
3 "divs with class *post*" jQuery_div_update.html:37
100 lastPostID jQuery_div_update.html:40
20 lastPostID jQuery_div_update.html:40
1 lastPostID

But with jQuery:

Output is bad:
null "lastPostID"

Why?

A: If you want to poll some external resource (with an AJAX call, for example) you can follow the "Recursive setTimeout pattern" (from https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval).  Example:
(function loop(){
  setTimeout(function(){

    // logic here

    // recurse
    loop();

  }, 1000);
})();

A: use setInterval() instead of setTimeout()
something like:
setInterval(function(){
    $.ajax({
      url: "test.html",
      context: document.body
    }).done(function() {
      //do something
    });
},1000*60);

http://www.w3schools.com/jsref/met_win_setinterval.asp
https://api.jquery.com/jQuery.ajax/


Q: perf get time elasped with field separator option I have a program which parses the output of the linux command perf. It requires the use of option -x, (the field separator option. I want to extract elapsed time (not task-time or cpu-clock) using perf. However when I use the -x option, the elapsed time is not present in the output and I cannot find a corresponding perf event. Here are the sample outputs
perf stat ls
============
 Performance counter stats for 'ls':

          0.934889 task-clock (msec)         #    0.740 CPUs utilized
                 6 context-switches          #    0.006 M/sec
                 0 cpu-migrations            #    0.000 K/sec
               261 page-faults               #    0.279 M/sec
         1,937,910 cycles                    #    2.073 GHz
   <not supported> stalled-cycles-frontend
   <not supported> stalled-cycles-backend
         1,616,944 instructions              #    0.83  insns per cycle
           317,016 branches                  #  339.095 M/sec
            12,439 branch-misses             #    3.92% of all branches

       0.001262625 seconds time elapsed //here we have it

Now with field separator option
perf stat -x, ls
================
2.359807,task-clock
6,context-switches
0,cpu-migrations
261,page-faults
1863028,cycles
<not supported>,stalled-cycles-frontend
<not supported>,stalled-cycles-backend
1670644,instructions
325047,branches
12251,branch-misses

Any help is appreciated

A: # perf stat ls 2>&1 >/dev/null | tail -n 2 | sed 's/ \+//' | sed 's/ /,/'

0.002272536,seconds time elapsed

A: Starting with kernel 5.2-rc1, a new event called duration_time is exposed by perf statto solve exactly this problem. The value of this event is exactly equal to the time elapsed value, but the unit is nanoseconds instead of seconds.


Q: passing bash a value with leading hyphen I have a bash command that requires a string value after "-v". When this string value has a leading "-", bash tries to interpret it as a new option of the bash command rather than the value I'm trying to give for -v. Is there a way I can escape this leading hyphen? I tried
-v -- -myValue but then it tells me "option '-v' needs a parameter."
The command is calling a ruby file. I think this is the meaningful part of the ruby code for the purposes of this question:
opts = Trollop::options do
  opt :method, "Encrypt or Decrypt", :short => "m", :type => :string, :default => "decrypt"
  opt :value, "Value to Decrypt or Encrypt", :short  => "v", :type => :string, :default => ""
end

A: There's two conventional ways to specify arguments, but these are not enforced at the shell level, they're just tradition:
-v xxxx
--value=xxxx

Now it's sometimes possible to do:
-vxxxx

If you have a value with a dash and it's not being interpreted correctly, do this:
--value=-value

A: cmd -v '-string value with leading dash'

edit
$ cat ~/tmp/test.sh
 #!/bin/bash
 str=
 while getopts "v:" opt; do
 case "$opt" in
    v) str=$OPTARG;;
 esac
 done
 shift $(( OPTIND -1 ))

 echo "option was '$str'"

simple test file, my bash is GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
results:
chris@druidstudio:~⟫ ~/tmp/test.sh -v string
  option was 'string'
chris@druidstudio:~⟫ ~/tmp/test.sh -v -string
  option was '-string'
chris@druidstudio:~⟫ ~/tmp/test.sh -v '-string'
  option was '-string'

so, maybe, the bash script handling your options is not written correctly, or you have an early version of bash. As I answered in another of these silly questions earlier, clairvoyance is not one of my skills.  So, be a good chap and possibly give us, the people you are asking for help from, the pertinent information (as you state, your script is failing at the bash level, not at the ruby level, so why bother to post a ruby script?)


Q: How to find if specific changeset within the parents in mercurial I am a git background and just moved to a project where is uses mercurial, the projects is branched with heads model.
Before pushing things to our testing server, I want to make sure that production head is one of my parents list. is there is a command for that?

A: actually I found a way to do so using "revsets" of mercurial.
in order to list all ancestors for specific changeset, we can use the command
hg log -r "ancestors(84e5bc6fd673)"

now in order to find specific changeset in these parents, we can use the matching function like below
hg log -r "ancestors(84e5bc6fd673) and id(hh6cjb9c48se)"

so if hh6cjb9c48se is part of 84e5bc6fd673 parents it will be printed to the terminal.


Q: Cannot build OpenCL program on Windows I have written a simple "do-nothing" OpenCL application (in C++ but using the C API) on Linux to get some data about OpenCL speed. It compiles fine and runs without error. I don't have a graphics card that supports OpenCL, but I need to test it on a GPU. I'm trying to build the application on my friend's Windows 7 64bit  computer using the OpenCL implementation provided with NVIDIA'S CUDA Toolkit.
When I try to link to the OpenCL.lib file in CUDA\x64 I get undefined references for each OpenCL call within the program (using the standard C API). The same thing happens when I link to the OpenCL.dll in the system32 directory. If I link to the win32 library that came with the CUDA Toolkit, I don't get errors, but OpenCL cannot acquire a platform. All the undefined references I get when linking have an @20 or @46 or some random number on the end of the symbol name. I'm not familiar enough with Windows development to know how to fix this problem. What could be my problem?
I apoligize for any newbie-ness. Thanks for any answers!

A: I believe you'll want to use the library that doesn't give link errors.
The other errors you're getting are because you're linking mismatched code together.
Then focus on trying to determine what your platform identifier should be.
I think you were close but gave up too soon


Q: Angular 2 error: Playing around with Angular 2 and trying to get this simple code working.
yet I keep getting an error of:

EXCEPTION: Cannot resolve all parameters for Tab(undefined). Make sure
  they all have valid type or annotations.

As far ng2 is not injecting in constructor(tabs:Tabs) {… into the constructor
Here is the entire code:
///<reference path="../../typings/zone.js/zone.js.d.ts"/>

import {Component, Input} from 'angular2/core';

@Component({
    selector: 'tab',
    template: `

        {{tab.tabTitle}}

    <ng-content></ng-content>
  `,
})
export class Tab {
    @Input() tabTitle: string;
    public active:boolean;
    constructor(tabs:Tabs) {
        this.active = false;
        tabs.addTab(this);
    }
}

@Component({
    selector: 'tabs',
    directives: [Tab],
    template: `
    <tab tabTitle="Tab 1">
        Here's some content.
    </tab>
  `,
})

export class Tabs {
    tabs: Tab[] = [];
    selectTab(tab: Tab) {
        this.tabs.forEach((myTab) => {
            myTab.active = false;
        });
        tab.active = true;
    }

    addTab(tab: Tab) {
        if (this.tabs.length === 0) {
            tab.active = true;
        }
        this.tabs.push(tab);
    }
}

tx
Sean

A: That's because your Tabs class is defined after your Tab class and classes in javascript aren't hoisted.
So you have to use forwardRef to reference a not yet defined class.
export class Tab {
    @Input() tabTitle: string;
    public active:boolean;
    constructor(@Inject(forwardRef(() => Tabs)) tabs:Tabs) {
        this.active = false;
        tabs.addTab(this);
    }
}

A: You have two solutions:
Inject your Tabs class globally at bootstrap:
bootstrap(MainCmp, [ROUTER_PROVIDERS, Tabs]);

On inject Tabs locally with a binding property,
@Component({
    selector: 'tab',
    bindings: [Tabs],   // injected here
    template: `

    [...]


Q: Hide formulas in excel without protecting the sheet I need to hid the formulas in my sheet without protecting the sheet,say i  have sheet 1 in that i need to hide the formulas from range(A1:G10) i can hide the formula but iam not able to provide input for  the whole sheet
My requirement is to hide the selected cells formulas and able to give inputs for other cells in the same sheet how can i achieve this.

A: Select the whole sheet, right click and then select Format Cells.... In the popup window, select Protection tab. Unselect both options and press OK button. This will unlock all cells on the sheet as by default all cells are locked. Next, select your range, repeat the above process again but this time ensure that both options (Locked and Hidden) are selected this time and press OK. Now protect your sheet (in Excel 2013, select the REVIEW tab and select Protect Sheet option and follow the steps).
This will hide your formulas and stop anyone changing the values in the protected cells


Q: Have border-bottom after grid-row css3 I have a grid container whose css is
.optionsInnerContainer {
        display: grid;
        // grid-template-columns: 1fr 1fr 1fr;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); /* see notes below */
        // grid-auto-rows: minmax(100px, auto);
        -webkit-column-gap: 10px;
        column-gap: 10px;
        row-gap: 2em;
        padding: 10px;
    }

I want to add a border-bottom below every row of grid. I dont know how to do that. Please help.


Q: Are there some methods in golang manipulate function like std::bind in C++? Here is my design:
type Handler func(c *gin.Context)
func PreExecute(c *gin.Context, handle_func Handler) Handler {
    if c.User.IsAuthorized {
        return handle_func
    } else {
        return some_error_handle_func
    }
}

and I want to decorate every handler by PreExecute just like the decoration in Python. So I am looking for some std::bind functions in golang to get PreExecute a exactly same signature as Handler
What I expect:
handler = std::bind(PreExecute, _1, handler) // where _1 hold the position for parameter `c *gin.Context`

some function like std::bind
How can I do that in Golang? Are there some more elegant methods to get this work?

A: Closure, here is my solution:
handler_new = func(c *gin.Context){ return PreExecute(c, handler_old)(c) } // since there is no return value of handler, so just do not use `return` statements, I will not correct this error

and then handler_new can be used as:
handler_new(some_context)

It's the same as
handler_new = std::bind(PreExecute, _1, handler_old)

in C++


Q: Why to use new to initialize something in JAVA? Why do we use this syntax in JAVA
FreshJuice juice = new FreshJuice();

instead of just
FreshJuice juice;

A: For many reasons, including:

*

*There is no guarantee that FreshJuice will be a concrete class; it can be an interface or an abstract class instead.

*You might not have a default constructor available.

*You might not have any constructor available at all.

A: Because you need to create an object before initializing it.
When you call new FreshJuice(); it firsts allocates memory for the object on heap, and then initializes it.(with default values in this case as provided in corresponding default constructor)


Q: How to make `format` function in python 2 to work with `unicode` type objects with UTF-8 encoding? I have huge code base with lots of format functions. I want to pass unicode type objects as arguments like:
# -*- coding: UTF-8 -*-
x = u"ñö"
print isinstance(x,unicode)#prints "True"

y = "Hello {0}".format(x)# "UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)"
print y

A: This did the trick for me without changing every line where format is used:
from __future__ import unicode_literals

Basically I had problems whenever "string {}" in "string {}".format("hello") was str object. Writing a simple u"string {}" would have helped, but huge code base remember? "hello" doesn't really matter.

A: # -*- coding: UTF-8 -*-
x = r"ñö"
print isinstance(x,unicode)#prints "True"

y = "Hello {0}".format(x)# "UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)"
print y


Q: Avoiding array assignment in autograd I understand from the autograd tutorial that array assignment is not supported when the array is contained in the objective to be differentiated. However, I currently have the following objective function in my code which I would like to differentiate with respect to theta:
def obj(theta):
    """
    Computes the objective function to be differentiated.

    Args:
        theta: np.array of shape (n, d)

    Return:
        res: np.array of shape (n,)
    """
    theta = np.atleast_2d(theta)
    n = theta.shape[0]

    res = np.zeros(n)  # Scores
    for i in xrange(n):
        res[i] = ... # Do some computations with theta[i, :]

    return res

Typically I can avoid the for loop by vectorizing the computation over theta; however, in this case the computation already involves various linear algebra operations (inverses, etc.) given a specific row of theta (as hyperparameters), and I found it quite difficult to vectorize the operation over all rows of theta. In this case, I don't know of a better way than filling the res array row by row with a for-loop.
I have tried a naive way to avoid array assignments by creating a list and at each iteration append the results to that list, then finally convert the list to the array upon returning res, but I get all-zero gradients in the end...
I wonder what is the general recommend solution in this setup?

A: You can use numpy.apply_along_axis to apply a function for certain axis in your data.
def func(row):
    # return the computation result for "row"

def obj(theta):
    """
    Computes the objective function to be differentiated.

    Args:
        theta: np.array of shape (n, d)

    Return:
        res: np.array of shape (n,)
    """
    theta = np.atleast_2d(theta)
    n = theta.shape[0]

    res = np.apply_along_axis(func1d=func, axis=1, arr=a)

    return res


Q: comparison of randomized algorithms Sometimes randomized algorithms return quite good results and they are often much faster than a deterministic alternatives. But how can I compare two randomized algorithms (or at least their implementations) ? The results will differ after each call and the output will highly depend on a (pseudo)-coincidence.
I have to compare some clustering algorithms and the majority of solutions is randomized.

*

*is it smart to compare the distribution of the output? (This will highly depend on input and the coincidence.)

*it is also quit hard to estimate the duration because some algorithms work until a threshold is reached (= depends highly on input).


Q: Joining python threads, sum totals My issue is I'm trying to loop over an array with a number of threads, each thread then adds the value into the global array. But for some reason the array is coming out as planned, I have noticed you need to use the join() thread function but am a little confused on how to implement it here
totalPoints = []

def workThread(i):
    global totalPoints
    totalPoints += i

threads = []
for i in range(NUMBER_OF_THREADS):
    t = threading.Thread(target=workThread, args=(i,))
    t.start()
    threads.append(t)

Any help would be appreciated. Thanks!

A: You just write a second loop to join the threads
totalPoints = []

def workThread(i):
    global totalPoints
    totalPoints += i

threads = []
for i in range(NUMBER_OF_THREADS):
    t = threading.Thread(target=workThread, args=(i,))
    t.start()
    threads.append(t)
for t in threads:
    t.join()

Your code will fail at totalPoints += i because totalPoints is a list. You don't handle exceptions in your threads so you may fail silently and not know what happened. Also, you need to be careful how you access a shared resource such as totalPoints to be thread safe.

A: does this help: ?
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import threading
import time
import random

NUMBER_OF_THREADS=20

totalPoints = []

def workThread(i):
    global totalPoints
    time.sleep(random.randint(0, 5))
    totalPoints.append((i, random.randint(0, 255)))

threads = []
for i in range(NUMBER_OF_THREADS):
    t = threading.Thread(target=workThread, args=(i,))
    t.start()
    threads.append(t)

for t in threads:
  t.join()
print totalPoints

It always prints something like this:
[(1, 126), (10, 169), (11, 154), (0, 214), (9, 243), (12, 13), (15, 152), (6, 24), (17, 238), (13, 28), (19, 78), (16, 130), (2, 110), (3, 186), (8, 55), (14, 70), (5, 35), (4, 39), (7, 11), (18, 14)]

or this
[(2, 132), (3, 53), (4, 15), (6, 84), (8, 223), (12, 39), (14, 220), (0, 128), (9, 244), (13, 80), (19, 99), (7, 184), (11, 232), (17, 191), (18, 207), (1, 177), (5, 186), (16, 63), (15, 179), (10, 143)]


Q: How to read pcapng (wireshark) files in Python? I have a capture of some TCP packets in pcapng format and I'd like to open it in python to inspect the TCP payloads with address 192.168.1.198. I've only found this library: https://python-pcapng.readthedocs.io/en/latest/api/blocks.html but it does not support inspecting TCP payloads.
Is there an easy way?

A: You can use python-pcapng package. First install python-pcapng package by following command.
pip install python-pcapng

Then use following sample code.
from pcapng import FileScanner

with open(r'C:\Users\zahangir\Downloads\MDS19 Wireshark Log 08072021.pcapng', 'rb') as fp:
    scanner = FileScanner(fp)
    for block in scanner:
        print(block)
        print(block._raw) #byte type raw data

Above code worked for me.
Reference: https://pypi.org/project/python-pcapng/


Q: Azure Logic Apps ACI Connector - BackOff state I am using the ACI connector in logic apps, and using a customized version of nginx docker image that keeps failing with "CrashLoopBackOff" error.

The customization I've made is just these two:
apt update
apt install ssh

and built a new image out of that. While using the base nginx image (from docker hub - library/nginx) works like a charm, the custom version with SSH installed, always gets into the loop with CrashLoopBackOff error.
I'm not a Linux/Ubuntu guy, any idea what could be the issue? I have in fact tried this many times and also used the Ubuntu base image to do the same customisation (install SSH), but the result is the same
Background: I am using ACI to run a simple shell script on creation. This probably doesn't have anything to do with the error since it works ok with the base nginx image.

A: To install the SSH in the image, you need to more than you have done. Here is the example:
FROM ubuntu:16.04

RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:THEPASSWORDYOUCREATED' | chpasswd
RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config

# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile

EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]

When you have built the image, I suggest you push it into the ACR. Then you can use it in the Logic App and it will work fine. For more details, see Dockerize an SSH service.


Q: OleDbCommand, two sequential "using" With two sequential "using", will both connections be disposed when exiting from {}?
using(OleDbConnection con = new OleDbConnection(conString))
using(OleDbCommand command = con.CreateCommand())
{
}

A: There's only one connection there - and a command using the same connection. Both will be disposed.
This is effectively:
using(OleDbConnection con = new OleDbConnection(conString))
{
    using(OleDbCommand command = con.CreateCommand())
    {
    } // command will be disposed here
} // con will be disposed here


Q: PHP remove duplicate values from a multidimensional array How to remove duplicate values from a multidimensional array.
For example, I have an array:
Array
(
    [0] => Array
        (
            [fruit_id] => cea2fc4b4058
            [title] => Apple title one
            [name] => Apple
            [weight] => 22
        )

    [1] => Array
        (
            [fruit_id] => sdfsdec4b4058
            [title] => Grapefruit title one
            [name] => Grapefruit
            [weight] => 19
        )

    [2] => Array
        (
            [fruit_id] => hjkvcbc4b4058
            [title] => Grapefruit title two
            [name] => Grapefruit
            [weight] => 17
        )

    [3] => Array
        (
            [fruit_id] => tyuutcgbfg058
            [title] => Lemon title one
            [name] => Lemon
            [weight] => 15
        )

    [4] => Array
        (
            [fruit_id] => lkjyurtws4058
            [title] => Mango title
            [name] => Mango
            [weight] => 13
        )

    [5] => Array
        (
            [fruit_id] => bner3223df058
            [title] => Lemon title two
            [name] => Lemon
            [weight] => 11
        )
)

In this array, I need to leave only one fruit with the maximum weight.
I want to save all the data, but at the same time remove duplicate fruits.
Thank.

A: You can sort by weight ascending and then create a result using the name as the key so the ones with larger weight will overwrite the smaller weight ones:
array_multisort(array_column($array, 'weight'), SORT_ASC, $array);
foreach($array as $v) { $result[$v['name']] = $v; }

Then if you want to re-index (not required):
$result = array_values($result);

A: Try to use array_unique($array); code