text:
Q: Is there someway to get a list of all missing photos from the photo library? I get the following error in Photos app on my Mac.
Missing File
Photos with unavailable original files cannot be opened.
The original photo "IMG_3076.JPG" is either offline or cannot be found. Click "Find Original" to reconnect.

I want to follow the instructions from how to avoid getting missing file error in photos, so my question now is, Is there some way to get all missing files from Photos library? It is going to be impossible to double click every photo to find out if it is missing. I need just the directories, i can place them back one by one and consolidate.

A: Short answer: you can use the script in this GitHub repo.
Long answer:
I had the same question, and it turns out that the photo library is backed by a SQLite database under the covers. On your machine, you can find the database file at <photo library root>/database/photos.db. There's a table called RKMaster, with a row for every photo, and a fileIsReference column that tells you whether the photo is "external" or not.
The script I linked to simply dumps the list of all external files, and then iterates through to check that each one exists on disk.
Note that the table also includes an isMissing column, but this is not good enough by itself.  It only tells you about the files that Photos "knows" are missing, because you tried to double-click them, or use them in some way.  If you simply delete a file from disk, but don't try to access it in Photos, the isMissing column will be false.

A: If what you want is just a list of all missing files, you can get that using osxphotos with the command
osxphotos query --missing

That will only give you the UUID of each file, not the path. However, once RepairPhotosBookmarks is integrated into OSXphotos (due shortly) you don't need the file path because that powerful app will be able to handle those missing files for you.

A: I've found that the isMissing flag doesn't mean that the image is gone, just that it's not currently on disk.  Using the Python script here, I was trying to copy all of my images out of Photos for backup. I noticed that several images were not being copied, and it turned out it was because they had the isMissing flag on them. But, I was able to take the image name (e.g., IMG_1234.JPG), search for it in Photos, and it found the image.  And when I opened the image in Photos for viewing, there was a progress circle shown in the lower right corner (as though it was loading the file from somewhere), and when I checked the folder inside the Photos library on disk, sure enough, the missing file was now there.
So now the mystery is, where are these "missing" files stored, and how do I access them (without having to visit each & every one within Photos)?
And has anyone reverse engineered & documented the schema of the Photos SQLLite DB, including what the various fields mean, like "isMissing"?  I haven't been able to find it myself.

A: (Note: The solution appears to only work if the Photos library has been converted from an older iPhoto library, and the images were missing already at that time. I leave it here for educational purpose, but have added another answer with a more thorough detection.)
Here's an AppleScript that can add all images in Photos.app to a new album, from where you can then select and delete them (e.g. with cmd-delete).
It only works if Photos has already detected that the file is missing. I don't know what causes this detection, it's just that I found a Photos library where this was the case, and then this script worked. But when I tried to reproduce this with another library, where I deleted the original files (and also made sure they were not recreated, which happens when they came from iCloud), even relaunching Photos with forcing a library repair would not update the image properties to a state where my script would detect them as missing. Maybe this only works with libraries that were converted from former iPhoto libraries (which I know the first one was).
To use it, launch Photos, switch to view all photos, and select all photos you want checked, e.g. with cmd-A. Then run the script, and it'll add all those photos for which there's no known or accessible image file to the automatically created "missing images" album.
tell application "Photos"
    set media_items to selection
    set missing_items to {}
    repeat with media_item in media_items
        if width of media_item is 0 then
            set end of missing_items to media_item
        end if
    end repeat
    if missing_items is {} then
        display dialog "Found no missing files" buttons ¬
            "OK" default button "OK"
    else
        if not (exists album "missing images") then
            make new album named "missing images"
        end if
        set dest to album "missing images"
        add missing_items to dest
        display dialog "Found " & (count of missing_items) & ¬
            " missing files" buttons "OK" default button "OK"
    end if
end tell

A: Note: The following solution, while working well in my own test case, is probably not suitable for large (100'000s) of images in the library, nor with Photos offloaded into iCloud. Take this as an educational answer but don't expect it to work in your case. I welcome others to improve on this script and post it in their own answers.
The following AppleScript parses the sqlite database to identify the paths to the files, then checks if those files are present. If it finds missing files, it then launches Photos.app and tries to identify the related images (or movies) and adds them to an album named "missing images".
It works with version 2 and 3 of the Photos library, tested with Photos.app v3.0 (on macOS 10.13 "High Sierra") and v7.0 (on macOS 12.6 "Montery").
To use this script, copy the code below and paste it into a new "Script Editor.app" document. If you only want to check particular images for missing files, open Photos, then select the items you want checked. Otherwise, to check all items (photos, movies), quit Photos. Then run the script. Once the script has checked all files, it will launch Photos and add the missing items to the album "missing images". When finished, it will show a message about it. Then you can view the album in Photos, select all items and delete them with cmd-delete if you want to get rid of them.
Beware, though, that if you have some images on external media and those disks are not mounted, then they'll also be considered missing by this script – yet, you should probably not want to delete those items, then!
use scripting additions

set path_to_photos_library to POSIX path of (choose file of type ¬
    "com.apple.photos.library" with prompt ¬
    "Choose the photos library that Photos.app currently uses" default location path to pictures folder)

--
-- Get the current selection from Photos
--
set selectedIDs to {}
if application "Photos" is running then
    tell application "Photos"
        local media_items
        set media_items to selection
        repeat with media_item in media_items
            set end of selectedIDs to id of media_item
        end repeat
        quit -- need to quit Photos so that we can access its database
        delay 0.5
    end tell
end if

--
-- Make sure the database is accessible and determine which DB version to use
--
repeat
    try
        local files_dir
        do shell script "sqlite3 " & quoted form of path_to_photos_library ¬
            & "database/photos.db 'SELECT value FROM LiGlobals WHERE keyPath=\"metaSchemaVersion\"'"
        ignoring white space
            if result = "2" then
                set db_version to 2
                set files_dir to "Masters"
                set db_name to "photos.db"
            else if result = "3" then
                set db_version to 3
                set files_dir to "originals"
                set db_name to "Photos.sqlite"
            else
                my showMessage("Sorry, the database appears to be in an unsupported format.")
                quit
            end if
        end ignoring
        set db_path to quoted form of path_to_photos_library & "database/" & db_name
        set files_path to path_to_photos_library & files_dir & "/"
        delay 0.1
        exit repeat
    on error
        with timeout of 86400 seconds
            display dialog "Can't access database - make sure Photos.app is quit, then click OK"
        end timeout
    end try
end repeat

--
-- Determine the file paths by querying the photos database
--
if selectedIDs is {} then
    set where_clause to ""
else
    if db_version = 2 then
        set where_clause to ¬
            " JOIN RKVersion v ON (m.uuid=v.masterUuid)" & ¬
            " WHERE v.uuid IN (\"" & joinText(selectedIDs, "\",\"") & "\")"
    else
        -- need to remove the "/L0/001" suffix from the IDs first
        set uuids to {}
        repeat with anID in selectedIDs
            set end of uuids to first item of splitText(anID, "/")
        end repeat
        set where_clause to " WHERE ZUUID IN (\"" & joinText(uuids, "\",\"") & "\")"
    end if
end if
if db_version = 2 then
    set sql to " 'SELECT m.imagePath FROM RKMaster m" & where_clause & "'"
else
    set sql to " 'SELECT printf(\"%s/%s\",ZDIRECTORY,ZFILENAME) FROM ZASSET" & where_clause & "'"
end if
do shell script "sqlite3 " & db_path & sql
set check_paths to my splitText(result, return)
delay 0.1

--
-- Check the availability of every file
--
set missing_paths to {}
repeat with relPath in check_paths
    set fullPath to (files_path & relPath)
    set theFile to POSIX file fullPath
    try
        (theFile as alias)
    on error
        set end of missing_paths to relPath as string
    end try
end repeat

if missing_paths is {} then
    my showMessage("Found no missing files")
    quit
end if

--
-- Query the database again to get the ids of the images that reference the missing files
--
with timeout of 86400 seconds
    if db_version = 2 then
        do shell script "sqlite3 " & db_path & ¬
            " 'SELECT v.uuid FROM RKMaster m JOIN RKVersion v ON (m.uuid=v.masterUuid)" & ¬
            " WHERE m.imagePath IN (\"" & joinText(missing_paths, "\",\"") & "\")'"
        set missing_ids to my splitText(result, return)
    else
        do shell script "sqlite3 " & db_path & ¬
            " 'SELECT ZUUID FROM ZASSET" & ¬
            " WHERE printf(\"%s/%s\",ZDIRECTORY,ZFILENAME) IN (\"" & joinText(missing_paths, "\",\"") & "\")'"
        set missing_ids to my splitText(result, return)
    end if
end timeout
delay 0.1

--
-- Launch Photos, locate the images by their ids and add them to the "missing images" album
--
tell application "Photos"
    set unlocated to {}
    set missing_items to {}
    set all_items to media items
    repeat with anID in missing_ids
        try
            if db_version = 2 then
                set anItem to media item id anID
            else
                set anItem to media item id (anID & "L0/001")
            end if
            set end of missing_items to anItem
        on error
            set end of unlocated to anID
        end try
    end repeat
    if missing_items is {} then
        my showMessage("Can't locate the images for the missing files." & return & return & ¬
            "Make sure you choose the same library that Photos.app currently uses!")
    else
        if unlocated is not {} then
            with timeout of 86400 seconds
                display dialog "" & (count of unlocated) & " missing items could not be found in Photos.app" & ¬
                    return & return & "This means that the script needs to be updated to handle this."
            end timeout
        end if
        if not (exists album "missing images") then
            make new album named "missing images"
        end if
        set dest to album "missing images"
        add missing_items to dest
        my showMessage("Found " & (count of missing_items) & " missing files")
    end if
end tell

--
-- Finished
--

on showMessage(theText)
    with timeout of 86400 seconds
        display dialog theText buttons "OK" default button "OK"
    end timeout
end showMessage

on splitText(theText, theDelimiter)
    set old_delimts to AppleScript's text item delimiters
    set AppleScript's text item delimiters to theDelimiter
    set theTextItems to every text item of theText
    set AppleScript's text item delimiters to old_delimts
    return theTextItems
end splitText

on joinText(theList, theDelimiter)
    set old_delimts to AppleScript's text item delimiters
    set AppleScript's text item delimiters to theDelimiter
    set theText to theList as string
    set AppleScript's text item delimiters to old_delimts
    return theText
end joinText


text:
Q: Should you make objects are generic as possible when planning out architecture? I'm trying to improve my skills in planning out clean, modular projects with minimal coupling. Is it best to keep objects as generic as possible?
If so, are there any pitfalls I should try and avoid when designing architecture?

A: Making every object generic is foolish.
Making every object specific is foolish.
Every object should have a name that ensures that what is found inside is not a surprise. It should make clear what belongs inside it and what belongs outside. Otherwise someone will fill it with clutter. The inside should look like your silverware drawer. Not your junk drawer. It may accept multiple messages (have many methods) but it's work should focus on one idea. It should have a single responsibility. It should be the one and only place you need to make changes when changing the one design decision it addresses.
How generic or specific it should be depends on how far it is from inputs or outputs. Everything close to any kind of IO (file, DB, GUI, web, controls, etc)   will have to be specific and will change often. Anything far from IO and close to high level policy will be more generic and stable.
Be willing to stay specific by ignoring cases that can be put off into different sibling objects that can stand in for this one, rather than over design the current one to handle every case.
Be willing to stay generic by pushing responsibly to deal with kinds of cases completely out the object and onto collaborators that can deal with them without making this object deal with their details.
So how to know when it's too much?
When the objects duties become unclear. Use of the object should be obvious.  If half of the object is at one level of abstraction and the other half at another then a tendency will develop to surround it's use with extra logic, keeping it on life support. When the object is well designed, the using code will be simple and clean.
Always look at how an object will be used. I often design by writing the using code first. Do this and controlling how abstract it is will fall out naturally.

A: It depends on what you mean by generic.
If you mean generic as "can handle anything", then no. Especially during the design phase, you don't know how things are going to change. And that's fine, just don't try to solve all of those problems now.
If you mean generic as "does one thing, ignoring context", then yes (with moderation). If you have something that works with text in a file, maybe don't tie it to a specific file path. Maybe don't even tie it to files at all if all the thing really needs is text.
It's all about anticipating likely change and accounting for it. You don't have to fix problems that don't exist yet, but it's usually worthwhile to spend a little bit of time now so your hands aren't tied when you finally find out how things need to change.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding a span to bootstrap label with rails? How do i add a span to a bootstrap form label generated using bootstrap form rails gems.
This is what i've tried so far with no luck:
= bootstrap_form_for resource, url: wizard_path, method: :put, layout: :horizontal do |form|

 = form.select :cover_type, form.object.cover_types, {include_blank: true, label: "Cover Type ".html_safe}

Thanks

A: Is there anything wrong with this?
= bootstrap_form_for resource, url: wizard_path, method: :put, layout: :horizontal do |form|
  = form.label
    Cover Type
    %span.fa.fa-question-circle.hidden-lg.hidden-md
  = form.select :cover_type, form.object.cover_types, {include_blank: true}

Any reason why you wouldn't just put the label before the select element?


text:
Q: Windows Scheduled Task - Error 2147943711 for "on startup" task I have a onstartup task that I want to automatically run, regardless of if someone is logged in or not.
I've set it up as Run whether user is logged in or not, Do not store password1, and Run with highest privileges, which I assume would work, using the below code:
schtasks /create /tn "My OnStartup Task"  /TR "powershell blah.ps1" /sc ONSTART /f /NP /RL HIGHEST

After enabling task scheduler history, I'm getting errors like:
Event ID: 104: Task Scheduler failed to log on "<Task Author>" . Failure occurred in "LsaLogonUser" . User Action: Ensure the credentials for the task are correctly specified. Additional Data: Error Value: 2147943711.

Event ID: 311: Task Scheduler failed to start Task Engine ""  process due to an error occurring in "LUAIsElevatedToken" . Command="taskeng.exe" . Additional Data: Error Value: 2147943711.

Event ID: 101: Task Scheduler failed to start "\My OnStartup Task" task for user "<Machine>\<Task Author>". Additional Data: Error Value: 2147943711.

I've specifically set not to store the password, yet the errors are saying it's trying to use the password. I recall reading somewhere that not the storing the password checkbox also counts for "do not run interactively", or something. Could someone point me into the right direction here?

A: My solution (noted here to give others help in addition to the accepted answer):
The task used to run under a local user. Run whether user is logged or not ticked; Do not store password not ticked.
Everything was OK until we renamed the machine - I then had to reassign the user which the job runs under to be the same user - but under a different computer.

A: You should not be specifying a user account under which to run the task if you do not want to save the password.  Run it as system if that would work or save the user account and password with the task.


text:
Q: Why img:hover doesn't work here? I'm hidding an anchor by setting visibility:hidden.
On image hover, I set the anchor visibility to visible, but the anchor doesn't appear on image hover.
Not sure what's going wrong in the snippet.
  #image{
    width :240px;
    height :190px;
  }
  #image:hover #link{
    visibility : visible;
  }
  #link{
    visibility : hidden;
    position: absolute;
    left: 150px;
    top: 170px;
  }

