text:
Q: onclick of parent of element I am using the following code:
$("#jplayer_playlist_item_" + i).data("index", i).click(function () {
  var index = $(this).data("index");

  if (playItem != index) {
    playListChange(index);
  } else {
    $("#jquery_jplayer").jPlayer("play");
  }

  $(this).blur();

  return false;
});

I am trying to get it so that when I click on the parent of "#jplayer_playlist_item_" + i" (which is a li) it continues with this function as it would if I had clicked the item itself.
I have tried to put .parent right before .click but it did not work.
Thanks

A: Have you tried removing .data("index",i) ?
The following should work:
$("#jplayer_playlist_item_" + i).parent().click(function()
    {
        var index = $(this).data("index");
        if (playItem != index)
        {
            playListChange(index);
        } else
        {
            $("#jquery_jplayer").jPlayer("play");
        }
        $(this).blur();
        return false;
    });

else start the selection with the following:
 $("#idofparentelement, #idofparentelement > #jplayer_playlist_item_" + i).data("index", i).click(function()
    {
        var index = $(this).data("index");
        if (playItem != index)
        {
            playListChange(index);
        } else
        {
            $("#jquery_jplayer").jPlayer("play");
        }
        $(this).blur();
        return false;
    });

A: If you want a click on the item and the parent to both be hooked up to the event handler, you could do this:
var item = $("#jplayer_playlist_item_" + i);
item.add(item.parent()).data("index", i).click(function() {
    ...
}

This will get your normal item into a jQuery object, then add the parent object to the select and then apply both the data("index", i) and the click handler to both item and click handler.
If we could see the actual HTML involved here, it's probably also possible to use delegated event handling and event bubbling to handle the click in one place for either element.

A: In addition to your code:
$("#jplayer_playlist_item_" + i).data("index", i).click(function() {
    var index = $(this).data("index");
    if (playItem != index) {
        playListChange(index);
    } else {
        $("#jquery_jplayer").jPlayer("play");
    }
    $(this).blur();
    return false;
});

Simply do this:
var $element = $("#jplayer_playlist_item_" + i);
$element.parent().click(function() {
    $element.click();
    return false;
});

A: Have you tried it this way. Since you knew that it is <li> and assuming its parent should be <ul>,
please try
$("#jplayer_playlist_item_" + i).data("index", i).parents('ul').click(function () {
.....
}


text:
Q: What are the hidden files on my new SD card? I just plugged in a brand new micro SDHC card; when I brought up Explorer there was a flash of a filename, and then nothing. The card shows as empty, but when I look at Properties it says there's 32K used. Going to a DOS prompt and using DIR shows nothing. Going to Cygwin and doing ls -la shows only . and .., but it also says there's 4 files in the directory.
I've configured Explorer to "show hidden files, folders, and drives" and unchecked "Hide protected operating system files".
It appears there's 2 super-hidden files. Any idea what they are or how to list them?

A: Try dir /a. It should show all files, even if they have the hidden attribute.
If they're still not showing, the first thing that comes to mind is that the card may have installed a rootkit that is hiding its own files. Do you have autorun enabled? The fact that the number of files reported and the actual list of files doesn't match up is very suspicious to me. dir should tell you the number of (non ./..) files in the directory being displayed in the summary
Try scanning with RootkitRevealer. If the files are only showing up in there you have a problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP / Ajax login to a network router We are making a system management website where we need to have the option to change the wifi channel and restart or shut down the router.
We made the Ajax functions that can do this if the router doesn't have a password. The functions simlpy sending the url with the necessary parameters to the router, for example: http://1.1.1.1/WifiRadioSet?adv_mode=bgn&adv_channel=11. But obviously you don't want to leave the router without password.
So my question is it possible to somehow login to a router automatically with PHP and/or Ajax or not?

A: Most routers use basic authentication. Therefore, you should be able to login via ajax using basic auth.
This article has a good example of how to do basic auth with ajax - https://zinoui.com/blog/ajax-basic-authentication
Or a good example I found here:
$.ajax({
     type: "GET",
     url: "http://localhost:8080/test",
     data: {username: "ajax", password: "code"},
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: OnSuccessCall,
     error: OnErrorCall
 });


text:
Q: What are the most effective unit upgrades in Atom Zombie Smasher? What do you find to be the most effective unit upgrades in Atom Zombie Smasher, and why?
Evac Helicopter

*

*Arrival Time or Load Time?

Artillery

*

*Impact Time or Reload Time?

Zed Bait

*

*Range, Lifetime, or Reload Time?

Infantry

*

*Accuracy or Speed?

Snipers

*

*Refire Time or Reposition Time?

A: Evac Helicopter
Arrival Time is my preference.  The faster it shows up, the faster I can get civilians out.  Load time is so short as to be inconsequential, really. (EDIT: As was pointed out in the comments) Load Time becomes more important if you increase the helicopter capacity by research - if you don't have faster load times, it may not fill entirely before lifting off.
Artillery
Reload Time is what I've found to be most useful, as it lets me fire more.  That said, without good Impact Time, it's hart to accurately target.  I keep these close to even, so it can shoot again as soon as the shells land.
Zed Bait
I'd say Range or Reload Time.  I must admit, I rarely use this enough to level it significantly.
Infantry
Accuracy has always been my first choice.  It stops more zeds, and if you structure your forces right, you end up funneling most of the to your infantry, so they don't have to move much.
Snipers
Refire Time, definitely.  Position them well at the start (I like a corner, with a target point across the map) and they can cover as many as half of the zed entry points.  This is wonderful when combined with artillery strikes on those areas.  Faster firing means more dead zed, and that leads to faster leveling of your snipers, and fewer victory points for the bad guys.


text:
Q: java getDeclaredAnnotations is not returning one attribute from an annotation java getDeclaredAnnotations is not returning one attribute from an annotation.
Steps:
1) Annotations are present in external Java class ( Carrier.java) which is compiled  and loaded dynamically :
@Facets(xpath = "/Carrier/Carrier_Id", displayString = "Carrier")
private String carrier_Id;

2) The annotation @Facets has this definition :
@Target(value = { ElementType.FIELD, ElementType.METHOD,ElementType.PARAMETER,
    ElementType.TYPE })

@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Facets {

@Target(value = { ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER,
        ElementType.TYPE })
@Retention(value = RetentionPolicy.RUNTIME)
public static @interface FacetDefinition {
    String xsdAttributeName() default VOID_STRING;
}

@FacetDefinition
String xpath() default VOID_STRING;

@FacetDefinition
String entityName() default VOID_STRING;

3) Below code to retrieve annotation attributes from the dynamically loaded class - (Carrier.class) :
Annotation[] annotations = field2.getDeclaredAnnotations();
for(Annotation annotation : annotations){

 if(annotation instanceof Facets)
 {
  Facets myAnnotation = (Facets) annotation;
  xpath = myAnnotation.xpath();
  displayName = myAnnotation.displayString();
  }

4) Value of one attribute - xpath is returned correctly, but second attribute -  displayString is always returned as an empty string.
displayString value is present in Carrier.class file:
javap -v Carrier.class
 #38 = Utf8               xpath
 #39 = Utf8               /Carrier/Carrier_Id
 #40 = Utf8               displayString
 #41 = Utf8               Carrier

But getDeclaredAnnotations is not retrieving this value, instead returning an empty string.
Could someone please help me with this.


text:
Q: Determine the number of occurrances of a character regardless of case I am new to Java & I want to be able to determine the number of occurrances of a character regardless of case. The text is inputted. This is what I have but I was readin by using indexOf its case sensitive and I don't want case sensitive:
public int getNumOfOccurrences(String source, String search) {
    int count = 0;
    int prevIndex = 0, curIndex = 0;
    if (source.length() > 0 && search.length()>0) {
        count=-1;
        while (curIndex >= 0) {
            curIndex = source.indexOf(search, prevIndex);
            prevIndex = curIndex + 1;
            count++;
        }
    }
    return count;
}

A: Do exactly the same as you have now, but call .ToLowerCase() on the source and search parameters before you start the counting. This will, obviously, put everything in lowercase.
Strings are immutable so you'll have to do String source = source.ToLowerCase(), or place it in a different variable if you want to keep the distinction.


text:
Q: How to get all jobs for current user and view every job
Missing keys required [:id] for child association show path

I have a job model that belongs to a user. In the user show page, I call all child jobs that belong to the user. Here is my code:
<% current_user.jobs.each do |j| %>
  <%= j.id %>
  <%= j.job_category %>
  <%= link_to 'show', job_path(j.id) %>

<% end %>

But it raises an error anytime I click on show jobs page:

No route matches {:action=>"show", :controller=>"jobs", :id=>nil, :user_id=>"1"} missing required keys: [:id]

Please, how do I rectify this error? the routes show jobs resources stands on its own with path: job_path. it works when I manually plug in the URL.
Here are my routes.rb:
resources :users do
  resources :jobs
  resources :applications
end

resources :jobs do
  collection do
    match 'search' => 'jobs#search', via: [:get, :post], as: :search
  end
end

and my controller code is:
class JobsController < ApplicationController

  def index
    @q = Job.ransack(params[:q])
      @jobs = @q.result(distinct: true)
  end

  def frontpage
    @q = Job.ransack(params[:q])
      if params[:q].present?
        redirect_to jobs_path(@q)
      end
    @jobs = Job.all
  end

  def search
    index
    render :index
  end

  def show
    @job = Job.find(params[:id])
  end

  def edit
  end

  def update
    @joblists.update(joblists_params)
    redirect_to joblists_path
  end

  def create
    @user = User.find(params[:user_id])
    @user_job = @user.jobs.create(joblists_params)
    flash[:notice] = "Job has been successfully Created"
    redirect_to user_path(@user)
  end

  def joblists_params
    params.require(:job).permit(:job_category, :job_title, :company_name, :location, :job_description,
      :monthly_salary, :deadline, :contact, :longitude, :lattitude, :full_time )
  end

end

A: Look after running rails routes it showing like this
user_job GET    /users/:user_id/jobs/:id(.:format)        jobs#show

so the link path is
user_job_path

on this link, you need to pass the user_id and job id then it will like this
<%= link_to 'show', user_job_path(@user, j.id) %> # or @user.id

Solved after chat
<% current_user.jobs.each do |j| %>
    <%= j.id %>
    <%= j.job_category %>
    <%= link_to 'show', user_job_path(current_user.id, j.id) %>

