text:
Q: Why do -Xmx and Runtime.maxMemory not agree When you add
 -Xmx????m

to the command line, the JVM gives you a heap which is close to this value but can be out by  up to 14%.  The JVM can give you a figure much closer to what you want, but only through trial and error.
 System.out.println(Runtime.getRuntime().maxMemory());

prints
-Xmx1000m ->  932184064
-Xmx1024m -Xmx1g ->  954728448
-Xmx1072m ->  999292928
-Xmx1073m -> 1001390080

I am running HotSpot Java 8 update 5.
Clearly, the heap can be something just above 1000000000 but why is this -Xmx1073m instead of say -Xmx1000m?
BTW 1g == 1024m which suggests that 1g should be 1024^3 which is 7% higher than 1000^3 but you get something 7% lower than 1000^3.

Being off by so much suggests that I am missing something fundamental about how the heap works.  If I asked for -Xmx1000m and it was 1001390080 I wouldn't care, I would assume there is some allocation multiple it needs to adhere to, but to give you 932184064 suggests to me the heap is more complicated than I can imagine.

EDIT  I have found that
-Xmx1152m gives 1073741824 which is exactly 1024^3

so it appears it is giving me exactly 128 MB less than I asked for in this case cf the maxMemory().

BTW 128 is my favourite number.  I was in a conference today at street number 128 and the speaker quoted a book from page 128 ;)

A: The difference appears to be accounted for by the size of the garbage collector's survivor space.
The -Xmx flag, as described in the docs, controls maximum size of the memory allocation pool. The heap portion of the memory allocation pool is divided into Eden, Survivor, and Tenured spaces. As described in this answer, there are two survivor regions, only one of which is available to hold live objects at any given point in time. So the total apparent space available for allocating objects, as reported by Runtime.maxMemory(), must subtract the size of one of the survivor spaces from the total heap memory pool.
You can use the MemoryMXBean and MemoryPoolMXBean classes to get a little more information about your memory allocation. Here's a simple program I wrote:
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryPoolMXBean;

public class MemTest {
  static String mb (long s) {
    return String.format("%d (%.2f M)", s, (double)s / (1024 * 1024));
  }

  public static void main(String[] args) {
    System.out.println("Runtime max: " + mb(Runtime.getRuntime().maxMemory()));
    MemoryMXBean m = ManagementFactory.getMemoryMXBean();

    System.out.println("Non-heap: " + mb(m.getNonHeapMemoryUsage().getMax()));
    System.out.println("Heap: " + mb(m.getHeapMemoryUsage().getMax()));

    for (MemoryPoolMXBean mp : ManagementFactory.getMemoryPoolMXBeans()) {
      System.out.println("Pool: " + mp.getName() +
                         " (type " + mp.getType() + ")" +
                         " = " + mb(mp.getUsage().getMax()));
    }
  }
}

The output of this on OpenJDK 7 for java -Xmx1024m MemTest is:
Runtime max: 1037959168 (989.88 M)
Non-heap: 224395264 (214.00 M)
Heap: 1037959168 (989.88 M)
Pool: Code Cache (type Non-heap memory) = 50331648 (48.00 M)
Pool: Eden Space (type Heap memory) = 286326784 (273.06 M)
Pool: Survivor Space (type Heap memory) = 35782656 (34.13 M)
Pool: Tenured Gen (type Heap memory) = 715849728 (682.69 M)
Pool: Perm Gen (type Non-heap memory) = 174063616 (166.00 M)

Note that Eden + 2*Survivor + Tenured = 1024M, which is exactly the amount of heap space requested on the command line. Much thanks to @Absurd-Mind for pointing this out.
The differences you observe between different JVMs are likely due to differing heuristics for selecting the default relative sizes of the various generations. As described in this article (applies to Java 6, wasn't able to find a more recent one), you can use the -XX:NewRatio and -XX:SurvivorRatio flags to explicitly control these settings. So, running the command:
java -Xmx1024m -XX:NewRatio=3 -XX:SurvivorRatio=6

You're telling the JVM that:
Young:Tenured = (Eden + 2*Survivor):Tenured = 1:3 = 256m:768m
Survivor:Eden = 1:6 = 32m:192m

So, with these parameters, the difference between the requested -Xmx value and the available memory reported by Runtime.maxMemory() should be 32m, which is verified using the above program. And now you should be able to accurately predict the available memory reported by Runtime for a given set of command-line arguments, which is all you ever really wanted, right?

A: The following graph shows the Runtime.maxMemory as a percentage of Xmx (on the y-axis) for different Xmx values (on the x-axis).
We see that for the most part only ~85% of the Xmx setting is available for the heap to grow. This analysis is conducted using java version "1.8.0_212" Java(TM) SE Runtime Environment (build 1.8.0_212-b10) Java HotSpot(TM) 64-Bit Server VM (build 25.212-b10, mixed mode)
Graph of (maxMem/Xmx) for varying Xmx sizes (in MB)


text:
Q: .NET WinForms language localization I have a WinForm .NET software and am trying to get translated localization to work. For each form, I set Localizable = True and set Language from Default (which were defined in English) to Italian (Italy). I then change all form strings from English to Italian.
I then set my PC's Region to Italy and language to Italian, but I do not see the Italian strings, just the default, English ones. I also tried Thread.CurrentThread.CurrentUICulture = New CultureInfo("it-IT") to force the EXE to be localized to it-IT, no luck.
What am I missing?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I detect when the user is X seconds from the end of a video? I need to detect when a video is 30 seconds from the end of the total. For example, if my video is 1m35s in length, I want to trigger an event when it reaches 1m05s.
UPDATE
I have worked out how to trigger an event at any point over 30 seconds from the end, i.e 30s, 29s, 28s and so on. The problem is, the code below trigger repeatedly each second, but I only want this event to occur once, wether it happens at -30s, -22s or -15s.
var video = $('#video');

function func() {
    if ( video[0].currentTime > video[0].duration-30 ) {
        console.log('You are less than 30 seconds from the end!');
    }
}

video.on('timeupdate', function() {
    func();
});

A: You can use a end of file event boolean variable - eofevent.
Logic : reset this variable when ever you start your playback. Use it as a flag , once triggered , don't call the func() again.
var video = $('#video');
var eofevent = false;

function func() {
    if ( video[0].currentTime > video[0].duration-30 ) {
        console.log('You are less than 30 seconds from the end!');
        eofevent = true;
    }
}

video.on('timeupdate', function() {
    if( eofevent == false )
       func();
});

video.on('play', function() {
     if ( video[0].currentTime < video[0].duration ) {
        console.log('on Playing Reset!');
        eofevent = false;
    }
});

video.on('playing', function() {
    if ( video[0].currentTime < video[0].duration ) {
        console.log('on Playing Reset!');
        eofevent = false;
    }
});

Note: I am not a jquery /javascript coder , any syntax mistake please excuse.

A: I would say you need to unbind the timeupdate event once you reach your goal:

var video = $('#video');

function func() {
    if ( video[0].currentTime > video[0].duration-30 ) {
        console.log('You are less than 30 seconds from the end!');
        video.off('timeupdate'); // <--
    }
}

video.on('timeupdate', function() {
    func();
});

(I have not tested the code)


text:
Q: Arm templates copy loop conditionally check index Is there option copy iteration check conditionally in ARM templates? Example if copy index is zero set another value?
My ARM Code:
{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
      "location": {
        "type": "string",
        "defaultValue": "[resourceGroup().location]"
      },
      "storageAccountName": {
        "type": "string"
      },
      "mediaServicesAccountName": {
        "type": "string"
      }
    },
    "functions": [],
    "resources": [
      {
        "type": "Microsoft.Storage/storageAccounts",
        "apiVersion": "2021-01-01",
        "name": "[concat('storage', copyIndex(), uniqueString(resourceGroup().id))]",
        "location": "[parameters('location')]",
        "sku": {
          "name": "Standard_LRS"
        },
        "kind": "StorageV2",
        "copy": {
            "name": "storagecopy",
            "count": 3
        }
      },
      {
      "type": "Microsoft.Media/mediaservices",
      "apiVersion": "2020-05-01",
      "name": "[parameters('mediaServicesAccountName')]",
      "location": "[parameters('location')]",
      "properties": {
        "storageAccounts": [
          {
            "type": "Primary", # Primary if copyIndex is zero otherwise Secondary
            "id": "[resourceId('Microsoft.Storage/storageAccounts', concat('storage', copyIndex(), uniqueString(resourceGroup().id)))]"
          }
        ]
      },
      "identity": {
        "type": "SystemAssigned"
      },
      "dependsOn": ["storagecopy"]
    }
    ],
    "metadata": {
      "_generator": {
        "name": "bicep",
        "version": "0.3.126.58533",
        "templateHash": "2006367938138350540"
      }
    }
  }

In above code I am creating 3 storage accounts and after that I am creating azure media service, I need to map storage accounts to azure media service dynamically. Under properties, I need to use copy loop and set Primary if index is zero else Secondary for defined number of storages.
Below Block implementation is required for copy loop condition:
"storageAccounts": [
              {
                "type": "Primary", # Primary if copyIndex is zero otherwise Secondary
                "id": "[resourceId('Microsoft.Storage/storageAccounts', concat('storage', copyIndex(), uniqueString(resourceGroup().id)))]"
              }
            ]

A: You need to make a separate loop over storageAccounts property:
 {
      "type": "Microsoft.Media/mediaservices",
      "apiVersion": "2020-05-01",
      ...
      "properties": {
        "copy": [
          {
            "name": "storageAccounts",
            "count": "3",
            "input": {
              "type": "[if(equals(copyIndex('storageAccounts'), 0), 'Primary', 'Secondary']", # Primary if copyIndex is zero otherwise Secondary
              "id": "[resourceId('Microsoft.Storage/storageAccounts', concat('storage', copyIndex('storageAccounts'), uniqueString(resourceGroup().id)))]"
            }
          }
        ]
      }
    }

See more information here: Property iteration in ARM templates


text:
Q: winforms how do I fix docking after adding a new control I start out with a control that has three child controls, docked to the top, bottom, and fill.  Two skinny bands at the top and a big rectangle in the middle.
Later on, programatically I want to add a slim band to the left.
But when I do it, I get the left band overlapping with the big middle one.
How should I be readjusting these controls?

A: Once you have instanciated the new control, you can give it a specific index to be located.
The lower the index, the higher priority it will have.
Example code*:
  var control = new Button();

  control.Dock = DockStyle.Left;

  this.Controls.Add(control);

  this.Controls.SetChildIndex(control, 0);

(I just used a button because it was easy to see inside a form.)
However doing this dynamically may not be the best thing. I would recommend creating the control on the left the entire time, then making it visible when applicable. Doing this method, you get the Designer to help place the control in the right spot, rather than generating the right spot.
If you so choose to use the enable/disable visibility at runtime, you may have to tweak the Document Outline. It's located at View -> Other Windows -> Document Outline when in the Designer view. (It's a dockable window like the toolbox.)

A: You need a control that holds the slim band and a control located on the right. Place the two skinny bands and one rectangle in the right-hand control.


text:
Q: Rust multiple levels of indirections - Performance impact? I've been experimenting with everyone's favorite new thing, rust. I'm coming from a C background, so I think this may be what is causing me issue here. I've tried to find a clear definitive answer online but could not. Here's my issue, simplified:
fn main() {
    let v : Vec<&str> = vec!["abc", "def"];
    let z : Vec<&&str> = v.iter().filter(|e| {e.starts_with("a")}).collect(); // type of `e` is &&&str!
    // do something with z
}