Goals Analysis App Link

The visibility issue got resolved once applying appropriate selector. But now, when i hover on the link, it starts flickering. Any hints on this ?
check the snippet  http://jsbin.com/yiqek/3/edit

A: #link is an adjacent sibling of #image so you need to write
  #image:hover + #link{
    visibility : visible;
  }

+ is the adjacent sibling selector
A + B matches B when is the immediate sibling of A

A: You need adjacent siblings selectors for this:
 #image:hover  + #link{
    visibility : visible;
  }

Demo

A: please add the code to the question body as well. Anyways, you wrote this:
#image:hover  #link{
  visibility : visible;
}

Which will make #link inside of  visible. Since you can have no links inside of an image, this is making no sense. The link is the direct sibling of the image, so you can do this:
#image:hover + #link{
  visibility : visible;
}

A: Instead of this
#image:hover #link{
visibility : visible;
  }

Use like this..
#image:hover + #link{
visibility : visible;
 }


text:
Q: Rails - Setting up karma with hamlc - getting parse error on hamlcoffee.js.coffee.erb I'm trying to set up an angular testing environment using Karma, Jasmine, and Phantomjs. It's a rails app using hamlcoffee as template language.
My problem is that when i try to run the tests i get the following error:
PhantomJS 1.9.7 (Linux) ERROR
SyntaxError: Parse error at /home/me/.rvm/gems/ruby-2.1.2/bundler/gems/haml_coffee_assets-a3c2951eca00/vendor/assets/javascripts/hamlcoffee.js.coffee.erb:1