<% end %>

A: Add user id
user_job_path(current_user.id, j.id)

Thanks for comment


text:
Q: React Native - Failed to build DependencyGraph:Cannot read property 'root' of null I'm trying to get React Native to run their hello world app (AwesomeProject) for the first time, and I'm getting this error in the console:
Failed to build DependencyGraph: Cannot read property 'root' of null
TypeError: Cannot read property 'root' of null
    at index.js:16:60
    at tryCallOne (/Users/Eduardo/Documents/Code/Personal/ReactNative/AwesomeProject/node_modules/promise/lib/core.js:37:12)
    at /Users/Eduardo/Documents/Code/Personal/ReactNative/AwesomeProject/node_modules/promise/lib/core.js:123:15
    at flush (/Users/Eduardo/Documents/Code/Personal/ReactNative/AwesomeProject/node_modules/asap/raw.js:50:29)
    at _combinedTickCallback (node.js:370:9)
    at process._tickCallback (node.js:401:11)
~
Process terminated. Press <enter> to close the window
First of all I'm a mobile developer (native ios and android) and I know squad about node.
I followed the Getting Started page of React Native, got npm installed with npm install and npm install -g
When I try to start the node server alone, with node server I get this:
$ node server
module.js:341
throw err;
^

Error: Cannot find module '/Users/Eduardo/Documents/Code/Personal    /ReactNative/AwesomeProject/server'
at Function.Module._resolveFilename (module.js:339:15)
at Function.Module._load (module.js:290:25)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:141:18)
at node.js:933:3`

Here's a screenshot of what I get in the iOS emulator, and the console when trying to run the app:

For what's worth, I'm running this on a Mac OS 10.10.5 with Xcode 7.2, and NativeScript creates a simple app without issues.
Any suggestions on what to do on this?
I currently just want to get my feet wet with React Native.
Thanks!

A: Try brew uninstall watchman and brew install watchman


text:
Q: Combining Sumif, Sum & Filter I have a huge form responses spreadsheet indicating what parts my engineers have used. The 2 formulas below I have created below work as intended individually, is there any way of combining them together to return the sum of parts used which is column D for an engineer for a given month?
B2 is the engineer from list & C2 is the date.
=SUMIF($B$5:$B6414,B2,$D$5:$D$6414) returns total for named engineer for all months
=SUM(FILTER($D$5:$D$6415, MONTH($C5:$C$6415)=C2)) returns total for month for all engineers

A: I'm not 100% clear on what you're asking for when you say "combine" (i.e., what the composite formula should be returning). But logic tells me that you may just be trying to return the total for one named engineer (B2) for one given month (C2). If that is correct, try this:
=SUM(FILTER($D$5:$D$6415, $B$5:$B6415=B2, MONTH($C5:$C$6415)=C2))


text:
Q: Returning a ruby variable into Rails.root.join So I'm currently localising a rails app, i'm currently loading only one locale file in a function, though i'm wondering how I could go about storing the currently active locale in a variable and adding that instead of the basic 'en.yml'. Here's my current code:
yml ||= YAML.load_file(::Rails.root.join('config', 'locales', 'en.yml'))
@permissions_list ||= yml['en']['permissions']

I've tried:
yml ||= YAML.load_file(::Rails.root.join('config', 'locales', 'I18n.locale'))

but with no luck

A: You don't need to.
Rails will automatically load the files for the current locale. If the locale for example is de rails will load:
config/locales/de.yml

You can get it to load from nested folders by changing config.i18n.load_path. See Rails Internationalization (I18n) API.
But to answer your original question you can construct a dynamic string in Ruby by:
I18n.locale + ".yml"
# or
"#{I18n.locale}.yml"
# or about 100 other ways


text:
Q: Websphere Stuck on RenderPhase We are having problem with WebSphere here in our company.
After 120 seconds the server is stoping execution with timeout, ok. This is the behavior expected after this delay.
The problem is that the SQL Query is taking about 30 seconds and after that the java thread
stuck on jsf renderphase. Like we have set sleep() in the thread.
using a APM Tool (new relic)  the trace is:
 -MS-------%----CLASS-----------------------------------------
98200    79.11% LifecycleImpl.render(){

----98200   79.11%  com.sun.faces.lifecycle.RenderResponsePhase/doPhase

-----874     0.70% our.service()

-----2.0     0.00% WSJdbcDataSource.getConnection()
-----37.0 0.03% SQL Database     29.012  s
-----94500  76.12% Application code (in com.sun.faces.lifecycle.RenderResponsePhase/doPhase)
}

http://i.stack.imgur.com/tX75I.jpg
The application stops for 94 seconds on renderphase until the timeout throw.
Seeing debug mode on chrome nothing happens on browser. Just stay in idle waiting the request. The JSF tree doesnt come to browser. (for me this means that the thread is stucking on container)
  http://i.stack.imgur.com/YURD5.gif
My ManagedBean implements Serializable
below the configuration:

*

*Websphere 7.0 with cluster.

*Java 1.6

*Oracle 10g

*JSF 1.2 Richfaces

*Myfaces Majorra


text:
Q: How to 'pivot' these 3 entries into a single row? ( tied together by the same composite key) So I have the following sample data (3 tables)
I have a 'main' driver table called CASE
CASE_ID      CASE_NAME        CASE_DATE
   1         Test1            01-JAN-18
   2         Test2            02-JAN-18
   3         Test1 p2         03-JAN-18
   4         Test2 p2         03-JAN-18

I have a rel_table called CASE_VAL_REL
CASE_VAL_ID       CASE_ID       VAL_ID          CASE_VAL_TYPE
    1               1             1             Weight
    2               3             2             Height
    3               3             3             Age
    4               2             4             Weight
    5               4             5             Height
    6               4             6             Age

And lastly I have a table that needs to be joined to the REL table called VAL
VAL_ID      VAL       TIMESTAMP      PERSON_NAME      GENDER
  1         150       06-FEB-19      Matt             Male
  2         62        06-FEB-19      Matt             Male
  3         25        06-FEB-19      Matt             Male
  4         100       06-FEB-19      Pauline          Female
  5         70        06-FEB-19      Pauline          Female
  6         22        06-FEB-19      Pauline          Female

I need a result set/table that looks like the following (it cannot be joined by the case_id, since they opened two separate cases to derive the needed information. Instead we may need to join on a 'composite key' of some sorts. Below is my desired result set:
 PERSON_NAME    GENDER     AGE      WEIGHT    HEIGHT
  Matt          Male       25       150       62
  Pauline       Female     22       100       70

Below is my attempt but it is not quite working like I want it to (at least for a larger data set)
SELECT  MAX(CASE WHEN CASE_VAL_TYPE = 'Weight'
            THEN VAL
             END)   as             Weight
     , MAX(CASE WHEN CASE_VAL_TYPE = 'Height'
            THEN VAL
             END)   as             Height
     , MAX(CASE WHEN CASE_VAL_TYPE = 'Age'
            THEN VAL
             END)   as             Age
     , PERSON_NAME
     , GENDER
   FROM CASE C
   JOIN CASE_VAL_REL CVR on C.CASE_ID = CVR.CASE_ID
   JOIN VAL V on CVR.VAL_ID = V.VAL_ID
  GROUP BY PERSON_NAME, GENDER;

Thanks in advance.

A: I suggest you of change the table mane case  in cases for avoid conflie with   the case when sintax
and starting  form VAL use a left join for CASES
SELECT  MAX(CASE WHEN CVR.CASE_VAL_TYPE = 'Weight'
            THEN V.VAL
             END)   as             Weight
     , MAX(CASE WHEN CVR.CASE_VAL_TYPE = 'Height'
            THEN V.VAL
             END)   as             Height
     , MAX(CASE WHEN CVR.CASE_VAL_TYPE = 'Age'
            THEN V.VAL
             END)   as             Age
     , V.PERSON_NAME
     , V.GENDER
   FROM VAL V
   INNER JOIN CASE_VAL_REL CVR on CVR.VAL_ID = V.VAL_ID
   LEFT JOIN  CASES C on C.CASE_ID = CVR.CASE_ID
   GROUP BY PERSON_NAME, GENDER;

A: I just took VAL_ID as sequence number and VAL ordered in Weight,Height and Age, not sure is my interpretation correct  to derive the expected result from final table 'VAL' only to avoid joins to other tables.
 create table VAL
    (VAL_ID NUMBER,
    VAL   NUMBER,
    TIMESTAMP DATE,
    PERSON_NAME varchar2(20),
    GENDER   varchar2(10));

    insert into VAL values(1,150,'06-FEB-19','Matt','Male');
    insert into VAL values(2,62,'06-FEB-19','Matt','Male');
    insert into VAL values(3,25,'06-FEB-19','Matt','Male');
    insert into VAL values(4,100,'06-FEB-19','Pauline','Female');
    insert into VAL values(5,70,'06-FEB-19','Pauline','Female');
    insert into VAL values(6,22,'06-FEB-19','Pauline','Female');

    select PERSON_NAME,GENDER,
          max(case when mod(VAL_ID,3)=1 then VAL end) "WEIGHT",
          max(case when mod(VAL_ID,3)=2 then VAL end) "HEIGHT",
          max(case when mod(VAL_ID,3)=0 then VAL end) "AGE"
    from VAL
    group by PERSON_NAME,GENDER;

A: I renamed the tables t1, t2, and t3.  Looking at the data I then dropped t1 from the solution as you seem to want one row per person so all target data is in t2 and t3.  I selected the name, gender and SUM( case when case_val_type = 'X' then val else 0) where X is each possible type FROM ( WITH people as (select distinct person_name from t3) select people.person_name, t3.gender, t2.case_val_type, t3.val from people join t3 on t3.person_name = people.person_name  join t2 on t2.val_id = t3.val_id  ) iq group by iq.person_name, iq.gender and the result is your two line target.  -- Forgive my not formatting this but I have yet to find the formatting instructions.


text:
Q: Is it possible for HTTPS server to provide different SSL certificate based on HTTP headers? I am trying to connect to a service over HTTPS, and currently the connection fails due to certificate mismatch with the hostname. I am receiving different certificate host name depending on whether I connect using hostname or IP address. The hostname does resolve to exact same IP address, but it consistently keeps giving different certificate for the IP address when using curl. Using python requests module, it always gives me the certificate I get with curl and IP address (which is unfortunately the wrong one).
Any explanations what might be going on here?


text:
Q: Python: Pass or Sleep for long running processes? I am writing an queue processing application which uses threads for waiting on and responding to queue messages to be delivered to the app.  For the main part of the application, it just needs to stay active.  For a code example like:

while True:
  pass

or

while True:
  time.sleep(1)

Which one will have the least impact on a system?  What is the preferred way to do nothing, but keep a python app running?

A: I would imagine time.sleep() will have less overhead on the system. Using pass will cause the loop to immediately re-evaluate and peg the CPU, whereas using time.sleep will allow the execution to be temporarily suspended.
EDIT: just to prove the point, if you launch the python interpreter and run this:
>>> while True:
...     pass
...

You can watch Python start eating up 90-100% CPU instantly, versus:
>>> import time
>>> while True:
...     time.sleep(1)
...

Which barely even registers on the Activity Monitor (using OS X here but it should be the same for every platform).

A: I've always seen/heard that using sleep is the better way to do it. Using sleep will keep your Python interpreter's CPU usage from going wild.

A: You don't give much context to what you are really doing, but maybe Queue could be used instead of an explicit busy-wait loop? If not, I would assume sleep would be preferable, as I believe it will consume less CPU (as others have already noted).
[Edited according to additional information in comment below.]
Maybe this is obvious, but anyway, what you could do in a case where you are reading information from blocking sockets is to have one thread read from the socket and post suitably formatted messages into a Queue, and then have the rest of your "worker" threads reading from that queue; the workers will then block on reading from the queue without the need for neither pass, nor sleep.

A: Why sleep? You don't want to sleep, you want to wait for the threads to finish.
So
# store the threads you start in a your_threads list, then
for a_thread in your_threads:
    a_thread.join()

See: thread.join

A: If you are looking for a short, zero-cpu way to loop forever until a KeyboardInterrupt, you can use:
from threading import Event

Event().wait()

Note: Due to a bug, this only works on Python 3.2+. In addition, it appears to not work on Windows. For this reason, while True: sleep(1) might be the better option.
For some background, Event objects are normally used for waiting for long running background tasks to complete:
def do_task():
    sleep(10)
    print('Task complete.')
    event.set()

event = Event()
Thread(do_task).start()
event.wait()

print('Continuing...')

Which prints:
Task complete.
Continuing...

A: signal.pause() is another solution, see https://docs.python.org/3/library/signal.html#signal.pause

Cause the process to sleep until a signal is received; the appropriate handler will then be called. Returns nothing. Not on Windows. (See the Unix man page signal(2).)

A: Running a method as a background thread with sleep in Python:
    import threading
    import time

    class ThreadingExample(object):
        """ Threading example class
        The run() method will be started and it will run in the background
        until the application exits.
        """

        def __init__(self, interval=1):
            """ Constructor
            :type interval: int
            :param interval: Check interval, in seconds
            """
            self.interval = interval

            thread = threading.Thread(target=self.run, args=())
            thread.daemon = True                            # Daemonize thread
            thread.start()                                  # Start the execution

        def run(self):
            """ Method that runs forever """
            while True:
                # Do something
                print('Doing something imporant in the background')

                time.sleep(self.interval)

    example = ThreadingExample()
    time.sleep(3)
    print('Checkpoint')
    time.sleep(2)
    print('Bye')


text:
Q: Using Table Based Layouts for Browsers IE 7 in Liferay I have this code,
#if ($browserSniffer.isIe($request) && $browserSniffer.getMajorVersion($request) < 8)

in my page layouts in Liferay to tell them to use table based Layouts for browser IE 7, but I get the following warning:
Invalid character used in text string ( #if($browserSniffer.isIe($request) && $browserSniffer.getMajorVersion($request) < 8) ).

The problem seems to be the AND (&&) parameter, but I don't see any problem in that. So, I would be grateful if someone could tell me what the problem is.
Thanks in advance, Adia.

UPDATE: The layout file

   #if ($browserSniffer.isIe($request) && $browserSniffer.getMajorVersion($request) < 8)

                    $processor.processColumn("column-1", "portlet-column-content portlet-column-content-first")

                    $processor.processColumn("column-2", "portlet-column-content portlet-column-content-last")

                    $processor.processColumn("column-3", "portlet-column-content portlet-column-content-first")

                    $processor.processColumn("column-4", "portlet-column-content portlet-column-content-first")

                    $processor.processColumn("column-5", "portlet-column-content portlet-column-content-last")

                    $processor.processColumn("column-6", "portlet-column-content portlet-column-content-last")

                    $processor.processColumn("column-7", "portlet-column-content portlet-column-content-last")

    #else

                $processor.processColumn("column-1", "portlet-column-content portlet-column-content-first")

                $processor.processColumn("column-2", "portlet-column-content portlet-column-content-last")

                $processor.processColumn("column-3", "portlet-column-content portlet-column-content-first")

               $processor.processColumn("column-4", "portlet-column-content portlet-column-content-first")

                $processor.processColumn("column-5", "portlet-column-content portlet-column-content-last")

            $processor.processColumn("column-6", "portlet-column-content portlet-column-content-last")

                $processor.processColumn("column-7", "portlet-column-content portlet-column-content-first")

    #end

A: You can easily determine and workaround the && problem, if that's indeed the problem - though it'd be the way that velocity handles logical operators:
#if ($browserSniffer.isIe($request))
  #if($browserSniffer.getMajorVersion($request) < 8)
     ... (your stuff here)
  #end
#end

If it isn't at least you get the new error message in only half the statement and can continue debugging from there.
In what kind of file do you have this? Layout-Template? Theme?


text:
Q: Java что располагается внутри фигурных скобок Встретил вот такой интересный участок кода, но ничего не могу про него найти:
JPanel contentPane = new JPanel() {
            BufferedImage [] img = new BufferedImage[] { // вот это поле
                ImageIO.read(new File("image/_1.png")),
                ImageIO.read(new File("image/_2.png"))
            };

            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(img[0],0,0,null);
            }
        };

Почему после конструкции new JPanel() внутри фигурных скобок присутствуют переменные? Как это называется?

A: То, с чем мы здесь имеем дело -- это не анонимные поля, это описание анонимного класса, который является потомком класса JPanel. То, что следует за вызовом конструктора new JPanel() в фигурных скобках -- это фактически описание нового класса; вы его описываете и сразу же создаете экземпляр этого нового класса и присваиваете его переменной contentPane типа JPanel (это возможно, поскольку новый клаcc - дочерний по отношению к JPanel), но вы не можете создавать переменные нового типа, поскольку у нового класса нет своего имени.
Как и любой дочерний класс, новый класс (хоть анонимный, хоть нет) может содержать дополнительные поля и методы, может также переопределять методы родительского класса. Как и при описании любого класса, переменные могут быть инициализированы выражениями, которые вычисляются в момент создания экземпляра класса. Выражения могут содержать вызовы методов, эти методы будут вызываться в момент инициализации. Ваш код
BufferedImage [] img = new BufferedImage[] { // вот это поле
            ImageIO.read(new File("image/_1.png")),
            ImageIO.read(new File("image/_2.png"))
        };,

занимается именно этим -- создается массив из двух элементов (не анонимный -- у него есть имя -- img!), для каждого из них вызывается метод read(), который возвращает значение, которое и присваивается элементу массива.
Анонимный класс отличается от нормального тем, что у него нет имени, а значит, нельзя описать переменную такого класса, а значит, нет честного способа обратиться извне к тем его полям и методам, которые не описаны в родительском классе. Но описанные в нем методы (в том числе переопределенные методы родительского класса) вполне могут к ним обращаться, например, в вашем коде это g.drawImage(img[0],0,0,null);.
Так что конструкция вида
MyClass myVar = new MyClass() {

   int number = 123;
   String name = new String("Это объект № ");

   @Override
   public String toString() {
     return name + number;
   }

   public void foolish() {
     System.out.println("Этот метод не может быть вызван");
   }
}

равносильна описанию
class NewClass extends MyClass {

   int number = 123;
   String name = new String("Это объект № ");

   @Override
   public String toString() {
     return name + number;
   }

   public void foolish() {
     System.out.println("Этот метод не может быть вызван");
   }
}

NewClass myVar = new NewClass();

за исключением того, что в случае обычного класса вы можете вызвать вновь описанный метод
myVar.foolish();

а в случае анонимного класса вы этого сделать не можете, поскольку переменная myVar относится к типу MyClass, который такого метода не содержит.

A: Это не поля класса. Просто создаётся массив экземпляров класса BufferedImage. Вызов метода ImageIO.read(new File("image/_1.png")), скорее всего, возвращает экземпляр этого класса. Переписал ваш код для наглядности:
public class some {

   public static void main(String[] args) {
        Other[] arrayOfOther = new Other[] {
            new Other(),
            new Other()
        };
    }

}

class Other{}

Update
Переписал для вас половину swing-a. Надеюсь будет понятней
import java.util.Arrays;

public class Test {
    public static void main(String[] args) {

        JPanel contentPane = new JPanel() {
                BufferedImage [] img = new BufferedImage[] { // вот это поле
                    ImageIO.read(),
                    ImageIO.read()
                };

                protected void paintComponent(String s) {
                    super.paintComponent(s);
                    System.out.println("Я метод класса-наследника. И да, я имею доступ к массиву `img` " + Arrays.toString(img));
                }
            };

        contentPane.paintComponent("");
    }

}

// "Оригинальный" класс JPanel. Понятия ни имеет о массиве `BufferedImage [] img`
class JPanel {
    protected void paintComponent(String s) {
        System.out.println("Я метод родительского класса. Меня вызвали. Ура");
    }
}

class BufferedImage {
    public String toString() {
        return "Красивая картинка";
    }
}

class ImageIO {
    static BufferedImage read() {
        return new BufferedImage();
    }
}

Попробуйте запустить эту программу.


text:
Q: Is Photo compression-ratio for JPEG exports too high? Despite selecting the High option when exporting JPEG images from Photo, I am finding the file size at destination is around 3MB - 60% smaller than when I exported the same images from iPhoto with the High option. Image size is unaffected. If Photo is compressing JPEG images more during export than iPhoto, I fear the image quality is also being reduced. Is this correct?
There is a possibility that Photo is actually extra-compressing images at the import stage, not during export. Or both!

A: You can export unmodified original photos from the Photos.app from File > Export > Export Unmodified Original.
You can also select a higher resolution when exporting from File > Export > Export or cmd + ⇧+ E; and select "Maximum" from the drop down menu.
I suspect it is still recompressed, so it is expectable that the image will be smaller.
Also, check this question and answers.


text:
Q: ignite cache query not working first time when i start remote cache server it gives output, but for second time query not working,but i'm getting cache size on client node. even i can fetch data via cache.iterator() but not getting via cache query not via sql ,scan neither via text queries.
code:-
 List<Cache.Entry<PersonKey, Person>> as = cache.query(new SqlQuery<PersonKey, Person>(Person.class, sql).
                setArgs("Manish")).getAll();

        System.out.println("data " + as);
        System.out.println("size " + cache.size());
        Iterator<Cache.Entry<PersonKey, Person>> abc = cache.iterator();
        while (abc.hasNext()) {
            Cache.Entry<PersonKey, Person> data = abc.next();
            System.out.println("data " + data);
        }
        for (Cache.Entry<PersonKey, Person> e : as) {
            System.out.println(e.getValue().toString());
        }

        SqlFieldsQuery qry = new SqlFieldsQuery("select firstname, lastname from Person where firstname='Manish'");

        try (FieldsQueryCursor<List<?>> cursor = cache.query(qry)) {
            for (List<?> row : cursor) {
                System.out.println("firstname:" + row.get(0) + ", lastname:" + row.get(1));
            }
        }

my cache config:-
    <import resource="classpath:cassandra/connection-settings.xml" />

<!-- Persistence settings for 'cache1' -->
<bean id="cache1_persistence_settings" class="org.apache.ignite.cache.store.cassandra.persistence.KeyValuePersistenceSettings">
    <constructor-arg type="org.springframework.core.io.Resource" value="classpath:persistence/primitive/persistence-settings-1.xml" />
</bean>

<!-- Ignite configuration -->
<bean id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
    <property name="cacheConfiguration">
        <list>
            <!-- Configuring persistence for "cache1" cache -->
            <bean class="org.apache.ignite.configuration.CacheConfiguration">
                <property name="name" value="cache1"/>
                <property name="readThrough" value="false"/>
                <property name="writeThrough" value="true"/>
                <property name="writeBehindEnabled" value="true"/>
                <property name="writeBehindFlushSize" value="2"/>
                <!--                    <property name="atomicityMode" value="TRANSACTIONAL"/>
                <property name="backups" value="1"/>-->
                <property name="cacheStoreFactory">
                    <bean class="org.apache.ignite.cache.store.cassandra.CassandraCacheStoreFactory">
                        <property name="dataSourceBean" value="cassandraAdminDataSource" />
                        <property name="persistenceSettingsBean" value="cache1_persistence_settings"/>
                    </bean>
                </property>
                <property name="queryEntities">
                    <list>
                        <bean class="org.apache.ignite.cache.QueryEntity">
                            <property name="keyType" value="com.manish.igniteexample.PersonKey"/>
                            <property name="valueType" value="com.manish.igniteexample.Person"/>

                            <property name="fields">
                                <map>
                                    <entry key="firstname" value="java.lang.String"/>
                                    <entry key="lastname" value="java.lang.String"/>
                                    <entry key="age" value="java.lang.Integer"/>
                                    <entry key="married" value="java.lang.Boolean"/>
                                    <entry key="birthDate" value="java.util.Date"/>
                                    <entry key="phone" value="java.lang.Integer"/>
                                </map>
                            </property>

                            <property name="indexes">
                                <list>
                                    <bean class="org.apache.ignite.cache.QueryIndex">
                                        <constructor-arg value="firstname"/>
                                    </bean>
                                    <bean class="org.apache.ignite.cache.QueryIndex">
                                        <constructor-arg value="lastname"/>
                                    </bean>
                                </list>
                            </property>
                        </bean>
                    </list>
                </property>
            </bean>
        </list>
    </property>
    <property name="clientMode" value="false"/>

and my output program is as shown in pic
first time execution , Second time execution

A: Fix this issue by correcting my POJO Classes ,added name property in QuerySqlField .
public class Person {

   @QuerySqlField(name = "firstname" , index = true)
   private String firstname;

   @QuerySqlField(name = "last_name" , index = true)
   private String lastname;

   @QuerySqlField(name = "age")
   private int age;

   @QuerySqlField(name = "married")
   private boolean married;

   @QuerySqlField(name = "birth_date")
   private Date birthDate;

   @QuerySqlField(name = "phones")
   private String phones;

   /**
    * getter and setter methods ...
    */
 }


text:
Q: Using bubble sort/swap to sort strings in c++ I'm very new to C++, and I cannot seem to figure this problem out. This code is just supposed to have the user enter a list of animals (no more than 25 animals, 30 letters long), then it will output them in the order they were entered and then also in alphabetical order (using bubble sort). I apologize if my code is hard to follow or understand.
Whenever I put in animals such as "dog", "cat", "fish" and terminate the list with a period, I usually get "Unhandled exception at 0x55b6d2f3 in CharacterStrings.exe: 0xC0000005: Access violation reading location 0xcccccccc." but then other times I get "A buffer overrun has occurred in CharacterStringsList.exe which has corrupted the program's internal state."
I'm just very confused as to how to fix this. I tried to Google both of them but I couldn't seem to find any solution that would work for me (as I'm still a beginner and don't know how to do much of the more advanced code). I'm pretty sure the error is somewhere in my swap function (maybe?) but I can't seen to figure it out. Maybe a logic error? I've tried everything I can think of.
If you have questions or anything, let me know. Any help or suggestions would be much appreciated! Thank you in advance :)
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;

void getInput(char animals[][30]);
void outputLists(char animals[][30]);
void bubbleSort(char animals[][30], int n);
void Swap(char *a, char *b);

void getInput(char animals[][30])
{
    cout << "Please enter a list of animals, terminated by a period: " << endl;

    for(int i = 0; i < 25; i++)
    {
        cin >> animals[i];
        if(strcmp(animals[i], ".") == 0)
            break;
    }
}

void bubbleSort(char animals[][30], int size)
{
    for(int i = 0; i < size-1; i++)
        for(int j = 0; j < size-1; j++)
            if(animals[j] < animals[j+1])
                Swap(animals[j], animals[j+1]);
}

void Swap(char *a, char *b)
{
    char t[30];
    strcpy(t, a);
    strcpy(a, b);
    strcpy(b, t);
}

void outputLists(char animals[][30])
{
    //Output original list
    for(int i = 0; i < 25; i++)
    {
        if(strcmp(animals[i], ".") == 0)
            break;
        cout << animals[i] << endl;
    }

    //Output sorted list
    for(int i = 0; i < 25; i++)
        cout << animals[i] << endl;

}

int main()
{
    char animals[25][30];

    getInput(animals);

    cout << endl;
    bubbleSort(animals,25);

    outputLists(animals);

    cout << endl;
    system("pause");
    return 0;
}

A: Use strcmp(s1, s2) for comparing C-style strings. It returns a value less than zero if s1 is less than s2.
And one more hint: C-style strings are null-terminated strings (i.e. there is a zero value after a string itself), so you need an array of size at least n+1 for storing a string of length n. In your case, 30 is not enough but 31 is.


text:
Q: For loop select specific part of string variable simple question:
I have a variable called x:
echo $x
3122;192.31.231.2 3379;183.3.202.111 3085;218.25.208.92

What I would like is to iterate over the IP's only, not the initial number.
192.31.231.2
183.3.202.111
218.25.208.92

Current code:
for ip in $x;
do
    echo `geoiplookup "$ip[$2]"`
done

A: One idea using parameter expansion:
x="3122;192.31.231.2 3379;183.3.202.111 3085;218.25.208.92"

for stuff in ${x}                 # process each '<number>;ip' pair separately
do
    ip="${stuff##*;}"             # strip off leading '<number>;'
    echo "${ip}"
    # geoiplookup "${ip}"
done

NOTE: I'm not familiar with the geoiplookup command so not sure why OP is wrapping the geoiplookup call inside an echo call versus just calling geoiplookup directly ... ??
This generates:
192.31.231.2
183.3.202.111
218.25.208.92

From here the OP can reference ${ip} as needed for the geoiplookup call.

A: If we can assume, that between each number and IP address is a semicolon, then we just need to cut until delimiter (i.e. ; in this case) and select second part.
We can do it in such manner: echo $var | cut -d';' -f2
Now to put this back into your code:
for ip in $x; do
    geoiplookup "$(echo $ip | cut -d';' -f2)"
    # wrapping it in `echo` would just print what would be printed either way
done

A: Use this Perl one-liner, connected to a while loop via a pipe:
perl -lne 'print for /\b\d+;([\d.]+)\b/g' <<<$x | \
    while read -r ip ; do
        echo "my_command ${ip}"
    done

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.
-l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing.
/\b\d+;([\d.]+)\b/g - Captures and returns IP addresses. Returns multiple matches (regex /g modifier). Matches \b - a word boundary, followed by \d+; -  a stretch of digits ending with a semicolon, followed by [\d.]+ - a stretch of digits or periods, followed by \b - another word boundary.


text:
Q: Can I safely remove mariadb from Centos Linux? I just did a clean install of CentOS Linux.  The first thing I did after installing CentOS was to download MySQL and try to install the -server rpm file.  But the installation fails with a lot of messages stating conflicts with MariaDB packages which seem to be redundant to those in MySQL.  I want to use MySQL as my database.
Are there any reasons why I should not just delete mariadb, so that the conflicts can be resolved? If mariadb performs some important functions in CentOS, I do not want to end up having my system crash.

A: You could use MariaDB as mysql version 5.5 for it is just another MYSQL branch...
In Centos 7, it is a alternative project of oracle mysql. It contains all mysql functions and optimize structures, data processing, Algorithm etc..
you could even login the server with a "mysql" command.
you don't need to pay attentions on the name, it is no problem to your former mysql projects.
ps:
I don't think that a linux system will have a "clean", "pure" os environment. Linux is a free and open source system which means you could install and remove every thing with no problem.

A: To have MySQL database functionality you can install either the MySQL packages or the MariaDB packages. MariaDB is a fork originating from the same MySQL code base. For compatibility see https://mariadb.com/kb/en/mariadb/mariadb-vs-mysql-compatibility/
Yes, you can remove MariaDB packages and replace them by MySQL packages.


text:
Q: convert nginx to htaccess(apache) I got the following rewrite rules in Nginx in which im trying to convert for apache/.htaccess rules in which i was keep getting errors and didn't work out well, didnt find any online convertor from nginx to .htaccess only the opposite, Im hoping if anyone could help me out converting it.
This is my nginx rules:
if (!-d $request_filename){
 set $rule_0 1$rule_0;
}
if (!-f $request_filename){
 set $rule_0 2$rule_0;
}
if ($rule_0 = "21"){
 rewrite ^/(.*?)([^/]*)$ /$1index.php?$2 last;
}

this is my .htaccess try:
<IfModule mod_rewrite.c>
RewriteEngine on
# Apache 2.4
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*?)([^/]*)$ $1index.php?$2 [QSA,PT,L]
RewriteEngine On
            RewriteBase /
        if (!-d $request_filename){
 set $rule_0 1$rule_0;
}
if (!-f $request_filename){
 set $rule_0 2$rule_0;
}
if ($rule_0 = "21"){
 rewrite ^/(.*?)([^/]*)$ /$1index.php?$2 last;
}

ErrorDocument 404 /404.php

</IfModule>

but i keep on getting parse error whenever i try to do this, anyone have experience to sort this out?

A: You appear to have already done it, but for some reason you have also embedded the original Nginx directives in the middle (which will naturally result in a parse error).
So, the equivalent Apache/.htaccess directives would seem to be the following only:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*?)([^/]*)$ $1index.php?$2 [QSA,L]

The PT flag is not required in a .htaccess context.
You do not need the <IfModule> wrapper, unless these directives are optional.

if (!-d $request_filename){
 set $rule_0 1$rule_0;
}

However, the first set directive implies that the $rule_0 variable might have already been set earlier in the config?


text:
Q: Gmail App Stripping Out Equals Sign in Mailto Body I am attempting to create a mailto link which populates the body of the email with the current URL.
The problem I am having, is that the gmail android app strips out equals signs, including %3D
Here is the code I am using.
$currentUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$currentUrl = str_replace('&', '%26', $currentUrl);
$currentUrl = str_replace('=', '%3D', $currentUrl);

Click to Send

Example Href
Create Email

On desktop, it works fine. On mobile, the query strings get cut off and the equals signs do not get included in the email body.
Would anyone be able to assist please, as to how to get the equals into gmail app? Thanks.
An example of the mailto body would contain a link like this: https://live.rail-record.co.uk/train/?c=H17216&d=11/12/2019
The URL inserted into the email body however, is cut off after ?c - the first equals sign. Works fine in desktop mail apps but doesnt work on gmail android. Regarding the above link, there is a bit at the bottom that says "Create Email" you can click that to test it.

A: In Android URL encoding is not enough, you need to double encode the URL and it will work fine (tied it out myself).
Here you can see how to do it in js:
How to double encodeURIComponent in javascript?


text:
Q: The set of diffeomorphisms preserving some metric. Let $M$ be a finite-dimensional, smooth manifold. Call a diffeomorphism $f : M \rightarrow M$ diagonalizable if there exists a Riemannian metric $g$ on $M$ such that $f : (M, g) \rightarrow (M, g)$ is an isometry. I have some questions regarding such objects.
a) Is the set Diag(M) of all diagonalizable diffeomorphisms a group under composition?
b) Note that, in order to be diagonalizable, a diffeomorphism must possess the following well-known property of isometries:
$$\text{If}~f(p) = p~\text{and}~df(p) = \mathrm{Id}_{T_pM}, \text{for some $p \in M$, then}~f = \mathrm{Id}_M. (*)$$
Is $(*)$ also a sufficient condition? In other words, given a diffeomorphism $f \in \mathrm{Diff}(M)$ satisfying $(*)$, is there a Riemannian metric for which $f$ is an isometry? Maybe this is too general, because any diffeomorphism not fixing any point satisfies $(*)$, but I don't know the answer.
My motivation here is to know how large is the set of diffeomorphisms that could be isometries within the set of all diffeomorphisms. I apologize if I'm missing some standard notation and/or vocabulary here. I'd appreciate, as always, any references.
Thanks in advance.

A: Here's one idea, but there are many problems in the details.
Let $f : M \to M$ be a diffeomorphism, and let $g_0$ be any Riemannian metric on $M$. For each $n$, let $g_{n+1} = f_* g_n$ be the pushforward of $g_n$ under $f$. By construction, each $f$ is an isometry $(M, g_n) \to (M, g_{n+1})$, but this is not what we want. However, it is well known that the space of Riemannian metrics is closed under positive linear combinations, so consider the following construction: set
$$\bar{g}_N = \frac{1}{N} \sum_{n=0}^{N-1} g_n$$
This gives rise to a new sequence of Riemannian metrics on $M$. Observe that
$$f_* \bar{g}_N = \frac{1}{N} \sum_{n=1}^{N} g_n$$
and so
$$f_* \bar{g}_N - \bar{g}_N = \frac{1}{N} (g_N - g_0)$$
This suggests that if the limit
$$\bar{g} = \lim_{N \to \infty} \bar{g}_N$$
exists and is a smooth Riemannian metric, and if
$$\lim_{N \to \infty} \frac{1}{N} (g_N - g_0) = 0$$
then we will have $f : (M, \bar{g}) \to (M, \bar{g})$ an isometry as desired.
Of course, there is no reason to believe that any of this works. For example, let us fix a norm on the space $V = \Gamma (M, T^*M \otimes T^* M)$, and consider the linear operator $f_* : V \to V$. If $f_*$ is not a bounded linear operator on $V$ there's no reason to believe that the sequence $(\bar{g}_1, \bar{g}_2, \ldots)$ should converge. If $f_*$ is bounded but with operator norm greater than $1$ we would have to modify our construction so that $g_{N-1}$ doesn't overshadow the contributions from the earlier metrics. If it is bounded with operator norm less than $1$ we have to worry about whether $\bar{g} = 0$ or other such degeneracies. There's no reason to believe that $\bar{g}$ is smooth even when it converges. But perhaps it's somewhere to start.

A: Regarding your question (a), the set $\text{Diag(M)}$ of all diagonalizable diffeomorphisms is not always closed under composition. (So in particular it is not a group).
For example take $M=\mathbb{R}^n$ , and consider linear diffeomorphims.
It is proved here that a linear automorphism $T:V \rightarrow V$ preserves some inner product on $V$ if and only if the matrix of $T$ w.r.t an arbitrary basis is similar to an orthogonal matrix. The point is that composition of two transformation of this type is not necessarily also of that type. (Which amounts to proving that the union of conjugacy classes of $O(n)$ is not a subgroup, see here).
In particular, if you take $A = \pmatrix{0&2\\-1/2&0}$, then $A,A^T$ both preserves some inner products on $\mathbb{R}^2$ , but their product $AA^T = \pmatrix{4&0\\0&\frac14}$ does not.
While the result above holds pointwise (it is an algebraic result, true for a single vector space, which can be thought of as a tangent space), note that for linear transformations, we can identify them with their differentials (after identifying the tangent spaces canonically with $\mathbb{R}^n$).
Now arise the natural question: what about other manifolds?


text:
Q: space graph - can objects have multiple parents, how to move them, and what include options are there? disclosure: this one is a bit stale on msdn
Hi there, the spacePaths=string[] attribute suggest that space objects can have multiple parents. That there can be multiple routes to an object. But then there's only one parent object to a space... which one is it?
Is "moving" an object in the graph achieved by simply running a Patch on a space object with a different parent id?
Is there documentation about the available "includes" for the different api's? for instance the spacePaths attribute for space objects is included if you add "fullpath" to the query... is there a way to obtain the full object model - the default on includes is typically none.
Kind regards, Gregor

A: Currently it's a tree through Parent Space ID. We're discussing internally how best to support many-to-many relationship while keeping the simplicity of our topologies.  In the meantime, we do see the tree enabling many core scenarios for developers and in some cases we've seen people build around the single-parent relationship by using extensible properties to tag additional related spaces.  There's a limitation in extended types/ontologies in terms of creating a spaceObject type in general extending the topology; we're looking to improve ontologies and are keeping this mind with our planning/requests.  As a side note, if you want to ask for new features/concepts I recommend posting to feedback.azure.com: https://feedback.azure.com/forums/916621-azure-digital-twins as we are actively using this to inform our scenarios :)

A: the spaces are represented as a tree, thus each space can only have 0 or 1 parent. You can move a space by changing its parentSpaceId attribute, but when it has a value, apparently you cannot remove it... Bug or by design?
In my current test Digital Twin, the spacePaths attribute always contains only 1 item, as I would expect. That doesn't make sense to me to have several parents in a tree. I didn't find any documentation on that either, maybe when it will be GA? The fact that it is an array is puzzling indeed.
Sorry for not being able to help much.
Cheers,
fred

A: One of possible option to define "parents" like "children" to handle multiple parents to space instead parentSpaceId. Or use edge to have relation. There should be a method to added to Parents for a spaceID.
Definitely it is needed requirement to have graph model of space.

A: 1st question (is it a tree or a graph): it's a tree and there are ways to get around single-parent restrictions by applying custom attributes.
2nd question (how to move space elements): space elements can be moved by patching with new parentSpaceId attributes. when changing the parentSpaceId permissions will adjust accordingly.
3rd question (what are the "includes" choices): the includes are a bit tricky, but a good way to study them is to use the swagger document and "try" the different routes (for instace get: /api/v1.0/spaces). those "includes" are dropdowns and they populate with the available choices.
avoiding responding to other answers: thank you Fred and Bobbie for your insight.


text:
Q: How can I get the build number of my Android app? How can I get the build number of my Android app and setText to a textview?
For example, "Build # 91".

A: Simple and short way: implement into your activity
String versionName = getApplicationContext().getPackageManager()
.getPackageInfo(getApplicationContext().getPackageName(), 0).versionName;
TextView tv=(TextView)findViewById(R.id.tv);
tv.setText(versionName);


text:
Q: How to control ESP-05 power using Arduino (both are 3v3 devices) I have ESP-05 connected to Arduino Pro Mini. Both are 3v3 devices. I need  Arduino to power on/off ESP-05 device using GPIO when needed. Please suggest.

I tried to use N Mosfet but that did not work possibly because example is with different power supplies.

A: You're on the right track, but what N-FET did you use?
First: how much power?
The article here suggests you might need to switch 500 mA.  ESP8266EX has a typical transmit current of about 170 mA and no listed maximum.
You don't say how much time you'll have the ESP-05 enabled nor how much power you can allow during its off-time.
Second: What threshold voltage?
Fundamentally an nFET is a voltage controlled switch.  The level at which it switches is the VGS(thresh) and you need one which will switch at 3.3V, often called a "3.3V logic-level MOSFET" (watch out for those which are good for 5V logic).  Many FETs, especially those for larger currents and voltages, have a much higher switching threshold.
Two questions about this specifically:

*

*https://electronics.stackexchange.com/a/106443

*https://electronics.stackexchange.com/a/235680
Sparkfun shows modules for which might immediately do what you need, if you don't mind using a ready-made module.  Seach for MOSFET on that site.

*

*One product there uses FDS6630A which has VGS(thresh) of min=1.0V, typ=1.7V, max=3.0V.

Once you've chosen a MOSFET, you look for examples for the details of its required current limit and bias resistors.  (You won't need the diode of your example circuit, that's for the back-EMF of the inductive load.)  The FDS6630A example above uses

Source: Sparkfun documentation
Other possibilities
SLEEP The ESP8266EX has various sleep modes its various sleep modes is 15 mA down to 0.5 μA according to its datasheet.  You can enable these with AT commands, and perhaps that will work for your application.
RESET Some ESP-05 models have a 5-pin connector with RESET signal.  If you assert this, I'll guess the power consumption will be very low (but couldn't find a value in the documentation) and perhaps that would work for you.

*

*Article about ESP-05 https://blog.startingelectronics.com/esp8266-esp-05/

*ESP-05 chip is ESP8266EX: datasheet

*ESP8266 AT Commands manual


text:
Q: Setting a textfield in actionscript to "0" causes it to be blank I have the following code that loads an XML file, parses it, and then sets various text fields to the contents of the XML file:
function loadData(): void {
var myXML: XML;
var myLoader: URLLoader = new URLLoader();
myLoader.load(new URLRequest("C:\\Program Files (x86)\\SplitmediaLabs\\XSplit\\streamcontrol.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);

    function processXML(e: Event): void {
        myXML = new XML(e.target.data);

        alliance1Score.text = myXML.elements("alliance1Score");
        alliance2Score.text = myXML.elements("alliance2Score");
    }
}

The XML file is set up as such:
<alliance1Score><![CDATA[2]]></alliance1Score>
<alliance2Score><![CDATA[0]]></alliance2Score>

When the value is 2 or 1 this works great and the textfields change.  When the value is 0, however, the textfields are blank.
Any help would be appreciated.

A: Turns out it was a problem with embedding my font.  I had accidentally missed checking "Numerals".


text:
Q: How to get logger Hierarchy in Log4j2 ? I am migrating from Log4j1 to log4j2. Earlier we were using the Hierarchy Class to get the Hierarchy Earlier we were doing like below :
This is code we had used to get the logger hierarchy and loggers. but now in log4j2 the Hierarchy class does not exist.
What is the alternative to achieve below in log4j2 ?
public class ReportHierarchy extends Hierarchy
{
    public ReportHierarchy(Logger root)
    {
        super(root);
    }

    public Logger getLogger(String name)
    {
        return getLogger(name, defaultFactory);
    }

    private LoggerFactory defaultFactory = new ReportFactory();
}

We are using the ReportHierarchy class like below :
static
    {
        ReportHierarchy h = new ReportHierarchy(new RootLogger(Level.DEBUG));
        LogManager.setRepositorySelector(new DefaultRepositorySelector(h), "nuova");
        LogManager.resetConfiguration();
        NuRollingFileAppender.initializeCleanupTimer();
    }

A: This part of architecture has not changed between Log4j 1.x and Log4j2, but the names changed. So you have:

*

*a ContextSelector instead of a RepositorySelector,

*a LoggerContext instead of Hierarchy.

You don't need to set the ContextSelector in code any more, just set the log4j2.contextSelector Log4j2 system property to the fully qualified class name of your selector. You can do it e.g. in a log4j2.component.properties file.


text: Q: How to load windows dll in Emscripten plateform I need load a windows dll from javascript code in my project. Is there a solution to realize it? For example, use Emscripten, but it can't load a dll in windows. If use V8, but it works only in node webkit application. I need your help.


text:
Q: Generate a .txt and then force download I have a php function for getting info out of my database. When they go to http://example.com/test/download
I want to create a fake test.txt (text is dynamic) and download it. It's contents should be the equivalent of executing foreach(databaseContent() as $content)  { echo $content . '<br/>' } inside of it.
How can I get started on this? (Using php)

A: You can link to a php document along these lines, which forces a download of type plain text. (Well, suggests to the browser that that should happen, at any rate.)
<?php
header('Content-disposition: attachment; filename=gen.txt');
header('Content-type: text/plain');

echo "this is the file\n";
echo " you could generate content here, instead.";
?>

Of course, pass in appropriate post or get args, to control it the way you like.


text:
Q: How to set the custom UserModel field value upon creation of the user in Django? I have a custom UserModel which has a CharField named as pbc_id. I want it to be set as something like below:
pbc_id = "PBC-" + str(user.pk)

In other words, I want to attach the newly created user's primary key value at the end of the string "PBC-" and then assign this value to the pbc_id field.
I have kind of done it, but it only work when I create a superuser using the terminal. But when I create a normal user using Django Administration Interface, it does not work and pbc-id gets empty value.
My User model is below:
class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=254, null=True, blank=True)
    email = models.EmailField(max_length=254, unique=True)
    first_name = models.CharField(max_length=254, null=True, blank=True)
    last_name = models.CharField(max_length=254, null=True, blank=True)
    pbc_id = models.CharField(max_length=254, null=True, blank=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_candidate = models.BooleanField(default=False)
    is_voter = models.BooleanField(default=False)
    votes = models.IntegerField(default=0)
    last_login = models.DateTimeField(null=True, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

    def get_absolute_url(self):
        return "/users/%i/" % (self.pk)

My UserManager class is below:
class UserManager(BaseUserManager):
    def _create_user(self, email, password, is_staff, is_superuser, is_candidate, is_voter, **extra_fields):
        if not email:
            raise ValueError('Users must have an email address')

        now = timezone.now()
        email = self.normalize_email(email)

        user = self.model(
            username=email,
            email=email,
            is_staff=is_staff,
            is_active=True,
            is_superuser=is_superuser,
            is_candidate=is_candidate,
            is_voter=is_voter,
            last_login=now,
            date_joined=now,
            **extra_fields
        )
        user.set_password(password)
        user.save(using=self._db)
        user.pbc_id = "PBC-" + str(user.pk)
        user.save(using=self._db)
        return user

    def create_user(self, email, password, **extra_fields):
        user = self._create_user(email, password, False, False, False, False, **extra_fields)
        user.pbc_id = "PBC-" + str(user.pk)
        user.save(using=self._db)

        return user

    def create_superuser(self, email, password, **extra_fields):
        user=self._create_user(email, password, True, True, False, False, **extra_fields)
        return user

In admins.py, I have UserAdmin class a below:
class UserAdmin(BaseUserAdmin):
    fieldsets = (
        (None, {'fields': ('username', 'email', 'password', 'first_name', 'last_name', 'last_login')}),
        ('Permissions', {'fields': (
            'is_active',
            'is_staff',
            'is_superuser',
            'is_candidate',
            'is_voter',
            'groups',
            'user_permissions',
        )}),
    )
    add_fieldsets = (
        (
            None,
            {
                'classes': ('wide',),
                'fields': ('email', 'password1', 'password2')
            }
        ),
    )

    list_display = ('username', 'email', 'first_name', 'last_name', 'pbc_id', 'is_staff', 'is_candidate', 'is_voter', 'last_login')
    list_filter = ('is_staff', 'is_candidate', 'is_voter', 'is_superuser', 'is_active', 'groups')
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ('groups', 'user_permissions',)

A: After hours of searching, I think I got it. You have to override the save method saving the object (see def save_model() at bottom), then assign the "pbc_id" + obj.id to the field, then obj.save()
also changed this
class UserAdmin(BaseUserAdmin)
To this:
class UserAdmin(admin.ModelAdmin):
fieldsets = (
    (None, {'fields': ('username', 'email', 'password', 'first_name', 'last_name', 'last_login','pbc_id')}),
    ('Permissions', {'fields': (
        'is_active',
        'is_staff',
        'is_superuser',
        'is_candidate',
        'is_voter',
        'groups',
        'user_permissions',
    )}),
)
add_fieldsets = (
    (
        None,
        {
            'classes': ('wide',),
            'fields': ('email', 'password1', 'password2',)
        }
    ),
)

list_display = ('username', 'email', 'first_name', 'last_name', 'pbc_id', 'is_staff', 'is_candidate', 'is_voter', 'last_login')
list_filter = ('is_staff', 'is_candidate', 'is_voter', 'is_superuser', 'is_active', 'groups')
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ('groups', 'user_permissions',)

def save_model(self, request, obj, form, change):
    super().save_model(request, obj, form, change)
    obj.pbc_id = "PBC-" + str(obj.pk)
    obj.save()

admin.site.register(models.User, UserAdmin)


text:
Q: template and operator overloading and iterator I am asked to write an iterator with the same function as istream_iterator, and the iterator's name is CMyistream_iterator. I want to set up the function of * operator as it is used in iterators.
  template<class T>
    class CMyistream_iterator{
        public:
        T my;
        T* cm;
        CMyistream_iterator(istream& x):my(x){};
        T operator * (CMyistream_iterator<T>& p);
    };
    template<class T>
    T CMyistream_iterator<T>::operator * (CMyistream_iterator<T>& p){return p.my;}
    int main()
    {
        CMyistream_iterator<int> inputInt(cin);
        int n1,n2,n3;
        n1 = * inputInt;
    }

But the code goes wrong and saying that" no match for 'operator*'(operand type is CMyistream)". Could anyone help me?

A: You problem is not related to templates, but to basics of operator overloading. You need to write simply
T operator * ();

and
T CMyistream_iterator<T>::operator * (){
    return my; // meaning this->my
}

The reason is that as your operators are already class members, they already have
one implicit parameter — the class object itself, and this is the parameter you need to use.
The code as you wrote it declares not indirection operator (*x) , but multiplication operator (x*y).
Another problem in your code is that you are trying to convert istream to int in CMyistream_iterator(istream& x):my(x){};, but that's unrelated to the compilation error you mentioned; and the solution of this problem depends on what exactly you need to do.


text:
Q: Display of million records in JqGrid I have a site where I have to fetch a million records from a database and show it in JqGrid. But when I do that it takes around 45 to 60 minutes to fetch and show the records.
I am using JqGrid with JSP, Hibernate, JPA and MySQL database.
Can anyone tell me how to go about this? So that time delay is reduced and records are loaded faster.
Thanks in advance
@UPDATE
I tried using JSON instead of XML and the time was reduced to 30 minutes. In this 30 minutes it is taking 16 minutes to fetch the data from the database and remaining 14 minutes to pass the data to frontend
@UPDATE 2
There are few ways by which I was able to decrease the time taken to load the data into jqgrid.
Way 1: I had ORDER BY clause in my query I removed that and the time was reduced from 45-60 minutes to 5 minutes
Way 2: Remove / reduce number of joins in the query.
Way 3: Instead of using the Hibernate or JPA object directly get the query result in result set and use that result set to create the json object.
By using 1 and 3 ways I have reduced my time to load a 200000 records to 1 min 32 secs.

A: Normally you don't need to show millions of records at the same time. That would be an insane thing to do and completely impractical. What you need is to implement pagination. Server side pagination. So that you fetch only the records you can currently show on the screen. 10-30 records at a time seems like a reasonable amount to show. It is important that you perform the pagination at the database level to avoid fetching millions of records and display only very few of them.


text:
Q: Connect to informix with python's ibm_db I'm pretty new to python. I'm trying to connect to an informix server using python and ibm_db.connect(). However I can't seem to succeed and the error messages don't help.
Using java and jdbc I can connect successfully with the following connection url:
jdbc:informix-sqli://10.20.30.40:1234/mydb:INFORMIXSERVER=foo_bar;USER=user;PASSWORD=pass;
My attempt at using ibm_db is:
ibm_db.connect('HOSTNAME=10.20.30.40;PORT=1234;DATABASE=mydb;PROTOCOL=ONSOCTCP;UID=user;PASSWORD=pass;', '', '')

But it gives an error (Exception: [IBM][CLI Driver] SQL0902C  A system error occurred. Subsequent SQL statements cannot be processed. IBM software support reason code: "".  SQLSTATE=58005)
I would like if possible an equivalent string I can put in as the first argument to
ibm_db.connect('', '', '')

So I can connect with python.

A: Please check https://code.google.com/p/ibm-db/issues/detail?id=116&can=1&q=ONSOCTCP, This might be helpful for you. If you still facing issue then you can post your query to https://groups.google.com/forum/#!forum/ibm_db for quick response.

A: Protocol onsoctcp is not supported by ibm_db.
Please check https://www.ibm.com/support/knowledgecenter/SSGU8G_11.50.0/com.ibm.admin.doc/ids_admin_0207.htm, This can help you to configure a DDRA (tcpip) access to your database.

A: I have faced the same issue with ibm_db and now I use jayDeBeApi to connect to Informix through python. it requires java JDBC driver and application is work like a charm.
https://pypi.org/project/JayDeBeApi/#:~:text=The%20JayDeBeApi%20module%20allows%20you,of%20the%20Java%20JDBC%20driver.

A: Your JDBC connection string points to a SQLI Informix listener, but the 'ibm_db' python module uses DRDA (IBM Data Server Driver) to connect to the Informix engine.
Informix allows both SQLI and DRDA clients (and others like MongoDB). SQLI is the 'native' Informix protocol and supports all the Informix server features and data types. DRDA is what other IBM databases use (like DB2). It does have some limitations in terms of what types you can use.
You have two options:
Configure the Informix server to listen for DRDA connections in a another port (basically, create an DBALIASES using 'drsoctcp') as described here:
https://www.ibm.com/support/knowledgecenter/SSGU8G_11.50.0/com.ibm.admin.doc/ids_admin_0207.htm
Or leave the server as it is, and use a different Python module, one that uses SQLI like 'IfxPy'
https://github.com/OpenInformix/IfxPy


text:
Q: Ribbon force refresh I'm working on a custom VSTO ribbon in Excel, more specifically a group that would look like below:

Using the code below, I want to turn off/on things like Screen Updating, Calculation, Enable events.
This is not how I'm going to use this, I will use that functionality in individual macros, what I want to do is signal the status of each of these items in the toggle buttons (DA, EE, SA, C), as I did with updateCheckboxes. I want to do this in case the user ran into an unhandled debug error, and the macro did not reach the end where the status is restored.
My problem comes when .ScreenUpdating = False, because this no longer allows the ribbon to refresh itself, so the toggle buttons do not show the updated values.
Is there any way to force refresh the ribbon, even if screen updating is set to false?
   Private Sub Button6_Click(sender As Object, e As RibbonControlEventArgs) Handles
    Button6.Click
        With Globals.ThisWorkbook.Application
            '.ScreenUpdating = False
            .Calculation = Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationManual
            .EnableEvents = False
            .DisplayAlerts = False
        End With
        updateCheckboxes()
    End Sub

    Private Sub Button7_Click(sender As Object, e As RibbonControlEventArgs) Handles Button7.Click
        With Globals.ThisWorkbook.Application
            .DisplayAlerts = True
            .EnableEvents = True
            .Calculation = Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationAutomatic
            '.ScreenUpdating = True
        End With
        updateCheckboxes()
    End Sub

    Private Sub updateCheckboxes()
        With Globals.ThisWorkbook.Application
            Me.tglDA.Checked = (.DisplayAlerts = True)
            Me.tglEE.Checked = (.EnableEvents = True)
            Me.tglSA.Checked = (.ScreenUpdating = True)
            Me.tglC.Checked = (.Calculation = Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationAutomatic)
        End With
        Application.DoEvents()
    End Sub

A: You need to call Globals.ThisAddIn.RibbonUI?.Invalidate() to cause Excel to fire all the getVisible/getEnabled/getLabel callbacks on ribbon controls, at which point you can return the updated control labels.

A: I don't think the Ribbon UI (aka Fluent UI) is calling ribbon callbacks when the ScreenUpdating property is set to false. However, as Dmitry suggested, you may try using the Invalidate method of the IRibbonUI interface. An instance of the IRibbonUI interface is passed to the Load callback:
Dim MyRibbon As IRibbonUI

Sub MyAddInInitialize(Ribbon As IRibbonUI)
 Set MyRibbon = Ribbon
End Sub

Sub myFunction()
 MyRibbon.Invalidate() ' Invalidates the caches of all of this add-in's controls
End Sub

Don't forget to specify the OnLoad callback in the ribbon XML:
<customUI … OnLoad="MyAddinInitialize" …>

Read more about the Fluent UI in the following series of articles:

*

*Customizing the 2007 Office Fluent Ribbon for Developers (Part 1 of 3)

*Customizing the 2007 Office Fluent Ribbon for Developers (Part 2 of 3)

*Customizing the 2007 Office Fluent Ribbon for Developers (Part 3 of 3)
Anyway, I'd recommend re-designing the application without relying on anything except returning back default values, so you can start a timer or set a timeout and etc. to stop a long running or faulty task.


text:
Q: Alphabetic footnote marks in pandoc I am writing a text using numeric bibliography references, i.e. a citation like [@foobar] results in a number as superscript. However, I also need to add footnotes. To distinguish between footnotes and bibliography references, I need the footnotes to be using letters of alphabet rather than numbers, i.e.
Here is some text [^a]

[^a]: This is a footnote

Should generate a superscript a rather than 1 as footnote reference when rendering the text. Otherwise it cannot be distinguished from a bibliography reference. Is there a way to achieve it with pandoc? I can think of a way of achieving it in LaTeX, but unfortunately the document must be generated as a Word document.


text:
Q: Is there any way to get portable apps to register in the Explorer context menu? I am using more and more portable apps which make switching from computer to computer much easier.
However for programs such as 7zip which makes sense really only if it is a choice in the context menu in Explorer, is there a way to get this programs to register themselves in the Explorer context menu even though they are portable apps?

A: There is a registry hack for Notepad++. I suppose you could modify it to work with 7-zip instead. Note that the script must be run with administrator privilege, and that you might need to restart the explorer.exe process after uninstalling.

A: If you open up the Options in 7-Zip you could potentially enable the context menu there, which may work for what you need.  The program should be intelligent enough to set up Explorer properly.
7-Zip -> Tools -> Options

Under the 7-Zip tab you can enable the context menu but selecting Integrate 7-Zip to shell contect menu
I would go through these options to disable the context menu before you remove the portable disk as I do not know how well Explorer would handle the context handler not being present without the USB device plugged in.


text:
Q: DIV behave like an IFRAME & load url using ajax DIV behave like an IFRAME & load url using ajax for a web application having many forms/web pages loading each form/webpages dynamically

A: A div can't behave exactly like an IFrame - An IFrame has it's own javascript environment, but a div shares the environment with the parent window.
However, you can make an ajax request to a url, and insert the response into a div.
I suggest using jQuery, they have a simple function $.get(url) for this.


text:
Q: Are there Gutenberg container blocks? In web design, a key design element is the container that may contain various other content and blocks and is styled in CSS.
Is there a Gutenberg container block that may contain other blocks? If so, I haven't found it yet.
It looks like the Gutenberg editor now supports representing nested blocks. Some folks have been requesting section blocks. Any love there yet?
I WAS able to change the Columns block to one column, but that feels like a clunky hack.

A: I had a very hard time getting my first container/wrapper block ready for action.
Here's what I've learned the last couple hours:
Because I had serious problems importing the InnerBlocks I decided to use the create-guten-block toolkit. After the installation I just had to execute npx create-guten-block. That provided me the structure of related files. Now I changed the file src/block/block.js to the following code:
import { registerBlockType } from '@wordpress/blocks';
import { InnerBlocks } from '@wordpress/editor';
const { __ } = wp.i18n;
registerBlockType( 'myplugin/container', {
    title: __( 'My Plugin Container', 'myplugin' ),
    icon: 'universal-access-alt',
    category: 'myplugin',
    getEditWrapperProps: function () {
        return {
            "data-align": "full"
        };
    },
    edit: function( props ) {
        return (

                <InnerBlocks />

        );
    },
    save: function( props ) {
        return (

                <InnerBlocks.Content />

        );
    },
} );

After entering the directory via cli and running npm run build my plugin was ready and worked as expected.
The simple css I've used for this first step was for both, front and backend:
.wp-block-myplugin-container{
    padding-top: 50px;
    padding-bottom: 50px;
    background-color: purple;
}

I used this on a windows machine, after updating node to the newest version everything worked as expected. I'm happy with the result and focus on advanced settings (background color/image, margins, paddings,...) for this container now.
Happy coding!

A: This what the second phase of Gutenberg development will focus on. Devs can create a parent block with predefined innerblock to smooth the page setup process for users.
For now you can use InnerBlocks component.
import { registerBlockType } from '@wordpress/blocks';
import { InnerBlocks } from '@wordpress/editor';

const ALLOWED_BLOCKS = [ 'core/image', 'core/paragraph' ];
<InnerBlocks
    allowedBlocks={ ALLOWED_BLOCKS }
/>

registerBlockType( 'my-plugin/my-block', {
    // ...

    edit( { className } ) {
        return (

                <InnerBlocks />

        );
    },

    save() {
        return (

                <InnerBlocks.Content />

        );
    }
} );

There's also templateLock and layouts options to manipulate the options. For more options see - Official Doc

A: There's a new core "Section" block that will be available in an upcoming Gutenberg update which is intended to serve the role you're looking for I think:
Add Section block

A: Update October 2020 - WP 5.5.1 ships with the Group block which you can use as a container.

A: Here are two "container blocks" I used. First one is the Melonpan block container. It has many features... But if you just need a basic container block, here is the section block that does the work pretty well.

A: A few plugins have added wrapper/container blocks to Gutenberg. Editor Blocks is just one example.

A: I've created a custom-block like so:
const { registerBlockType } = wp.blocks;
const { InnerBlocks } = wp.blockEditor;
const { Dashicon, TextControl, CheckboxControl } = wp.components;

registerBlockType('gutenberg/custom-container', {
    title: 'Container',
    description: 'Control the max-width of a content or section',
    icon: 'slides',
    category: 'layout',

    attributes: {
        maxWidth: {
            type: 'number',
            default: 0
        },
        collapse: {
            type: 'boolean',
            default: false
        }
    },

    edit({attributes, setAttributes}) {
        const { maxWidth, collapse } = attributes;

        function setValue(value){
             const numberValue = parseInt(value);
             setAttributes({ maxWidth: numberValue });
        }

        function checkCollapse(){
            setAttributes({ collapse: !collapse });
        }

        return (

                    <Dashicon icon="slides" />
                    Container

                        <TextControl
                            className="default-label"
                            label="Width(px)"
                            type="number"
                            name="max-width"
                            value={maxWidth}
                            onChange={setValue}
                        />

                    <CheckboxControl
                        className="default-label"
                        heading="Collapse Padding"
                        checked={collapse}
                        onChange={checkCollapse}
                    />

                <InnerBlocks />

        );
    },
    save({attributes}) {
        const { maxWidth, collapse } = attributes;

        return (
            <div
                className={!collapse ?
                              'custom-container' :
                              'custom-container space-none'
                          }
                style={{ maxWidth: `${maxWidth}px`}}
            >
                <InnerBlocks.Content />

        ); }
});

Hope it helps someone.


text:
Q: How to locate the complete definition of a struct at the site lxr.free-electrons.com? The site lxr.free-electrons.com is very useful when I want to find the definition of a struct in linux kernel.
However, what's annoying is:
If a struct is declared in many other header files, then the found results will be a lot of incomplete declarations and one complete definition of the struct. It's hard to distinguish the definition and the declarations.
For instance, the search results of struct task_struct are:

task_struct
Defined as a struct type in:
drivers/mmc/card/queue.h, line 7 drivers/oprofile/cpu_buffer.h, line 21
drivers/net/wireless/cw1200/cw1200.h, line 34
include/uapi/linux/capability.h, line 18
include/asm-generic/syscall.h, line 22
......
......

That's very terrible to locate the complete definition of struct task_struct.
How to solve this problem?

A: This seems to be a limitation of LXR, the engine behind lxr.free-electrons.com: it doesn't differentiate forward declarations (struct task_struct;) from full definitions.
My method of choice is always by looking at file names, since it's usually obvious where a given structure definition should be (e.g., in your case, it's related to scheduling, so sched.h in the file list should have it). However, I understand that one might be unfamiliar with the Linux kernel source code, and thus have no idea where to go.
The best way to find a structure definition in the Linux source tree is by searching for literally:
struct struct_name {

Since a strict coding style is followed by Linux contributors, the structure definitions should always take this form.
LXR has a freetext search to cope with its limitations. Unfortunately, it uses Google Search, which ignores most punctuations. GitHub seems to ignore them too, as well as Google Code.
My advice is to clone the mainline Linux Git repository:
git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git

and then grep (or, better, ag) what you're looking for in the include directory:
grep -rin 'struct task_struct {' include

or, using ag:
ag 'struct task_struct {' include

You will see the files that define this structure (usually only one) in the results, and then you may go to the appropriate file on LXR and continue your research.
Here's a shell function to go to the appropriate LXR page using the first result:
lxr() {
    chromium "http://lxr.free-electrons.com/source/$(grep -rl "$1" include | head -1)"
}

or, using ag:
lxr() {
    chromium "http://lxr.free-electrons.com/source/$(ag -l "$1" include | head -1)"
}

Replace chromium with whatever your favorite browser command is. Use it like this:
lxr 'struct task_struct {'

Hope it helps.

A: I find it much useful to download the linux source code in my system and browse using cscope command line tool. It together with ctags is very useful for code navigation.

A: Try this
https://code-grep.com/view/project/54b083273b2082684a000008/linux-3.19-rc2?search=task_struct&type=definitions&page=0
it is actually showing up the line of the definition so we do not need to go back and forth to check.


text:
Q: Force ssh to always use SSH_ASKPASS I want to force ssh to always use the program specified by SSH_ASKPASS. In my case the program is just a bash script returning the passphrase.
The problem is, as the ssh documentation says:

If ssh needs a passphrase, it will read the passphrase from the current terminal if it was run from a terminal.

So if I run ssh from a terminal, SSH_ASKPASS is ignored.
There is a similar question:
Tell SSH to use a graphical prompt for key passphrase
which proposes create an alias for ssh, like this
$ alias ssh="setsid ssh"

but doesn't work for me, because I don't call ssh directly, is called from git or rsync.
I also found an open issue in the OpenSSH Bugzilla asking for a fix, but was opened in 2002, so I don't believe is going to be implemented.
I'm thinking on probably weird solutions:

*

*Make a fake ssh agent, which calls the script and returns the passphrase.

*Create a process looking for new ssh processes and detach them from the    terminal before ssh asks for the password.

Any better sugestion?

A: A per ssh manual:

If ssh does not have a terminal associated with it but DISPLAY and SSH_ASKPASS are set, it will execute the program specified by SSH_ASKPASS.

Therefore you need to disassociate the terminal (e.g. by adding a pipe) and make sure DISPLAY isn't set (if you want to use terminal for your passphrase instead).
Simple example:
echo foo | SSH_ASKPASS=/my/cmd DISPLAY= ssh ...

The same with ssh-add:
$ echo foo | SSH_ASKPASS=/my/cmd DISPLAY= ssh-add id_rsa
ssh_askpass: exec(/my/cmd): No such file or directory

A: Unfortunately, I cannot access the open issue that you have linked, but I have tried @npostavs' suggestion (set DISPLAY to some value) and it seems to work1.
For example:

# List heads in a remote git repo
DISPLAY=: setsid git ls-remote -h git@github.tik.uni-stuttgart.de:NFL/tests.git

Where

$ cat ${SSH_ASKPASS}
#!/bin/bash
echo ABCSuperPassword

In this example, SSH_AGENT is invoked by git (set GIT_TRACE=2 for verboser output) effectively providing "ABCSuperPassword" as password for the private key.
Notes
1 DISPLAY is often unset if login into remote terminals.


text:
Q: Nokogiri without DIV I am trying to scrape information from an HTML table. There are multiple tables on the page. Before each table there is a paragraph with text. I want to key off of this text field ("CONSOLIDATED" text in the pastebin below) to identify the table since there are no DIV tags on the page and therefore no other way to uniquely identify the table. How would I do this? What XPath statement would I use? Here's a link to the HTML page: http://pastebin.com/HeapZvPV
Thanks!


text:
Q: Update values by shifting 1 row in Pandas On sparse matrix on pandas dataframe, I want to update values where values are 1 by shifting one row.
from
   0  1  2
0  0  1  1
1  1  1  0
2  0  0  0
3  0  0  1
4  0  0  0
5  1  1  0

to
   0  1  2
0  0  1  1
1  1  1  1
2  1  1  0
3  0  0  1
4  0  0  1
5  1  1  0

I understand that updating values in a certain location is given by table[table==1] = 1
I don't want to use for sentence because it has huge number of records.

A: I guess this should work:
newdf = df.shift().fillna(0).astype(int) | df
#   0  1  2
#0  0  1  1
#1  1  1  1
#2  1  1  0
#3  0  0  1
#4  0  0  1
#5  1  1  0


text:
Q: hyper Link on Text in react How to make a Link on text i tried please help what i am doing wrong

Signup is Component when i click Join Now text the only path change
  e.g Signup/

<BrowserRouter>
     <Link to="/Signup"> Join now</Link>
</BrowserRouter>

Error
index.js:2178 Warning: validateDOMNesting(...):  cannot appear as a descendant of .
    in a (created by Link)
    in Link (at Login.js:205)
    in Router (created by BrowserRouter)
    in BrowserRouter (at Login.js:203)
    in a (at Login.js:123)
    in MyLink (created by WithStyles(MyLink))
    in WithStyles(MyLink) (at Login.js:200)
    in p (created by Typography)
    in Typography (created by WithStyles(Typography))
    in WithStyles(Typography) (at Login.js:197)
    in div (created by Paper)
    in Paper (created by WithStyles(Paper))
    in WithStyles(Paper) (created by Card)
    in Card (created by WithStyles(Card))
    in WithStyles(Card) (at Login.js:166)
    in div (at Login.js:164)
    in Login (created by WithStyles(Login))
    in WithStyles(Login) (at App.js:35)
    in div (at App.js:33)
    in App (created by WithStyles(App))
    in WithStyles(App) (at index.js:9)

A: import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router, Route, NavLink} from 'react-router-dom';

ReactDOM.render(
<Router>

      {/*You can add more links here*/}

<NavLink to='/Signup'>Join Now</NavLink>

    <Route path='/SignUp' component={ComponentName} />

)