text:
Q: Very strange rosegarden crash issue? I have been all over the internet about this problem, and everyone seems to have slightly different but unrelated errors to mine.
Rosegarden was working yesterday. Now, every time without fail, it will display the splash screen, some hint of a window, but then the area of the screen "freezes" and doesn't refresh (where you can "paint" over the area by dragging a window over it ;))
I tried:
sudo apt-get purge rosegarden
sudo apt-get autoremove
sudo apt-get install rosegarden

With a seemingly fresh install, things happened the exact same way.
Here's the terminal output:
Setting graphics system for Qt 4.5+ to: raster
Thorn - false
System Locale: en_US
Qt translations path: /usr/share/qt4/translations
Qt translations not loaded.
RG Translation: trying to load :locale/en_US
RG Translations loaded successfully.
Loaded application icon "rg-rwb-rose3-16x16"
Loaded application icon "rg-rwb-rose3-32x32"
Loaded application icon "rg-rwb-rose3-48x48"
Loaded application icon "rg-rwb-rose3-64x64"
Loaded application icon "rg-rwb-rose3-128x128"
NOTE: Found stylesheet at ":/rosegarden.qss", applying it
Not loading stylesheet per user request.  Caveat emptor.
QSettings::endGroup: No matching beginGroup()
AlsaDriver::AlsaDriver [begin]
Rosegarden 10.10 - AlsaDriver [ALSA library version 1.0.23, module version 1.0.23, kernel version 2.6.38-8-generic]
Cannot connect to server socket err = No such file or directory
Cannot connect to server socket
PluginFactory::instance(dssi): creating new DSSIPluginFactory
LADSPAPluginFactory::discoverPlugins - discovering plugins; path is [/home/chase/.dssi] [/usr/local/lib/dssi] [/usr/lib/dssi]
Cannot connect to server socket err = No such file or directory
Cannot connect to server socket
jackdmp 1.9.7
Copyright 2001-2005 Paul Davis and others.
Copyright 2004-2010 Grame.
jackdmp comes with ABSOLUTELY NO WARRANTY
This is free software, and you are welcome to redistribute it
under certain conditions; see the file COPYING for details
Cannot create thread 1 Operation not permitted
Cannot create thread 1 Operation not permitted
JACK server starting in realtime mode with priority 10
Cannot lock down memory area (Cannot allocate memory)
LADSPAPluginFactory::discoverPlugins - done
PluginFactory::instance(ladspa): creating new LADSPAPluginFactory
LADSPAPluginFactory::discoverPlugins - discovering plugins; path is [/home/chase/.ladspa] [/usr/local/lib/ladspa] [/usr/lib/ladspa]
control device hw:0
control device hw:0
audio_reservation_init
Acquire audio card Audio0
creating alsa driver ... hw:0|hw:0|1024|2|44100|0|0|nomon|swmeter|-|32bit
control device hw:0
Using ALSA driver HDA-Intel running on card 0 - HDA Intel at 0x90700000 irq 46
configuring for 44100Hz, period = 1024 frames (23.2 ms), buffer = 2 periods
ALSA: final selected sample format for capture: 32bit integer little-endian
ALSA: use 2 periods for capture
ALSA: final selected sample format for playback: 32bit integer little-endian
ALSA: use 2 periods for playback
port created: Midi-Through:midi/playback_1
port created: Midi-Through:midi/capture_1
port created: USB-Uno-MIDI-Interface:midi/playback_1
port created: USB-Uno-MIDI-Interface:midi/capture_1
Cannot use real-time scheduling (RR/10)(1: Operation not permitted)
AcquireSelfRealTime error
LADSPAPluginFactory::discoverPlugins - done
Cannot lock down memory area (Cannot allocate memory)
Cannot use real-time scheduling (RR/5)(1: Operation not permitted)
AcquireRealTime error

JackDriver::initialiseAudio - JACK sample rate = 44100Hz, buffer size = 1024
JackDriver::initialiseAudio - creating disk thread
JackDriver::initialiseAudio - found 4 JACK physical outputs
JackDriver::initialiseAudio - connecting from "rosegarden:master out L" to "system:playback_1"
JackDriver::initialiseAudio - connecting from "rosegarden:master out R" to "system:playback_2"
JackDriver::initialiseAudio - found 4 JACK physical inputs
JackDriver::initialiseAudio - connecting from "system:capture_1" to "rosegarden:record in 1 L"
JackDriver::initialiseAudio - connecting from "system:capture_2" to "rosegarden:record in 1 R"
JackDriver::initialiseAudio - initialised JACK audio subsystem

  ALSA Client information:

    14,0 - (Midi Through, Midi Through Port-0)          (DUPLEX) [ctype 2, ptype 655362, cap 99]
    20,0 - (USB Uno MIDI Interface, USB Uno MIDI Interface MIDI 1)      (DUPLEX) [ctype 2, ptype 589826, cap 127]

AlsaDriver::setCurrentTimer((auto))
extractVersion: major = 1, minor = 0, subminor = 23, suffix = ""
AlsaDriver::versionIsAtLeast: is version 1.0.23 at least 1.0.14? yes
extractVersion: major = 2, minor = 6, subminor = 38, suffix = "generic"
AlsaDriver::versionIsAtLeast: is version 2.6.38-8-generic at least 2.6.20? yes
Using low-resolution system timer, sending a warning
    Current timer set to "system timer" with timer checks
    WARNING: using system timer with only 250Hz resolution!
AlsaDriver::initialiseMidi -  initialised MIDI subsystem

AlsaDriver::setCurrentTimer((auto))
extractVersion: major = 1, minor = 0, subminor = 23, suffix = ""
AlsaDriver::versionIsAtLeast: is version 1.0.23 at least 1.0.14? yes
extractVersion: major = 2, minor = 6, subminor = 38, suffix = "generic"
AlsaDriver::versionIsAtLeast: is version 2.6.38-8-generic at least 2.6.20? yes
Using low-resolution system timer, sending a warning
    Current timer set to "system timer" with timer checks
    WARNING: using system timer with only 250Hz resolution!
Composition::getTrackById(0) - WARNING - track id not found, this is probably a BUG src/base/Composition.cpp:1560
Available track ids are:
AlsaDriver::addDevice(0,0)
CREATED OUTPUT PORT 3:out 1 - unnamed for device 0
Renamed 129:3 to General MIDI Device
AlsaDriver::addDevice(0,1)
AlsaDriver::setRecordDevice: device 1, action 1
WARNING: AlsaDriver::renameDevice: Cannot find device 1 in port map
port created: rosegarden:midi/capture_1
port created: rosegarden:midi/playback_2
port created: rosegarden:midi/playback_3
port created: rosegarden:midi/capture_3
port created: rosegarden:midi/playback_4
audio file manager emitting fake setValue(100)
RosegardenDocument::openDocument: Successfully opened document "/home/chase/.local/share/rosegarden/autoload/autoload.rg"
Object::connect: No such slot Rosegarden::AudioInstrumentParameterPanel::updateAllBoxes() in src/gui/editors/parameters/AudioInstrumentParameterPanel.cpp:81
Object::connect:  (receiver name: 'Audio Instrument Parameter Panel')
Object::connect: No such signal Rosegarden::CompositionView::contentsMoving (int, int) in src/gui/editors/segment/compositionview/SegmentMover.cpp:58
Object::disconnect: No such signal Rosegarden::CompositionView::contentsMoving (int, int) in src/gui/editors/segment/compositionview/SegmentMover.cpp:65
Object::connect: No such signal Rosegarden::CompositionView::contentsMoving (int, int) in src/gui/editors/segment/compositionview/SegmentPencil.cpp:61
Connecting my port 3 to 20:0 on reconnection
AlsaDriver::setPlausibleConnection: connection like "" requested for device 0
AlsaDriver::setPlausibleConnection: fuzzy match 20:0 USB Uno MIDI Interface MIDI 1 (duplex) available with fitness 1
AlsaDriver::setRecordDevice: device 1, action 0
AlsaDriver::setRecordDevice: port is 0:0
AlsaDriver::setRecordDevice: device 1, action 1
AlsaDriver::setRecordDevice: port is 20:0
AlsaDriver::setRecordDevice - successfully subscribed device 1 as record port
AlsaDriver::setPlausibleConnection: connection like "" requested for device 1
AlsaDriver::setPlausibleConnection: fuzzy match 20:0 USB Uno MIDI Interface MIDI 1 (duplex) available with fitness 1
DataBlockRepository::clear()
Studio::getMetronomeFromDevice: Having a look at device 1000
Studio::getMetronomeFromDevice: Having a look at device 10000
Studio::getMetronomeFromDevice: Having a look at device 0
Studio::getMetronomeFromDevice(0): device is a MIDI device
rosegarden: could not connect to socket
rosegarden: No such file or directory
Rosegarden: WARNING: No accurate sequencer timer available (and kernel is new enough for RTC addendum)
MAIN WINDOW DISPLAY WARNING:  type 2 text
System timer resolution is too low!

Rosegarden: WARNING: No accurate sequencer timer available (and kernel is new enough for RTC addendum)
SystemFont::loadSystemFont[Qt]: wanted family LilyPond-feta-rosegarden at size 12, got family LilyPond-feta-rosegarden (exactMatch 1)
SystemFont::loadSystemFont[Qt]: wanted family LilyPond-feta-nummer-rosegarden at size 12, got family LilyPond-feta-nummer-rosegarden (exactMatch 1)
SystemFont::loadSystemFont[Qt]: wanted family LilyPond-parmesan-rosegarden at size 12, got family LilyPond-parmesan-rosegarden (exactMatch 1)
SystemFont::loadSystemFont[Qt]: wanted family bitstream vera serif at size 12, got family DejaVu Serif (exactMatch 0)
SystemFont::loadSystemFont[Qt]: wanted family luxi serif at size 12, got family DejaVu Serif (exactMatch 0)
SystemFont::loadSystemFont[Qt]: wanted family times new roman at size 12, got family Liberation Serif (exactMatch 0)
SystemFont::loadSystemFont[Qt]: wanted family times at size 12, got family Nimbus Roman No9 L (exactMatch 0)
SystemFont::loadSystemFont[Qt]: wanted family fughetta at size 12, got family DejaVu Sans (exactMatch 0)
Warning: Unable to load any of the fonts in "fughetta"
SystemFont::loadSystemFont[Qt]: wanted family georgia at size 12, got family DejaVu Sans (exactMatch 0)
SystemFont::loadSystemFont[Qt]: wanted family inkpen2 at size 12, got family DejaVu Sans (exactMatch 0)
Comparing current version "10.10" with latest version "11.06"
MAIN WINDOW DISPLAY WARNING:  type 4 text
Newer version available