It looks like the file hamlcoffee.js.coffee.erb is the problem here, so i tried adding everything ending with .erb to the exclude list in the karma config file, but unfortunately with no luck.
This is my Karma config file:
// Karma configuration
module.exports = function(config) {
  config.set({

    // base path, based on tmp/ folder
    basePath: '..',

    // frameworks to use
    frameworks: ['jasmine', 'ng-scenario'],

    // list of files / patterns to load in the browser
    files: [
      APPLICATION_SPEC,
      'app/assets/javascripts/*/*.{coffee,js}',
      'spec/javascripts/**/*_spec.{coffee,js}',
      'app/assets/*.haml'
    ],

    // list of files to exclude
    exclude: [
      '**/*.erb'
    ],

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera (has to be installed with `npm install karma-opera-launcher`)
    // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
    // - PhantomJS
    // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
    browsers: ['PhantomJS'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    // Preprocessors
    preprocessors: {
        '**/*.coffee'                         : 'coffee',
        'app/assets/javascripts/**/*.hamlc'   : 'haml'
    },

    hamlPreprocessor: {
      options: {
        language: 'coffee'
      }
    }

  });
};

I'm using the karma-haml-preprocessor for my .hamlc templates.


text:
Q: counting strings within strings I have an array that looks like this:
a = ['UCI_99648;102568',  'UCI_99648;102568',  'UCI_99648;102568;99651', 'UCI_99651', 'UCI_99652', 'SIB_99658;102568;506010;706080', NaN]

I want to find out how many stings have a single number like UCI_99651, UCI_99652
So, the expected outcome is 2.
How I can do this in python.
NOTE: my actual data is very large and the numbers can be anything and, as stated in the example, may involve missing values.

A: Assuming that the structure of all strings follows that of the example above, a list comprehension as the following will do:
l = ['UCI_99648;102568',  'UCI_99648;102568',  'UCI_99648;102568;99651',
     'UCI_99651', 'UCI_99652', 'SIB_99658;102568;506010;706080', 'NaN']

[i for i in l if ';' not in i and i != 'NaN']

 Output
['UCI_99651', 'UCI_99652']

A: Since you have tagged pandas,another way:
s=pd.Series(a).dropna()
s[s.str.split(';').str.len().eq(1)]

3    UCI_99651
4    UCI_99652

A: You can try like below.Hope this will address your problem.
p = [word.split(";")[0] for word in uci if word != 'NaN']
print(Counter(p))
#Counter({'UCI_99648': 3, 'UCI_99651': 1, 'UCI_99652': 1, 'SIB_99658': 1})
#To filter only one occurance you can try below.
b = [word for word in p if p.count(word)==1]
print(b)

For more you can refer the list comprehension doc here.
http://dataunbox.com/course/24/119/Python%20for%20dummies

A: You can extract numbers using regular expressions.
For example, something like this:
import re
import numpy as np
from collections import Counter

def count_strings_with_unq_nums(list_of_strings):

    # Initialize two lists - one to keep track of where the numbers occur and another to isolate unique occurences of numbers
    all_nums_nested = []
    all_nums_flat = []

    # Loop through all strings and extract integers within
    for s in list_of_strings:
        try:
            nums = re.findall(r'\d+', s)
            all_nums_nested.append(nums)
            all_nums_flat.extend(nums)
        except:
            continue

    # Count occurences of all extracted numbers
    num_counter = Counter(all_nums_flat)

    # Loop through nested list to find strings where unique numbers occur
    unq_items = []
    for key, val in num_counter.items():
        if val == 1:
            for n, num_list in enumerate(all_nums_nested):
                if key in num_list:
                    unq_items.append(list_of_strings[n])

    # Return the number of strings containing unique numbers.
    return len(set(unq_items))

if __name__ == '__main__':
    a = ['UCI_99648;102568',  'UCI_99648;102568',  'UCI_99648;102568;99651', 'UCI_99651', 'UCI_99652', 'SIB_99658;102568;506010;706080', np.NaN]

    print(count_strings_with_unq_nums(a))

>>> 2


text:
Q: Color bars/dots in a PGFPlots plot based on data I would like to color every dot red where the corresponding second column of the data is set to 1.
This is my minimal working example:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

\begin{document}

\pgfplotstableread[header=false, col sep=comma]{
    Label 1,1,0.0443
    Label 2,0,0.0371
    Label 3,1,0.0191
    Label 4,0,0.0638
    Label 5,0,0.0149
}\data

\begin{figure}
    \begin{tikzpicture}
        \centering
        \begin{axis}[
            axis x line=bottom,
            axis y line=left,
            xmin=0,
            width=10cm,
            ymajorgrids,
            bar width=2ex, y=3ex,
            enlarge y limits={abs=0.75},
            ytick=data,
            scaled ticks=false,
            yticklabels from table={\data}{0},
            xticklabel style={/pgf/number format/fixed},
        ]
            \addplot[only marks] table [
                y expr=-\coordindex,
                x index=2
            ]{\data};
        \end{axis}
    \end{tikzpicture}
\end{figure}

\end{document}

The first and the third dot should be red as defined in the data.
I have not yet found any approach to defining colors (or shape!) based on the data. Is it possible with TikZ/PGFPlots?

A: You can use scatter/classes for this.

\documentclass{standalone}
\usepackage[utf8]{inputenc}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

\begin{document}

\pgfplotstableread[header=false, col sep=comma]{
    Label 1,1,0.0443
    Label 2,0,0.0371
    Label 3,1,0.0191
    Label 4,0,0.0638
    Label 5,0,0.0149
}\data

    \begin{tikzpicture}
        \centering
        \begin{axis}[
            axis x line=bottom,
            axis y line=left,
            xmin=0,
            width=10cm,
            ymajorgrids,
            bar width=2ex, y=3ex,
            enlarge y limits={abs=0.75},
            ytick=data,
            scaled ticks=false,
            yticklabels from table={\data}{0},
            xticklabel style={/pgf/number format/fixed},
            scatter src=explicit,
            scatter/classes={
                0={mark=*,black},
                1={mark=*,red}
            }
        ]
            \addplot[scatter,only marks] table [
                y expr=-\coordindex,
                x index=2,
                meta index=1 % specify meta column
            ]{\data};
        \end{axis}
    \end{tikzpicture}

\end{document}

A: Add red in \addplot[only marks,red] option
   \documentclass{article}
   \usepackage[utf8]{inputenc}
   \usepackage{tikz}
   \usepackage{pgfplots}
   \usepackage{pgfplotstable}

   \begin{document}

    \pgfplotstableread[header=false, col sep=comma]{
     Label 1,1,0.0443
     Label 2,0,0.0371
     Label 3,1,0.0191
     Label 4,0,0.0638
     Label 5,0,0.0149
    }\data

   \begin{figure}
    \begin{tikzpicture}
      \centering
      \begin{axis}[
        axis x line=bottom,
        axis y line=left,
        xmin=0,
        width=10cm,
        ymajorgrids,
        bar width=2ex, y=3ex,
        enlarge y limits={abs=0.75},
        ytick=data,
        scaled ticks=false,
        yticklabels from table={\data}{0},
        xticklabel style={/pgf/number format/fixed},
           ]
          \addplot[only marks,red] table [
            y expr=-\coordindex,
            x index=2
          ]{\data};
         \end{axis}
        \end{tikzpicture}
    \end{figure}

    \end{document}


text:
Q: Open activity_xx.xml upon activity creation Upon creation of a new activity in Android Studio the java class and the content_xx.xml file opens automatically for editing.
Is there a way to automatically open the activity_xx.xml file for editing alongside the content xml and java class?


text:
Q: What does this symbol mean, to which topic does it belong, and how do I know more about it? What does this symbol mean, to which topic does it belong, and how do I know more about it?

A: It's long division of polynomials.  In the first image you need to divide $x^2+1$ into $2x^3+x^2+3x+7$.  The letter $A$ is the quotient you get, and the letter $B$ is the remainder.  It might have been better (though there's nothing you can do about it) had the question used different letters to the multiple choice answers (which appear to be A, B, C and D).
The second image you're dividing $5AB$ by 11 and the quotient you get is $AB$ with remainder $10$.  Of the answers we can see, only one can be right, though I would argue that the implication arrow $\implies$ is incorrect since you cannot evaluate $B$ from the long division.


text:
Q: calculate dominant mixed strategy in two person game w/ finite strategies For a two person game, player one has strategies A,B,C. Inspection reveals strategy B is strictly dominated by some mixture between A and C.
How does one calculate the probabilities assigned to A and C in the dominant strategy?

A: The way we did it in my Combinatorics and Game Theory class was to let $p$ be the probability that we chose strategy A and $1-p$ be the probability that we chose strategy C. Then we drew a graph that has two vertical "axes" and a horizontal axis connecting the two in the middle. The horizontal axis is the value of $p$, ranging from 0 to 1. On the left "axis", put a dot corresponding to the value of strategy A when $p=0$ and another dot corresponding to the value of strategy C when $p=0$. Do the same for the right "axis" but when $p=1$. Thus, you will have two lines (that may or may not intersect) that show the values of strategies A and C depending on the choice of $p$. My guess is that you want the value of $p$ such that VA($p$) and VC($p$) are equal, which corresponds to the intersection of the lines you constructed on the graph.
I hope that's what you're asking for...

A: In general, finding an optimal strategy in a finite two-person zero-sum game reduces to a linear programming problem.


text:
Q: "The name you entered can't be used. The name is not available. Enter a different name." I'm installing El Capitan on a MacBook Air that I aquired with no internal drive, so no previous OS.
I proceed through several steps fine until "Create a Computer Account".

But it doesn't like the details I enter and shows this cryptic error box:

The name you entered can't be used.
  The name is not available. Enter a different name.

The worst part is that it now does not allow me to edit any of the text fields! I can click on them and drag and select them, but I cannot type new letters or delete existing letters, etc.
Is this a known problem? I can't find a solution to it via Google though I do find a tiny number of people asking about it. If not, what am I missing?

A: I ran into this issue today. Apparently the error message is trying to tell you that there is an existing person with the same "Full Name" as you. Hence it cannot let you add another username with the same "Full Name". In my case, I was recovering from Time Machine and getting this error msg. So I just changed the full name to my last name. Was able to create an account using that and proceed further.

A: I came across this problem today. I simply restarted the system and guess what, the account was successfully created. It didn't require me to change the name.


text:
Q: Unable to delete recyclerview item In my recylerview item, there is an option to delete the item. I am trying to achieve it in this way from activity class :
list.remove(position);
recyclerView.removeViewAt(position);
adapter.notifyItemRemoved(position);
adapter.notifyItemRangeChanged(position, list.size());

But I am getting the following error :
java.lang.NoSuchMethodError: No virtual method notifyItemRemoved(I)V in class RecyclerviewAdapter

What is wrong here?

A: Do not try to remove it by getting a position in Recycler view. Please refer any unique id or unique attribute of that element for it. If there are no unique elements in your objects in recycling view, please add the unique id.
Then get unique id when the user clicks an item in recycle view. After that search through whole the list and delete a relevant item from a list using a unique id


text:
Q: Liu Exercise 5.21 I'm trying to solve Liu's exercise 2.1 Chapter 5 which states:

Here is what I'm thinking so far:
a) This is vacuously true since J is a single element set so there is no $i<j$ and this is trivial.
b) 1) Consider $(df)_{ijk\alpha}$. Without loss of generality, assume $i<j$. This gives $(df)_{ijk\alpha} = 0 = f_{jk\alpha} - f_{ik\alpha} + f_{ijk} - f_{jk\hat{\alpha}} \implies f_{jk\alpha} + f_{ij\alpha} = f_{ik\alpha} + f_{ijk\hat{\alpha}}$. Now since $f_{ij\alpha} = g_{j\alpha} - (dg_i)_{j\alpha}$, we get that $f_{jk\alpha} + g_{j\alpha} - (dg_i)_{j\alpha} = f_{ik\alpha} + f_{ijk\hat{\alpha}}$. I'm having trouble dealing with this last $f_{ijk\hat{\alpha}}$ term and I don't know how we can develop it to get everything to cancel out nicely.