My issue occurs with the type of z and e (within the closure). I understand the need for the additional layer of reference for the ownership system. I also understand I can go around this issue using things liked copied() or into_iter() (for z's type) or use |&e|.
However, I am wondering if there's a performance impact here. Even if I used copied, the type of e in |e| would still be a double reference. If pointers and references map 1:1, this seems like a waste. But references and pointers do not need (in this case at least) to map 1:1. The compiler could create a reference for the ownership rules, without deref a reference.
So here's my question: does multiple references translates 1:1 to pointers? Are there optimizations? In this case (e for example), am I going through two levels of indirection?

A:
Does multiple references translates 1:1 to pointers?

Yes.
But the compiler can optimize them out, as usual. In the case of iterators, it usually does. When all stuff will be inlined, the compiler will be able to convert the iterator to a simple loop, so this is rarely a problem. If it is, you can always use copied(), or even switch to simple loops. This is part of Rust's zero-cost abstraction story.


text:
Q: Testing nested resource controllers with Rspec and Factory girl in Rails 3.1 I have a nested resource specialty under user.
My routes.rb looks like
  resources :users do
     resources :specialties do
     end
  end

My factories.rb looks like
Factory.define :user do |f|
  f.description { Populator.sentences(1..3) }
  f.experience { Populator.sentences(1..5) }
  f.tag_list { create_tags }
end

Factory.define :specialty do |f|
  f.association :user
  specialties = CategoryType.valuesForTest
  f.sequence(:category) { |i| specialties[i%specialties.length] }
  f.description { Populator.sentences(1..5) }
  f.rate 150.0
  f.position { Populator.sentences(1) }
  f.company { Populator.sentences(1) }
  f.tag_list { create_tags }
end

My Specialties_controller.rb looks like
class SpecialtiesController < ApplicationController

def index
    @user = User.find(params[:user_id])
    @specialties = @user.specialties
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @specialties }
    end
  end

My specialties_controller_spec.rb looks like
require 'spec_helper'

describe SpecialtiesController do
  render_views

  describe "GET 'index'" do
    before do
      @user = Factory.create(:user)
      @specialty = Factory.create(:specialty, :user => @user)
      @user.stub!(:specialty).and_return(@specialty)
      User.stub!(:find).and_return(@user)
    end

    def do_get
      get :index, :user_id => @user.id
    end

    it "should render index template" do
      do_get
      response.should render_template('index')
    end

    it "should find user with params[:user_id]" do
      User.should_receive(:find).with(@user.id.to_s).and_return(@user)
      do_get
    end

    it "should get user's specialties" do
       @user.should_receive(:specialty).and_return(@specialty)
       do_get
    end
   end
 end