SystemFont::loadSystemFont[Qt]: wanted family inkpen at size 12, got family DejaVu Sans (exactMatch 0)
Warning: Unable to load any of the fonts in "inkpen2,inkpen"
SystemFont::loadSystemFont[Qt]: wanted family inkpen2 text at size 12, got family DejaVu Sans (exactMatch 0)
SystemFont::loadSystemFont[Qt]: wanted family inkpen text at size 12, got family DejaVu Sans (exactMatch 0)
SystemFont::loadSystemFont[Qt]: wanted family comic sans ms at size 12, got family DejaVu Sans (exactMatch 0)
SystemFont::loadSystemFont[Qt]: wanted family maestro at size 12, got family DejaVu Sans (exactMatch 0)
Warning: Unable to load any of the fonts in "maestro"
SystemFont::loadSystemFont[Qt]: wanted family opus at size 12, got family DejaVu Sans (exactMatch 0)
Warning: Unable to load any of the fonts in "opus"
SystemFont::loadSystemFont[Qt]: wanted family opus text at size 12, got family DejaVu Sans (exactMatch 0)
SystemFont::loadSystemFont[Qt]: wanted family petrucci at size 12, got family DejaVu Sans (exactMatch 0)
Warning: Unable to load any of the fonts in "petrucci"
SystemFont::loadSystemFont[Qt]: wanted family sonata at size 12, got family DejaVu Sans (exactMatch 0)
Warning: Unable to load any of the fonts in "sonata"
SystemFont::loadSystemFont[Qt]: wanted family steinberg notation at size 12, got family DejaVu Sans (exactMatch 0)
Warning: Unable to load any of the fonts in "steinberg notation"
SystemFont::loadSystemFont[Qt]: wanted family xinfonia at size 12, got family DejaVu Sans (exactMatch 0)
Warning: Unable to load any of the fonts in "xinfonia"

  ALSA Client information:

    14,0 - (Midi Through, Midi Through Port-0)          (DUPLEX) [ctype 2, ptype 655362, cap 99]
    20,0 - (USB Uno MIDI Interface, USB Uno MIDI Interface MIDI 1)      (DUPLEX) [ctype 2, ptype 589826, cap 127]

And that's it. Rosegarden just hangs there. Every time. I don't know what could possibly create some sort of error that would persist across a fresh install. It also appears that it can't load any fonts for some reason....

A: As you stated in your question:
Deleting everything listed by
find ~ -name "*rosegarden*"

under home directory fixed the issue. Rosegarden creates some hidden directories and files that I suppose became corrupt.
In this case, I'll see what causes the condition and file a bug.


text:
Q: Reading an online XML file with VB.net I need to make an application in which a vb.net application takes in a XML file from a url and display it in my program. An example of a place to get a url would be www.example.com/yx3234.xml then take the contents of this and read it into my program.

A: Use Linq XML. You can pass the uri to XDocument.Load() method.
Dim doc As XDocument
doc = XDocument.Load("http://dl.dropbox.com/u/8842115/sample.xml")
For Each node In doc.Descendants("first")
  Console.WriteLine(CType(node.Element("no"), String))
Next

A: Here's an example to show you how you can download a web page from the Internet into a string in your Vb.Net program. You need to create a new WebClient class instance and then specify the URL you want to download as the parameter to the DownloadString method, which will return a string containing the HTML source (or XML in your case). If no accept-encoding is specified, the server usually returns a plain text string.
Imports System
Imports System.Net

Class Program
    Private Shared Sub Main()
        ' Create web client.
        Dim client As New WebClient()

        ' Download string.
        Dim value As String = client.DownloadString("http://battless59.evony.com/default.html?logfile/20111121/4c/6b/4c6b0c2f1ca16b8dbdf971154741dd4c.xml")

        ' Write values.
        Console.WriteLine("--- WebClient result ---")
        Console.WriteLine(value.Length)
        Console.WriteLine(value)
    End Sub
End Class

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why shouldn't I always use dynamic allocation in spark? Spark's dynamic allocation enables a more efficient use of resources. It is described here: https://spark.apache.org/docs/latest/job-scheduling.html#dynamic-resource-allocation
It is not a default, and must be set for each job.
What are the downsides of setting every job to use dynamic allocation by default? What effects might be seen if I change this setting for all my running jobs?

A: To understand it lets take a look at Documentation
Here you can find this:

spark.dynamicAllocation.enabled   false(default)
Whether to use dynamic resource
allocation, which scales the number of executors registered with this
application up and down based on the workload. For more detail, see
the description here.
This requires spark.shuffle.service.enabled or
spark.dynamicAllocation.shuffleTracking.enabled to be set. The
following configurations are also relevant:
spark.dynamicAllocation.minExecutors,
spark.dynamicAllocation.maxExecutors, and
spark.dynamicAllocation.initialExecutors
spark.dynamicAllocation.executorAllocationRatio

Default values for revelevant parameters are:
spark.dynamicAllocation.initialExecutors = minExecutors
spark.dynamicAllocation.minExecutors = 0
spark.dynamicAllocation.maxExecutors = infinite
spark.dynamicAllocation.executorAllocationRatio = 1

Lets take a look at executorAllocationRatio description:

By default, the dynamic allocation will request enough executors to
maximize the parallelism according to the number of tasks to process.
While this minimizes the latency of the job, with small tasks this
setting can waste a lot of resources due to executor allocation
overhead, as some executor might not even do any work. This setting
allows to set a ratio that will be used to reduce the number of
executors w.r.t. full parallelism. Defaults to 1.0 to give maximum
parallelism. 0.5 will divide the target number of executors by 2 The
target number of executors computed by the dynamicAllocation can still
be overridden by the spark.dynamicAllocation.minExecutors and
spark.dynamicAllocation.maxExecutors settings

So what may happen when you just turn dynamic allocation on?
Lets say you have a job which at some stage is doing repartition(2000). Number of cores avilable per executor is set to 2. What is Spark going to do with dynamic allocation enabled with default parameters? It will try to get as many executors as it needs for max paralellism. In this case it will be 2000/2 (number of tasks at given stage/number of cores per executor, executorAllocationRatio is set to 1 so i am skipping it) = 1000 executors.
I saw a real scenarios in which some jobs where taking a lot of resources to work on really small inputs just because dynamic allocation was turned on
Imo if you want to use it you should tune also other parameters and for sure limit maxExecutors, especially if you are not alone on your cluster and you dont want to waste time&resources. Sometimes overhead for creating new exeuctor is just not worth it


text:
Q: how can we get the value of of VARRAY from IN Parameter in procedure I am new to PL/SQL... In Varray how can i get multiple value from IN parameter..... else Is there another ways to get the values...
I want to interate the values through VArray... if any other options then its fine..
coding:
CREATE OR REPLACE
PROCEDURE dynamic_query_build(
    vr_plan_sku_id IN VARCHAR2 )
IS
type plan_sku_id_array IS VARRAY(999) OF VARCHAR2(5000);
plan_sku_id plan_sku_id_array;
total           INTEGER;
vrx_plan_sku_id VARCHAR2(3000);
BEGIN
  vrx_plan_sku_id:= REPLACE(vr_plan_sku_id,',',chr(39)||','||chr(39));
  plan_sku_id    := plan_sku_id_array(chr(39)||vrx_plan_sku_id||chr(39));
  total          := plan_sku_id.count;
  FOR i          IN 1 .. total
  LOOP
    dbms_output.put_line(plan_sku_id(i));
  END LOOP;
EXCEPTION
WHEN OTHERS THEN
  raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
END dynamic_query_build;

Execution:
set serveroutput on;
declare
vr_plan_sku_id varchar2(200) := '5863314,5863315';
BEGIN
   dynamic_query_build(vr_plan_sku_id);
END;
/

My Output:
anonymous block completed
'5863314','5863315'

Expected output:
5863314
5863315

now it is considering as single value....