*I'm guessing here is where we use the note mentioned in part (a) that $\mathcal{C}^{p}(\mathcal{U,F}) = \mathcal{C}^{p-1} (\mathcal{U_i,F}) \times \prod_{i \neq i'} \mathcal{C}^{p-1} (\mathcal{U_{i'}},F)$ to glue together the $g_i$s we fund before for each $i$ but I haven't had too much insight with that. I don't quite understand this and the final part of b.

c) I'm honestly quite confused by this. Why would we need to use Zorn's lemma here? wouldn't part a) and b) be enough by induction?
I'm mainly looking for either help with these questions or a reference. Thanks


text:
Q: jQuery UI Tabs select function not working I have the following jquery which is used to create tabs on my website (wrapped in document ready function):
$('#understanding-water-management').tabs({
    select: function(event, ui) {
        alert('hi');
    }
});

However, on my site the select function isn't been fired on tab change.  I have created a fiddle but this works as I would expect it to (it alerts hi on tab change).
The only difference between the two sites is that on my own website I have used a lighter version of jQuery UI where I have only downloaded the Core, Widget (from UI Core) and Tabs (from Widgets) options.  Is there any other option I need to download to get the select function above to work - I don't want to use the full jQuery UI as all I need is the tabs so want to make my js files as minimal as possible

A: Try to wrap your code inside DOM ready handler $(function() {...}); to make sure all your DOM elements are loaded properly before executing your jQuery code:
$(function() {
    $('#understanding-water-management').tabs({
        select: function(event, ui) {
            alert('hi');
        }
    });
});

Your jsFiddle works because they've done above part for you by default when you include jQuery.

A: jQuery UI 1.10 change the select to beforeActivate (if you want the function to fire before the tab is selected) or activate (if you want it to fire after the tab has been selected)
try
$('#understanding-water-management').tabs({
    beforeActivate: function(event, ui) {
        alert('hi');
    }
});


text:
Q: Imgur API (rapidAPI) no longer works Two days ago, something changed and the RapidAPI endpoint of the Imgur API just stopped working for uploads.
Also, it seems Imgur isn't responding over at the RapidAPI discussions, so hopefully their engineers see this. There's a thread about it here. I have no idea why Imgur does not have a contact point for their paying customers though.
My website has worked just fine and let me upload stuff with no problems, but it just returns a 404 error on the https://imgur-apiv3.p.rapidapi.com/3/image endpoint now. No other errors or messages.

A: Seems like many developers are getting this error. This can fix the issue
Add the ?client_id=<imgur_client_id> query string parameter to API endpoint (POST /3/image).
However, you can always write to RapidAPI support team at support@rapidapi.ciom


text:
Q: How to only keep dataframe rows that shares same value on a specific column I have two dataframes that I want to compare, but first I want to assert that the first column (that I'm using as index) is the same for both.
df1
    A   B   C   D   E
0   a   10  5   18  20
1   b   9   18  11  13
2   c   8   7   12  5
3   z   6   5   3   90

df2
    A   B   C   D   E
0   a   10  45  10  22
1   b   99  18  11  13
2   e   8   7   12  5
3   f   6   5   3   90

I want to keep only the rows where the value in column A is in both dataframes. So I expect an output like that for df1 and df2.
df3
    A   B   C   D   E
0   a   10  5   18  20
1   b   9   18  11  13

df4
    A   B   C   D   E
0   a   10  45  10  22
1   b   99  18  11  13

I'd also like to retrieve the deleted rows.
deleted_df
    A   B   C   D   E
0   c   8   7   12  5
1   z   6   5   3   90
2   e   8   7   12  5
3   f   6   5   3   90

I've tried this for now:
df3 = df1[df1['A'].isin(df2['A'])]
df4 = df2[df2['A'].isin(df1['A'])]

which seems to work but I'm not sure, but I still want to retrieve the difference between df3 & df1 (and espectively, df4 & df2)

A: One thing you can do is outer merge with passing True for indicator:
>>> df1.merge(df2, on='A', indicator=True, how='outer', suffixes=('1',  '2',))

   A    B1    C1    D1    E1    B2    C2    D2    E2      _merge
0  a  10.0   5.0  18.0  20.0  10.0  45.0  10.0  22.0        both
1  b   9.0  18.0  11.0  13.0  99.0  18.0  11.0  13.0        both
2  c   8.0   7.0  12.0   5.0   NaN   NaN   NaN   NaN   left_only
3  z   6.0   5.0   3.0  90.0   NaN   NaN   NaN   NaN   left_only
4  e   NaN   NaN   NaN   NaN   8.0   7.0  12.0   5.0  right_only
5  f   NaN   NaN   NaN   NaN   6.0   5.0   3.0  90.0  right_only

This way, you will have the information if the row has been derived from both the columns, or only one of the left/right.

A: use isin:
df1.loc[df1.A.isin(df2.A)]

   A   B   C   D   E
0  a  10   5  18  20
1  b   9  18  11  13

isin returns a boolean Series which you use to filter :
df1.A.isin(df2.A)
0     True
1     True
2    False
3    False
Name: A, dtype: bool

For deleted rows:
df1 = df1.set_index('A')
df2 = df2.set_index('A')
deleted = df1.index.symmetric_difference(df2.index)
pd.concat([df1, df2]).loc[deleted]
   B  C   D   E
A
c  8  7  12   5
e  8  7  12   5
f  6  5   3  90
z  6  5   3  90


text:
Q: Rounding off all numeric columns in data frame to different numbers of digits I have a data frame containing many columns of different classes, I'm including a very simplified example below:
df <- data.frame( col1=c("mary", "john", "luke", "peter", "agnes", "anne", "july", "judy", "tina", "ben"),
                  col2=c(0.1111,0.3123,0.7875,0.6789,0.87862,0.37512,0.69875,0.1785,0.1777, 0.9999),
                  col3=c(0.1111,0.3123,0.7875,0.6789,0.87862,0.37512,0.69875,0.1785,0.1777, 0.9999),
                  col3=c(124.6, 763.8, 222.9, 765.0, 564.7, 761.8, 683.9, 655.9, 897.3, 566.1))

I would like to round off all of the numeric columns, but to different values. For example: col2 and col3 should be rounded off to 2 digits and col4 to 0 digits.
The style of code I was able to come up with is something like this:
df2 <- df %>% mutate_at(2, round, 2)
df3 <- df2 %>% mutate_at(3, round, 2)
df4 <- df3 %>% mutate_at(4, round, 0)

If I don't assign the value to a new data frame each time around it doesn't save the values to my data frame.
For instance if I do something like this:
df %>% mutate_at(2, round, 2)
df %>% mutate_at(3, round, 2)
df %>% mutate_at(4, round, 0)

It writes out the desired output to the console, but doesn't save it to df. I was wondering if there was more elegant and intuitive way of doing this?

A: You can keep using the pipe operator to connect the code together.
df <- df %>%
  mutate_at(c(2, 3), round, 2) %>%
  mutate_at(4, round, 0)

A: _at, _all, _if variants are now superseded by across which also allows you to input multiple operations in the same mutate pipe.
library(dplyr)

df <- df %>%
        mutate(across(2:3, round, 2),
               across(4, round, 0))
df

#    col1 col2 col3 col3.1
#1   mary 0.11 0.11    125
#2   john 0.31 0.31    764
#3   luke 0.79 0.79    223
#4  peter 0.68 0.68    765
#5  agnes 0.88 0.88    565
#6   anne 0.38 0.38    762
#7   july 0.70 0.70    684
#8   judy 0.18 0.18    656
#9   tina 0.18 0.18    897
#10   ben 1.00 1.00    566


text:
Q: How can I assign STDOUT to a var and print to that while using 'use strict'? perl-5.24.0-gcc620 on linux
I have some existing code in a perl module that uses IO::Tee to direct stdout to both a file and the terminal...
use strict;
use IO::Tee;
our $tee;

sub common {
    open $tee, ">", "my.log";
    $tee = new IO::Tee(\*STDOUT, $tee);
    etc...
}
.
.
.
sub some_sub {
    print $tee "I want this to go to the log file and the terminal. Works fine.\n";
}

Now, I want to use "some_sub" using a perl script that does not run the "common" sub which does the  IO::Tee piece.  So $tee will be undefined and I'll get compilation errors when I try to use it.
The hack I did is...
if($tee) {
    print $tee "I want to print this\n";
} else {
    print "I want to print this";
}

But the print statements are all over the place and I want a more elegant way of dealing with this.
What I want to do is something like this...
if(!($tee)) {
    $tee = STDOUT;
}

... then leave all the existing "print $tee ..." statements alone.
But this gives me a bareword error because I'm using "use strict"...
Bareword "STDOUT" not allowed while "strict subs" in use at ./change_tee_STDOUT.pl line 4.

If I get rid of the "use strict", it seems to work.
How can I get the functionality of "$tee = STDOUT" while retaining the "use strict" ?  I feel that perhaps there is a way to cast STDOUT to a filehandle type, or something like that.  Am I close ?

A: $tee = \*STDOUT;      # Reference to a glob containing the IO object.

or
$tee = *STDOUT;       # Glob containing the IO object.

or
$tee = *STDOUT{IO};   # Reference to the IO object.

I use the first one. (And you did as well in your existing code!) The second should work just as well. I'm not sure how universally supported the last one is. (Perl itself won't have any problem with it, but XS modules?)

A: It's better to use a neutral file handle in the functions and connect it to whatever outputs that mode of operation calls for.
use strict;
use diagnostics;

our $OUTPUT;

if ($mode1) {
    open $OUTPUT, ">", $file;
}
elsif ($mode2) {
    open $OUTPUT, ">&=", *STDOUT;
}
elsif ($mode3) {
    my $tee = tee_up("my.log");
    open $OUTPUT, ">&=", $tee;
}
else { die; }

sub tee_up {
    require IO::Tee;
    open my $fh, ">", $_[0];
    return IO::Tee->new(\*STDOUT, $fh);
}

sub some_sub {
    print $OUTPUT "I want this to go where I want\n";
}

Thanks.


text:
Q: Prevent using B or b from jumping to previous line in vim I found the following code on SO and it works great for using E to jump to words and stopping at the end of the line like this: nnoremap <expr> E getline('.')[col('.') - 1:] =~# '\s\S' ? 'E' : (col('.') + 1 == col('g_') ? 'E' : '$').
But I only recently started dabbing into vimscripts and can't get it to work for going backwards with b/B.
I attempted to do something like this but didn't work as it doesn't stop at the start of the line:
nnoremap <expr> B getline('.')[col('.') + 1:] =~# '\S\s' ? 'B' : (col('.') - 1 == col('^') ? 'B' : '^')

A: I suggest the following:
nnoremap <expr> B strpart(getline('.'), 0, col('.') - 1) =~ '^\s*$' ? '0' : 'B'

strpart(getline('.'), 0, col('.') - 1) picks up the substring left to the current cursor position. If this is empty or consists only of whitespaces (i.e., when B would normally jump to the previous line), then B is mapped to 0, i.e., it goes to the first character of the line without jumping to the previous line. Otherwise, B behaves like the original B.


text:
Q: Add weeks to a date column to create a new date column I have a file with 100s of dates (dd/mm/yyyy) like so:
10112017
23012012
01022008

And in bash I need to add 8 weeks to these dates to get output like so:
10112017 05012018
23012012 19032012
01022008 28032008

I am thinking possibly awk, or possibly something starting while read p, but I can't get the output I want.
Help would be much appreciated.

A: You could use perl, with the Time::Piece module:
perl -MTime::Piece -MTime::Seconds -lpe '
  $dt = Time::Piece->strptime($_,"%d%m%Y") + 8 * ONE_WEEK;
  $_ .= $dt->strftime(" %d%m%Y")
' file
10112017 05012018
23012012 19032012
01022008 28032008

or with GNU awk (gawk) and GNU date
gawk -v FIELDWIDTHS='2 2 4' '{
    cmd = sprintf("date +%%d%%m%%Y -d \"%s/%s/%s + 8 weeks\"", $2, $1, $3);
    cmd |& getline dt;
    close(cmd)
  }
  {
    print $0,dt
  }
' file
10112017 05012018
23012012 19032012
01022008 28032008

or (my new favorite for this kind of thing), Miller
$ mlr --nidx put -S '$2 = strftime(strptime($1,"%d%m%Y") + 4838400,"%d%m%Y")' file
10112017 05012018
23012012 19032012
01022008 28032008

where 4838400 is 8 weeks in seconds (3600 x 24 x 7 x 8).

A: ]# date -d '2020-2-1 +8 week' +%Y-%m-%d
2020-03-28

]# date -d '2019-2-1 +8 week' +%Y-%m-%d
2019-03-29

]# date -d '2019-7-1 +8 week' +%Y-%m-%d
2019-08-26