The first two tests pass, but the last test fails with the error message
Failure/Error: @user.should_receive(:specialty).and_return(@specialty)
       (#<User:0x007fe4913296a0>).specialty(any args)
           expected: 1 time
           received: 0 times

Does anybody have an idea what this error means and how to fix it? I've looked at similar posts and can't find an error in my code. Thanks in advance.

A: @user.should_receive(:specialty).and_return(@specialty)

specialtyis a one-to-many relation and should be plural: specialties. And indeed you have in your controller:
@specialties = @user.specialties


text:
Q: rails4, carrierwave upload file name too long I'm uploading image using carrierwave remote_url.
info.remote_image_url = "IMG_URL_HOST/IMG_PAHT/IMG_NAME"

Return error message is

Errno::ENAMETOOLONG: File name too long @ rb_sysopen
  - /Users/kai/rails/rails_pjt/public/uploads/tmp/1421373782-65124-7719/D-__E1_84_8B_E1_85_A1_E1_86_AB_E1_84_8C_E1_85_B5_E1_84_8B_E1_85_A7_E1_86_AB__E1_84_82_E1_85_A1_E1_86_AF_E1_84_8D_E1_85_A1_E1_84_87_E1_85_A7_E1_86_AF_E1_84_8B_E1_85_A5_E1_86_B8_E1_84_86_E1_85_AE_0423__E1_84_8B_E1_85_A9_E1_84_85_E1_85_B3_E1_84_89_E1_85_A5_E1_86_BC_E1_84_92_E1_85_A7_E1_86_BC_E1_84_8B_E1_85_AC_E1_84_80_E1_85_AA-_E1_84_80_E1_85_AE_E1_86_BA_E1_84_83_E1_85_A1_E1_86_A8__E1_84_87_E1_85_A9_E1_86_AF_E1_84_85_E1_85_B2_E1_86_B7_E1_84_8C_E1_85_B5_E1_84_87_E1_85_A1_E1_86_BC_E1_84_8B_E1_85_B5_E1_84_89_E1_85_B5_E1_86_A8__E1_84_86_E1_85_A1_E1_86_AF_E1_84_84_E1_85_A9_E1_86_BC_E1_84_80_E1_85_A1_E1_84_85_E1_85_B5_orps3_landing_05.jpg
  from /Users/kai/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/fileutils.rb:1396:in `initialize'

Image file's length is 101
but after encoding UTF-8 length is 637
and them
I found this solution.
http://stackoverflow.com/questions/16472894/modify-filename-before-saving-with-carrierwave
But it is different version image path
ex) file_name     : D-__E1_84_8B_E1_85_A1_E1_86_AB_E1_84.png
android_version   : android_D-__E1_84_8B_E1_85_A1_E1_86_.png
thumbnail_version : thumbnail_D-__E1_84_8B_E1_85_A1_E1_8.png

How to fix extend file name limit.

A: According to this (rejected) pull request, you can put this code into an initializer and have the issue fixed
# Monkey patch for long filenames
# @see https://github.com/carrierwaveuploader/carrierwave/pull/539/files
module CWRemoteFix

  # 255 characters is the max size of a filename in modern filesystems
  # and 100 characters are allocated for versions
  MAX_FILENAME_LENGTH = 255 - 100

  def original_filename
    filename = super
    if filename.size > MAX_FILENAME_LENGTH
      extension = (filename =~ /\./) ? filename.split(/\./).last : false
      # 32 for MD5 and 2 for the __ separator
      split_position = MAX_FILENAME_LENGTH - 32 - 2
      # +1 for the . in the extension
      split_position -= (extension.size + 1) if extension
      # Generate an hash from original filename
      hex = Digest::MD5.hexdigest(filename[split_position, filename.size])
      # Create a new name within given limits
      filename = filename[0, split_position] + '__' + hex
      filename << '.' + extension if extension
    end
    # Return original or patched filename
    filename
  end

end

# Monkeypatch downloader class using prepend
CarrierWave::Uploader::Download::RemoteFile.prepend CWRemoteFix

This patch will rename the file as <prefix-from-original-filename>__<md5-of-original-filename>.<extension-if-present>


text:
Q: How do I pass the Hadoop Streaming -file flag to Amazon ElasticMapreduce? The -file flag allows you to pack your executable files as a part of job submission and thus allow you to run a MapReduce without first manually copying the executable to S3. Is there a way to use the -file flag with Amazon's elastic-mapreduce command? If not, what is the easiest way to upload the binary you want to run?

A: The answer is no. I ended up uploading the executable separately from invoking elastic-mapreduce.


text:
Q: Integrating Exp[Cos^2] I'm trying to integrate something of this form:
$\int_0^se^{\cos^2x}~dx$
I looked in different tables and tried with Mathematica but without success... Could you give me the solution (if obvious) or advices on how to proceed?

A: $\int_0^se^{\cos^2x}~dx=\int_0^s\sum\limits_{n=0}^\infty\dfrac{\cos^{2n}x}{n!}dx=\int_0^s\left(1+\sum\limits_{n=1}^\infty\dfrac{\cos^{2n}x}{n!}\right)dx$
For $\int\cos^{2n}x~dx$ , where $n$ is any natural number,
$\int\cos^{2n}x~dx=\dfrac{(2n)!x}{4^n(n!)^2}+\sum\limits_{k=1}^n\dfrac{(2n)!((k-1)!)^2\sin x~\cos^{2k-1}x}{4^{n-k+1}(n!)^2(2k-1)!}+C$
This result can be done by successive integration by parts, e.g. as shown as http://hk.knowledge.yahoo.com/question/question?qid=7012022000808
$\therefore\int_0^s\left(1+\sum\limits_{n=1}^\infty\dfrac{\cos^{2n}x}{n!}\right)dx$
$=\left[x+\sum\limits_{n=1}^\infty\dfrac{(2n)!x}{4^n(n!)^3}+\sum\limits_{n=1}^\infty\sum\limits_{k=1}^n\dfrac{(2n)!((k-1)!)^2\sin x~\cos^{2k-1}x}{4^{n-k+1}(n!)^3(2k-1)!}\right]_0^s$
$=\left[\sum\limits_{n=0}^\infty\dfrac{(2n)!x}{4^n(n!)^3}+\sum\limits_{n=1}^\infty\sum\limits_{k=1}^n\dfrac{(2n)!((k-1)!)^2\sin x~\cos^{2k-1}x}{4^{n-k+1}(n!)^3(2k-1)!}\right]_0^s$
$=\sum\limits_{n=0}^\infty\dfrac{(2n)!s}{4^n(n!)^3}+\sum\limits_{n=1}^\infty\sum\limits_{k=1}^n\dfrac{(2n)!((k-1)!)^2\sin s~\cos^{2k-1}s}{4^{n-k+1}(n!)^3(2k-1)!}$


text:
Q: Can I use the word "escape" instead of "escapism" in this context?
I want to escape from school and I love with this "escapism".

Can I use escape in place of escapism?
Similarly can I use escapism instead of escape in this sentence?

Romantic novel should present an "escape" from dreary realities of life.

Both escapism and escape are nouns. So can I choose any of them? If I interchange would the meaning will be same or altered?

A: The noun "escapism" has only one definition - a way of avoiding an unpleasant or boring life, especially by thinking, reading, etc. about more exciting but impossible activities.
The noun "escape" has several definitions - the act of successfully getting out of a place or a dangerous or bad situation; a loss that happens by accident; something that helps you to forget about your usual life or problems.
As you can see the 3rd definition of "escape" and the definition of "escapism" are similar, yet, I wouldn't say that they are the same.
Take the second example, it can be rewritten using either word:

*

*Romantic novels should present an escape from dreary realities of life.

*Romantic novels should be a form of escapism for those tired of dreary realities of life.

A:
I want to escape from school and I [am in] love with this "escape."

The problem is that this escape would resolve to an actual single instance of you escaping, but you only mention an escape you want to do.
You can't say this escape unless there was an actual escape.  You can say this desire to escape or this want to escape.
Escapism means something different than escape and is not really related to a physical escape as in breaking free from a place.  It means the overall tendency indulging in fantasies unrelated to reality in order to avoid reality.  Escapism would be something like:

I often daydream that I'm a cartoon rabbit in a TV show.  And other things.  I am in love with my escapism.

Similarly can I use escapism instead of escape in this sentence?

Escapism is an -ism that isn't used to describe specific things, but rather an overall tendency of a person.  A person wanting to indulge in escapism will do certain things, but it's odd to say doing certain things gives or provides escapism.


text:
Q: Error while creating continuous aggregate (materialized view) when source and new time columns have the same name (PSQL/TSDB) I'm facing a problem when creating a continuous aggregate on timescaledb (based on materialized views) when the source time column and the new time column have the same name like below:
CREATE MATERIALIZED VIEW IF NOT EXISTS minute_table
WITH (timescaledb.continuous) AS
SELECT
    time_bucket(INTERVAL '1 minute', my_time_col) AS my_time_col,
    ...
FROM source_table
GROUP BY my_time_col
WITH NO DATA;

I get the following error:
ERROR:  continuous aggregate view must include a valid time bucket function

But if I change the new time column name like in the below example just works:
CREATE MATERIALIZED VIEW IF NOT EXISTS minute_table
WITH (timescaledb.continuous) AS
SELECT
    time_bucket(INTERVAL '1 minute', my_time_col) AS my_time_col_asdf,
    ...
FROM source_table
GROUP BY my_time_col_asdf
WITH NO DATA;

How can I work around this? I need the source and new time columns to have the same name...

A: I found out.
There are two ways if you want to keep same name in both columns:

*

*GROUP BY time_bucket(INTERVAL '1 minute', my_time_col)

*GROUP BY 1
The first one more robust the second one shorter.


text:
Q: How to fix rails 4 hyperlinks? I'm trying to display someone's profile links to their social media profiles. My current code is

Linkedin:
<%= link_to @person.linkedin, @person.linkedin %>

It works and the link does load, but it goes to localhost:3000/user/linkedin.com/in/user instead of linkedin.com/in/username
Thanks!

A: You need to add make sure the linkedin hyperlinks have a protocol (http, https, etc).
Any link without a protocol is assumed to be a relative path, which is why the hyperlinks are getting appended to your website url.
A solution would be to manually add a "http://" string at the beginning of every person's linkedin hyperlink in your database. Your code should work fine after that.
Edit: Or you can change it on the fly like so (the other answers won't work since it looks like @person.linkedin contains the entire hyperlink not just the linkedin user)
<%= link_to @person.linkedin, "https://#{@person.linkedin}" %>

A: Rails link helpers follow the format:
link_to(name = nil, options = nil, html_options = nil, &block)

The second @person.linkedin path is a local path as determined by your routes file in your config folder.  If the link you need follows a certain format you can do something like
<%= link_to "LinkTextHere", "http://www.linkedin.com/#{@person}/profile" %>

I can answer in more detail if you give me the exact outcome you need as well as what you want from the .linkedin value.  Also, typing "rake routes" in your console will show all paths you currently have and can help troubleshoot issues like why @person.linkedin is routing locally.


text:
Q: Build configuratuin depended constants in UWP/C# I'm trying to make a multiple branded UWP application. Everything wokrs fine, but I can't define my constants for builds.
I have made build configurations for the brands and I added some pre build action they copies the assets and the other things, depends on the current build configuration.
How can I make this work:
#if brandAlpha
public string const MYCONST = "alpha";
#endif

#if brandBeta
public string const MYCONST = "beta";
#endif

It works when I use debug, but when I try to create a store package it says MYCONST is not exists...
I have made a screenshot:

This is how I would like to use it:

A: That is probably because neither the brandAlpha or brandBeta symbols were defined in your build configuration.
Assuming you're using Visual Studio, you should follow these steps :

*

*Open the projects properties (double-click the property node in the solution explorer)

*Click on the Build tab

*Make sure the Configuration and Platform combo boxes have the values you're interested in.

*In the field Conditional compilation symbols put either brandAlpha or brandBeta


text:
Q: Why my code is not displaying in a react return? I have created basic home page with search option, but unfortunatelly ,,There aren't any hotels h2 tag is not displaying. I am rendering a list of hotels adding them on the firebase and i have delete option as well. Upon deleting all of the hotels from the list I was hoping to see a message that there aren't any hotels, but surprisingly it's not displaying. Any idea why?

function Card() {
  const [hotels, setHotels] = useState<NewHotelType[]>([]);
  const [search, setSearch] = useState("")

  useEffect(
    () =>
      onSnapshot(hotelsCollection, (snapshot: QuerySnapshot<DocumentData>) => {
        setHotels(
          snapshot.docs.map(doc => {
            return {
              id: doc.id,
              ...doc.data(),
            };
          })
        );
      }),
    []
  );

  return (

        <input className="inputsearch"
        value={search} type="text" placeholder="Search for the hotel" onChange={(e) => setSearch(e.target.value)}
        />

    {!!hotels? (

    {hotels?.filter((item:NewHotelType) => {
          if (search === "" && !search.length) {
            return item;
          }
          return item?.title === search;
        })
        ?.map((hotel:NewHotelType) => (<Information key={hotel.id} hotel={hotel}
        />
        )
        )}

    ) : (

There are no hotels. Please add one

    )}

  );
}

export default Card;

A: Array types do not have the "duck-type" functionality you're trying to use.
const arr = []
console.log(!!arr) // -> true

What you'll want to do is either setHotels to null as initial state and when there are none returned, and do a "duck-type" check in your return
{hotels ? {hotels.filter()} :
No hotels

OR keep the same data structures and check for an array length:
{hotels.length ? {hotels.filter()} :
No hotels

EDIT
If no results are returned from your filter, I assume you'll also want to display the fallback h2.  In that case do a check on the filtered hotels in your condition:
{hotels.filter().length ? {hotels.filter().map()} :
No hotels
}


text:
Q: Notice: Undefined index: in $_FILES[audio_data] may used upload function for the upload recorded voice. also it's work properly but the thing is its shows notice message like
Notice: Undefined index: audio_data in C:\xampp\htdocs\test-wordpress\wp-content\plugins\bookmypte\upload.php on line 4
this is my upload code for the file upload
var upload = document.createElement("a");
  upload.href="#";
  upload.innerHTML = "<button>Upload</button>";
  upload.addEventListener("click", function(event){
      var xhr=new XMLHttpRequest();
      xhr.onload=function(e) {
          if(this.readyState === 4) {
              console.log("Server returned: ",e.target.responseText);
          }
      };
      var fd=new FormData();
      fd.append("audio_data",blob, filename);
      xhr.open("POST","upload.php",true);
      xhr.send(fd);
  })
  li.appendChild(document.createTextNode (" "))
  li.appendChild(upload)

this is my upload.php file code.
<?php
define ('SITE_ROOT', realpath(dirname(__FILE__)));
print_r($_FILES);
$input = $_FILES['audio_data']['tmp_name'];
$output = SITE_ROOT."/upload/".uniqid().date("Y-m-d").".wav";
move_uploaded_file($input, $output);
require_once('bookmypte.php');


text:
Q: How does Chrome Extension get user credential from Firebase web app without user having to sign in twice? I have both a Firebase web app and a Chrome Extension - user will use Chrome Extension to save article that can be read later from their web app.
For web app, I use Firebase Auth. But I am unsure how to pass user token or id to Chrome Extension, so that user does not need to login twice.
I have read this question, but it is not clear to me how to send token to Chrome Extension from web app.
Thanks!

A: There's a detailed answer with examples in this github post
Short scheme is following:

*

*Create cloud function that generates custom firebase token

*In web app upon login request a custom token from the cloud function

*Using chrome API send message to extension

*In extension on message use token to log into firebase

*In extension listen to firebase auth state change to log out

Details from post:
Firebase function / Auth Server
In a Firebase function (or a custom server) handle the token creation using firebase function createCustomToken
const admin = require('firebase-admin')
const functions = require('firebase-functions')

admin.initializeApp()

module.exports functions.https.onCall(uid =>
  admin.auth().createCustomToken(uid)
)

Webapp
After a successful login, request the server for a custom Token passing the uid of the logged user
firebase.functions().httpsCallable('createToken')(uid)
Then send it to the chrome extension
chrome.runtime.sendMessage(extensionID, token)
Extension
Finally in the extension when receiving a message, log the user with firebase using the custom token
firebase.initializeApp(firebaseConfig)

firebase.auth().onAuthStateChanged(function (user) {
  console.log(
    'User state change detected from the Background script of the Chrome Extension:',
    user
  )
})

chrome.runtime.onMessageExternal.addListener(
  (token, sender, sendResponse) => {
    firebase
      .auth()
      .signInWithCustomToken(token)
      .catch((error) => {
        console.log('error', error)
      })
    return true
  }
)

Your background script will log the authStateChanged event where you can see that the auth is not isAnonymous anymore and the email attributes is the one of the user logged through your app !


text:
Q: How to avoid closing Popup I have an Popup(not modal window) which shows textbox, when I start typing in the textbox I need to open another popup which show listbox,when I select any item from list box the popup disappears as well the previous popup also disappears how can I avoid closing of the very first popup on close of 2nd popup.

A: Use a standard "bandpopup" component - in this case you wouldn't even have a second popup to manage. Other thing which comes to my mind is add onClose event listener or event handler - whichever you prefer - and stop event propagation with Event.stop(caughtEvent). It will effectively prevent propagation of OnClose event and your first popup wouldn't be closed.


text:
Q: curl send JSON payload I'm just strating with RabbitMQ and I try to send a json payload to it. Unfortunately I'm getting error:
{"error":"bad_request","reason":"payload_not_string"}

I read somewhere that I need to use "content_type": "application/json" but that has not helped either.
This is the body I'm trying to send:
{
    "properties": {
        "delivery_mode": 2,
        "content_type": "application/json"
    },
    "routing_key": "git",
    "payload": {
        "action": "created",
        "comment": {
            "url": "https://api.github.com/repos/baxterthehacker/public-repo/comments/11056394",
            "id": 11056394
        }
    },
    "payload_encoding": "string"
}

And the full curl:
curl -i -X POST \
   -H "Content-Type:application/json" \
   -H "Authorization:Basic Z3Vlc3Q6Z3Vlc3Q=" \
   -d \
'{
    "properties": {
        "delivery_mode": 2,
        "content_type": "application/json"
    },
    "routing_key": "git",
    "payload": {
        "action": "created",
        "comment": {
            "url": "https://api.github.com/repos/baxterthehacker/public-repo/comments/11056394",
            "id": 11056394
        }
    },
    "payload_encoding": "string"
}' \
 'http://localhost:8090/api/exchanges/%2f/amq.topic/publish'

Is it possible to send the json payload at all? I was thinking of sending Github webhooks to one of the queues.

A: The RabbitMQ team monitors this mailing list and only sometimes answers questions on StackOverflow.

The error you see is correct, your payload is not a string. I had to reproduce this and re-visit the HTTP API docs for this to become clear.
The value you are passing to the payload key in your JSON is more JSON - in order for it to be a string, you must escape it correctly and pass it like this:
$ curl -4vvv -u guest:guest -H 'Content-Type: application/json' localhost:15672/api/exchanges/%2f/amq.topic/publish --data-binary '{
    "properties": {
        "delivery_mode": 2,
        "content_type": "application/json"
    },
    "routing_key": "git",
    "payload":"{\"action\":\"created\",\"comment\":{\"url\":\"https://api.github.com/repos/baxterthehacker/public-repo/comments/11056394\",\"id\":11056394}}",
    "payload_encoding": "string"
}'

The other alternative is to base-64 encode the JSON from GitHub and pass that as the payload - you won't have to escape anything if you do that.


text:
Q: Rails 3.0 - Turn Compass/SASS off in Production - Stylesheets 404 I am running on Compass on Rails 3.0 on Heroku and its pretty much working fine, but I occasionally have an issue where (some?) stylesheets aren't compiled as fast as the rest of the page so they aren't served (the .css links cause 404's and the page is then displayed unstyled).
Do you guys know of a way to make Compass compile all stylesheets on server start up (in prod) and then not touch them again? That way it'll basically precompile all the necessary stylesheets and there won't be an issue?
Or alternately, would it make more sense to call some script before heroku deploy that compiled all the stylesheets to public/stylesheets, and then turn off Compass in production altogether?
Thanks!

A: Based on the discussion here:
Using Compass on Heroku: /tmp for stylesheets remotely and locally
I decided that I would rather turn off stylesheet compilation on the server entirely as you suggest as your alternate approach.
I have the following in my app's config.ru which is intended to achieve just that.
if (ENV['RACK_ENV'] || 'development') != 'development'
    require 'sass/plugin/rack'
    use Sass::Plugin::Rack
    Sass::Plugin.options[:never_update] = true
end

UPDATE: I replaced this approach with the simpler one of adding
Sass::Plugin.options[:never_update] = true

to the very bottom of my production.rb environment file which works a charm on Heroku. As described here:
http://ariejan.net/2010/09/28/precompile-sass-to-css-for-deployment-to-heroku


text:
Q: Paginated Posts - Social Media Buttons Share First Page URL I currently have the HTML5 Facebook, Twitter and G+ share buttons inserted into my single.php in WordPress, so it appears on all my post pages.
Everything works great until I write a very long article split into multiple pages using the nextpage tag.
The problem is if the reader is on page 3, and wanted to share the article, when they click the share button, they are prompted to share the URL of that particular page - nameofsite.com/nameofpost/3 and not of the first/main page of the article - http://www.nameofsite.com/nameofpost, so I am left with many post shares for different pages of the same article! Frown | :-(
Is there anyway I can overcome this for all my paginated posts?
Thank you,
James
Edit: I have used the following HTML:

Share This Post

Tweet

<a href="<?php comments_link(); ?>"><?php comments_number('No Comments', 'One Comment', '%' );?>

I have then entered in the following in .js file called nbzsocial.js:
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');

  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/platform.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();

(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=225721797619871";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

Which I have placed in a js folder in my child theme and enqueued in my functions PHP with this:
function wpse_load_scripts() {
    wp_enqueue_script( 'nbz-social', get_stylesheet_directory_uri() . '/js/nbzsocial.js', array(), '1.0', true );
}

add_action( 'wp_enqueue_scripts', 'wpse_load_scripts' );

Thank you for getting back to me so quickly, I have had no luck on the WordPress forums and Stack Overflow!

A: Is that share javascript getting called before or after the next page tag? Presumably, if its a shortcode, you want to be inserting it after the next page tag?


text:
Q: Would a regular expression help this search string? IN: "abc d efg" OUT: ["%abc%","%efg%"] Could this code be optimised with a regex?
search = search.split.delete_if{|s|s.length==1}.map{|s|s="%#{s}%"}

It takes a string, splits it into an array and removes any elements with a length of 1 and wraps each string in percent symbols ready for SQL.
IN: "abc d efg" OUT: ["%abc%","%efg%"]

A: This works, but it benchmarks slower, I don't think a regex based solution is going to be faster.
string.scan(/\S{2,}/).map { |word| "%#{word}%" }

Avoiding duplicating arrays seems to be the fastest I can think of:
words = string.split
words.reject! { |s| s.length == 1 }
words.map! { |s| "%#{s}%" }
words


text:
Q: initiate sp_databases for a c# listbox I have found that using sp_databases, it might possibly be able to populate a ListBox with all the databases on my remote server.
How I would incorporate that code on my form to get it to work properly?

A: From this namespace:
using System.Data.SqlClient;

Here is a solution:
using (SqlConnection cn = new SqlConnection("connection string to yer database"))
{
    SqlCommand cm = new SqlCommand("exec sp_databases", cn);
    SqlDataReader rdr;

    cn.Open();
    rdr = cm.ExecuteReader();
    if (rdr.HasRows())
    {
       while (rdr.Read())
       {
           listBox1.Items.Add(rdr["DATABASE_NAME"].ToString());
       }
    }
    rdr.Close();
}

As for connection string.  Here is a good reference:
http://www.connectionstrings.com/sql-server-2008


text:
Q: Android - Detect when the last item in a RecyclerView is visible I have a method that will check if the last element in a RecyclerView is completely visible by the user, so far I have this code
The problem is how to check  if the RecyclerView has reached it's bottom ?
PS I have items dividers
public void scroll_btn_visibility_controller(){
    if(/**last item is visible to user*/){
        //This is the Bottom of the RecyclerView
        Scroll_Top_Btn.setVisibility(View.VISIBLE);
    }
    else(/**last item is not visible to user*/){
        Scroll_Top_Btn.setVisibility(View.INVISIBLE);
    }
}

UPDATE : This is one of the attempts I tried
boolean isLastVisible() {
    LinearLayoutManager layoutManager = ((LinearLayoutManager)rv.getLayoutManager());
    int pos = layoutManager.findLastCompletelyVisibleItemPosition();
    int numItems =  disp_adapter.getItemCount();
    return (pos >= numItems);
}
public void scroll_btn_visibility_controller(){

    if(isLastVisible()){
        Scroll_Top.setVisibility(View.VISIBLE);
    }
    else{
        Scroll_Top.setVisibility(View.INVISIBLE);
    }
}

so far no success I think there is something wrong within these lines :
int pos = layoutManager.findLastCompletelyVisibleItemPosition();
int numItems =  disp_adapter.getItemCount();

A: You can create a callback in your adapter which will send a message to your activity/fragment every time when the last item is visible.
For example, you can implement this idea in onBindViewHolder method
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
    if(position==(getItemCount()-1)){
        // here goes some code
        //  callback.sendMessage(Message);
     }
    //do the rest of your stuff
}

UPDATE
Well, I know it's been a while but today I ran into the same problem, and I came up with a solution that works perfectly. So, I'll just leave it here if anybody ever needs it:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        LinearLayoutManager layoutManager=LinearLayoutManager.class.cast(recyclerView.getLayoutManager());
        int totalItemCount = layoutManager.getItemCount();
        int lastVisible = layoutManager.findLastVisibleItemPosition();

        boolean endHasBeenReached = lastVisible + 5 >= totalItemCount;
        if (totalItemCount > 0 && endHasBeenReached) {
            //you have reached to the bottom of your recycler view
        }
    }
});

A: try working with onScrollStateChanged it will solve your issue

A: You should use your code with following change:
boolean isLastVisible() {
    LinearLayoutManager layoutManager =((LinearLayoutManager) rv.getLayoutManager());
    int pos = layoutManager.findLastCompletelyVisibleItemPosition();
    int numItems = rv.getAdapter().getItemCount();
    return (pos >= numItems - 1);
}

Be careful, findLastCompletelyVisibleItemPosition() returns the position which start at 0. So, you should minus 1 after numItems.

A: Assuming you're using LinearLayoutManager, this method should do the trick:
boolean isLastVisible() {
  LinearLayoutManager layoutManager = ((LinearLayoutManager)mRecyclerView.getLayoutManager());
  int pos = layoutManager.findLastCompletelyVisibleItemPosition();
  int numItems = mRecyclerView.getAdapter().getItemCount();
  return (pos >= numItems);
}

A: Try this solution as it depends on how you want to implement the chat.
In your onCreate() method add the call to post to your recyclerview and implement the runable method, this to guarantee that the element has already been loaded and then execute the scrollToPosition method adding the last element of your list as a parameter.
recyclerView.post(new Runnable() {
   @Override
   public void run() {
      recyclerView.scrollToPosition(yourList().size()-1);
   }
});


text:
Q: Blazor always shows dates in UTC format I'm currently working on some Blazor demos and samples and find out that in any supported browser it always displays date time and timezone in UTC format. My actual time zone is different from UTC.
Are there any restrictions in Blazor or WebAssembly? I'm using Blazor version 0.7.0 and there is a code snippet
@functions
{
    protected override void OnInit()
    {
        Console.WriteLine($"OS: {RuntimeInformation.OSDescription} {RuntimeInformation.OSArchitecture}");
        Console.WriteLine($"Processor: {RuntimeInformation.ProcessArchitecture}");

        Console.WriteLine($"Timezone is {TimeZoneInfo.Local}");
        Console.WriteLine($"Date time is {DateTime.Now}");
    }
}

Edit: Accroding to the WebAssembly: Missing Timezone implementation GitHub issue, it's still an open issue

A: This is a known issue related to Mono Runtime when Blazor is run in Client Side. Is being tracked by WebAssembly: Missing Timezone implementation
You can use this library as workaround Toolbelt.Blazor.TimeZoneKit

A: localisation isn't currently supported by mono. I've written a post (https://chrissainty.com/simple-localisation-in-blazor/) showing how you can implement localisation in your Blazor apps.
I've also published a nuget package Blazored.Localisation if you just want to get on and not write things yourself.

A: If you are wanting to show dates and times in your browsers local time check out the Blazor Time library.
It introduces a <ToLocal> tag where you feed it a UTC or Server time and it will convert it to local.
<ToLocal DateTime="testUtcTime" Format="ddd mmm dd yyyy HH:MM:ss"></ToLocal>


text:
Q: How to implement drawerlayout with custom action bar? If i use default actionbar i can set home button to open and close drawerlayout with this code.
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);

And it's work well.
But i dont't want default actionbar i want actionbar with customlayout.
When i use custom actionbar i don't know how to implement home button for open and close drawerlayout.
How to implement drawerlayout with custom action bar?
PS. I use custom actionbar because i want set title text to align center of actionbar, set text and text size to it's.
EDIT
thank you every body i can solve it's by use this.
getActionBar().setCustomView(R.layout.actionbar);
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP);

it's work well but the home button image change from app logo to app icon.

A: You can create custom Action bar like this ..
// gets actionBar reference ..
actionBar = getSupportActionBar();

// This sets custom layout to action bar
actionBar.setCustomView(R.layout.action_provider);

// this is how... .... you get id of layout defined
iv_d = (ImageView) actionBar.getCustomView().findViewById(R.id.action_menu);

Now just open you drawer on click of this icon using OnClick()
That's it .. you are good to go.


text:
Q: Vim filter command for one word Is it possible to run vim filter command(:!) for only one word. Not on whole line as default? Or maybe is it possible to run something like: command (word from file)?

A: I think you can use the system() function.
Test in Windows
before:
date /t

run command:
:s@date /t@\=system(submatch(0))@

after:
Sun 02/19/2012


text:
Q: use Python .format(urlencode) in a for Loop I have a dict with some Id's as a value list. For this list I want to use a loop to insert each ids and the key in the URL using .format.
The goal is that the URL looks like this:
data = urllib.request.urlopen('https://lignumdata.ch/api/v1.cfc?method=getBauteil&type=all&condition={"**KEY**":"**ITEM FROM LOOP**"}').read()

How do I have to proceed?
my code:
myDict = {'={"id":'['1838A0BD-EFED-AC5F-110BFF3266C2A08C', '1838C66B-0E3C-0073-A52F55BFEF1CDDD7', '1838D369-FE2D-54FD-993706CE152D2A1D', '18398B8C-0B6B-33A6-92BAA6FB216995F9', '18399F2E-BCA9-0457-C28BAFA5F7466181', '1839AD62-B125-1D7C-E4FD205840A3B7B4', '183A43AD-9D1C-8121-D3FA5FB69C2BE2CF', '183A53B2-CBB5-13B3-29B77034EABCE1C8', '183A61F0-CD79-878B-EA9943B8C9EA12D0', '183A692D-ED62-DA89-057A2630F061B29F', '183AC5C6-BF39-0359-12C6FBB14392EAFC', '183AD460-9F06-3841-E660630702C40991']}

Result should look like this:
data = urllib.request.urlopen('https://lignumdata.ch/api/v1.cfc?method=getBauteil&type=all&condition={"id":"192E4CD9-B41B-09E3-1C2148F313A3A83B"}').read()

Thanks for your help! :)

A: In python3 You can use f' ' syntax to format a string. Combination of that with a Lambda function can define you formatting template.
Also to iterate over keys of a dictionary you can use dict.keys function.
d = {"id": ["1", "2", "3"]}
url = lambda k,v : f'https://lignumdata.ch/api/v1.cfc?method=getBauteil&type=all&condition={{"{k}":"{v}"}}'

for k in dict.keys(d):
    for v in d[k]:
        print(url(k,v))


text:
Q: GTK - Enable/set dark theme on a per-application basis Is there a way to set gtk-application-prefer-dark-theme for an application?
This is normally set in the code by the application. Apps such as Eye of Gnome and Totem turn it on. I want to, as a user turn it on, on a per application bases.
For gnome-terminal, I normally use a white text on black background color scheme, and having the dark window border would improve the overall look.
I also want to turn it on for vlc.

A: If somebody still need it, I've created simple app that will automatically set dark theme for specified apps.
You can find it here: https://github.com/galczo5/gnome-dark-apps

A: I wrote a little wrapper script for that:
#!/bin/bash

if [ $# -eq 0 ]; then
    xprop -f _GTK_THEME_VARIANT 8u -set _GTK_THEME_VARIANT "dark"
    exit $?
fi

GTK_THEME="$(gsettings get org.gnome.desktop.interface gtk-theme)"
export  GTK_THEME="${a%%:*}:dark"
export GTK_THEME_VARIANT="dark"
"$@" & PID="$!"
echo "started darkening for PID=$PID"
cnt=0
while :; do
    if [ $cnt -lt 1000 ]; then
        sleep .1
        let 'x=x-1'
    else
        sleep 5
    fi
    if ! kill -0 $PID 2>/dev/null; then
        echo "darkening for PID=$PID done"
        exit 0
    fi
    REGEX="$(echo $PID | cat - <(command ps -o pid:1 --no-headers --ppid $PID) | paste -sd "|" -)"
    wmctrl -lp \
        | rg -i "^(0x[a-f0-9]+)\s+\d+\s+($REGEX)\s" -o --replace '$1' \
        | xargs -I @ xprop -f _GTK_THEME_VARIANT 8u -set _GTK_THEME_VARIANT "dark" -id @
done

It'S using https://github.com/BurntSushi/ripgrep for REGEX

A: For GTK+-3 applications, you can enforce the dark theme variant using GtkSettings' settings.ini:
$ mkdir -p $HOME/.config/gnome-terminal/gtk-3.0 # the path before gtk-3.0 is arbitrary
$ cat >> $HOME/.config/gnome-terminal/gtk-3.0/settings.ini << EOF
[Settings]
gtk-application-prefer-dark-theme=true
EOF
$ echo 'alias gnome-terminal="XDG_CONFIG_HOME=$HOME/.config/gnome-terminal gnome-terminal" >> $HOME/.bashrc

For non-GTK+ applications like vnc, you can still enforce dark window decorations by setting the _GTK_THEME_VARIANT X property of type UTF8_STRING to dark. To do this with xprop, type the following command and click the window afterwards:
$ xprop -f _GTK_THEME_VARIANT 8u -set _GTK_THEME_VARIANT "dark"

xprop can also select windows by the WM_NAME property (the title bar label) or by window id:
$ xprop -f _GTK_THEME_VARIANT 8u -set _GTK_THEME_VARIANT "dark" -name "Spotify Premium - Linux Preview"
$ xprop -f _GTK_THEME_VARIANT 8u -set _GTK_THEME_VARIANT "dark" -id 0x380002b

To get window ids and names, use xlsclients -l.

A: Specifically for gnome-terminal, you can use the following to make the specific application dark:
gsettings set org.gnome.Terminal.Legacy.Settings theme-variant 'dark'

A: I have the same issue with dark theme on Ubuntu 20.04 and have a work around for the issue with vmware horizon client.  I would prefer dark mode to be supported but this will do for now.

*

*Close vmware horizon client.

*In terminal navigate to this directory:
cd /usr/share/applications

*Once in there
sudo nano vmware-view.desktop

*On line 4 it should have:
Exec=vmware-view %u

*Change it to:
Exec=env GTK_THEME=Yaru-light vmware-view %u

*Save the file.

Restart app and now you should be able to view everything properly.
If you don't have Yaru-light as a theme you may need to change it to what ever your OS light theme is named.
I hope this helps some people.

A: With gtk+ ≥ 3.12 you can load a specific theme and its variant (dark, light) on a per-application1 basis via the environment variable GTK_THEME=theme:variant. As per the gtk+ reference manual:
GTK_THEME.  If set, makes GTK+ use the named theme instead of the theme that is
specified by the gtk-theme-name setting [...] It is also possible to specify a
theme variant to load, by appending the variant name with a colon, like this:
GTK_THEME=Adwaita:dark.

So, to load2 the dark variant you would run:
GTK_THEME=Adwaita:dark gedit

Likewise, to achieve the opposite (when the default theme is dark), you load the light variant:
GTK_THEME=Adwaita:light gedit

Note that if you want to use it via a custom launcher (.desktop file) you'll have to prepend env to the  command in the Exec line:
Exec=env GTK_THEME=Adwaita:dark eog %U

1: Worth noting that - as per the devs decision - newer gnome-terminal has its own configuration via menu > preferences and it ignores the theme. Also, since this is rather new stuff, some gtk+ 3 applications might not (yet) honor the GTK_THEME environment variable.
2: This doesn't seem to work if you already have a running instance of that application e.g. if nautilus is already running in dark mode then running GTK_THEME=Adwaita:light nautilus will open a new nautilus window but still in dark mode. I don't know if this is a feature or a bug...

A: Here is a bash script I have used to launch a application with a different theme. Haven't used it in years though, so I don't know if it will work with the current GTK.
#!/bin/bash
# lauch a gtk application with a different theme
# set GTKRCFILE variable to your favourite theme
GTKRCFILE=Clearlooks
GTK2_RC_FILES=/usr/share/themes/"$GTKRCFILE"/gtk-2.0/gtkrc "$@"

Here is a bit of info I got off the ubuntu fourms archives. Not sure if it will be a problem. (here) There is also a blog post detailing this method a little more. (here) and (here). There is also a similar question on this site that has already been answered. (here)

Under gnome, apps get their theme from the gnome-settings-daemon. This instantaneously applies any theme change to all active applications, making per-appplication theme changing impossible.

A: This is my solution as of August 2022, based on galczo5's answer & code:
#!/bin/bash
PREVID=
CLASSES=(
    "code"
    "insomnia"
    "spotify"
)
while true;
do
    ID=$(xprop -root _NET_ACTIVE_WINDOW | egrep -o '0x[a-fA-F0-9]+')
    if [[ "$ID" != "0x0" ]]; then
        CLASS=$(xprop -id "$ID" WM_CLASS)
        if [[ "$ID" != "$PREVID" ]]; then
            PREVID=$ID
            for i in "${CLASSES[@]}"
            do
                if echo "$CLASS" | grep -lq "$i"; then
                    echo "Set dark theme to $CLASS $ID"
                    xprop -f _GTK_THEME_VARIANT 8u -set _GTK_THEME_VARIANT "dark" -id "$ID"
                fi
            done
        fi
    fi
    sleep 1
done

Put this in a script anywhere in your system, it'll run in a loop every 1 second (or whatever you set in the last sleep 1 line). Put the window classes you want to have dark theme on in the CLASSES array, following the example.

A: Merging the various solutions by paveloom and DARKGuy:
watch -n 5 "xdotool search --sync --onlyvisible --classname '' | xargs -I{} -r xprop -f _GTK_THEME_VARIANT 8u -set _GTK_THEME_VARIANT 'dark' -id {}"

It runs every 5 seconds and set every window title bar to black.
The xargs call needs an -n1 or the -I{} <command> {} syntax, including when setting an explicit classname as there may be multiple pids and the command should be set on every of them (the command would fail if more than one pid is passed).

A: Simplifying the solution proposed by Black Rain and expanding on the Florian Müllner's answer, you can use xprop to dynamically change the theme variant and xdotool to find the target window's ID after it's open, all in one call. Here's an example for an Emacs client:
emacsclient -c -a '' & xdotool search --sync --onlyvisible --classname "emacs" | xargs -r xprop -f _GTK_THEME_VARIANT 8u -set _GTK_THEME_VARIANT "dark" -id

To use it in a .desktop file, wrap it in a shell call:
Exec=bash -c 'emacsclient -c -a "" %F & xdotool search --sync --onlyvisible --class "emacs" | xargs -r xprop -f _GTK_THEME_VARIANT 8u -set _GTK_THEME_VARIANT "dark" -id'


text:
Q: "object object" in Suggested review if reject option selected This I found while reviewing suggested edit on stackoverflow... As you can see from screenshot below .. [object Object] is displayed and Im curious what that might be...

Steps to reproduce:-

*

*Visit suggested edit review queue.

*When question pop up, click on reject option..

There it is...
Checked on Chrome(Version 30.0.1599.101 m) and FireFox(Version 25.0)

A: Thanks for reporting.
A bit of JavaScript was expecting HTML and I was feeding it jQuery.
A rare case of too much jQuery.
Fixed in the next build.


text:
Q: Unable to Unit test Angular application using Karma and Jasmine Trying to unit test Angular (not AngularJS) application.
Here is the package.json
  "dependencies": {
    "@angular-redux/store": "^6.4.2",
    "@angular/animations": "^5.2.9",
    "@angular/cdk": "5.1.1",
    "@angular/common": "^5.2.9",
    "@angular/compiler": "^5.2.9",
    "@angular/core": "^5.2.9",
    "@angular/forms": "^5.2.9",
    "@angular/http": "^5.2.9",
    "@angular/material": "5.1.1",
    "@angular/platform-browser": "^5.2.9",
    "@angular/platform-browser-dynamic": "^5.2.9",
    "@angular/platform-server": "^5.2.9",
    "@angular/router": "^5.2.9",
    "@progress/kendo-angular-buttons": "^3.0.4",
    "@progress/kendo-angular-dateinputs": "^2.2.0",
    "@progress/kendo-angular-dropdowns": "^2.1.0",
    "@progress/kendo-angular-excel-export": "^1.0.7",
    "@progress/kendo-angular-grid": "^2.1.2",
    "@progress/kendo-angular-inputs": "^2.2.0",
    "@progress/kendo-angular-intl": "^1.3.2",
    "@progress/kendo-angular-l10n": "^1.1.0",
    "@progress/kendo-data-query": "^1.2.1",
    "@progress/kendo-drawing": "^1.5.1",
    "@progress/kendo-theme-bootstrap": "2.11.8",
    "@progress/kendo-theme-default": "^2.49.0",
    "angular2-jwt": "^0.2.2",
    "angular2-moment": "^1.7.0",
    "angular2-recaptcha": "^0.6.0",
    "angular5-recaptcha": "0.0.2",
    "core-js": "^2.4.1",
    "echarts": "^3.5.1",
    "font-awesome": "^4.7.0",
    "hammerjs": "^2.0.8",
    "immutability-helper": "2.6.0",
    "jquery": "^3.2.1",
    "jquery-slimscroll": "^1.3.8",
    "mdn-polyfills": "^3.1.0",
    "ng2-validation": "^4.2.0",
    "ngx-pagination": "^3.0.1",
    "popper.js": "^1.12.5",
    "redux": "^3.6.0",
    "reflect-metadata": "^0.1.10",
    "rxjs": "^5.5.6",
    "web-animations-js": "^2.2.5",
    "webfontloader": "^1.6.27",
    "zone.js": "^0.8.5"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.6.0",
    "@angular/cli": "1.7.0",
    "@angular/compiler-cli": "^5.2.9",
    "@angularclass/hmr": "^1.2.2",
    "@angularclass/hmr-loader": "^3.0.2",
    "@types/core-js": "^0.9.41",
    "@types/hammerjs": "^2.0.34",
    "@types/jasmine": "~2.8.0",
    "@types/jasminewd2": "^2.0.3",
    "@types/jquery": "^2.0.41",
    "@types/node": "^7.0.12",
    "add-asset-html-webpack-plugin": "^1.0.2",
    "angular-router-loader": "^0.6.0",
    "angular2-template-loader": "^0.6.2",
    "autoprefixer": "^6.7.7",
    "awesome-typescript-loader": "^3.1.2",
    "bootstrap": "~4.0.0-alpha.6",
    "browser-sync": "^2.18.8",
    "copy-webpack-plugin": "^4.0.1",
    "css-loader": "^0.28.0",
    "del": "^2.2.1",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.11.1",
    "gulp": "~3.9.0",
    "gulp-load-plugins": "^1.5.0",
    "gulp-open": "~2.0.0",
    "gulp-plumber": "~1.1.0",
    "gulp-pug": "~3.3.0",
    "gulp-task-listing": "~1.0.0",
    "gulp-util": "~3.0.4",
    "html-webpack-plugin": "^2.28.0",
    "json-loader": "^0.5.4",
    "ng-router-loader": "^2.1.0",
    "postcss-loader": "^1.3.3",
    "raw-loader": "^0.5.1",
    "rimraf": "^2.6.1",
    "sass-loader": "^6.0.4",
    "style-loader": "^0.16.1",
    "ts-helpers": "^1.1.2",
    "ts-node": "^3.0.2",
    "tslib": "^1.6.0",
    "tslint": "^5.0.0",
    "typescript": "^2.7.2",
    "webpack": "^2.2.1",
    "webpack-dev-server": "~2.3.0",
    "webpack-dll-bundles-plugin": "^1.0.0-beta.5",
    "webpack-merge": "^4.1.0",
    "yargs": "^7.0.2",
    "jasmine-core": "~2.99.1",
    "jasmine-marbles": "^0.3.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~1.7.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~1.4.2",
    "karma-jasmine": "~1.1.1",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-phantomjs-launcher": "^1.0.2"
  },
  "engines": {
    "node": ">=6.9.0",
    "npm": ">= 3"
  }
}

Here is tsconfig.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

Here is karma.config.js
module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular/cli/plugins/karma'),
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev'
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

With the above details ng test was throwing the following error
12 07 2018 11:12:27.391:INFO [Chrome 67.0.3396 (Windows 7.0.0)]: Connected on socket Y_50WuISYFnxSEPLAAAA with id 9725077
Chrome 67.0.3396 (Windows 7.0.0) ERROR
  Uncaught Error: Missing: SyncTestZoneSpec
  at http://localhost:9877/_karma_webpack_/vendor.bundle.js:202926
I tried to update the karma.config.js based on the
https://github.com/angular/zone.js/issues/404
by adding following references to karma config
  require('zone.js/dist/zone'),
  require('zone.js/dist/long-stack-trace-zone'),
  require('zone.js/dist/async-test'),
  require('zone.js/dist/fake-async-test'),
  require('zone.js/dist/sync-test'),
  require('zone.js/dist/proxy-zone'), // since zone.js 0.6.14
  require('zone.js/dist/jasmine-patch') // put here since zone.js 0.6.14

I see the following error there after
12 07 2018 11:39:54.918:ERROR [config]: Error in config file!
 ReferenceError: XMLHttpRequest is not defined
 at patchXHR (node_modules\zone.js\dist\zone.js:2892:39)
Any thoughts

A: Apprently I was updating karma config with zone.js details, instead it should be updated on tests.ts, and also it's a good idea to compare with a brand new application and try to keep the differences between them as minimal as possible.
As we update from one Angular version to another, we initially started with version 2 as we progressed to version 5 there were number of differences, and any one of those could break.
I have also compared the files for package.json, karma.config.js, tsconfig.json .
And it made the trick.


text:
Q: 20.04 launcher highlighting On 16.04 keyboard shortcut Alt+f1 highlights launcher (same as super + t on Windows) then arrow keys left/rieght can go through icons to open hitting enter, see info if hitting menu, selct action from opened list in menu.
This function is not possible on 20.04 ; similar is just super + number 1 to 9 opening corresponding app to the numbered icon.
Any workaround ?

A: On Ubuntu 20.04, Alt+F1 opens the Activities Overview. The same is achieved using Super+s and also pressing and releasing Super.
The shortcut to directly go to the Applications overview is Super+a. Once you are there, you can use the arrow keys to move to the different icons, and PgUp/PgDn to move between the pages.
Once an application icon is highlighted, press Enter to run it. Hit Shift+F10 to see its context menu.
You could change Alt+F1 to show the applications overview rather than the activities overview in "Settings" - "Keyboard Shortcuts". Disable the existing binding of "Show activities overview" (under the "System" section) then change the binding for "Show all applications" to Alt+F1


text:
Q: Reset custom file input after ajax submit I have custom file inputs on a form that submits files through ajax. Everything works correctly and the form gets reset. But I have some javascript actions that are supposed to take place after there's a change in the file input but it only works the first time a file is selected and submitted.
_form.html.erb
<%= simple_form_for(@medium, :html => { :id => 'media_form', :multipart => true }, remote: true) do |f| %>

         Browse
          <%= f.input :asset, label: false, error: false, as: :file, :input_html => { id: 'file-upload', class: 'cfu' } %>

    <%= f.button :submit, 'Upload', :class => "btn btn-warning" %>

<% end %>

file-input.css
.custom-file-upload input[type="file"] {
    /*opacity: 0;
    filter: alpha(opacity=0);*/
    position: absolute;
    left: -9999px;
}
.cfu_label {
  padding: 6px 12px;
  display: inline-block;
  background: #f06048;
  cursor: pointer;
  color: #fff;
  /* font-size: 15px; */
  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
  border-radius: 5px;
  opacity: .85;
}
.cfu_label:hover {
    opacity: 1;
}

file-input.js
$(document).ready(function() {

    $('#file-upload').change(function() {
        $('i', '.fu1_wrap').removeClass("icon-arrow-up");
        $('i', '.fu1_wrap').addClass("icon-ok");
        $('label[for="file-upload"]', '.fu1_wrap').css("background-color", '#3fa46a');
    });

});

create.js.erb
$('i', '.custom-file-upload').removeClass("icon-ok");
$('i', '.custom-file-upload').addClass("icon-arrow-up");
$('.cfu_label', '.custom-file-upload').css("background-color", '#f06048');
$(".m_list").prepend("<%= escape_javascript(render :partial => @medium, :locals => {:medium => @medium}) %>");
$('#media').modal('hide');
$('#media_form')[0].reset();

As I stated the form submits perfectly fine; the problem is that if I try to submit another file after the first one the code from my file-input.js doesn't seem to be firing as the button doesn't change again. It only works the first time. What am I missing here? Thanks in advance.

A: You are attaching your event handler on document "ready" event, but this event only fires once - when the page is first fully loaded. Right code would be something like this:
$(document.body).on('change', '#file-upload', function() {
  $('i', '.fu1_wrap').removeClass("icon-arrow-up");
  $('i', '.fu1_wrap').addClass("icon-ok");
  $('label[for="file-upload"]', '.fu1_wrap').css("background-color", '#3fa46a');
});

Here I attached event handler unobtrusively to the body tag.
see documentation.
Edit: to give you more insight on what is happening - you are attaching event handler to your input DOM node, but after you re-render rails view via ajax, that node is gone, rails UJS driver removes it with the rest of the page before inserting re-rendered view, and so event handler is gone too.


text:
Q: How to get the name of an object to call a class method if I don't know the name? I have a class called AttendanceSystem:
LinkedList<LinkedList<String>> student = new LinkedList<LinkedList<String>>();

public AttendanceSystem(String s){
    student.add(new LinkedList<String>());
    student.get(student.size()-1).add(s);
}

public void setEmail(String d){
     student.get(student.size()-1).add(d);
}

In my main I have this:
System.out.println("Please enter your ID.");
String s = keyboard.nextLine();
new AttendanceSystem(s);

System.out.println("Please enter your Email.");
String d = keyboard.nextLine();

I want to add more elements into the object but since I used new AttendanceSystem(s) I don't know the name of the object I created so I cannot simply do objectname.setEmail(s). How can I call a method to that very object? Or is there a better way to do this?
I am using a scanner so I can keep adding new objects automatically until I tell it to stop.
UPDATED:
My main now:
  LinkedList<AttendanceSystem> list = new LinkedList<AttendanceSystem>();

System.out.println("Please enter your ID.");
String s = keyboard.nextLine();
list.add(new AttendanceSystem(s));

System.out.println("Please enter your Email.");
String d = keyboard.nextLine();
list.get(list.size()-1).setEmail(d);

I stored all the objects in a linked list so I can just do this list.get(list.size()-1).setEmail(d);.

A: Simply:
AttendanceSystem identiferName = new AttendanceSystem(s);

then use the setEmail to set the relevant data for that object.
EDIT
you might want to create an addAttendee method which will take the ID and Email then simply add it to the LinkedList inside the AttendanceSystem class.
public void addAttendee(String id, String email){
       LinkedList<String> myList = new LinkedList<>();
       myList.add(id);
       myList.add(email);
       this.student.add(myList);
}

note - in this case, you should just get rid of the constructor parameter & don't use it to add any IDs or Emails.
With does changes in mind and considering that you don't want to store a reference to a new object, you call it like this:
new AttendanceSystem().addAttendee(id,email);


text:
Q: Create Azure Automation Start/Stop solution through Terraform I'm trying to set up machines to be automatically start/stopped using the newish Azure Automation add-in (https://learn.microsoft.com/en-us/azure/automation/automation-solution-vm-management) with this being set up by Terraform.
I can create the automation account but I don't know how to create the start-stop functionality, can someone help fill in the blanks?

A: the AzureRM provider can manage aspects of runbooks. If you have a look at the documentation here. Using azurerm_automation_runbook and azurerm_automation_schedule you can create and schedule runbooks. The Microsoft solution requires parameters on the runbooks, I don't see any attributes in the provider to add parameters so this may not be possible.

A: You can pass the required parameter in this resource provider "azurerm_automation_job_schedule". Please note the Parameters attribute in the below code this is how we can pass the required parameter. You can refer this link for more details. https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/automation_job_schedule
resource "azurerm_automation_job_schedule" "startvm_sched" {
  resource_group_name     = "IndraTestRG"
  automation_account_name = "testautomation"
  schedule_name           = azurerm_automation_schedule.scheduledstartvm.name
  runbook_name            = azurerm_automation_runbook.startstopvmrunbook.name
   parameters = {
    action        = "Start"
  }
  depends_on = [azurerm_automation_schedule.scheduledstartvm]
}

Below is the complete code for VM Start/Stop job schedule resource provider "azurerm_automation_schedule" and "azurerm_automation_job_schedule"
resource "azurerm_automation_schedule" "scheduledstartvm" {
  name                    = "StartVM"
  resource_group_name     = "IndraTestRG"
  automation_account_name = "testautomation"
  frequency               = "Day"
  interval                = 1
  timezone                = "America/Chicago"
  start_time              = "2021-09-20T13:00:00Z"
  description             = "Run every day"
}

resource "azurerm_automation_job_schedule" "startvm_sched" {
  resource_group_name     = "IndraTestRG"
  automation_account_name = "testautomation"
  schedule_name           = azurerm_automation_schedule.scheduledstartvm.name
  runbook_name            = azurerm_automation_runbook.startstopvmrunbook.name
   parameters = {
    action        = "Start"
  }
  depends_on = [azurerm_automation_schedule.scheduledstartvm]
}

resource "azurerm_automation_schedule" "scheduledstopvm" {
  name                    = "StopVM"
  resource_group_name     = "IndraTestRG"
  automation_account_name = "testautomation"
  frequency               = "Day"
  interval                = 1
  timezone                = "America/Chicago"
  start_time              = "2021-09-20T10:30:00Z"
  description             = "Run every day"
}

resource "azurerm_automation_job_schedule" "stopvm_sched" {
  resource_group_name     = "IndraTestRG"
  automation_account_name = "testautomation"
  schedule_name           = azurerm_automation_schedule.scheduledstopvm.name
  runbook_name            = azurerm_automation_runbook.startstopvmrunbook.name
  parameters = {
    action        = "Stop"
  }
  depends_on = [azurerm_automation_schedule.scheduledstopvm]
}


text:
Q: How do I add a hyperlink to an image located inside a data array? I'm trying to add a hyperlink to an image that is located inside a data array and cannot figure it out. I want the link to point to JackRussell.html. Maybe someone here can help me out. The code is inside the index.js page.
data = [
   {
      "animal":"Dog",
      "type":"Jack Russell Terrier",
      "image":"img/JackRussell.jpg"
   }

];

I've tried the following code and the picture shows up but no hyper link were created as a result
"image":"img/JackRussell.jpg.http://www.jackrussell.html
What I need as a final result is to make the image clickable and take to me the corresponding page.
Thank you in advance.

A: It's fairly simple as long as you have the name of the page you want to go to:

const data = [{
  animal: "Dog",
  type: "Jack Russell Terrier",
  image: "img/JackRussel.jpg",
  page: "jackrussell.html"
}];
let myDog = data[0];
document.getElementById("linkBox").innerHTML = `<a href="${myDog.page}"><img src="${myDog.image}" alt="This is a(n) ${myDog.type}" title="${myDog.animal}"></a>`;

A: Have a look to W3school | HTML Images the below is simple example to open the link in new tab using target="blank"

In your example if the clickable link is the image URL, check the below

data = [
 {
  "make": "Gibson",
  "model": "Les Paul",
  "type": "Electric",
  "price": "$3,000",
  "image": "http://www.sweetwater.com/images/items/120/LPST5HTHDCH-medium.jpg?9782bd"
 },
 {
  "make": "Gibson",
  "model": "SG",
  "type": "Electric",
  "price": "$1,500",
  "image": "http://www.sweetwater.com/images/items/120/SGSEBCH-medium.jpg?e69cfe"
 },
 {
  "make": "Fender",
  "model": "Telecaster",
  "type": "Electric",
  "price": "$2,000",
  "image": "http://www.sweetwater.com/images/items/120/TelePLMPHB-medium.jpg?28e48b"
 },
 {
  "make": "Fender",
  "model": "Stratocaster",
  "type": "Electric",
  "price": "$2,000",
  "image": "http://www.sweetwater.com/images/items/120/StratAMM3SB2-medium.jpg?dfd0a9"
 },
 {
  "make": "Gretsch",
  "model": "White Falcon",
  "type": "Electric",
  "price": "$5,000",
  "image": "http://www.sweetwater.com/images/items/120/G613655GE-medium.jpg?9bfb0e"
 },
 {
  "make": "Paul Reed Smith",
  "model": "Custom 24",
  "type": "Electric",
  "price": "$5,000",
  "image": "http://www.sweetwater.com/images/items/120/HBII10BGWB-medium.jpg?982763"
 },
 {
  "make": "Gibson",
  "model": "Hummingbird",
  "type": "Acoustic",
  "price": "$2,500",
  "image": "http://www.sweetwater.com/images/items/120/SSHBHCNP-medium.jpg?11fbea"
 }
];

var products = "",
 makes = "",
 models = "",
 types = "";

for (var i = 0; i < data.length; i++) {
 var make = data[i].make,
  model = data[i].model,
  type = data[i].type,
  price = data[i].price,
  rawPrice = price.replace("$",""),
  rawPrice = parseInt(rawPrice.replace(",","")),
  image = data[i].image;

 //create product cards
 products += "

Make: " + make + "
Model: " + model + "
Type: " + type + "
Price: " + price + "

";

 //create dropdown of makes
 if (makes.indexOf("<option value='" + make + "'>" + make + "</option>") == -1) {
  makes += "<option value='" + make + "'>" + make + "</option>";
 }

 //create dropdown of models
 if (models.indexOf("<option value='" + model+"'>" + model + "</option>") == -1) {
  models += "<option value='" + model + "'>" + model + "</option>";
 }

 //create dropdown of types
 if (types.indexOf("<option value='" + type + "'>" + type + "</option>") == -1) {
  types += "<option value='" + type + "'>" + type + "</option>";
 }
}

$("#products").html(products);
$(".filter-make").append(makes);
$(".filter-model").append(models);
$(".filter-type").append(types);

var filtersObject = {};

//on filter change
$(".filter").on("change",function() {
 var filterName = $(this).data("filter"),
  filterVal = $(this).val();

 if (filterVal == "") {
  delete filtersObject[filterName];
 } else {
  filtersObject[filterName] = filterVal;
 }

 var filters = "";

 for (var key in filtersObject) {
    if (filtersObject.hasOwnProperty(key)) {
   filters += "[data-"+key+"='"+filtersObject[key]+"']";
   }
 }

 if (filters == "") {
  $(".product").show();
 } else {
  $(".product").hide();
  $(".product").hide().filter(filters).show();
 }
});

//on search form submit
$("#search-form").submit(function(e) {
 e.preventDefault();
 var query = $("#search-form input").val().toLowerCase();

 $(".product").hide();
 $(".product").each(function() {
  var make = $(this).data("make").toLowerCase(),
   model = $(this).data("model").toLowerCase(),
   type = $(this).data("type").toLowerCase();

  if (make.indexOf(query) > -1 || model.indexOf(query) > -1 || type.indexOf(query) > -1) {
   $(this).show();
  }
 });
});
body {
 padding-top: 30px;
}
.product {
 margin-bottom: 30px;
}
.product-inner {
 box-shadow: 0 0 10px rgba(0,0,0,.2);
 padding: 10px;
}
.product img {
 margin-bottom: 10px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

  <form id="search-form" action="" method="POST" enctype="multipart/form-data">

    <input class="form-control" type="text" placeholder="Search" />

    <button type="submit" class="btn btn-block btn-primary">Search</button>

  </form>

  <form>

    <select data-filter="make" class="filter-make filter form-control">
     <option value="">Select Make</option>
     <option value="">Show All</option>
    </select>

    <select data-filter="model" class="filter-model filter form-control">
     <option value="">Select Model</option>
     <option value="">Show All</option>
    </select>

    <select data-filter="type" class="filter-type filter form-control">
     <option value="">Select Type</option>
     <option value="">Show All</option>
    </select>

    <select data-filter="price" class="filter-price filter form-control">
     <option value="">Select Price Range</option>
     <option value="">Show All</option>
    </select>

  </form>


text:
Q: strange html5 behavior The following html(5) produces a black line at the bottom of the div. This is caused, because the div get's heigher than the contained image. But I wonder why this happens?
<!DOCTYPE html>

I dont think it's a browser bug, because the result is the same in Firefox, Chrome and Opera. It renders fine when a XHTML doctype is used:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

BTW: It does work in html5 too, but only when I set display:block for image. Is this really needed?

A: It's not the XHTML doctype as such that changes it, it's more like strict vs transitional.
Using a XHTML 1.0 transitional doctype puts the browser into limited-quirks mode, whereas the HTML5 style doctype selects standards mode. The vertical-align of images is different between the two modes.
You can see the same black line if you use <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">which also puts the browser into standards mode.
There are a number of ways to remove the black line. One is to set the img to display:block.
Another is to set the img to vertical-align:bottom.

A: The black bar is your background color showing. If you don't want to see the black, one option is to remove the background:#000 from your div's style attribute.
Also, why are you using height: 50px in your style attribute? If you're trying to resize the image itself, use the height attribute instead.
OPTION 2:
This code seems to also remove the black background form showing:
<!DOCTYPE html>


text:
Q: Can't confirm any actors are being created In Service Fabric I am trying to call an ActorService and get a list of all actors. I'm not getting any errors, but no actors are returned. It's always zero.
This is how I add actors :
ActorProxy.Create<IUserActor>(
  new ActorId(uniqueName),
  "fabric:/ECommerce/UserActorService");

And this is how I try to get a list of all actors:
var proxy = ActorServiceProxy.Create(new Uri("fabric:/ECommerce/UserActorService"), 0);

ContinuationToken continuationToken = null;
CancellationToken cancellationToken = new CancellationTokenSource().Token;
List<ActorInformation> activeActors = new List<ActorInformation>();

do
{
  var proxy = GetUserActorServiceProxy();
  PagedResult<ActorInformation> page = await proxy.GetActorsAsync(continuationToken, cancellationToken);

  activeActors.AddRange(page.Items.Where(x => x.IsActive));

  continuationToken = page.ContinuationToken;
}
while (continuationToken != null);

But no matter how many users I've added, the page object will always have zero items. What am I missing?

A: The second argument int in ActorServiceProxy.Create(Uri, int, string) is the partition key (you can find out more about actor partitioning here).
The issue here is that your code checks only one partition (partitionKey = 0).
So the solutions is quite simple - you have to iterate over all partitions of you service. Here is an answer with code sample to get partitions and iterate over them.
UPDATE 2019.07.01

I didn't spot this from the first time but the reason why you aren't getting any actors returned is because you aren't creating any actors - you are creating proxies!
The reason for such confusion is that Service Fabric actors are virtual i.e. from the user point of view actor always exists but in real life Service Fabric manages actor object lifetime automatically persisting and restoring it's state as needed.
Here is a quote from the documentation:

An actor is automatically activated (causing an actor object to be constructed) the first time a message is sent to its actor ID. After some period of time, the actor object is garbage collected. In the future, using the actor ID again, causes a new actor object to be constructed. An actor's state outlives the object's lifetime when stored in the state manager.

In you example you've never send any messages to actors!
Here is a code example I wrote in Program.cs of newly created Actor project:
// Please don't forget to replace "fabric:/Application16/Actor1ActorService" with your actor service name.

ActorRuntime.RegisterActorAsync<Actor1> (
  (context, actorType) =>
    new ActorService(context, actorType)).GetAwaiter().GetResult();

var actor = ActorProxy.Create<IActor1>(
  ActorId.CreateRandom(),
  new Uri("fabric:/Application16/Actor1ActorService"));

_ = actor.GetCountAsync(default).GetAwaiter().GetResult();

ContinuationToken continuationToken = null;
var activeActors = new List<ActorInformation>();

var serviceName = new Uri("fabric:/Application16/Actor1ActorService");
using (var client = new FabricClient())
{
  var partitions = client.QueryManager.GetPartitionListAsync(serviceName).GetAwaiter().GetResult();;

  foreach (var partition in partitions)
  {
    var pi = (Int64RangePartitionInformation) partition.PartitionInformation;
    var proxy = ActorServiceProxy.Create(new Uri("fabric:/Application16/Actor1ActorService"), pi.LowKey);
    var page = proxy.GetActorsAsync(continuationToken, default).GetAwaiter().GetResult();

    activeActors.AddRange(page.Items);

    continuationToken = page.ContinuationToken;
  }
}

Thread.Sleep(Timeout.Infinite);

Pay special attention to the line:
_ = actor.GetCountAsync(default).GetAwaiter().GetResult();
Here is where the first message to actor is sent.

Hope this helps.


text:
Q: One-way Chi-Square goodness of fit and Cramér's V Would it make sense to apply a measure of association test like Cramér's V on a 1xk table?
I am a bit puzzled because in the literature phi and Cramér V are normally used on 2x2 or bigger contingency tables, but while I was looking for some more info, I found the following statement on Wikipedia:
"Cramér's V may also be applied to goodness of fit chi-squared models when there is a 1×k table (e.g.: r=1). In this case k is taken as the number of optional outcomes and it functions as a measure of tendency towards a single outcome."
No reference is provided though. What do you think about it? Could you please give me some bibliographic reference?


text:
Q: ALSA linking when cross-compiling Rust program for ARM I'm trying to cross-compile a simple Rust program to record sound with ALSA drivers on a Raspberry Pi Zero using the wavy crate inside a Docker container that has the libasound-dev library installed. However, the linker complains about:
 note: /opt/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/../lib/gcc/arm-linux-gnueabihf/4.8.3/../../../../arm-linux-gnueabihf/bin/ld: cannot find -lasound
          collect2: error: ld returned 1 exit status

It seems that Cargo is asking rustc to link against the asound lib dynamically with the argument -Bdynamic" "-lasound". How do I tell Cargo where to look for these ALSA libraries?
Update: I added the following to my Cargo.toml file and added --features "alsa-backend" to my cargo build command which seems to have progressed the build:
[features]
alsa-backend = ["alsa"]

[dependencies]
alsa            = { version = "0.2.1", optional = true }

It now throws:
note: /usr/lib/x86_64-linux-gnu/libasound.so: file not recognized: File format not recognized
          collect2: error: ld returned 1 exit status

OK, so it's linking against the x86_64 version of libasound.so. I typed dpkg -L libasound-dev in my Docker container and indeed, it lists /usr/lib/x86_64-linux-gnu/libasound.so instead of an ARM version.
How do I tell the Raspbian Docker container to link against the ARM version of libasound.so?

A: Solution:

*

*Install the armhf version of libasound-dev to your Raspbian docker image:

apt-get install libasound-dev -y
apt-get install libasound-dev:armhf -y

(If you only install libasound-dev:armhf, it will complain about alsa-sys linker errors.)

*Add alsa dependency to Cargo.toml:

[dependencies]
alsa = { version = "0.2.1", optional = true }
wavy = { path = "./wavy" }

*Set alsa-backend flag in Cargo.toml:

[features]
alsa-backend = ["alsa"]

*Pass --features "alsa-backend" to cargo build --target arm-unknown-linux-gnueabihf (target should be applied)

*Tell rustc to use the armhf version in .cargo/config:
[build]

[target.arm-unknown-linux-gnueabihf.libasound]
linker = "arm-linux-gnueabihf-gcc"
rustc-link-lib = ["libasound"]
rustc-link-search = ["/usr/lib/arm-linux-gnueabihf"]

(Depending on the order it links, it may try to use the x86 version instead of the armhf version.)


text:
Q: Enable Windows Time Service on Secondary Domain Controller We have an interesting scenario at my workplace.  Our primary domain controller started to fail, so we installed a secondary domain controller to allow people to login when the primary would fail.  Eventually the primary died completely (motherboard).  I replaced the motherboard with the same model, and the operating system works 99%.  However, when I plug the original primary domain controller back into the network, some users experience strange behaviors, such as randomly having no domain permissions, etc.
Anyway, we currently have the primary domain controller off of the network, and the backup is working fine for the most part.  I have been noticing that the time isn't synchronizing though.  Now when I try to force it by running from a client machine:
>w32tm /resync

I get the following message:
Sending resync command to local computer
The computer did not resync because no time data was available.

From what I have read, it seems that by default in a domain configuration, the time server is set to the primary domain controller.  Is there a way that I can set the secondary/backup domain controller to function as a time server so that the client machines will be able to sync with the domain?
If that is not possible, is there an easy way (either command-line, or through GPO) to configure the clients to just use a global time server such as time.windows.com to synchronize?

A: There is no primary or secondary domain controller, these are old, old, concepts that no longer exist, and a lot of people will get a bit huffy if you carry on referring to a primary and secondary domain controller.
In a Windows domain the domain hierarchy time sync has the PDC Emulator domain controller syncing from an internet time source (eg. pool.ntp.org, time.windows.com).  Other DCs sync from the PDC emulator, and the clients sync from any DC.
Is the DC that you have removed holding FSMO roles including PDC Emulator?  If so you have borked it.  Either re-introduce the DC you have removed, or seize the FSMO roles to the new DC you have created.
It's not good practice to set domain clients to sync from an internet time source, so I'll not provide instructions for that.  10 seconds with Google would get you that anyway.
Refer to this technet document for information about the windows time service:
https://technet.microsoft.com/en-us/library/cc773013(v=ws.10).aspx

A: Your biggest problem at the moment is you need to seize the FSMO roles and assign them to your remaining domain controller.
Seize the Operations Master Role
https://technet.microsoft.com/en-us/library/cc816779(v=ws.10).aspx
Probably a good idea to install a second domain controller.


text:
Q: Pointers passed by reference in Delphi (import functions from DLL) I want to use a function declared in a DLL which takes pointers as in/out parameters to fill up a record with non-pointer parameters.
Function from DLL:
function WFS_GetMlaData(   handle: WFS_HDL;
                           mla_idx: Integer;
                           mla_name:  TCharWFSBufferArray;
                       var cam_pitch_um: PDouble;
                       var lenslet_pitch_um: PDouble;
                       var center_spot_offset_x: PDouble;
                       var center_spot_offset_y: PDouble;
                       var lenslet_f_um: PDouble;
                       var grd_corr_0: PDouble;
                       var grd_corr_45: PDouble): Integer stdcall;

Record:
MlaInfo = record
    i : Integer;
    idx : Integer;
    name : TCharWFSBufferArray;
    camPitchUm : double;
    lensletPitchUm : double;
    spotOffsetx : double;
    spotOffsety : double;
    lensletFocalLengthUm : double;
    grdCorr0 : double;
    grdCorr45 : double;
end;

Function call:
if err = WFS_GetMlaData(handle,
                        MlaList[i].idx,
                        MlaList[i].name,
                        PDouble(MlaList[i].camPitchUm),
                        PDouble(MlaList[i].lensletPitchUm),
                        PDouble(MlaList[i].spotOffsetx),
                        PDouble(MlaList[i].spotOffsety),
                        PDouble(MlaList[i].lensletFocalLengthUm),
                        PDouble(MlaList[i].grdCorr0),
                        PDouble(MlaList[i].grdCorr45) ) then MyWFS_HandleErrors(handle, err);

With a similar function which passes pointers to integer it works, in the case above I have Invalid Typecast error.

A: Your DLL function is declared incorrectly. The original C code has all those parameters as pointers to double — double*. The sure-fire, can't-go-wrong solution is for you to change the function declaration to match the C code. Remove the var modifiers from all the function parameters.
The alternative solution is again for you to change the function declaration, but this time to make it look a little more like idiomatic Delphi. Keep the var modifiers, but change the parameters' type to Double instead of PDouble.
If you make the first change, then you would call the function by passing pointers to the record members: @MlaList[i].camPitchUm with no type casting. If you make the second change instead, then you would call the function by passing the record members directly, again with no type casting: MlaList[i].camPitchUm.

A: The answer is in the Parameters (Delphi) - Value and Variable Parameters documentation. My bold emphasizes it:

If a routine's declaration specifies a var parameter, you must pass an assignable expression - that is, a variable, typed constant (in the {$J+} state), dereferenced pointer, field, or indexed variable to the routine when you call it.

Regarding your case, my advice is to declare a new type:
PMlaInfo = ^TMlaInfo;

And change the signature of the function:
function WFS_GetMlaData(AHandle: WFS_HDL; const AMlaInfo: PMlaInfo): Integer stdcall;

But there's a sort of "hack" (dereferenced pointer):
PDouble((@MlaList[i].camPitchUm)^)


text:
Q: How to create regex with whitespace for filtering datatable I've a few predefined filter options on my page to filter my datatable. When clicking one, it gets added to the filter of the specific column. But I've a big problem with whitespaces... for example I've those options:
"old & good", "cheap & nice", "expensive"
All clicked options are stored in an array. For filtering I do
var term = array.join('|'); //--> term = "old & good|cheap & nice|expensive"
dataTable.fnFilter(term, column, true, true);

It works fine if there are no strings with whitespaces and "&" or only one.
a solo "cheap & nice" is working, but "cheap & nice|expensive" doesn't... also "expensive|what|ever" works when there are no whitespaces.
How can I get the filter work?
--------edit----------
some further explanation:
My code imports data from (user-defined) csv and generates for the first column some buttons, one for every unique entry in this column. The user can click on the buttons to filter the table, only the clicked entrys should be displayed. The button gets the entry as value, like in this example.
<input type="button" value="cheap & nice" onclick="myFilterFunction(this)"/>

To know wich buttons have been clicked, their value gets stored in a normal array. My callback function for the click looks into this array, joins the names to one regexp and gives this string to the fnFilter(), like posted above.
This works fine as long as there is no entry with whitespaces in it. But i can't remove the whitespaces, because then the filter can't find the entry wich really has whitespaces in it.

A: Finally, after a lot of hours, I found a solution for my problem.
var array = ["old & good","cheap & nice","expensive"];
var regexp = array.join('|').replace("&", "\\&").replace(/\s/g, "\\s");
--> "old\s\&\sgood|cheap\s&\snice|expensive"

Giving this term to the fnFilter() works!
But it would be nice to have a function, wich can convert all special characters to the corresponding regexp, in the style of @BoomyJee suggestion. If there is such a function, please let me know.

A: You should quote special characters.
If this is constant string just use slash 'old /& good'
If this is user input you should use quote function. There is no such function by default in JS, but you can use http://phpjs.org/functions/preg_quote/
    function preg_quote (str, delimiter) {
      return (str + '').replace(new RegExp('[\&.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');
    }

So if you have user input like:
    var input = ["old & good","cheap & nice","expensive"];
    var regexp_string = input.map(function(val){ return preg_quote(val,"/") }).join("|");

A: You could use something like this to remove whitespace in javascript instead of regex:
s.replace(/\s+/g, ' ');

Or  this
var str = "       Hello World!        ";
alert(str.trim());


text:
Q: Allocating memory to Array of structs in c++ and Initialisation I am fairly new to c++ programming. At least not very comfortable with the concept of pointers.
Here is a struct that I have defined as a part of a large program
typedef struct _MTLinfo {
    char* name;
    GLfloat Ns;
    GLfloat Ka[3];
    GLfloat Kd[3];
    GLfloat Ks[3];
    GLfloat Ni;
    GLfloat d;
    GLuint illum;
    GLfloat Km;
    char* mapKd;
    char* mapbump;
} MTLinfo;

Now I want to work with an array of such structs. However,I am immediately thrown with a memory corruption error sometimes and other times also the program does not work fine.
My task is to store certain values in an array of structs. The code I have been trying to get to work is
    MTLinfo* readmtl(GLMmodel* glmmodel,char* filename) {
        int index=-1;
        MTLinfo *info;
        /*Line Below is how I am allocating memory */
        info=(MTLinfo*)malloc((glmmodel->nummaterials)* sizeof *info) ;
        /* I have some other commands like the one below to store some text*/
     /* into the   array . They are not included because of irrelevance. */
        fscanf(file,"%s",&info[++index].name

Also, In some places, I am not initialising any value. For example info[4].d may not be defined anywhere. Should i make every single thing NULL/0 first or is not required? If yes, a small piece of code demonstrating so would help. I have tried a lot but have not been successful