A: Put a replace in the dbms_output statement this will eliminate the quotes from the string
     ....
     dbms_output.put_line replace (replace (plan_sku_id(i), '''' ))',',chr(10);
     .....

A: I created anonymous block with procedure dynamic_query_build. Added there code, that will split VARCHAR2 variable into varray.
I think, the key to your question is this line - plan_sku_id.EXTEND();
You can extend varray dynamically, but only till it reaches defined maximum (in your case - 999).
DECLARE
vr_plan_sku_id varchar2(200) := '5863314,5863315';
PROCEDURE dynamic_query_build(
    vr_plan_sku_id IN VARCHAR2 )
IS
type plan_sku_id_array IS VARRAY(999) OF VARCHAR2(5000);
plan_sku_id plan_sku_id_array;
total           INTEGER;

position PLS_INTEGER := 0;
last_position PLS_INTEGER := 1;
tmp VARCHAR2(5000);
counter PLS_INTEGER := 1;
BEGIN
  plan_sku_id := plan_sku_id_array();
  LOOP
    position := INSTR(vr_plan_sku_id, ',', last_position);
    IF position > 0 THEN
      tmp := SUBSTR(vr_plan_sku_id, last_position, position - last_position);
      last_position := position + 1;
    ELSE
      tmp := SUBSTR(vr_plan_sku_id, last_position);
    END IF;
    plan_sku_id.EXTEND();
    plan_sku_id(counter) := tmp;
    counter := counter + 1;
    EXIT WHEN position = 0 OR counter > 10;
  END LOOP;
  total          := plan_sku_id.count;
  FOR i          IN 1 .. total
  LOOP
    dbms_output.put_line(plan_sku_id(i));
  END LOOP;
EXCEPTION
WHEN OTHERS THEN
  raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
END dynamic_query_build;
BEGIN
   dynamic_query_build(vr_plan_sku_id);
END;
/


text:
Q: CakePHP Not Saving BelongsTo Key I'm trying to save a record that belongs to another model.  Yet, I get an error that the foreign key is missing.  The CakePHP docs show examples of this working but I can't get it to work.
Here is the Form:
    echo $this->Form->create('Message', array('action'=>'add'));
                echo $this->Form->hidden('Ticket.id');
                echo $this->Form->input('Message.message');
                echo $this->Form->submit('Save Message');
                echo $this->Form->end();

Here is what is returned to the controller upon submit:
    Array(
        [Ticket] => Array
        (
            [id] => 2
        )

        [Message] => Array
        (
            [message] => Message text
        )

    )

Here is my Message model:
    class Message extends AppModel {
            public $belongsTo = array('Ticket');
    }

Here is my Ticket model:
    class Ticket extends AppModel {
        public $hasMany = 'Message';
    }

Here is my controller logic:
        $this->Message->save($this->request->data);

Here is the error message I receive:
    Error: SQLSTATE[HY000]: General error: 1364 Field 'ticket_id' doesn't have a default value

The CakePHP documents are pretty clear that Cake will grab the id from the Ticket array.  The only way I can get this to work is if I manually assign the ticket id to the message array.
    $this->request->data['Message']['ticket_id'] = $this->request->data['Ticket']['id']

I shouldn't have to do that.  Where's the magic?  I've read at least 20 similar posts but none exactly like this (probably because this is so basic that nobody has this problem because it works for them).
I'm using version 2.4.2
Thanks for any help.

A: Don't use Model::save() in this case, the reason is that you also want to save associated data, in order for you save data for the main model along with its associated models you need to use Model::saveAssociated().
Your controller should be looking like this
  $this->Message->saveAssociated($this->request->data);


text:
Q: How can I allow users to login only during working hours? I want to make a code which restricts users from login after work hours:
Users should only login from 8:00 to 4:35 :
Bellow is the code I have tried and I managed to make two conditions work but the third condition does not work : any help will be really appreciated :
<?php
    # function to get right time of the targeted city
    date_default_timezone_set('Africa/Johannesburg');
    function time_diff_conv($start, $s)
    {
        $string="";
        $t = array( //suffixes
            'd' => 86400,
            'h' => 3600,
            'm' => 60,
        );
        $s = abs($s - $start);
        foreach($t as $key => &$val) {
            $$key = floor($s/$val);
            $s -= ($$key*$val);
            $string .= ($$key==0) ? '' : $$key . "$key ";
        }
        return $string . $s. 's';
    }
$date = date('h:i');
 echo  $date;
 /*Start time for work*/
 $workStart = strtotime("08:00");//am
  /*Stop time for work*/
 $workStop = strtotime("04:35");//pm
 /*This is the current time*/
 $currentTime = strtotime($date);
 //$fromSatrtToEnd = $workStart->diff($workStop);
 /*This Condition works*/
 if($currentTime >=$workStart){
 echo "Start Working";
 /*This Condition also  works*/
 } else if($currentTime < $workStart){
 echo "You too early at work";
 }
 /*This Condition does not works*/
 else if($currentTime < $workStop){
 echo "Its after work";
 }

?>

A: if($currentTime >=$workStart AND $currentTime <= $workStop){
    echo "Start Working";
    /*This Condition also  works*/
} else if($currentTime < $workStart){
    echo "You too early at work";
}
/*This Condition does not works*/
else if($currentTime < $workStop){
    echo "Its after work";
}

Your first condition was always true if the time was after the start time. You need to check if it's within the time range.

A: You have to explicit the period of your date, the program can't recognize that 08:00 it's an AM date and 04:35 it's a PM date.
just change your variable declaration in
 /*Start time for work*/
 $workStart = strtotime("08:00 AM");//am
  /*Stop time for work*/
 $workStop = strtotime("04:35 PM");//pm

or convert the second variable to an 24-h format:
$workStop = strtotime("16:35 PM");//pm
This way $workStart will be correctly evaluated as a minor value compared to $workStop.
Then change your if to correctly match the condition:
if($currentTime >=$workStart && $current <= $workstop){
    echo "Start Working";
} else if($currentTime < $workStart){
    echo "You too early at work";
}
else if($currentTime > $workStop){
    echo "Its after work";
}

A: First, if you have to manage AM/PM hours, you should convert your hours to 24H-format in every line you use them :

$date = date('H:i'); // H rather than h
$workStart = strtotime("08:00");
$workStop = strtotime("16:35");

and your conditions aren't right you should have something like :
if($currentTime >=$workStart AND $current <= $workstop){ // need to check both
    echo "Start Working";
} else if($currentTime < $workStart){
    echo "You too early at work";
}
else if($currentTime > $workStop){ // > rather than <
    echo "Its after work";
}


text:
Q: Ramda: How to remove keys in objects with null values, empty arrays and empty lists recursively? Similar to Ramda: How to remove keys in objects with empty values? but I am looking for something that works recursively.  This is so I can workaround a "feature" of AJV and JSON Schema where null !== undefined.
I started with this... which is to remove the nulls but does not work recursively
import R from 'ramda';
describe('filter null values', () => {
  it('should filter out null values', () => {
    const specimen = {
      tasks: [
        { id: 'foo', blank: '', zero: 0, nool: null },
        { nool: null },
        { id: '', blank: null, zero: 0, nool: null },
      ],
      useless: { nool: null },
      uselessArray: [{ nool: null }],
      nool: null,
    };
    const expectation = {
      tasks: [
        { id: 'foo', blank: '', zero: 0 },
        { id: '', zero: 0 },
      ],
    };
    const removeNulls = R.reject(R.equals(null));
    expect(removeNulls(specimen)).toEqual(expectation);
  });
});

A: Map the passed item. If the value is an Object (or Array), recursively call removeNulls on the current value. After mapping the values, reject all undefined, null, or empty non string values (see R.isEmpty).

const { pipe, map, when, is, reject, ifElse, F, either, isEmpty, isNil } = R;

const removeNulls = pipe(
  map(when(is(Object), v => removeNulls(v))),
  reject(ifElse(is(String), F, either(isEmpty, isNil))),
);

const specimen = {"tasks":[{"id":"foo","blank":"","zero":0,"nool":null},{"nool":null},{"id":"","blank":null,"zero":0,"nool":null}],"useless":{"nool":null},"uselessArray":[{"nool":null}],"nool":null};

const result = removeNulls(specimen);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


text:
Q: accessing hadoop job tracker ui I'm trying to setup a hadoop cluster. Currently, I have setup a master node and submitted a map reduce job using Python.
The jobs got submitted and I can see the results in the console.
Now, I had been trying to view the job tracker web ui to see the job properties but not sure which port should I use?
ipaddress : 50070 - Shows me all the namenode and datanode
ipaddress : 8088 - Shows me the cluster information
Which port should I use to view the job tracker? I tried port 50030 but nothing is displayed.
Using hadoop version 2.7.3

A:
I dont see any value set for mapreduce.framework.name , what should be the correct value to be set, so that it can be displayed on the YARN?

You don't see it, so it is the default

Property mapreduce.framework.name
  Default: local
  Description: The runtime framework for executing MapReduce jobs. Can be one of local, classic or yarn.

mapred-default.xml

You need to update mapred-site.xml with that property set to yarn


text:
Q: Error by Compiler gcc: undefined reference to `main' I am writting this program for K_ mean clustering in C and Compiling this program on GCC compiler in Linux
Compiler error massages are following
***/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status***

My complete Programme is following
#include <stdlib.h>
#include <assert.h>
#include <float.h>
#include <math.h>

int *k_means(double **data, int n, int m, int k, double t, double
**centroids) {    /* output cluster label for each data point */    int *labels = (int*)calloc(n, sizeof(int));

   int h, i, j; /* loop counters, of course :) */    int *counts =
(int*)calloc(k, sizeof(int)); /* size of each cluster */    double
old_error, error = DBL_MAX; /* sum of squared euclidean distance */
double **c = centroids ? centroids : (double**)calloc(k,
sizeof(double*));    double **c1 = (double**)calloc(k,
sizeof(double*)); /* temp centroids */

   assert(data && k > 0 && k <= n && m > 0 && t >= 0); /* for
debugging */

   /****    ** initialization */

   for (h = i = 0; i < k; h += n / k, i++) {
      c1[i] = (double*)calloc(m, sizeof(double));
      if (!centroids) {
         c[i] = (double*)calloc(m, sizeof(double));
      }
      /* pick k points as initial centroids */
      for (j = m; j-- > 0; c[i][j] = data[h][j]);    }

   /****    ** main loop */

   do {
      /* save error from last step */
      old_error = error, error = 0;

      /* clear old counts and temp centroids */
      for (i = 0; i < k; counts[i++] = 0) {
         for (j = 0; j < m; c1[i][j++] = 0);
      }

      for (h = 0; h < n; h++) {
         /* identify the closest cluster */
         double min_distance = DBL_MAX;
         for (i = 0; i < k; i++) {
            double distance = 0;
            for (j = m; j-- > 0; distance += pow(data[h][j] - c[i][j], 2));
            if (distance < min_distance) {
               labels[h] = i;
               min_distance = distance;
            }
         }
         /* update size and temp centroid of the destination cluster */
         for (j = m; j-- > 0; c1[labels[h]][j] += data[h][j]);
         counts[labels[h]]++;
         /* update standard error */
         error += min_distance;
      }

      for (i = 0; i < k; i++) { /* update all centroids */
         for (j = 0; j < m; j++) {
            c[i][j] = counts[i] ? c1[i][j] / counts[i] : c1[i][j];
         }
      }

   } while (fabs(error - old_error) > t);

   /****    ** housekeeping */

   for (i = 0; i < k; i++) {
      if (!centroids) {
         free(c[i]);
      }
      free(c1[i]);    }

   if (!centroids) {
      free(c);    }    free(c1);

   free(counts);

   return labels; }

Please help us .
#include <stdlib.h>
#include <assert.h>
#include <float.h>
#include <math.h>

int *k_means(double **data, int n, int m, int k, double t, double
**centroids) {    /* output cluster label for each data point */    int *labels = (int*)calloc(n, sizeof(int));

   int h, i, j; /* loop counters, of course :) */    int *counts =
(int*)calloc(k, sizeof(int)); /* size of each cluster */    double
old_error, error = DBL_MAX; /* sum of squared euclidean distance */
double **c = centroids ? centroids : (double**)calloc(k,
sizeof(double*));    double **c1 = (double**)calloc(k,
sizeof(double*)); /* temp centroids */

   assert(data && k > 0 && k <= n && m > 0 && t >= 0); /* for
debugging */

   /****    ** initialization */

   for (h = i = 0; i < k; h += n / k, i++) {
      c1[i] = (double*)calloc(m, sizeof(double));
      if (!centroids) {
         c[i] = (double*)calloc(m, sizeof(double));
      }
      /* pick k points as initial centroids */
      for (j = m; j-- > 0; c[i][j] = data[h][j]);    }

   /****    ** main loop */

   do {
      /* save error from last step */
      old_error = error, error = 0;

      /* clear old counts and temp centroids */
      for (i = 0; i < k; counts[i++] = 0) {
         for (j = 0; j < m; c1[i][j++] = 0);
      }

      for (h = 0; h < n; h++) {
         /* identify the closest cluster */
         double min_distance = DBL_MAX;
         for (i = 0; i < k; i++) {
            double distance = 0;
            for (j = m; j-- > 0; distance += pow(data[h][j] - c[i][j], 2));
            if (distance < min_distance) {
               labels[h] = i;
               min_distance = distance;
            }
         }
         /* update size and temp centroid of the destination cluster */
         for (j = m; j-- > 0; c1[labels[h]][j] += data[h][j]);
         counts[labels[h]]++;
         /* update standard error */
         error += min_distance;
      }

      for (i = 0; i < k; i++) { /* update all centroids */
         for (j = 0; j < m; j++) {
            c[i][j] = counts[i] ? c1[i][j] / counts[i] : c1[i][j];
         }
      }

   } while (fabs(error - old_error) > t);

   /****    ** housekeeping */

   for (i = 0; i < k; i++) {
      if (!centroids) {
         free(c[i]);
      }
      free(c1[i]);    }

   if (!centroids) {
      free(c);    }    free(c1);

   free(counts);

   return labels; }

A: It would be more readable if you kept the code formatting for the whole code, not just its part.
But when I tried to find a main function, I didn't find any. Therefore there is no reference to main because you haven't implemented one, at least not in the code you posted here.


text:
Q: Why TryInto needs Copy trait in T? I have this code but fails because T needs has implemented Default AND Copy to convert the slice to a array.
Why needs the trait Copy?
use std::convert::TryInto;

fn fill_default<T: Default, const N: usize>() -> [T; N] {
    std::iter::repeat_with(|| T::default())
        .take(N)
        .collect::<Vec<T>>()
        .as_slice()
        .try_into()
        .unwrap()
}

A: The TryInto trait is defined as consuming the value so that implementations can be more efficient (eg. reuse data already allocated for the value in the converted value by taking it and throwing away the rest).
Since you are returning an array by move, and the vector that is collected is not used for anything else, you don't need to use .as_slice(), which returns a reference to the vector, but instead pass the vector directly to .try_into() which will consume the vector and produce the correct output.
When I tried compiling it, I was getting an additional error cause by the unwrap() combined with the type parameter T not having a std::fmt::Debug constraint.  You can either add the constraint or return a Result or 'Option` to get around that.


text:
Q: Buildozer compiled apk doesn't keep font size I'm trying to learn python and kivy by writing an app which dynamically creates modules inputted by the user in order to be counted using + and - buttons.
I am using buildozer to create the apk and deploy it to my phone (Samsung Galaxy S21 Ultra, Android 11).
I have encountered two problems:

*

*Though there is no problem when I run the code in a virtual environment in PyCharm, when I run the apk on the phone, it does not keep the size of the text that I set in the code;

*Pdf file is being created in the virtual environment in PyCharm but it crashes the apk on the phone.
Any help will be very much appreciated. Thanks a lot.
Here is the full code:

Python file:

from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from fpdf import FPDF

class pdf(FPDF): # Setting the header and footer for the pdf document
    def header(self):
        self.image('inventory_management.png', 10, 8, 25)
        self.set_font('helvetica', 'B', 20)
        self.cell(0,10, app.root.ids.project_name.text, ln=True, align='C')
        self.ln(20)

    def footer(self):
        self.set_y(-15)
        self.set_font('helvetica', 'I', 10)
        self.cell(0, 10, f'Page {self.page_no()}/{{nb}}', align='C')

class popup_empty(Popup): # Message box if user doesn't inputs a module name
    pass

class popup_exist(Popup): # Message box if user inputs an existent module name
    pass

class Row(BoxLayout): # Creates a row for each module
    quantity = ObjectProperty()
    entry = ObjectProperty()

    def change_label(self): # Setting the module name with the user input
        self.name_label.text = app.root.ids.name_input.text

    def add_entry(self): # Function used by the + button to add to the quantity
        self.quantity.text = str(int(self.quantity.text) + int(self.entry.text))
        app.root.Lista_module[self.ids.name_label.text] = int(self.quantity.text)

    def deduct_entry(self): # Function used by the - button to deduct from the quantity
        self.quantity.text = str(int(self.quantity.text) - int(self.entry.text))
        app.root.Lista_module[self.ids.name_label.text] = int(self.quantity.text)

    def del_row(self): # Function used by the del button to remove a module row
        del app.root.Lista_module[self.ids.name_label.text]
        app.root.ids.rows_container.remove_widget(self)

class mainContainer(BoxLayout): # Main container which holds all the widgets

    Lista_module = {}

    def file_name(self): # replaces the spaces user inputs in the module name to create the pdf filename
        name = self.ids.project_name.text
        name = name.replace(" ", "_")
        return name

    def add_a_row(self): # function used to dynamically add rows to the scrollview

        if self.ids.name_input.text != "":
            name = self.ids.name_input.text
            exist = False
            for key in self.Lista_module.keys():
                if key == name:
                    exist = True
            if exist:
                popup = popup_exist()
                popup.open()
            else:
                temp_row = Row()
                temp_row.change_label()
                self.ids.rows_container.add_widget(temp_row)
                key = self.ids.name_input.text
                self.Lista_module[key] = 0
        else:
            popup = popup_empty()
            popup.open()
    pass

    def print(self): # function used by the print button to create the pdf file
        name = self.file_name() + '.pdf'
        document = pdf('P', 'mm', 'A4')
        document.add_page()
        document.alias_nb_pages()
        document.set_auto_page_break(auto=True)
        document.set_font('times', '', 14)
        for mod in self.Lista_module:
            document.cell(0, 10, f'{mod}: {self.Lista_module[mod]}', border=True, ln=True)
        document.output('I', name)

class lysuApp(App):

    def build(self):
        return mainContainer()

if __name__ == "__main__":
    app = lysuApp()
    app.run()

kv file:

<popup_exist>
    size_hint: 0.5, 0.5
    pos_hint: {"x":0.2, "top":0.9}
    title: "Eroare nume"
    BoxLayout:
        orientation: "vertical"
        size: root.width, root.height
        Label:
            text: "Modul existent, reintrodu!"

        Button:
            text: "OK"

            on_release: root.dismiss()

<popup_empty>
    size_hint: 0.5, 0.5
    pos_hint: {"x":0.2, "top":0.9}
    title: "Eroare nume"
    BoxLayout:
        orientation: "vertical"
        size: root.width, root.height
        Label:
            text: "Trebuie sa introduci un nume!"

        Button:
            text: "OK"

            on_release: root.dismiss()

<Row>
    name_label: name_label
    quantity: quantity
    entry: entry
    orientation: "horizontal"
    size_hint_y: None
    height: 30
    id: root.module_name
    Label:
        id: name_label
        font_size: 20
        text: ""
    Label:
        font_size: 20
        text: ":"
    Label:
        id: quantity
        font_size: 20
        text: "0"
    TextInput:
        id: entry
        font_size: 20
        text: "1"
    Button:
        font_size: 20
        text: "-"
        on_press: root.deduct_entry()
    Button:
        font_size: 20
        text: "+"
        on_press: root.add_entry()
    Button:
        font_size: 20
        text: "del"
        on_press: root.del_row()

<mainContainer>

    id: mainpage
    BoxLayout: # the main container
        orientation: "vertical"
        size: root.width, root.height
        padding: 25
        spacing: 20
        BoxLayout: # Contains the title
            orientation: "vertical"
            size_hint: (1, .2)
            spacing: 5
            Label:
                font_size: 20
                text: "Creaza modulele si incepe editarea!"
                size_hint: (1, .5)

            BoxLayout: # Box for project name and print button
                size_hint: (1, .5)
                orientation: "horizontal"
                Label:
                    font_size: 20
                    text: "Numeste proiectul: "
                TextInput:
                    id: project_name
                    font_size: 20
                Button:
                    font_size: 20
                    text: "Printeaza"
                    on_release: app.root.print()

        ScrollView: # Will hold the dynamically created rows
            BoxLayout:
                size_hint_y: None
                height: self.minimum_height
                row_force_default: True
                row_default_height: dp(40)
                orientation: "vertical"
                id: rows_container
                spacing: 10
        BoxLayout: # Bottom of the page used to input the name of the modules that will be dynamically created
            orientation: "horizontal"
            size_hint: (1, .1)
            Label:
                font_size: 20
                text: "Nume modul"
            TextInput:
                id: name_input
                font_size: 20
            Button:
                font_size: 20
                text: "Adauga"
                on_press:
                    root.add_a_row()

A: This is because you are setting your font sizes in terms of pixels, which varies across screens. You can set the font sizes based on measurements (inches, centimeters) or pixel density as follows:
In your .kv file, instead of font_size: 20, use font_size: '20dp', font_size: '20cm', or whatever your desired unit is.
In you want to set font sizes in a .py file, first import the desired unit from kivy.metrics. For example, if you wanted to use inches, you would write from kivy.metrics import inch and then replace numeric pixel values with inch(2), inch(1), or whatever value you want.
See Metrics for more.
As for your second question, the line document.output('I', name) is a typo (it should be document.output(name, "F") if you are creating a file with the name name). If that is not the cause of the issue, look into debugging your APK with logcat.
In the future, please separate questions into two separate posts.

A: I sub-classed TextInput and gave it its own on_size callback like this:
    def on_size(self,instance,value):
        # run parent on_size manually
        super(MyTextInput,self).on_size(instance,value)
        self.font_size = self.height*0.8

so the font size is a fraction of the textInput height, whatever device it may be running on. (Note there's probably a better/correct way to bind a callback for an on_size event in the sub-class so it works in parallel with the parent callback instead of over-riding it.)


text:
Q: RC Circuit with dependent source How to find i(t) t>0.I stuck.If cannot help me okey.

A: No full solutions to homeworks, only guidance!
Only the capacitor in your circuit needs something based on differential equations. Even it can be handled elementarily because the charging of the capacitor obeys a well known equation:
\$U_c = U_t + (U_{co}-U_t)e^{\frac{-t}{RC}}\$ where

*

*Uc=capacitor voltage

*Uco=initial value of Uc

*Ut=Thevenin equivalent voltage seen by the capacitor

*R=Thevenin equivalent resistance seen by the capacitor

*t=time

*C=capacitance

So, you must calculate

*

*the initial voltage of the capacitor when the switch still was closed; assume a steady state, the cap is fully charged to the voltage what the rest of the circuit can offer, Uco=Uc when the current of the capacitor is zero, solve the KVL equation for Uc.

*the Thevenin equivalent for the rest of the circuit seen by the capacitor when t>0 and the switch is open

*the final numeric equation for Uc

*the equation how the asked current i depends on Uc

*the final numeric equation for i by substituting the equation of Uc.

As well you can form the equation for current i in Laplace domain and find the solution with Laplace transforms. This sounds simpler but the amount of work is quite the same.
An auxiliary hint: There's total 80 ohm resistance with current i. The controlled source in parallel gives exactly half of it. Together the controlled source and the 50+30 ohm resistance are equivalent with a 160 ohm resistance when seen by the rest of the circuit.
An opinion: This would be an excellent question in an exam. Persons who have things clear in their heads need few minutes for full solution, the others can fight a hour with no result.


text:
Q: could not transpose excel file with 1 row in dataframe r shiny I have an excel file with 2 columns (1st column with headers & 2nd with data) and I'm trying it to transpose it(1st row with headers & 2nd with data). For some reason my code is only working for the data with >= 2rows.
  Input Excel:

    Expected Output:

    Code:
    df <- df_customer_upload()                     # original excel file
    df <- t(df_customer_upload())                  # Transposed excel file, in matrix format
    colnames(df) <- (df[1, ])                      # Copies 1st row to the header
    df <- df[-1,]                            # after copying 1st row as header, deletes the 1st row
    View(df)

Output I got:

Any help would be appreciated.
Thanks in advance!!


text:
Q: jQuery editable plugin and jquery datatable not working together I have an html table which is configured with jQuery editable plugin. Later I configured jQuery datatable with the same. After that the editable plugin is not working.
$('#user_list_table').DataTable();
$('.editable').editable();

Please give me some suggestions

A: You don't need to use editable with Datatable but you should use inline-editing of datatable.
check demo here

A: Please make sure $('.editable').length>0, ie, that is present in the dom.
If its inside datatable the initialize editable in rowcallback.


text:
Q: The flutter tool cannot access the file or directory. Unable to grant read/write permissions for the current user This is the first time I am installing flutter on the mac. I have followed all the steps that are told in flutter.dev. After setting up the path in .zshrc, I get this strange error.

The flutter tool cannot access the file or directory.
Please ensure that the SDK and/or project is installed in a location that has
read/write permissions for the current user.

This is the .zshrc file looks like.

After running flutter doctor getting this.

Thanks in advance.

A: I encountered this issue when moving my project from windows to a Mac folder. It seems to be an issue with some extended attributes. Using the below command worked for me.
sudo xattr -c -r  <project_folder_path>

A: I'm not sure about this but try it. go to the folder where you installed Flutter, click the folder with to fingers which will show options. got to {Get info} look down at the Sharing & Permission, make sure your current user has read and write.

I just hope this will fix your problem

A: For Windows 11 on VScode it shows the same problem. Another way to fix, is to run VScode with Admin Privilleges


text:
Q: document.createElement react doesn't add options to div i'm trying to add attributes to div, but div is always without any attributes, how can i sole this?
I'm working with next.js, mb it is a problem, i don't know.
Here is my component:
import React, { useEffect, useState } from "react";
import reactDom from "react-dom";

const Portal = ({ children, isModal=false }) => {
  const [container, setContainer] = useState();

  useEffect(() => {
    setContainer(document.createElement("div", {role: 'dialog'}, null));
  }, []);

  useEffect(() => {
    if (container) {
      document.body.appendChild(container);
    }
    return () => {
      if (container) {
        document.body.removeChild(container);
      }
    };
  }, [container]);

  return container ? reactDom.createPortal(children, container) : null;
};

export default Portal;

Inside inspector div has no role


text:
Q: Android scrollable table How can I achieve to get this table scroll if content is too big horizontal and vertical?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:id="@+id/banner" />
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:id="@+id/myTableLayout"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent">
        <TableRow
                  android:background="@drawable/standard"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content">
            <TextView android:text="@string/rankColumnHeader"
                      android:layout_margin="6sp"
                      android:textColor="@color/black"/>
            <TextView android:text="@string/teamColumnHeader"
                      android:layout_margin="6sp"
                      android:textColor="@color/black"/>
            <TextView android:text="@string/matchesColumnHeader"
                      android:layout_margin="6sp"
                      android:textColor="@color/black"/>
            <TextView android:text="@string/winColumnHeader"
                      android:layout_margin="6sp"
                      android:textColor="@color/black"/>
            <TextView android:text="@string/drawColumnHeader"
                      android:layout_margin="6sp"
                      android:textColor="@color/black"/>
            <TextView android:text="@string/looseColumnHeader"
                      android:layout_margin="6sp"
                      android:textColor="@color/black"/>
            <TextView android:text="@string/winPercentColumnHeader"
                      android:layout_margin="6sp"
                      android:textColor="@color/black"/>
            <TextView android:text="@string/pointsColumnHeader"
                      android:layout_margin="6sp"
                      android:textColor="@color/black"/>
            <TextView android:layout_margin="6sp"
                  android:textColor="@color/black"
                  android:id="@+id/demoTextView"/>
        </TableRow>
    </TableLayout>
</LinearLayout>

A: I think you should be able to put the table into a ScrollView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:id="@+id/banner" />
<ScrollView
    android:layout_height="wrap_content"
    android:id="@+id/scrollView1"
    android:layout_width="fill_parent">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@+id/myTableLayout"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent">
    <TableRow
              android:background="@drawable/standard"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content">
        <TextView android:text="@string/rankColumnHeader"
                  android:layout_margin="6sp"
                  android:textColor="@color/black"/>
        <TextView android:text="@string/teamColumnHeader"
                  android:layout_margin="6sp"
                  android:textColor="@color/black"/>
        <TextView android:text="@string/matchesColumnHeader"
                  android:layout_margin="6sp"
                  android:textColor="@color/black"/>
        <TextView android:text="@string/winColumnHeader"
                  android:layout_margin="6sp"
                  android:textColor="@color/black"/>
        <TextView android:text="@string/drawColumnHeader"
                  android:layout_margin="6sp"
                  android:textColor="@color/black"/>
        <TextView android:text="@string/looseColumnHeader"
                  android:layout_margin="6sp"
                  android:textColor="@color/black"/>
        <TextView android:text="@string/winPercentColumnHeader"
                  android:layout_margin="6sp"
                  android:textColor="@color/black"/>
        <TextView android:text="@string/pointsColumnHeader"
                  android:layout_margin="6sp"
                  android:textColor="@color/black"/>
        <TextView android:layout_margin="6sp"
              android:textColor="@color/black"
              android:id="@+id/demoTextView"/>
    </TableRow>
</TableLayout>
</ScrollView>
</LinearLayout>


text:
Q: Выдает ошибку NameError:name 'txt' is not defined при использовании функций * и /, х from tkinter import *

root = Tk()

def plus_op():
    if txt.get() != '' and txt2.get() != '':
        res = float(txt.get()) + float(txt2.get())

        lbl.configure(text=res)
    else:
        lbl.configure(text='')

def minus_op():
    if txt.get() != '' and txt2.get() != '':
        res = float(txt.get()) - float(txt2.get())

        lbl.configure(text=res)
    else:
        lbl.configure(text='')

#def multiply_op():
#    if txt.get() != '' and txt2.get() != '':
#        res = float(txt.get()) * float(txt2.get())
#
#        lbl.configure(text=res)
#   else:
#        lbl.configure(text='')

#def divide_op():
#    if txt.get() != '' and txt2.get() != '':
#        res = float(txt.get()) / float(txt2.get())
#
#        lbl.configure(text=res)
#    else:
#       lbl.configure(text='')

top_frame = Frame(root)
top_frame.pack()

button1 = Button(top_frame, text='+', fg='blue', command=plus_op)
button1.pack(side=LEFT)
button2 = Button(top_frame, text='-', fg='blue', command=minus_op)
button2.pack(side=LEFT)
#button3 = Button(top_frame, text='*', fg='blue', command=multiply_op())
#button3.pack(side=LEFT)
#button4 = Button(top_frame, text='/', fg='blue', command=divide_op())
#button4.pack(side=LEFT)
button5 = Button(top_frame, text='=', fg='blue')
button5.pack(side=LEFT)
button6 = Button(top_frame, text='exit', fg='blue', command=root.quit)
button6.pack(side=RIGHT)
txt = Entry(root, width=10)
txt.pack(padx=10, pady=10)

txt2 = Entry(root, width=10)
txt2.pack(padx=10, pady=10)

root.title("Calculator")
root.geometry('350x200')
lbl = Label(root, text="Hello!")
lbl.pack()
lbl2 = Label(root, text="Thanks", bg='blue')
lbl2.pack(side=BOTTOM, fill=X, padx=25, pady=25)
root.mainloop()

Программа выполняет команды + и -. Но на команды * и /, показывает ошибку:
NameError: name 'txt' is not defined
Хотя параметр txt уже идентифицирован.

A: В общем-то это типовая ошибка, много раз встречавшаяся в вопросах на этом сайте.
button1 = Button(top_frame, text='+', fg='blue', command=plus_op)
button1.pack(side=LEFT)
button2 = Button(top_frame, text='-', fg='blue', command=minus_op)
button2.pack(side=LEFT)
#button3 = Button(top_frame, text='*', fg='blue', command=multiply_op())
#                                                                    ^^
#button3.pack(side=LEFT)
#button4 = Button(top_frame, text='/', fg='blue', command=divide_op())
#                                                                  ^^
#button4.pack(side=LEFT)

Посмотрите внимательно, чем отличаются определения закомментированных кнопок. Обратите внимание на скобки после названия функции. Вы там не указываете функцию, которую нужно вызывать по нажатию кнопок, а вы её уже сразу вызываете в этих строках!
А на момент описания кнопок в этих строках переменная txt ещё не описана, поэтому и выходит ошибка - функции где используется переменная txt уже вызываются, а переменной txt ещё нет.
Уберите скобки после функций, чтобы код работал правильно. Даже если бы ошибка не вылезла на данном этапе из-за переменной txt, она вылезла бы потом, поскольку сами эти функции ничего не возвращают и такое описание command=multiply_op() в результате эквивалентно command=None, т.е. по нажатию этих кнопок всё-равно бы ничего потом не вызывалось.


text:
Q: Path parameters in Angular2 How are we meant to handle path parameters in Angular 2 when doing RESTful calls to a Web Service?
I've found the URLSearchParams object for query parameters but from what I have found it seems we'll have to make do with string-concatenation for the path itself. Like
let url = 'api/v1/something/' + encodeURIComponent(someParameter) +
          '/etc/' + encodeURIComponent(anotherParam) + '/and/so/on';

Is there, included in angular2, something that does similar to:
let url = new URL('api/v1/something/{id}/etc/{name}/and/so/on', param1, param2);

I can of course create something similar myself but prefer if there is something included in angular2.

A: Indeed, you can use string interpolation and nearly exactly the same thing you suggest, assuming id and name are already set and encoded.
let url = new URL(`api/v1/something/${id}/etc/${name}/and/so/on`);

I'll note that currently the ES6 URL class only supports searchParams, but has no notion of path parameters.
Also, I know of no method that will automatically encode your parameters without implementing your own QueryEncoder with URLSearchParams

A: If anybody is interested, this is what I ended up doing:
export interface PathParameters {
  [parameterName: string]: string;
}

export class Url {

  public static create(url: string, parameters: PathParameters) {
    const placeholders = url.match(/({[a-zA-Z]*})/g);
    placeholders.forEach((placeholder: string) => {
      const key = placeholder.substr(1, placeholder.length - 2);
      const value = parameters[key];
      if (!value) {
        throw new Error(`parameter ${key} was not provided`);
      }
      url = url.replace(placeholder, encodeURIComponent(value));
    });
    return url;
  }

}

How to use:
const url = Url.create('/api/cars/{carId}/parts/{partId}', {
    carId: carId,
    partId: partId
  });


text:
Q: What is x[ : , 0]? I don't understand what it does, and only saw it used by a sklearn-object.
On trying some testing like this
x = [(1, 2), (2, 3), (3, 4)]
y = [[1, 2], [2, 3], [3, 4]]

print(y[:, 0])

I got this error (with both x and y):
TypeError: list indices must be integers or slices, not tuple

My assumption was that the : before the comma tells Python to take all entries, while the 0 specifies which 'subset'.
How does one use this expression properly and what does it do?

A: What you express would work with more complex objects, like numpy (and its famous slicing). In the case of vanilla Python, this is not possible. To access a specific number (in your case) you would have to do x[2][1] (yielding 4 in your example).
To achieve what you want (take the first item of each tuple), you would do
[item[0] for item in y]. This is list comprehension: iterate through y, take the object at the first index of each item, and make a list out of that.

A: As explained here this is a numpy-specific notation to index arrays, not plain python. This is why it does not work on your code. In your (initial) case, the sklearn object probably wraps a numpy array that supports the numpy slicing syntax.
In your specific case, it would work as follows:
import numpy as np

y = np.array([[1, 2], [2, 3], [3, 4]])
print(y[:, 0])

# prints: [1 2 3]

This would yield all indexes along the first axis (i.e. use full column vectors), but use only index 0 in the second axis (i.e. use only the first column vector).


text:
Q: Is it normal practice to use variables to store parameter data? In some examples of PHP, I see people assign things to shorthand variables, and then use the shorthand variables instead.  Is this common practice?  Is this good practice?
$name = $_POST['name'];

and then they use they use $name down here to echo it or use it as a function parameter.
Another example is:
DEFINE('DB_USER', 'username');
mysqli_connect(DB_USER.......);

A: Pros:

*

*Shorthand variables can be easier to type and remember.

*A shorthand variable might allow an expensive operation to be done once instead of repeated many times.  But beware of premature optimization!  Most of the time this sort of optimization would be premature.

*A shorthand variable can be used to make a copy that can be changed without modifying the original variable.

*In some languages, a shorthand variable can be used to make a copy that is guaranteed to persist even if the the original variable is modified.

Cons:

*

*Indiscriminate use of shorthand variables can result in multiple names for the same values.

*In some languages and situations, a shorthand variable will make an unnecessary copy, using additional resources.

A: I have been doing php professionally for about 5 years now.
Usually when getting post variables it is a good idea, but even more common is to wrap it in an isset ternary if statement:
$name = isset($_POST['name']) ? $_POST['name'] : false;
This way if the variable isn't passed then you don't get an undefined variable warning.
Further, it saves you having to type $_POST every time, and it helps encapsulate the code a bit better.

A: The most important thing when writing code is writing readable code, not just for others but also for yourself. We do this all the time, i.e. abstracting and applying oo methods of programming.
So predefining the variables we'll be using and setting defaults makes perfect sense.
I would do something like this...
class ValueTooLong extends Exception {}

function R($param, $default=null, $type='string', $max_length=null) {
    if(!isset($_REQUEST[$param]))
        return $default;
    $r = $_REQUEST[$param];
    if($max_length && strlen($r) > $max_length)
        throw new ValueTooLong('Length of '.$param.' was '.strlen($r).'. Max length is: '.$max_length);
    if($type === 'bool' || $type === 'boolean') {
        if($r === 'false' || $r === 'no')
            return false;
        return !empty($r);
    }
    settype($r, $type);
    return $r;
}

# Which allows me do do this:
$name = R('name');
# or:
$count = R('count', 1, 'int');

EDIT: Function now takes a max_length parameter (as suggested by comment) and throws an exception if value of request parameter is too long


text:
Q: Restrict the length with the help of directive I wanted to add a custom directive as attribute which will not allow user to enter text in placeholder more than specified length
   <ui-select-match placeholder="Add one..." maxlength></ui-select-match>

The new directive can be like "maxlength" which will restrict the length of text

A: <textarea my-maxlength="15" ng-model="result"></textarea>

app.directive('myMaxlength', function() {
  return {
    require: 'ngModel',
    link: function (scope, element, attrs, ngModelCtrl) {
      var maxlength = Number(attrs.myMaxlength);
      function fromUser(text) {
          if (text.length > maxlength) {
            var transformedInput = text.substring(0, maxlength);
            ngModelCtrl.$setViewValue(transformedInput);
            ngModelCtrl.$render();
            return transformedInput;
          }
          return text;
      }
      ngModelCtrl.$parsers.push(fromUser);
    }
  };
});


text:
Q: Edge maps in Grothendieck spectral sequence Let $\mathcal{A},\mathcal{B}$ and $\mathcal{C}$ be abelian categories such that $\mathcal{A},\mathcal{B}$ have enough injectives (we can WLOG assume they're categories of modules for the following) and $G\colon\mathcal{A}\rightarrow\mathcal{B}$ and $F\colon\mathcal{B}\rightarrow\mathcal{C}$ be left-exact functors, such that $G$ sends injective objects of $\mathcal{A}$ to $F$-acyclic objects of $\mathcal{B}$. Under these conditions, there is a first-quadrant Grothendieck spectral sequence with second page $E_2^{p,q}=(R^pF)(R^qG)(A)$ (the $R^{\bullet}$ denote right-derived functors) and converging to $R^{p+q}(FG)(A)$ for any object $A\in\mathcal{A}$ (in a natural manner, though we will keep $A$ fixed). Now, the fact that the spectral sequence is first quadrant means that we have two edge maps ($F^{\bullet}$ denotes the filtration of the limit object, indexed contravariantly)
$$R^q(FG)(A)\twoheadrightarrow R^q(FG)(A)/F^1R^q(FG)(A)\cong E_{\infty}^{0,q}\hookrightarrow\dotsc\hookrightarrow E_2^{0,q}=F(R^qG)(A),\\
(R^pF)(GA)=E_2^{p,0}\twoheadrightarrow\dotsc\twoheadrightarrow E_{\infty}^{p,0}\cong F^pR^p(FG)(A)\hookrightarrow R^p(FG)(A).$$
In Weibel's book, it is said that these edge maps are the "natural maps". However, I do not see any obviously describable maps between these. My questions are:

*

*What are the natural maps? I.e. how do we describe them a priori?

*How do we actually see that these (once they have been defined) agree with the edge maps from the Grothendieck spectral sequence?
It appears that Weibel doesn't really address either question and other standard texts, as such as Rotman's, seem to not discuss the edge maps at all. The closest to a reference discussing this question that I could find is this MO question, which, however, only gives partial and rather cryptic answers to 1. and does not address 2. at all. I've tried reverse engineering the edge maps from the construction of the Grothendieck spectral sequence using Cartan-Eilenberg resolutions, but the amount of natural identifications going on throughout has made me lose track at clearly identifying maps obtained at the end.
The reason I care is that the Inflation-Restriction sequence for (continuous) group cohomology can be derived from the Hochschild-Serre spectral sequence, which is a special case of the Grothendieck spectral sequence. However, while deriving an exact sequence with the right objects from this spectral sequence is not particularly hard from general spectral sequence formalism (and is done in a lot of places), the finer detail of showing that the maps obtained by this formalism are actually the inflation/restrictions maps as they are a priori defined requires knowledge of these edge maps, and I have not found any discussion of this. My hope, on the basis of Weibel calling these maps "natural", is that 1. and 2. admit reasonable answers, and the application to the Hochschild-Serre spectral sequence then being a mere formal afterthought. But, for now, I'm stuck.
Edit: I'm starting to understand the first edge map, as per the linked MO answer. Indeed, derived functors are universal among non-exact $\delta$-functors and the $F\circ R^qG$ constitute a non-exact $\delta$-functor. The a priori description of the natural maps $R^q(FG)(A)\rightarrow F(R^qG)(A)$ ought to be that these are components of the unique natural transformation of $\delta$-functors, which is the canonical isomorphism $R^0(FG)\cong FG\cong F\circ R^0G$ in degree $0$.
It remains to see why this describes the edge morphisms in the Grothendieck SS. Two facts, left as exercises in Weibel chapter 5.7, are that chain maps between complexes lift to chain maps between Cartan-Eilenberg resolutions and chain homotopies between such maps lift to chain homotopies between the Cartan-Eilenberg resolutions. Furthermore, one can check that homotopic maps between double complexes induce the same map between their spectral sequences from page $2$ onward, and also on the graded pieces of the total complexes cohomology in a compatible manner. From these observations, plus the analogous facts about injective resolutions on their own, it follows that the Grothendieck SS (taken to start at page $2$) is well-defined up to canonical isomorphism and functorial in $A$. This functoriality includes the convergence data. This implies the edge map $R^q(FG)\Rightarrow F\circ R^qG$ is a natural transformation. However, I lack the clarity to see why it is compatible with the differentials in the long sequences coming from short exact sequences in $\mathcal{A}$, i.e. why they are natural transformations of $\delta$-Functors.


text:
Q: Clickhouse connection refuse I have a problem with connection to clickhouse-server by http over 8123 port. All parameters are default.
Status: Downloaded newer image for yandex/clickhouse-server:latest
Include not found: clickhouse_remote_servers
Include not found: clickhouse_compression
2017.11.09 13:05:37.975332 [ 1 ] <Warning> Application: Logging to console
2017.11.09 13:05:37.978638 [ 1 ] <Information> : Starting daemon with revision 54310
2017.11.09 13:05:37.978733 [ 1 ] <Information> Application: starting up
2017.11.09 13:05:37.979947 [ 1 ] <Debug> Application: rlimit on number of file descriptors is 1048576
2017.11.09 13:05:37.979979 [ 1 ] <Debug> Application: Initializing DateLUT.
2017.11.09 13:05:37.980015 [ 1 ] <Trace> Application: Initialized DateLUT with time zone Zulu'.
2017.11.09 13:05:37.980651 [ 1 ] <Debug> Application: Configuration parameter 'interserver_http_host' doesn't exist or exists and empty. Will use 'c9a1a0a75b97' as replica host.
2017.11.09 13:05:37.980783 [ 1 ] <Debug> ConfigReloader: Loading config /etc/clickhouse-server/users.xml'
2017.11.09 13:05:37.983605 [ 1 ] <Warning> ConfigProcessor: Include not found: networks
2017.11.09 13:05:37.983633 [ 1 ] <Warning> ConfigProcessor: Include not found: networks
2017.11.09 13:05:37.984168 [ 1 ] <Information> Application: Loading metadata.
2017.11.09 13:05:37.984738 [ 1 ] <Information> DatabaseOrdinary (default): Total 0 tables.
2017.11.09 13:05:37.984766 [ 1 ] <Information> DatabaseOrdinary (default): Starting up tables.
2017.11.09 13:05:37.984999 [ 1 ] <Debug> Application: Loaded metadata.
2017.11.09 13:05:37.985454 [ 1 ] <Information> Application: Listening http://0.0.0.0:8123
2017.11.09 13:05:37.987644 [ 1 ] <Information> Application: Listening tcp: 0.0.0.0:9000
2017.11.09 13:05:37.987692 [ 1 ] <Information> Application: Listening interserver: 0.0.0.0:9009
2017.11.09 13:05:37.988186 [ 1 ] <Information> Application: Available RAM = 1.95 GiB; physical cores = 4; threads = 4.
2017.11.09 13:05:37.988212 [ 1 ] <Information> Application: Ready for connections.
2017.11.09 13:05:39.980980 [ 2 ] <Debug> ConfigReloader: Loading config /etc/clickhouse-server/config.xml'
2017.11.09 13:05:39.985393 [ 2 ] <Warning> ConfigProcessor: Include not found: clickhouse_remote_servers
2017.11.09 13:05:39.985462 [ 2 ] <Warning> ConfigProcessor: Include not found: clickhouse_compression

$ curl 'http://localhost:8123/'
curl: (7) Failed to connect to localhost port 8123: Connection refused

Please help me to resolve this problem.

A: First of all check if even you clickhouse-server is running properly or not using this command:
sudo lsof -i :8123
You should be able to see a similar output:
COMMAND    PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME

clickhous 8752 root    9u  IPv6  38265      0t0  TCP ip6-localhost:8123 (LISTEN)

clickhous 8752 root   12u  IPv4  38268      0t0  TCP localhost:8123 (LISTEN)

Make sure that you have these entries in the config.xml file located at /etc/clickhouse-server
<listen_host>::1</listen_host>
<!-- Localhost Binding -->
<listen_host>127.0.0.1</listen_host>
<!-- Remote Access Binding -->
<listen_host>< IP / URL></listen_host>

Once you make sure these entries exist, run these commands to restart your server:
cd /usr/bin
sudo ./clickhouse-server --config /etc/clickhouse-server/config.xml &

Again execute sudo lsof -i :8123 to see if your clickhouse-server is listening at that port.

A: UPD
If you don't want to change a network type, a good solution will be to publish a container's port to the host. It can be done with the -p HOST_PORT:CONTAINER_PORT argument. In your case, it would be -p 8123:8123. An example:
docker run -d --name clickhouse-server --ulimit nofile=262144:262144 -p 8123:8123 yandex/clickhouse-server
Original answer
It seems like a docker container is attached to a network you don't have an access to from your host machine. Try to launch an image with --net=host flag. Then, run curl again.
Additional information about docker network types and its abilities can be found in the official documentation


text:
Q: Проблема с загрузкой страницы по хеш Не загружается страница, которая создана Аяксом. Мобильный сайт построен на jq mobile .
Есть страница /#auth без Ajax. При обновлении страницы перехожу сразу на неё.
Есть страница /#training_25, созданная Аяксом. При обновлении страницы ничего не происходит.
Создавал страницу по окончанию работы Ajax:
$( '#training_'+training_id ).page({
 create: function( event, ui ) {}
});

Классы jquery обновляются, а переход по хешу не срабатывает.


text:
Q: displaying several pictures from a shared File Here is 2lines that display pictures from my projects folder Assets in
String path = Directory.GetCurrentDirectory() + @"\Assets";
myFlipView.ItemsSource = Directory.GetFiles(path).Select(p => "ms-appx:///"+ p);

in the same idea I would like to add several pictures to my flipView  but it's in a shared file
myFlipView.ItemsSource = Directory.GetFiles(http://localhost/Pictures).
Pictures is a Folder that contain Pictures and their numbers can change
how can I add it to myFlipView.ItemsSource

A: as getFiles implements ILISt as long as the method GetFiles returns a list of strings for example I did that

List<string> myPathListPictures=new List<string>();
myPathListPictures = GetPictures();
fv.ItemsSource = myPathListPictures.Select(p=> "Http://localhost" + p);


text:
Q: Check Dictionary WIth ObjectForKey IsEqualToString not working i have this code and searched the internet and find it ok but its not working with me
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    .....
    NSLog(@"%@",[dict objectForKey:@"STATUS"]);

    if ([[dict objectForKey:@"STATUS"] isEqualToString:@"Y"]) {

       NSLog(@"Done");

    }

The NSLog Shows Y Which Should Work With if statment

A: When you do:
 [dict setObject:[arr objectAtIndex:1] ...

i think this is adding the strings to the dictionary as objects.  The NSLog line is working because NSLog sends each object it is passed the "description" message to convert it to its string value.  you can do the same thing.
try changing this:
if ([[dict objectForKey:@"STATUS"] isEqualToString:@"Y"])

to this:
if ([[[dict objectForKey:@"STATUS"] description] isEqualToString:@"Y"])

That would get the string value of the object returned by objectForKey: before doing the comparison.
If you think there might be a white space throwing off the compare, trim the string before comparing, like this:
if ([[[dict objectForKey:@"STATUS"] stringByTrimmingCharactersInSet:
    [NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@"Y"])


text:
Q: Import CSV row into a dict? This question has been asked before but in my scenario none of the answers apply.
I'm reading a csv file with this:
with codecs.open('./products.csv', 'r',  encoding="utf-8") as _filehandler:
    csv_file_reader = csv.DictReader(_filehandler)
    for row in csv_file_reader:

in my CSV file I have a column in a row that contains this:
'#custom_shrink_wrapping': '700', '#custom_green_paper': '338'

my goal is to add this to a dict.  The above column is in one column.
Here is an example of the data:
item,parse_dropdowns,fixed_dropdowns_values,links
postcards,"#quantity, #paper, #size, #color, #turnaround,  #coating","'#custom_finishing': '497', '#custom_shrink_wrapping': '700', '#custom_green_paper': '338'",http://www.example.com/products/postcards
flyers,"#quantity, #paper, #size, #color, #turnaround, #coating, #folding","'#custom_green_paper': '338', '#custom_hole_punch': '204', '#custom_shrink_wrapping': '700'",http://www.example.com/products/brochures
brochures,"#quantity, #paper, #size, #color, #turnaround, #coating, #folding","'#custom_green_paper': '338', '#custom_hole_punch': '204', '#custom_shrink_wrapping': '700'",http://www.example.com/products/brochures
business cards,"#quantity, #paper, #size, #color, #turnaround,  #coating","'#custom_green_paper': '338', '#custom_shrink_wrapping': '700', '#versionCustomerPulldown': '1'",http://www.example.com/products/businesscards
bookmarks,"#quantity, #paper, #size, #color, #turnaround,  #coating","'#custom_finishing': '497', '#custom_shrink_wrapping': '700', '#custom_green_paper': '338'",http://www.example.com/products/bookmarks
calendars,"#quantity, #paper, #size, #color, #turnaround, #page, #coating","'#custom_green_paper': '338', '#custom_finishing': '13356', '#custom_hole_punch': '205', '#custom_shrink_wrapping': '700'",http://www.example.com/products/calendars

The end goal would be to do have this:
{'#custom_shrink_wrapping': '700', '#custom_green_paper': '338'}

I thought this would be as easy as doing this:
dropdownValuesCsv = dict()
dropdownValuesCsv.append( row['fixed_dropdowns_values'] )

That failed.  Then I tried this:
dropdownValuesCsv = dict()
dropdownValuesCsv.update( row['fixed_dropdowns_values'] )

This produced this error:
ValueError: dictionary update sequence element #0 has length 1; 2 is required

Then I tried this:
dropdownValuesCsv = { row['fixed_dropdowns_values'] }

but this produces a set which gives an error and is not what I'm looking for.

A: I think there's just a points of confusion in your problem which will clear it up for you.
First off, it's unclear to me when you say that your CSV has one column with the value '#custom_shrink_wrapping': '700', '#custom_green_paper': '338', as that includes a comma (and you haven't specified a different separator), so that should be two columns?  I'll be answering your question with the assumption that that's replaced with another separator (say, a semicolon).
Edit: this has since been clarified with the added screenshot.
I believe your main problem is that you're not considering the type of the output of csv.DictReader.  When it parses your csv, it will be mapping keys to strings, so when you attempt to update a dictionary with its output you're not getting the multiple values you want (just one string, which is implying these values).  We can get around this by parsing the strings though.
Here's my working example:
tmp.csv
fixed_dropdown_values, other
"'#custom_shrink_wrapping': '700', '#custom_green_paper': '338'", 'other': 'other'

test.py
import csv

dropdownValuesCSV = {}
with open('./tmp.csv') as file_handler:
    reader = csv.DictReader(file_handler)
    for row in reader:
        # We split multiple key-value pairs by comma
        for mapping in row['fixed_dropdown_values'].split(','):
            # We do an additional split on a colon to differentiate keys and values
            # ... and do some extra cleanup to remove extra spaces and quotation marks
            key, val = [s.strip(' ').replace("'", '') for s in mapping.split(':')]
            dropdownValuesCSV[key] = val
print dropdownValuesCSV
# dropdownValuesCSV is:
# {'#custom_green_paper': '338', '#custom_shrink_wrapping': '700'}

Hope that helps.

A: Edit: Modified code to use ast.literal_eval() instead of the more powerful (and potentially more dangerous) built-in eval() because it's safer since that's all that's needed here.
Note that for testing I created a products.csv file from the data you added to your question—although I had to change the ' characters in it into ' chars resulting in it containing this (because otherwise reading the file results in a codec error):
item,parse_dropdowns,fixed_dropdowns_values,links
postcards,"#quantity, #paper, #size, #color, #turnaround,  #coating","'#custom_finishing': '497', '#custom_shrink_wrapping': '700', '#custom_green_paper': '338'",http://www.example.com/products/postcards
flyers,"#quantity, #paper, #size, #color, #turnaround, #coating, #folding","'#custom_green_paper': '338', '#custom_hole_punch': '204', '#custom_shrink_wrapping': '700'",http://www.example.com/products/brochures
brochures,"#quantity, #paper, #size, #color, #turnaround, #coating, #folding","'#custom_green_paper': '338', '#custom_hole_punch': '204', '#custom_shrink_wrapping': '700'",http://www.example.com/products/brochures
business cards,"#quantity, #paper, #size, #color, #turnaround,  #coating","'#custom_green_paper': '338', '#custom_shrink_wrapping': '700', '#versionCustomerPulldown': '1'",http://www.example.com/products/businesscards
bookmarks,"#quantity, #paper, #size, #color, #turnaround,  #coating","'#custom_finishing': '497', '#custom_shrink_wrapping': '700', '#custom_green_paper': '338'",http://www.example.com/products/bookmarks
calendars,"#quantity, #paper, #size, #color, #turnaround, #page, #coating","'#custom_green_paper': '338', '#custom_finishing': '13356', '#custom_hole_punch': '205', '#custom_shrink_wrapping': '700'",http://www.example.com/products/calendars

Here's code that can read it and do what you want:
import ast
import codecs
import csv

COL_NAME = 'fixed_dropdowns_values'  # Column of interest.

with codecs.open('./products.csv', 'rb',  encoding="utf-8") as _filehandler:
    csv_file_reader = csv.DictReader(_filehandler)
    for row in csv_file_reader:
        dropdownValuesCsv = ast.literal_eval('{' + row[COL_NAME] + '}')
        print(dropdownValuesCsv)

And here's the dictionaries it creates and prints while reading the (modified) input:
{'#custom_finishing': '497', '#custom_green_paper': '338', '#custom_shrink_wrapping': '700'}
{'#custom_hole_punch': '204', '#custom_shrink_wrapping': '700', '#custom_green_paper': '338'}
{'#custom_hole_punch': '204', '#custom_shrink_wrapping': '700', '#custom_green_paper': '338'}
{'#versionCustomerPulldown': '1', '#custom_shrink_wrapping': '700', '#custom_green_paper': '338'}
{'#custom_finishing': '497', '#custom_green_paper': '338', '#custom_shrink_wrapping': '700'}
{'#custom_hole_punch': '205', '#custom_finishing': '13356', '#custom_shrink_wrapping': '700', '#custom_green_paper': '338'}


text:
Q: Hello Android OpenCV I went through this tutorial:http://docs.opencv.org/doc/tutorials/introduction/android_binary_package/dev_with_OCV_on_Android.html#hello-opencv-sample and it did not go so well. :/
I found the steps confusing and a few spelling errors. Anyway, for instance step 2, "Set name, target, package and minSDKVersion accordingly. The minimal SDK version for build with OpenCV4Android SDK is 11. Minimal device API Level (for application manifest) is 8".
I am left wondering what to enter exactly. When I look through the AndroidManifest.xml for the OpenCV Tutorial 1 - Camera Preview Manifest I see that the minSDKVersion is set as <uses-sdk android:minSdkVersion="9" />. This seems to contradict step 2. What am I missing here stackoverflow?
Figure 1 below shows the screen that is causing me my first problems with the 'hello world' OpenCV/Android program.

Does anyone know of or want to help me create a better hello world android/opencv example?
Regards,
user3870315

A: Set the minimum required API to 11, and leave the target as 21. If it does not work properly, set the minimum to 9 and try again.
This is just a configuration to be sure your app will be working on old devices.


text:
Q: Extending session / cookie lifetime for customers (Amazon-style) When visiting Amazon, I've noticed that I always get greeted by name:

However, when I try click onto my account, it forces me to log-in again. I'm not 100% sure about the logic here, but I'm assuming they're identifying me by cookie.
This is really useful because it allows you to target specific products to specific customers based on their order history, like this:

How is it possible to identify customers who aren't logged in by cookie? Is it possible to set up a similar behaviour to Amazon?
Do I just need to extend the cookie lifetime? I'm not very familiar with this aspect of Magento.

A: I agree with what Cags states Persistent Cart is probably the closest thing to what your describing so the short answer would be no its not possible out of the box.
However, you could look into extending the functionality a little. Create a module which observes the event customer_login
As you might expect this would be used when a customer logs in, from this you could then create some abstract cookie to set their name.
The same module would also need to check for the customer_logout since this action would be triggered when someone actually logs out you can use it to destroy your created cookie which would have its own lifetime separately from the Magento sessions.
This would then allow you in your template files (or perhaps via a suitable helper) to retrieve the contents of your cookie and display their name similar to how Amazon keeps you logged in by its name cookie.
I do not recommend you put anything into the cookie which could be potentially used to identify the customer ID itself however.

A: You can extend the cookie session for guests in admin system>config>web>cookie lifetime.  But your setting also needs mirrored in your php.ini file session.gc_lifetime, should match or exceed your admin setting.
You can also set your admin session separately via system>config>admin
And yes, persistence is best option for logged in customers.


text:
Q: Split a dataframe by time column - pandas I would like to select the right portion of a dataset as explain with the following example:
input df:
id_B, ts_B,value
id1,2017-04-27 01:35:30,0
id1,2017-04-27 01:35:40,0
id1,2017-04-27 01:35:50,1
id1,2017-04-27 01:36:00,4
id1,2017-04-27 01:36:10,5
id1,2017-04-27 01:36:20,100
id1,2017-04-27 01:36:30,155
id1,2017-04-27 01:36:40,235
id1,2017-04-27 01:36:50,0
id1,2017-04-27 01:36:60,0
id1,2017-04-27 01:37:00,2353
id1,2017-04-27 01:37:10,221
id1,2017-04-27 01:37:20,2432
id1,2017-04-27 01:37:30,2654
id1,2017-04-27 01:37:40,12
id1,2017-04-27 01:37:50,5
id1,2017-04-27 01:38:00,5
id1,2017-04-27 01:38:10,23
id1,2017-04-27 01:38:20,5
id1,2017-04-27 01:38:30,2
id1,2017-04-27 01:38:40,2
id1,2017-04-27 01:38:50,1
id1,2017-04-27 01:39:00,0
id1,2017-04-27 01:39:10,0
id1,2017-04-27 01:39:20,0
id1,2017-04-27 01:39:30,0
id1,2017-04-27 01:39:40,0
id1,2017-04-27 01:39:50,0
id1,2017-04-27 01:40:00,0
id1,2017-04-27 01:40:10,1
id1,2017-04-27 01:40:20,5
id1,2017-04-27 01:40:30,221
id1,2017-04-27 01:40:40,2432
id1,2017-04-27 01:40:50,2654
id1,2017-04-27 01:40:60,12
id1,2017-04-27 01:41:00,5
id1,2017-04-27 01:41:10,5
id1,2017-04-27 01:41:20,23
id1,2017-04-27 01:41:30,5
id1,2017-04-27 01:41:40,2
id1,2017-04-27 01:41:50,1

considering the following:
  segment_number = 1
  duration = 3 minuts
I want to select the first segment of the dataframe starting from the first df.value non zero until the last value covering the duration of 3 minutes.
output:

    id1,2017-04-27 01:35:50,1
    id1,2017-04-27 01:36:00,4
    id1,2017-04-27 01:36:10,5
    id1,2017-04-27 01:36:20,100
    id1,2017-04-27 01:36:30,155
    id1,2017-04-27 01:36:40,235
    id1,2017-04-27 01:36:50,0
    id1,2017-04-27 01:36:60,0
    id1,2017-04-27 01:37:00,2353
    id1,2017-04-27 01:37:10,221
    id1,2017-04-27 01:37:20,2432
    id1,2017-04-27 01:37:30,2654
    id1,2017-04-27 01:37:40,12
    id1,2017-04-27 01:37:50,5
    id1,2017-04-27 01:38:00,5
    id1,2017-04-27 01:38:10,23
    id1,2017-04-27 01:38:20,5
    id1,2017-04-27 01:38:30,2
    id1,2017-04-27 01:38:40,2
    id1,2017-04-27 01:38:50,1
considering the following:
  segment_number = 2
  duration = 1.40 minuts
I want to select the second segment of the dateframe starting from the first df.value non zero until the last value covering the duration of 1.40 minutes.
output:
id1,2017-04-27 01:40:10,1
id1,2017-04-27 01:40:20,5
id1,2017-04-27 01:40:30,221
id1,2017-04-27 01:40:40,2432
id1,2017-04-27 01:40:50,2654
id1,2017-04-27 01:40:60,12
id1,2017-04-27 01:41:00,5
id1,2017-04-27 01:41:10,5
id1,2017-04-27 01:41:20,23
id1,2017-04-27 01:41:30,5
id1,2017-04-27 01:41:40,2
id1,2017-04-27 01:41:50,1

so far, I did indexed df w.r.t to the ts_B by using `pd.to_datetime and set_index' and using a variable "last_end_point" that keeps track of the index of the previous segment.
But I do not get the right output.
Any help would be appreciated.

A: This is the answer I formulated:
import pandas as pd
import numpy as np
import datetime

df = pd.read_csv("filename.csv")
df['ts_B'] = pd.to_datetime(df['ts_B'])

def find_the_energenies_segment(key_mapped, duration, energenie_df, threshold):
    non_zero_indexs = energenie_df[energenie_df["value"]>threshold].index

    first_index = non_zero_indexs[0]  if len(non_zero_indexs)>0 else None

    if(not first_index):
       return {"sub_df": None,
           "start_index": None,
           "end_index":None,
           "duration": duration}

    start_time = energenie_df.loc[first_index].ts_B
    hours,minutes,seconds = duration.split(":")
    end_time = start_time + datetime.timedelta(hours=int(hours),minutes=int(minutes),seconds=int(seconds))

    last_index = energenie_df[energenie_df["ts_B"]>end_time].index[0]-1

    return {"sub_df": energenie_df.loc[first_index:last_index],
       "start_index": first_index,
       "end_index":last_index,
       "duration": duration}

out = find_the_energenies_segment("id1", "00:03:00", df, 0 )
print(out)


text:
Q: Recursively print diamond in python Can anyone help me out here, I am stuck on the base cases for turning this code into a recursive function... Can't use loops in the recursive function obviously.
def diamond(a):

assert a > 0, "width must be greater than zero"

for i in range(0, a, 2):

    for c in range(0, a - i, 2):
        print(" ", end='')

    if a % 2 == 0:
        i += 1

    for m in range(0, i - 1):
        print("*", end='')

    print()

for i in range (0, a, 2):

    for c in range(0, i, 2):
        print(" ", end='')

    for m in range(0, a - i):
        print("*", end='')

    print()

A: Because this must be homework, I won't give you the code, but explain how to do it in  words:
Instead of looping, you make a function that calls itself, and passes the variables you need as parameters. Then you have a test with an "if" in the function that when true, stops the looping and instead returns. That was you will then "fall" out of the loop.
So in this case you would pass in a and i as parameters, increase i with one in the function, and when i is greater than a, just return.

A: Try this
def triangles(n):
     if not n & 1:
         raise ValueError('n must be odd')
    print_diamond(0, n, n >> 1)

def print_diamond(start, stop, midpoint):
    if start < stop:
        if start <= midpoint:
            print('  ' * (midpoint - start) + '* ' * ((start << 1) + 1))
        else:
            print('  ' * (start - midpoint) + '* ' * ((stop - start << 1) - 1))
        print_diamond(start + 1, stop, midpoint)

triangles(5)


text:
Q: Export image for documentation I want to export my classified image to drive in GEE, for presenting in a document.
I have used this code.
Export.image.toDrive({
  image: classified,
  description: 'classified_basin_with_points',
  scale: 30,
  region: geometry,
  fileFormat: 'GeoTIFF',
});

But the exported image showed no color whereas my cassified layer have 4 clssifying color on it. How can i get a colorful image that will cover my classifying layer color?

A: Based on the Google Earth Engine documentation, to get an image exported as it appears in Google Earth Engine, you need to create Visualization images.

Exporting images as they appear in the Code Editor
  To export imagery as rendered on screen in Earth Engine, create visualization images as demonstrated in the Visualization images and the Compositing and Mosaicking sections. Since the Code Editor uses the 'EPSG:3857' CRS, specify a CRS of 'EPSG:3857' in the export to get an image in the same projection as that displayed in the Code Editor map. See the section on configuring image exports for details on specifying the resolution and coordinate system of the output.

https://developers.google.com/earth-engine/image_visualization#visualization-images

Visualization images
Use the image.visualize() method to convert an
  image into an 8-bit RGB image for display or export. For example, to
  convert the false-color composite and NDWI to 3-band display images,
  use:
// Create visualization layers.
var imageRGB = image.visualize({bands: ['B5', 'B4', 'B3'], max: 0.5});
var ndwiRGB = ndwiMasked.visualize({min: 0.5,   max: 1,   palette: ['00FFFF', '0000FF'] });


text:
Q: v-img can't locate resource from assets folder I am having problems displaying a static image located at src/assets/images/logo.png folder with the v-img Vuetify component.
      <v-img src="@/assets/images/rima_logo.png"></v-img>

It doesn't load with Vuetify, but using a plain img tag it does find the resource. Also vscode provides completion for the image relative path so I don't know why vuetify isn't loading it correctly.

A: It works on <img> due to the vue compiler feature transformAssetUrls. Vuetify's vite plugin has a preset for this to support vuetify components:
// vite.config.js
import vuetify, { transformAssetUrls } from 'vite-plugin-vuetify'

export default {
  plugins: [
    vue({
      template: { transformAssetUrls }
    }),
    vuetify(),
  ],
}

https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vite-plugin#image-loading

A: You code looks no problem, on condition that you have configured the path alias in your vue.config.js:
 module.exports = {
  ...
  chainWebpack: (config) => {
    config.resolve.alias
      .set('assets', resolve('src/assets'));
    },
};

Vite config:
export default function ({ command }: ConfigEnv): UserConfigExport {
  const isProduction = command === 'build';
  const root = process.cwd();
  return {
    root,
    resolve: {
      alias: [
        // /@/xxxx => src/xxxx
        {
          find: '@',
          replacement: resolve(__dirname, 'src'),
        },
        {
          find: /\/#\//,
          replacement: pathResolve('types') + '/',
        },
        { find: /^~/, replacement: '' },
      ],
    },
    server,
    plugins: createVitePlugins(isProduction),
    build: {
      sourcemap: true,
   },
  };
}

There some other solutions which should also works:
use required
<v-img :src="require(@/assets/images/rima_logo.png)"></v-img>

Import image as a resource:
// template
<v-img :src="rimaLogo"></v-img>

// scripts
import rimaLogo from 'assets/images/rima_logo.png';


text:
Q: Show a path integral in a non-simply connected domain is zero I've been trying to solve this for a couple of days now,
$U$ is an open set containing $[-1,1]$ and $O$ is the set $U\backslash [-1,1]$. Let $\alpha_\varepsilon = (1+\varepsilon)\cos(t)+i\varepsilon\sin(t)$ for $0 \leq t \leq 2\pi$. Then the trace of $\alpha_\varepsilon \subseteq O$ for $\varepsilon$ small enough (say $\varepsilon<\varepsilon_0$). If $g$ is a function which is holomorphic on $O$ and continuous on $U$. Show that $$\int_{\alpha_\varepsilon} g(\zeta)d\zeta=0.$$
The hint I got was to use "cancellation" and the fact that $g$ is continuous on an open set containing the interval.
We have a homotopy theorem about every path integral is zero when the path is homotopic to a point and another cluster of statements which culminate in evaluating $\int_\gamma f(z)dz = \sum \text{ind}_\gamma(a_j)\int_{\Gamma_j}f(z)dz$. Neither of which will work because $O$ isn't simply connected and I can't construct a cycle which is homologous to zero.
I tried explicitly constructing an anti-derivative for $g$ but don't have any information on $g$ at all really so I don't think I can show that the integral of g over any path in $O$ depends only on the endpoints.
Any recommendations?

A: A more complete version of the hint you were given: The homotopy version of Cauchy's Theorem shows that the integral is independent of $\epsilon$. So  it's enough to show that the limit of the integral as $\epsilon$ tends to $)$ is $0$.
And you can show that by "cancellation". It's an "epsilon-delta" argument; we can't use "$\epsilon$" because that letter's already in use, so I'm going to use $s$ instead: Fix $A>1$ such that $[-A,a]\subset O$. If $s>0$ there exists $\delta>0$ such that if $0<y<\delta$ then $$|g(x+iy)-g(x-iy)|<s\quad(x\in[-A,A]).$$
Note that the "upper half" of $\alpha_\epsilon$ is the same as the conjugate of the lower half, except that the direction is reversed...
Final Hint: Fix $y>0$. Define $\gamma_1,\gamma_2:[0,1]\to\Bbb C$ by $\gamma_1(t)=t-iy$, $\gamma_2(t)=(1-t)+iy$. Then $$\int_{\gamma_1}g(z)\,dz+\int_{\gamma_2}g(z)\,dz=\int_0^1(g(t-iy)-g(t+iy))\,dt.$$Something analogous happens if you split your curve $\alpha_\epsilon$ into the part iwth positive imaginary part plus  the part with negative imaginary part...


text:
Q: strtok() behavior is different across compilers I wrote a program which parses a string according to this format:
somethingsomething:number:

On my computer, this program works flawlessly.
However, once I have uploaded the code and compiled it on the school's computer, strtok() has a different behavior.
For instance, with this string: p2test/f4.txt:1:, on my computer the first token would be p2test/f4.txt. However, on the school's computer, the token ends up as p2test/f4.t.
Here is the code segment:
            char *token;
            char delim[1] = ":";

            if ((token = strtok(tmp_string, delim)) != NULL) {
                ...
            }

Here, tmp_string would be p2test/f4.txt:1:.
Here is my computer's compiler version: gcc version 4.9.1 (Ubuntu 4.9.1-16ubuntu6)
Here is my school's compiler version: gcc version 4.8.1 20130909 [gcc-4_8-branch revision 202388] (SUSE Linux)

A: Besides the couple of issues noted in the comments, it looks like there is a bigger problem with the code. According to the description of the getline() function in the man pages:

  If  *lineptr  is set to NULL and *n is set 0 before the call, then get‐
  line() will allocate a buffer for storing the line.  This buffer should
  be freed by the user program even if getline() failed.

  Alternatively, before calling getline(), *lineptr can contain a pointer
  to a malloc(3)-allocated buffer *n bytes in size.  If the buffer is not
  large  enough  to  hold the line, getline() resizes it with realloc(3),
  updating *lineptr and *n as necessary.

You did not initialize tmp_string, hence its value is some uninitialized junk that points to some random address, and the second alternative behavior of getline(), described above, occurs.
This looks like undefined behavior to me.
P.S. You did initialize the length value to 0 bytes, which, according to getline()'s man page causes it to call realloc. So, it looks to me your code ends up, indirectly, passing a garbage pointer to realloc.

A: Another issue is that you have a memory overwrite here:
char delim[1] = ":";

There are two characters in the string, not 1.  Much safer to do this:
char delim[] = ":";