info date has some additional examples. I used the YYYY-MM-DD notation, it didn't work with your DDMMYYYY form.
This is with a GNU date. The example shows that month lengths and leap years are working.
With date you have a basic tool for calendar handling. Maybe there is a better way to integrate this into your script - as you see the input "DDMMYYYY" needs (?) treatment.
For output formatting+%Y-%m-%d can be changed to +%d%m%Y.

A: Annotated bash script below. Run like: ./script.sh < inputfile > outputfile.
#!/bin/bash

# date1 is orignal date string in 1st column
# date2 is 8 weeks later than date1

while read date1 ; do

    # Skip emtpy lines
    #
    [ "$date1" ] || continue

    # We want to use 'date' command to calculate 8 weeks later.
    # However the 'date' command does not accept 'ddmmyyyy', but it
    # does accept 'yyyy-mm-dd'. So we need to convert first.
    #
    dd=${date1%??????}
    mm=${date1#??} ; mm=${mm%????}
    yyyy=${date1#????}

    # The 'date' command does have its own option to specify output
    # format of the date. It also just lets specify the input date
    # like this: "1983-04-18 + 8 weeks" to have it calculate what we
    # need here.
    #
    date2=$(date -d "${yyyy}-${mm}-${dd} + 8 weeks" +'%d%m%Y')

    # Now just output both dates on one line
    #
    echo $date1 $date2

done


text:
Q: Make a Recyclerview Android from API but, it doesn't work I've been working with Recycler view Android. I try to make a Recycler view from API Response. But, the list didn't show up, my adapter was not working. When i tried to debug this program, I got List<Produclist> list is null.
This my JSON Response from API
{
  "code": 0,
  "data": [
    {
      "product_list": [
        {
          "return_level": 0,
          "image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
          "risk_level": "Aggresive",
          "code": "P0011",
          "price": {
            "date": null,
            "value": 0
          },
          "name": "Dana Ekuitas Prima"
        },
        {
          "return_level": 0,
          "image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
          "risk_level": "Aggresive",
          "code": "P0001",
          "price": {
            "date": "2017-01-03T11:44:52.6152Z",
            "value": 150000
          },
          "name": "Manulife Dana Saham"
        },
        {
          "return_level": 0,
          "image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
          "risk_level": "Aggresive",
          "code": "P0008",
          "price": {
            "date": null,
            "value": 0
          },
          "name": "Trim Kapital Plus"
        },
        {
          "return_level": 0,
          "image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
          "risk_level": "Aggresive",
          "code": "P0004",
          "price": {
            "date": "2017-01-03T11:44:52.6152Z",
            "value": 150000
          },
          "name": "Manulife Syariah Sektoral Amanah"
        }
      ],
      "type": "Reksa Dana Saham"
    }
  ],
  "info": "Product list successfully loaded"
}

This My setter getter
public class ProductListResponse {

    @SerializedName("code")
    @Expose
    private Integer code;
    @SerializedName("info")
    @Expose
    private String info;
    @SerializedName("data")
    @Expose
    private List<CategoryType> listCategory = new ArrayList<>();

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    public List<CategoryType> getListCategory() {
        return listCategory;
    }

    public void setListCategory(List<CategoryType> listCategory) {
        this.listCategory = listCategory;
    }

}

Setter getter of category type
    public class CategoryType {

        @SerializedName("type")
        @Expose
        private String type;

        @SerializedName("product_list")
        @Expose
        private List<ProductList> productList = new ArrayList<ProductList>();

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public List<ProductList> getProductList() {
            return productList;
        }

        public void setProductList(List<ProductList> productList) {
            this.productList = productList;
        }
}

Setter getter of ProductList
public class ProductList implements Serializable {

    @SerializedName("code")
    @Expose
    private String code;

    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("price")
    @Expose
    private Price price;

    @SerializedName("risk_level")
    @Expose
    private String riskLevel;

    @SerializedName("return_level")
    @Expose
    private Double returnLevel;

    @SerializedName("image")
    @Expose
    private String image;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getRiskLevel() {
        return riskLevel;
    }

    public void setRiskLevel(String riskLevel) {
        this.riskLevel = riskLevel;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Price getPrice() {
        return price;
    }

    public void setPrice(Price price) {
        this.price = price;
    }

    public Double getreturnLevel() {
        return returnLevel;
    }

    public void setReturnLevel(Double returnLevel) {
        this.returnLevel = returnLevel;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

This my Activity
public class ProductActivity extends AppCompatActivity {

    private RecyclerView rvView;
    private RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    public List<ProductList> list;
    Context context;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.f_list_of_product);
        request(constructSignUpRequest());

        rvView = (RecyclerView) findViewById(R.id.rv);
        rvView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);

        rvView.setLayoutManager(layoutManager);
        adapter = new ProductAdapter(context, list);
        rvView.setAdapter(adapter);
    }

    public BTNService.Api getApi() {
        return getBTNService().getApi();
    }

    public BTNService getBTNService() {
        return new BTNService(this);
    }

    void request(final ProductListRequest productListRequest) {
        getApi().loadproductlist(productListRequest.getCode())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<ProductListResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Timber.e(e.getLocalizedMessage());
                    }

                    @Override
                    public void onNext(ProductListResponse response) {
                        if (response != null) {
                            Intent intent = new Intent(ProductActivity.this, ProductList.class);
                            startActivity(intent);
                        }

                    }
                });
    }

    public ProductListRequest constructSignUpRequest() {
        ProductListRequest request = new ProductListRequest();
        request.setCode(Category);
        return request;
    }

}

This my Adapter
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.CatalogueHolder> {

    private Context context;
    private List<ProductList> list;

    public ProductAdapter(Context context, List<ProductList> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public CatalogueHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_product, parent, false);
        CatalogueHolder catalogueHolder = new CatalogueHolder(itemView);
        return catalogueHolder;
    }

    @Override
    public void onBindViewHolder(CatalogueHolder holder, int position) {
        final ProductList item = list.get(position);
        holder.itemView.setTag(item);
        holder.productName.setText(item.getName());
    }

    @Override
    public int getItemCount() {
        return list != null ? list.size() : 0;
    }

    public static class CatalogueHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.productname)
        TextView productName;
        @Bind(R.id.typeProduct)
        TextView typeProduct;
        @Bind(R.id.price)
        TextView price;
        @Bind(R.id.date)
        TextView date;

        public CatalogueHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}

Sorry, if it's quite long. I have to show all my code to make it clear. I really need your help guys. Thanks

A: Set adapter inside onComplete method:
void request(final ProductListRequest productListRequest) {
    getApi().loadproductlist(productListRequest.getCode())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(new Observer<ProductListResponse>() {
                @Override
                public void onCompleted() {

                rvView.setHasFixedSize(true);
                layoutManager = new LinearLayoutManager(this);

                rvView.setLayoutManager(layoutManager);
                adapter = new ProductAdapter(context, list);
                rvView.setAdapter(adapter);

                }

                @Override
                public void onError(Throwable e) {
                    Timber.e(e.getLocalizedMessage());
                }

                @Override
                public void onNext(ProductListResponse response) {
                    if (response != null) {
                        Intent intent = new Intent(ProductActivity.this, ProductList.class);
                        startActivity(intent);
                    }

                }
            });
}


text:
Q: Using onFocus/onClick to trigger a function within an input field in React OK so I have an input field that whose value is pre-loaded when the component mounts (this.state.color) and I'm attempting to add a handleColorPicker() function either onClick or onFocus that will dropdown a color picker from https://casesandberg.github.io/react-color/. I'll paste the relevant code below:
import React, { Component } from 'react';
import { ChromePicker } from 'react-color';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
       color: 'FFFFFF',
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleColorPicker = this.handleColorPicker.bind(this);
  }

  handleChange(event) {
    this.setState({[event.target.name]: event.target.value});
  }

  handleColorPicker(){
    console.log('open');
    return(
      <ChromePicker />
    )
  }

  render() {
    return(
      <input
        className="App-textForm"
        type="text"
        name="color"
        value={this.state.color}
        onChange={this.handleChange}
        onClick={this.handleColorPicker}
      />
    );
  }
}

As constructed, it console.logs 'open' every time I click on it.
Is there anything obvious I'm missing as to why that onClick wouldn't trigger the ChromePicker? I've tried changing onClick to onFocus and have tried wrapping my input in a div with an onClick={this.handleColorPicker}. Any help would be appreciated, thanks!

A: onClick event listener doesn't do anything with the returned component. You need to set a state the renders the component conditionally like
import React, { Component } from 'react';
import { ChromePicker } from 'react-color';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
       color: 'FFFFFF',
       isColorPickerOpen: false
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleColorPicker = this.handleColorPicker.bind(this);
  }

  handleChange(event) {
    this.setState({[event.target.name]: event.target.value});
  }

  handleColorPicker(){
    console.log('open');
    this.setState({ isColorPickerOpen: true });
  }

  render() {
    return(
      <React.Fragment>
      <input
        className="App-textForm"
        type="text"
        name="color"
        value={this.state.color}
        onChange={this.handleChange}
        onClick={this.handleColorPicker}
      />
      {isColorPickerOpen?  <ChromePicker /> : null}
      </React.Fragment>
    );
  }
}

A: You are attaching your handleColorPicker to run correctly, but you shouldn't be returning the ChromePicker in that function.
Take a look at this CodeSandbox Example.
Notice how I have state in my component (isColorPickerOpen) that keeps track of whether the color picker is showing or not. My click handler toggles this state between true and false.
Then in my render method, I only render the ChromePicker component when isColorPickerOpen is true.

A: The problem is that you are not rendering the picker, you are just returning it and then doing nothing with it.
What you need to do is render the picker, you can do that by using the state and hide/show the picker based on the user selection. For example:
state = {
  showPicker: false,
};

handleColorPicker(){
  console.log('open');
  this.setState(current => ({
    showPicker: !current.showPicker, // <-- Toggle the state
  }));
}

render() {
  const { showPicker } = this.state;

  return (

    <input
      className="App-textForm"
      type="text"
      name="color"
      value={this.state.color}
      onChange={this.handleChange}
      onFocus={this.handleColorPicker} // <--- Open the picker on focus
      onBlur={this.handleColorPicker}  // <--- Hide it on blur? You need to define when to hide it
     />
     { showPicker && <ChromePicker /> }

 );
}

using onFocus and onBlur the state change and the picker gets renderer or not, based on the value of showPicker.
You need to define when to hide it, onBlur might not be what you want.

A: OK, so you are not rendering the <ChromePicker />
try this

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
       color: 'FFFFFF',
       isPickerActive: false
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleColorPicker = this.handleColorPicker.bind(this);
  }

  handleChange(event) {
    this.setState({[event.target.name]: event.target.value});
  }

  handleColorPicker(){
    this.setState({isPickerActive: true});
  }

  render() {
    return(

      <input
        className="App-textForm"
        type="text"
        name="color"
        value={this.state.color}
        onChange={this.handleChange}
        onClick={this.handleColorPicker}
      />
      {this.state.isPickerActive && <ChromePicker />}

    );
  }
}

But it will just open the picker. Hope it will help.

A: With the onClick you are not render ChromePicker when it return.
Instead you can have an state to handle the ChromePicker render. Every time that you click or focus on you input, you can change the state, and then the component will be re render again.
Example:
import React, { Component } from 'react';
import { ChromePicker } from 'react-color';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
       color: 'FFFFFF',
       showChromePicker: false,
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleColorPicker = this.handleColorPicker.bind(this);
  }

  handleChange(event) {
    this.setState({[event.target.name]: event.target.value});
  }

  handleColorPicker(){
    console.log('open');

    this.setState({
      showChromePicker: true,
    });
  }

  render() {
    const { showChromePicker } = this.state;

    return(

        <input
        className="App-textForm"
        type="text"
        name="color"
        value={this.state.color}
        onChange={this.handleChange}
        onClick={this.handleColorPicker}
        />
        {showChromePicker ? <ChromePicker /> : null}

    );
  }
}


text:
Q: sizeof a function types in C I have a some cases about sizeof operator, which is used with function types.
Case 1 :  [Live Demo]
#include <stdio.h>

char func()
{
    printf("sizeof func = %zu\n", sizeof(func())); //Ok. Output : 1
    return 0;
}

int main(void)
{
    func();
}

Is sizeof(func()) valid in C?
Case 2 : [Live Demo]
printf("sizeof func = %zu\n", sizeof(&func())); // error

It is not working. compiler give an error. Why?
Case 3 : [Live Demo]
printf("sizeof func = %zu\n", sizeof(&func)); //Ok. Output : 8

Here, Is sizeof(&func) equal to the sizeof the pointer?
Here, case 3 working fine, where as case 2 give an error. Why?

A: The operand of sizeof can have two forms:

*

*A paranthesized type name, e.g. (char), (int), (struct mystruct), ...
The result is the storage size of the named type.

*An expression. The result is the storage size of the type the expression would evaluate to (but it isn't evaluated).
None of your examples is a type name. The type name for your function would be char (void). So all your parantheses are superfluous.
In your first example, you have sizeof func(). Evaluating func() would return a char, therefore the result is 1.
In your third example, you have sizeof &func. Evaluating &func would give you a function pointer and the size of a function pointer is 8 on your machine.
The second example is just wrong, &func() is not a valid expression. You can't take a pointer to a function call. In standard terms, func() is not an lvalue, which is required to apply &.

A: sizeof(type) returns the size in bytes of the object representation of type.
sizeof(expr) returns the size in bytes of the object representation of the type that would be returned by expression, if evaluated.
case 1
func is a function that returns a value of type char. So sizeof(func()) is the same as sizeof(char), which is 1
case 2
&func() is not a valid expression (you are trying to get the address of the return value of the function, which is undefined)
case 3
&func returns the address of the function func, which is a pointer. On a 64-bits system, sizeof(&func) will be the size of a pointer, that is 8. It will be 4 on a 32-bits OS.

A: In this statement
printf("sizeof func = %zu\n", sizeof(func()));

there is outputted the size of the expression (that is not evaluated) func(). As the return type of the function is char then the expression func() has the type char and sizeof( char ) is equal to 1.
From the C Standard (6.5.3.4 The sizeof and alignof operators)

4 When sizeof is applied to an operand that has type char, unsigned
  char, or signed char, (or a qualified version thereof) the result is
  1....

In this statement
printf("sizeof func = %zu\n", sizeof(&func()));

there is an attempt to apply the unary operator & to a temporary object that is evaluated as the expression func(). You may not apply the operator to a temporary object.
From the C Standard (6.5.3.2 Address and indirection operators)

1 The operand of the unary & operator shall be either a function
  designator, the result of a [] or unary * operator, or an lvalue
  that designates an object that is not a bit-field and is not declared
  with the register storage-class specifier.

for comparison consider the following program
#include <stdio.h>

char * func()
{
    static char i = 0;

    printf("sizeof func = %zu\n", sizeof(&*func()));

    return &i;
}

int main(void)
{
    func();
}

In this program the function returns pointer to the lvalue i with the static storage duration. So applying the unary operator * you will get the lvalue. So you may apply the operator & in this case.
The program output will be
sizeof func = 8

In this statement
printf("sizeof func = %zu\n", sizeof(&func));

there is evaluated the operator sizeof for a function pointer of the type char ( * )( void ). Again according to the quote from the C Standard the operator & may be applied to a function designator.
Take into account that the function definition shall look like
char func( void )
           ^^^^
{
    printf("sizeof func = %zu\n", sizeof(func())); //Ok. Output : 1
    return 0;
}


text:
Q: How is this a valid answer when converting boolean value to a string we have a function bool_to_string(flag) and you're supposed to define it so that the bool value passed to the function i.e flag is always returned as a string.
bool_to_string = str

This was a valid answer but I don't understand how it works. I know about lambda but this doesn't appear to be that. Can someone explain to me how it is so short?
edit: like the person below highlighted, our original function was just converting a value to string. That is the same the built-in function str() does so we have just swapped out our original function with str. Simple and clean solution.

A: The expression creates a new function bool_to_string and assigns it the value of function str. In essence, bool_to_string is an alias for the str function.
In Python, everything is an object you can work with functions in the same way as with any other data type.


text:
Q: WiQuery SortableAjaxBehavior on ListView target.add() Hy Everyone,
I'm a bit confused using wicket, wiquery and SortableAjaxBehavior...
Got a Class which extends BasePanel (TestPanel)
I'll create a WebMarkupContainer (ListViewContainer) and in it a ListView (ListItem)...
Then I'm adding a SortableAjaxBehavior to the WebMarkupContainer and the list is Sortable
-> everything is fine...
BUT...
... I've got an AjaxLink which updates the ListView onClick
if I add the Container to Target the ListView isn't sortable anymore
-> getting error in "Wicket Ajax Debug"
-> ERROR: TypeError: 'null' is not an object (evaluating '$('#sortable').sortable')
Does anybody have an Idea how to let the ListView be Sort- and updateable?
here my Java Code:
public class TestPanel extends BasePanel {

private static final long serialVersionUID = 1L;

private final static Logger LOG = Logger.getLogger(TestPanel.class);

private final FeedbackPanel feedbackPanel = new FeedbackPanel("feedbackPanel");

private WebMarkupContainer listViewContainer = createListViewContainer("listViewContainer");

public TestPanel(String id) {
    super(id);

    // Adds feedback panel.
    feedbackPanel.setOutputMarkupId(true);
    add(feedbackPanel);

    // AjaxButton
    add(createAjaxLink("loadListLink"));

    // ListViewContainer
    listViewContainer.add(createSortableBehavior());
    add(listViewContainer);
}

/* ---- CONTAINER ---- */

private WebMarkupContainer createListViewContainer (String id) {
    LOG.info("-- CreateListViewContainer");

    listViewContainer = new WebMarkupContainer(id);
    listViewContainer.setOutputMarkupId(true);

    List<String> liste = Arrays.asList("Node A", "Node B", "Node C");
    ListView<String> listView = createListView("listItem", liste);

    listViewContainer.add(listView);

    return listViewContainer;
}

/* ---- LISTS-/DATAVIEWS ---- */

private ListView<String> createListView (String id, List<String> liste) {
    LOG.info("-- CreateListView");
    ListView<String> listView = new ListView<String>(id, liste) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(ListItem<String> item) {
            item.setOutputMarkupId(true);
            item.add(new Label("itemTitle", item.getModelObject().toString()));
        }

    };

    return listView;
}

/* ---- AJAX BUTTONS/LINKS ---- */

private AjaxLink<Void> createAjaxLink (String id) {
    LOG.info("-- CreateAjaxLink");
    AjaxLink<Void> ajaxButton = new AjaxLink<Void>(id) {
        private static final long serialVersionUID = 1L;

        List<String> liste = Arrays.asList("Node A 1", "Node B 2", "Node C 3");

        @Override
        public void onClick(AjaxRequestTarget target) {
            LOG.info("ONCLICK");

            ListView<String> listView = createListView("listItem", liste);
            listViewContainer.replace(listView);

            //listViewContainer.add(createSortableBehavior());

            target.add(listViewContainer);
        }
    };

    return ajaxButton;
}

private SortableAjaxBehavior<Component> createSortableBehavior () {
    LOG.info("-- CreateSortableAjaxBehavior");
    SortableAjaxBehavior<Component> sortableBehavior = new SortableAjaxBehavior<Component> () {
        private static final long serialVersionUID = 1L;

        @Override
        public void onReceive(Component arg0, int arg1, Component arg2, AjaxRequestTarget arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onRemove(Component arg0, AjaxRequestTarget arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onUpdate(Component arg0, int arg1, AjaxRequestTarget arg2) {
            LOG.info("SORTABLE UPDATE");
        }

    };

    sortableBehavior.getSortableBehavior().setConnectWith(".sortableList");

    return sortableBehavior;
}

}
here my HTML:

    LOAD LIST

A: When you are updating your ListView container you are not adding the sortable behaviour again.
Try moving
listViewContainer.add(createSortableBehavior());

to
createListViewContainer (String id)

It'll then look like this:
private WebMarkupContainer createListViewContainer (String id) {
    LOG.info("-- CreateListViewContainer");

    listViewContainer = new WebMarkupContainer(id);
    listViewContainer.setOutputMarkupId(true);
    listViewContainer.add(createSortableBehavior());

    List<String> liste = Arrays.asList("Node A", "Node B", "Node C");
    ListView<String> listView = createListView("listItem", liste);

    listViewContainer.add(listView);

    return listViewContainer;
}


text:
Q: Using XML to generate SAP ABAP and/or SAPScript? Has anyone got examples and/or experience of generating SAP ABAP or SAPScript form code from XML that came from an external application?
This would help:

*

*creation of SAP-based applications in a data-driven way by automating the knowledge to do so from the export of XML from an external application

*automated inputting of knowledge from an external application into SAP applications, rather than manually copying between systems

*enable 3rd-party external tools to be used to create data, perhaps in a more easier-to-use way than could be done in SAP. Or if there was already heavy investment in training with these third party tools rather than SAP, or if the employment market favoured staff with knowledge of these tools

*enable creation of data for multiple purposes, views: those in SAP and outside SAP.

*enable inter-operability of SAP with 3rd-party external tools

I'm looking for:

*

*experiences as to the feasibility

*tools, e.g. parsers, XSLT etc.

*examples

A: Definitely feasible - take a look at http://www.volker-wegert.de/en/mdd-sap-r3. Be aware that you really need a deep knowledge of the R/3 side before you attempt to generate anything. As a rule of thumb, if you can't create it manually, you can't generate it either.
I'd recommend to keep the actual generation process out of the R/3 system because there are tools like EMF and the former oAW components that really kick ass when it comes to generating stuff. I'd also recommend a two-phase generation approach - generate an (external) model that represents what you want to generate in the SAP system, then transfer the contents of that model into the system. This way, the generator is much easier to debug.
RCER http://rcer.sf.net has a (very incomplete) repository object model - that could be extended to hold whatever entities you need. Personally, I'd love to see a SAPlink <--> RCER ROM converter - don't have the time to write one myself, though. This would allow you to

*

*create a modeling application based on Eclipse / EMF

*use oAW tools (Xtend / Xpand) for model transformation and code generation

*convert the resulting model to a SAPlink file

*upload the generated file into the system

I've done pretty much the same thing, except that instead of SAPlink, I've used RFC calls. Since I've had to write the function modules to generate classes and other objects myself, it's not really reusable - and it belongs to my former employer...

A: You could look at SAPLink.
This is an application that allows to generate such programs / functions /etc from a set of XML files. It also allow you to generate these files from the objects, thus allowing to transport the objects between two unrelated systems.
You could simply generate the xml files, and use SAPLink to import and generate the code.
Regards
Guillaume


text:
Q: How to get min value of all cities of yesterday?
How to get min value(temp) of all cities of yesterday.
I want:
Indore:min value:yesterday date
Bhopal:min value:yesterday date
Mumbai:min value:yesterday date

A: In Postgres, you can do:
select name, min(temp)
from t
where write_date < current_date and
      write_date >= current_date - interval '1 day'
group by name;

You can also write the where clause as:
where date_trunc('day', write_date) = current_date - interval '1 day'

However, using the function date_trunc() prevents the use of the index for the where clause.

A: select name, min(temp) from table
where date(write_date) BETWEEN TRUNC(SYSDATE - 1)
AND TRUNC(SYSDATE) - 1/86400
group by name

this will do your job


text:
Q: How to use NSCache with multiple pieces of information that together act as a 'key'? I'm trying to understand the concept of NSCache, and one thing that strikes me is that a NSCache instance does not guarantee to give back the value to a key you stored before. It might not even store the key value pair when you try to add it, if it deems that the performance is more important at the moment.
What that implies, for me, is that:

*

*Each key must 'hold' enough information to generate the value if necessary

*Each query for the NSCache, which essentially is just in the form of a key, should thus wrap up all the information needed to generate the corresponding value.

*From the above two points one can say that NSCache serves no purpose of establishing any kind of association between a key and a value - the user must be able to generate the value independent of the cache, and the sole purpose of using a NSCache is not to 'look up' some value, but rather just to trade memory for some performance boost

So my problem is about storing transparency masks for images. Initially I thought I just need to use the names of the images as the keys, but from my deductions above it seems that's not sufficient - I also have to include all other parameters used in generating a mask e.g. the transparency threshold, for example. It also means that every time I ask the cache for a mask I have to provide ALL the parameters. And the only way that I can think of about doing that is to use something like NSInvocation as the key; but that seems a rather clunky solution.

A: It is the very nature of a cache to be volatile, so caches should only ever be used to speed up access to information that could also be acquired some other way.
Your idea to create keys that hold all this information should work - just remember to store all your keys somewhere other than the cache as well.
As for the key, you can create a very simple class that has nothing but a couple of properties (the ones that make up a key), an isEqual: and hash method and maybe an initializer that takes parameters for each of your properties.
This requires extremely little code, since accessors and iVars for properties are autogenerated, so the only thing you really need to write is the isEqual: method (and hash).
This class is so small and taylor-made for the particular case you need it for, it makes sense to declare and implement it at the top of the .m file you're going to use it in. This way, you don't pollute the rest of the system. Just add @interface and @implementation sections for your class at the top of your .m file.

A: After more thought about this I think I've got one thing wrong - the keys in a NSCache do not necessarily need to hold all the information for generating the values. A key in a NSCache can serve the same purpose as that in a NSDictionary - a unique identifier to look up the value. The only difference, though, is that you'd always need to have a backup plan B for a NSCache in case the key-value pair added before is destroyed.
In simplier terms, operations on the two different classes look like this:
NSDictionary

*

*generate each value V for each key K and add the pairs to the dictionary

*look up V using K
NSCache

*

*look up V using K

*if V == nil, generate the value V and add the pair to the cache

Therefore it's possible to convert almost any NSDictionary to a NSCache, only that after the conversion you can't pass the NSCache around - you have to know how to generate the values at all times and thus the NSCache instance would most probably be a private property used exclusively in a certain class.
For my problem I've resolved to use a method like this (self is supposedly pointing to a subclass of NSCache, but I haven't tested it yet)
- (Mask *) maskForImageName:(NSString *)name maskGenerator:(Mask *(^)(NSString *))generator {
    Mask *mask = [self objectForKey:name];
    if (!mask) {
        mask = generator(name);
        [self setObject:mask forKey:name];
    }
    return mask;
}

It would be further simplified if objective-c is a functional, lazy-style language, in which case I don't even need to wrap the generator in a block; but I'm satisfied with this solution for now. In fact I feel that this pattern is almost always used with NSCache so I'd just add it as a category to NSCache.


text:
Q: The system cannot find the path while createTempFile I get an exception saying 'the system cannot find the path specified' while calling java function createTempFile("test", "test").
Tried googling but no luck.
Does anyone know from where java gets its default temp path and how can it be not found?
Windows variables seem to be correct and changing them does not affect java.

A: Independently of how the default value is obtained, you can set the temporary files directory by setting the system property java.io.tmpdir when starting the JVM:
java -Djava.io.tmpdir=/path/to/where/ever/you/like YourClass

If you want to know where the default value comes from, you'll have to read the source code for your JVM. For example, OpenJDK on Windows calls the API function GetTempPathW (search for the file java_props_md.c in the JDK source code), which looks up the path in environment variables and registry in the following way:

The GetTempPath function checks for the existence of environment variables in the following order and uses the first path found:

*

*The path specified by the TMP environment variable.

*The path specified by the TEMP environment variable.

*The path specified by the USERPROFILE environment variable.

*The Windows directory.

  Note that the function does not verify that the path exists, nor does it test to see if the current process has any kind of access rights to the path.

A: Try:
String path = System.getProperty("java.io.tmpdir");

See: get property method
And to add it here for completeness sake, there's also the methods createTempFile(String prefix,String suffix) and createTempFile(String prefix, String suffix, File directory) methods from Java's file class.
Here is my code to fin path of temp file and find temp path:
public class GetTempFilePathExample
{
    public static void main(String[] args)
    {

        try{

            //create a temp file
            File temp = File.createTempFile("temp-file-name", ".tmp");

            System.out.println("Temp file : " + temp.getAbsolutePath());

        //Get tempropary file path
            String absolutePath = temp.getAbsolutePath();
            String tempFilePath = absolutePath.
                substring(0,absolutePath.lastIndexOf(File.separator));

            System.out.println("Temp file path : " + tempFilePath);

        }catch(IOException e){

            e.printStackTrace();

        }

    }
}

Output of this code is :
Temp file : /tmp/temp-file-name3697762749201044262.tmp
Temp file path : /tmp

A:
Does anyone know from where java gets its default temp path

It is read from the java.io.tmpdir property.
Files.createTempFile("test", "test");

essentially calls java.nio.file.TempFileHelper.createTempFile(null, prefix, suffix, attrs); which again calls java.nio.file.TempFileHelper.create(dir, prefix, suffix, false, attrs);. There, if dir is null, it is set to tmpdir which is declared as follows:
private static final Path tmpdir =
    Paths.get(doPrivileged(new GetPropertyAction("java.io.tmpdir")));

You can set the property explicitly as shown in the answer from @Joni. If you do not set it explicitly, the JVM initializes it to a platform specific default value at startup - see also Environment variable to control java.io.tmpdir?

and how can it be not found?

If the property java.io.tmpdir points to an invalid directory, the temporary file can not be created.


text:
Q: How is it possible to join dock to railway station? It seems openttd does not allowed to join dock to railway station, only in separated way. Unfortunately.

A: If you build a station of one type (eg. dock) next to a station of a different type (eg. rail) the game will automatically join the two, provided that the combined station does not exceed the maximum permitted station size.
From version 0.7.0 onwards, if distant joining of stations is enabled in the advanced settings, you can hold down the control key while placing a station near another station: the game will give you the option to combine the two stations if the resulting station will not exceed the maximum station size.
In both cases, the combined station will share a common pool of cargo and have a single approval rating for each cargo type, but will count as two (or more) stations for the purposes of the company performance rating score.


text:
Q: Add list of dictionaries from AJAX response to datatable I'm trying to refresh a DataTable using a list of dictionaries received as AJAX response, but the table gets cleared and no data gets added. No errors in the network log, and successfully receiving a response.
This is just as mentioned in https://datatables.net/reference/api/rows.add()
Flask:
    c_data = []
    for c in myData:
        c_data.append({
            'name': c[0],
            'branch': c[1],
            'city': c[2],
            'state': c[3],
            'country': c[4],
            'pin': c[5],
            'landmark': c[6],
            })

    return json.dumps(c_data)

JQuery:
function makeRequest() {
var pageNum = table.hasOwnProperty('page') ? table.page.info().page : 1;
 if (pageNum > 0) {
        $.ajax({
        data: JSON.stringify({ "pageNum": pageNum }),
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/my/url",
        success: function(data){
                console.log(jQuery.type(data);
                console.log(data);
                table.clear();
                table.rows.add(data);
                table.draw();
                }
        })

}

Response in Network log:

type- array data- [{"name": "XYZ", "branch": "main", "city": "Tokyo",
"state": "P3", "country": "Japan", "pin": "110011", "landmark":
"L1"},{"name": "XYZ", "branch": "main", "city": "Tokyo", "state":
"P3", "country": "Japan", "pin": "110011", "landmark":
"L2"},...{"name": "XYZ", "branch": "main", "city": "Tokyo", "state":
"P3", "country": "Japan", "pin": "110011", "landmark": "L30"}]

Can you please suggest how I can map the data using table.rows.add ?


text:
Q: Running a Selenium script only if a certain element is present I have an if else statement nested in a for loop and I am trying to figure out a way to only run the program for the current feature (u) if the element exists. The element in question is a value in a select/option format.  Basically, I need a certain option in that drop down menu to be present for the code to run and if it is not I would like to move onto the next url and try again.  The option is either present or it's not (it won't pop up if the driver waits).
for u in urls:
    bot.get(u)
    if *statement to check if the value exists*:
       -- runs my intended function --
    else:
        print("This site is not reporting yet")

Thank you.

A: You need to loop through the urls and check if the value exists within a try-catch{} block and you can use the following solution:
for u in urls:
    try:
        bot.get(u)
        #check if the value exists using WebDriverWait with expected_conditions as visibility_of_element_located
        #runs my intended function
    except TimeoutException as e:
        print("This site is not reporting yet")
        continue


text:
Q: O que é tree depth e height? Fiz a pergunta O que é Breadth First e Depth First?. Talvez um assunto um pouco mais simples seria o que são a profundidade e altura de uma estrutura de árvore. E por que isto importa na estrutura de dados e afeta o algoritmo que cruza a árvore?

A: Uma árvore tem altura ('height') e diâmetro o largura ('diameter' o 'width').

*

*Altura - O número de arestas no rumo entre o nodo raiz e o nó folha mais distante. A altura da árvore abaixo é 3. (As vezes pessoas aumentam 1 por contar os nívels da árvore em vez das arestas.)

*Diâmetro - O número de nodos no rumo mais longo na árvore. A árvore abaixo tem um deâmetro de 6.
Os nodos da árvore tem altura (height) e profudidade (depth).

*

*Altura - O número de arestas no rumo entre este nodo e o nó folha mais distante em baixo deste nodo. (A altura do nodo raiz é o mesmo que a altura da árvore.)

*Profundidade - O número de arestas no rumo entre este nodo e o nodo raiz.

O nodo laranja sólido é o nodo raiz ('root node'), os nodos cinzentos são os nodos interiores ('inner nodes'), e os nodos com linhas laranjas são os nós folhas ('leaf nodes').
Achei a imagen nesta resposta a What is the difference between tree depth and height


text:
Q: Looking for properties of, or formulae for eigenvalues of a symmetric matrix reminiscent of Toeplitz matrices I'm looking at $N\times N$ matrices $M_N$ of the form
$$M_4=\begin{pmatrix}1 & a & a^2 & a^3 \\ a & 1 & a & a^2 \\ a^2 & a & 1 & a \\ a^3 & a^2 & a & 1\end{pmatrix},$$
where $a$ is a complex number of unit modulus. I'm particularly interested in large matrices with the property $a^N=1$. I've come up empty in several attempts trying to find eigenvalues or eigenvectors of this matrix analytically for sizes larger than 4, but the fact that this matrix only has one parameter and its close relation to Toeplitz matrices makes me hope someone has studied these things before.


text:
Q: TwitterService does not use ITwitterService I was wondering why there is an ITwitterService interface in TweetSharp because this isn't used by the TwitterService class. I would like to use dependency injection in my application and even all methods of twitter service are virtual, it bothers me a bit that there is an interface I can not use.
Thx.


text:
Q: How to lock a database row using JPA until another table is updated I am new to JPA using Hibernate/Spring. My use case is:
I have 2 tables - A and B. When the user queries table A and gets a row, it should be locked and won't be issued to anyone else until the user is done doing some operation using the returned data and updated table B.
I can add a column (say IS_LOCKED) in table A and then update it once the operation is complete. But I am trying to figure out if there is a better solution to this problem. Not sure if the javax.persistence.LockModeType is of much use in this case.

A: Yes, you can do that with Hibernate and with LockModeType.
There are many possibilities based on your needs, so the best way is to choose from here.


text:
Q: iOS developer certificate expired I recently have renewed my iOS membership by paying the $99 fee. However, it seems that all my certificates have expired so I am trying to renew them manually. So I went into the provisioning portal--> Certificates --> Development and issued a new certificate which I downloaded. So now I have .cer file downloaded from Apple. I believe last time around all I had to do was double click this file and it would ask if I wanted to add it to the keychain.
This time, nothing happens other than the fact keychain access is launched but it does not ask me anything and I do not see the certificate in the certificate section or key section.
What do I need to do to get this file into Xcode to continue development?
Thanks!

A: Here:

Once you get the new profiles, download them and import them in Xcode Organizer then sync with the development devices. You are done.

A: Go into XCode Option Devices, select Provisioning Profiles and then click on Refresh in the corner on the right bottom.


text:
Q: How do I use a Vue 2 component in a HTML single file that uses Vue 3 UMD build I'm trying to use https://vue-treeselect.js.org/ (multi-select component with nested options) in a Vue 3 single local HTML file (I don't want to use the Vue CLI for this specific task), using the standalone UMD build Vue 2, it works as it follows (as showed in the docs):

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@riophae/vue-treeselect@^0.4.0/dist/vue-treeselect.min.css">

      <treeselect v-model="value" :multiple="true" :options="options" />

How can I do the same using the UMD build for Vue 3?
I tried it switching the script line from Vue 2 to Vue 3, and adding the value and option variables inside data() like this (but does not recognize the new treeselect tag):

    <link rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@riophae/vue-treeselect@^0.4.0/dist/vue-treeselect.min.css">

        <treeselect v-model="value" :multiple="true" :options="options" />

A: It seems that Vue.js 3 is not supported yet by this components.


text:
Q: problem in installing ImageMagick on centos7 I'm trying to install ImageMagick-c++-devel using "yum install ImageMagick-c++-devel"
but this error occurs:
Transaction check error:
  file /usr/lib64/libgs.so.9 from install of libgs-9.25-2.el7_7.3.x86_64 conflicts with file from package ghostscript-9.07-28.el7_4.2.x86_64
  file /usr/lib64/libijs-0.35.so from install of libgs-9.25-2.el7_7.3.x86_64 conflicts with file from package ghostscript-9.07-28.el7_4.2.x86_64

Even when I removed libijs-0.35.so file, this error repeated again.
Could anyone help me please?

A: Just delete the package of this document conversion
yum remove ghostscript-fonts-5.50-32.el7.noarch


text:
Q: Colorbox html from a function i have a html code

<link rel="stylesheet" href="http://www.jacklmoore.com/colorbox/example1/colorbox.css" />

CLICK ME

When i click on CLICK ME, alert pop up comes 2 times rather it should come only once. Please tell me

A: any way here are some problems with your code:
$("#bag").click(function{
$("#bag").click(function(){


text:
Q: Stop website because of startup errors If my web service runs into some initialization error during startup, such as not being able to connect to its database, is it possible for me to stop the website? This will make it easier for administrators to see that something has gone wrong without checking the log files and would analogous to terminating an application early if the command line parameters are wrong. One more caveat, I can't use Microsoft.Web.Administration.

A: You could raise a specific type of Exception for those fatal errors and handle it on Application_Error.
When those catastrophic events happen and are handled there you could just generate an App_Offline.htm that'll bring the website down without phisically stopping it on IIS.
This will make your website return 503 Service Unavailable which is probably the most semantically correct way of a web service communicating it's down because of a catastrophic event.


text:
Q: Initialize Bootstrap Scrollspy After Removing the Active Class I have bootstrap scrollspy working on load perfectly, however on a mouseover event using Angular, I have some of the navbar content change, and in doing so I remove the active class from the relevant list item. On mouseleave it reverts back, but the active class does not return. How do I properly reinitialize scrollspy so it comes right back, without having to scroll again to retoggle it? I tried the refresh method but it did not work.
My relevant code excerpts:
HTML:

Summer Mill

                    Locations

                          {{headerLink.text}}
                          {{headerLink.alternativeText}}

Angular:
$scope.removeActiveList = function() {
    $(".active").removeClass("active");
  },

  $scope.addActiveList = function() {
    $('body').scrollspy({ target: '#nav' })
  };

If not possible, should I maybe do something different like try to hide the active class and then bring it back depending on the state of isOver ?

A: Well, turns out I solved this by using jquery to create an intermediate class.
$scope.removeActiveList = function() {
        $(".active").addClass("tobeactive");
        $(".active").removeClass("active");
      },

      $scope.addActiveList = function() {
        $(".tobeactive").addClass("active");
        $(".tobeactive").removeClass("tobeactive");
      };