text:
Q: ActionBar with ViewPager - clicking partially visible tab crashes the app I'm using a ViewPager to display 4 different fragments. I use the action bar to display the tabs for the navigation. It looks like that:

My problem is that initially 3 of the tabs are fully visible and the last one is partially visible. Clicking on any of the first 3 tabs is ok but when I click on the last one, the app crashes:
09-06 13:35:01.825: E/AndroidRuntime(6676): FATAL EXCEPTION: main
09-06 13:35:01.825: E/AndroidRuntime(6676): java.lang.IllegalStateException: Content view not yet created
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at com.szymontrapp.englishverbs.DictionaryListFragment.onLoadFinished(DictionaryListFragment.java:200)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at com.szymontrapp.englishverbs.DictionaryListFragment.onLoadFinished(DictionaryListFragment.java:1)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:427)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.support.v4.app.LoaderManagerImpl.initLoader(LoaderManager.java:562)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at com.szymontrapp.englishverbs.DictionaryListFragment.onCreate(DictionaryListFragment.java:94)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.support.v4.app.Fragment.performCreate(Fragment.java:1455)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:893)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:823)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.support.v4.app.Fragment.setUserVisibleHint(Fragment.java:819)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1066)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:550)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:509)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:490)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at com.szymontrapp.englishverbs.DictionaryActivity$4.onTabSelected(DictionaryActivity.java:91)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.support.v7.app.ActionBarImplICS$TabWrapper.onTabSelected(ActionBarImplICS.java:454)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at com.android.internal.app.ActionBarImpl.selectTab(ActionBarImpl.java:587)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at com.android.internal.app.ActionBarImpl$TabImpl.select(ActionBarImpl.java:1084)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at com.android.internal.widget.ScrollingTabContainerView$TabClickListener.onClick(ScrollingTabContainerView.java:532)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.view.View.performClick(View.java:4211)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.view.View$PerformClick.run(View.java:17267)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.os.Handler.handleCallback(Handler.java:615)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.os.Looper.loop(Looper.java:137)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at android.app.ActivityThread.main(ActivityThread.java:4898)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at java.lang.reflect.Method.invokeNative(Native Method)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at java.lang.reflect.Method.invoke(Method.java:511)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
09-06 13:35:01.825: E/AndroidRuntime(6676):     at dalvik.system.NativeStart.main(Native Method)

It seems that somehow the last fragment is not loaded initially. I'm using a custom class extending FragmentPageAdapter and GetItem method is called only for the first 3.
Should I try to force load all 4 fragments initially? Alternatively, how to handle loading of the last fragment properly?
There's quite a lot of code around the view pager and those fragments, I'm not sure how much code will be needed to answer my question. Let me know if I need to post the full code here.

A: Start the Loader in one of the callbacks(like onActivityCreated()) that run after the onCreateView() is called so you make sure that the Loader returning the data very fast doesn't put you in a position where the view of the Fragment is not yet created(the problem in your case).


text:
Q: Xamarin Forms - Units in px, dp, percentage or? What is the unit type used by xamarin forms If i set the width of a label to 50 or size of label to 12, what does that mean in Xamarin Forms? Does it scale on different devices? So will my tekst be bigger on a tablet with size 12 then tekst on a phone with size 12? What about widthrequest and heightrequest?
Hope someone can clear this up.

A: It will be consistent on every device, or theoretically should be consistent on every device. Here is more info about font size. The height request should be consistent on both Android and iOS for the height of a label, although I am not sure what unit it is in. I am gonna assume pixels, but could be wrong.
You can use Device if you want different sizes on different device types.

A: As mentioned in the Xamarin documentation:

These sizes are not pixels. Instead, they are device-independent units recognized independently by each platform.

Check the complete documentation here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is String.split() in Java guaranteed to return an ordered array? I'm writing an application where I'm receiving a message that is a sequence of tag1=value1|tag2=value2|tag3=value3 etc. I want to split it around the | delimiter.
Having read the Javadoc there is nothing to say that the String.split(String regex) method is guaranteed to maintain the original order of the message. I've played about and it seems ok, but I'd rather not commit to this approach if I'm going to get caught out later.
So, does anybody know if there are any situations where the order of array elements returned by split() can be altered from the original String? Or can anyone point out any documentation that says the order is guaranteed to be maintained?
(Apologies if this is a dupe, but I can't find a similar question on the site.)

A: The javadoc says:

The substrings in the array are in the order in which they occur in
  this string.

EDIT: the above is for the two-argument split(String regex, int limit) version, but the single-argument version

works as if by invoking the two-argument split method with the given
  expression and a limit argument of zero.

A: I'm seeing The substrings in the array are in the order in which they occur in this string. in http://docs.oracle.com/javase/7/docs/api/java/lang/String.html...


text:
Q: Flask-Sqlalchemy doesn't work as expected when use filter by Hello I am triying the following querie
record = Record().query.filter(
    Record.id == record_id,
    Record.status.isnot(Status.COMPLETE)
    ).one()
print(record)

status is a str and id is a int
class Status(str, Enum):
    SCHEDULED = 'SCHEDULED'
    RECORDING = 'RECORDING'
    UPLOADING = 'UPLOADING'
    COMPLETE = 'COMPLETE'
    CANCELED = 'CANCELED'
    FAILED = 'FAILED'

@dataclass
class Record(db.Model, TimestampMixin):
    __tablename__ = 'records'
    id: int
    status: Status
    start: int
    time_duration:int
    camera_id: int
    bucket_destination:str
    local_video:str
    fail_type:FailType
    acceptance: int

    id = db.Column(db.Integer, primary_key=True)
    status = db.Column(db.Enum(Status), nullable=False, default=Status.SCHEDULED)
    start = db.Column(db.Integer, nullable=False)
    time_duration = db.Column(db.Integer, nullable=False)
    camera_id = db.Column(db.Integer, db.ForeignKey('cameras.id'), nullable=False)
    fail_type = db.Column(db.Enum(FailType))
    local_video = db.Column(db.String(1000))
    bucket_destination = db.Column(db.String(1000), nullable=False)
    acceptance = db.Column(db.Integer, nullable=False, default=75)

But when executing the queries I get the following error:
sqlalchemy.exc.ProgrammingError: (MySQLdb._exceptions.ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''COMPLETE'' at line 3")
[SQL: SELECT records.created_at AS records_created_at, records.updated_at AS records_updated_at, records.id AS records_id, records.status AS records_status, records.start AS records_start, records.time_duration AS records_time_duration, records.camera_id AS records_camera_id, records.fail_type AS records_fail_type, records.local_video AS records_local_video, records.bucket_destination AS records_bucket_destination, records.acceptance AS records_acceptance
FROM records
WHERE records.id = %s AND records.status IS NOT %s]
[parameters: (1, 'COMPLETE')]

What is the problem?
Thanks

A: sorry to be five months late and also point out something that's pretty minor
in flask-sqlalchemy, you use a singular = when filtering. i know in regular sqlalchemy they use == but i think that's your issue


text:
Q: Will a Modem connected to a UPS (Uninterruptible Power Supply) prevent loss of internet connection during a power outage? If i power the modem (the gateway to the internet) with a UPS, will it prevent loss of internet connection during a power outage? Or is this not possible (I don't know what else needs to be powered on beyond the modem). The case assumes that the ISP also doesn't lose power/runs on a generator when power outage occurs.

A: Yes.  Put your main modem, and main router, and (if possible) your desktop computer all on a decent UPS.
In the event of a power failure, turn off the main computer after about 2 minutes of the failure, and a decent UPS should keep your network going for a couple of hours.
I do precisely as above here in my home office. Laptops have batteries, I turn the Desktop Off, and I have Internet for a couple of hours.
Very workable and having a UPS for this saves a lot of aggravation.

A: Real world data:  Some days ago we had a 2 minute outage.  The modem and router are on the UPS, nothing dropped.


text:
Q: QGIS python processing.runalg Clip returns None I'm writing a script in pyQGIS, which would emulate measurement of a line by "walking" along it with a compass with constant length. I have a problem with the Clip algorythm from processing module, namely it returns None, regardless of whether I add layers as inputs or selected features. What do I do wrong? I believe, that should the clip result in an empty layer, it would still be there, just empty? Below is the piece of code with problems,
while d.measureLine(QgsPoint(coorFin[0],coorFin[1]),QgsPoint(coor[0],coor[1]))>step: # If the distance between current and last point is more than chosen step
    # Create buffer polygon around a point
    bufCirc = point.geometry().buffer(step,10) # do a buffer from existing point
    buforek = QgsFeature()
    buforek.setGeometry(bufCirc)

# Create layer and put the polygon inside
    bufferLayer = QgsVectorLayer("Polygon", "temporary_polygons", "memory")
    pz = bufferLayer.dataProvider()
    bufferLayer.setCrs(my_crs)
    pz.addFeatures([buforek])
    bufferLayer.commitChanges()

# select the buffer
    buforSel = bufferLayer.setSelectedFeatures([buforek])

# Clip coastline with the buffer
    liniaWarstwa = processing.runandload("qgis:clip", selectedCoastLine, buforSel, "memory:liniaWarstwa")
    print liniaWarstwa
    layer = QgsMapLayerRegistry.instance().mapLayersByName("memory:liniaWarstwa")[0]

The print prints "none", QgsMapLayerRegistry says "index out of range".

A: Aside of what Joseph mentioned, there is a number of other things you need to keep in mind when clipping from/to memory, so a little check-list for all of you using processing algorithms and memory layers:

*

*check, that your version of processing plugin is the newest (2.12.2 behaves in a way described by Joseph), update if not.

*Make sure all layers are in the same crs, as is your canvas. Have it explicitly set in code.

*Run your desired algorithm from GUI and check what name does an output have. For example Polish version of QGIS has the output names translated, so I had to put "Przycięte" instead of "Clipped"... Alternatively you can change language to English, which may be safer, to avoid specific characters of your language.

*Have both clip layers loaded onto canvas (use QgsMapLayerRegistry.instance().addMapLayer(layerIHoldInMemory) )

*But the most important part of my solution was: Don't use QGIS versions newer than 2.4. It seems, that there is some sort of problem with processing polygons/lines, it works nicely, but on QGIS 2.2 Valmiera.

A: In the newer versions of the Processing plugin, it would seem that you can no longer define the name of the output memory layer. The name of the algorithm is used instead (see similar post).
Therefore, you should replace the last section of your code with something similar:
# Clip coastline with the buffer
    processing.runandload("qgis:clip", selectedCoastLine, buforSel, None)
    layer = QgsMapLayerRegistry.instance().mapLayersByName("Clipped")[0]


text:
Q: Swift visual delay in text height change I have a main display with a button, and when that button is clicked, it transitions to a second screen.  In that second screen, I have a text label with a colored background that changes depending on the size of the screen using auto layout / constraints.
I am then changing the size of the font in that label relative to the label size using:
LabelName.font = LabelName.text.fontWithSize(LabelName.frame.height)

it works, but there is an issue.  When I put the above line in viewDidLoad, nothing happens...the text remains unchanged.  When I put it in viewDidAppear, it changes, but for a brief moment the original text size shows on the label before changing.
The issue I'm having here is that when I segue onto that screen, I can see the label is always the correct, adjusted size (even during the segue).  It enlarges itself based on the screen size just fine...so since that's always not delayed shouldn't the text size line not be delayed?  I used some output lines and in viewDidAppear the frame for that label is the original size, and in viewDidAppear it is the size it should be without delay.  Yet the text delays.
Only reason I can see is that the auto/layout constraints are adjusted after the view loads but before it appears, and the actual swift code in viewDidAppear is only performed after the view is done seguing and appears completely on the screen.  But I'm not sure if this is true....
Clarification would be appreciated, and even a better way to adjust the text based on label size without direct code would be awesome.  I don't see a simple "Adjust font size to label size" option in the attributes.  Maybe there is and I just haven't picked up on it.  Any way to do it before having to code it directly would be nice, but just a general workaround solution works.  I just don't want to see that little bit of delay.  It's not very smooth or pleasing to see.

A: Your theory is correct.  Auto Layout lays out the views after ViewDidLoad() and you need this to be done before you can adjust your font.  Move you font adjustment code to an override of viewDidLayoutSubviews() which happens after Auto Layout but before the view appears on screen.
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    LabelName.font = LabelName.text.fontWithSize(LabelName.frame.height)
}


text:
Q: canOpenURL: failed for URL: "fbauth2:/" - error: "(null)" Must say this error is driving me nuts and I am at my wits end. I would like to say that I've read through tons of articles on how to fix this error, I've implemented the solutions given, and this error is still here.
Here is some information on what I am using
Facebook iOS sdk v4.7.1
Parse iOS sdk 1.9.1
Xcode Version 7.1.1
Swift 2.1
I have seen all sorts of solutions regarding the plist, i have updated my plist many times over with, to my knowledge, the proper credentials. Here is my entire plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.9.1</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>fb1679166828968529</string>
            </array>
        </dict>
    </array>
    <key>CFBundleVersion</key>
    <string>1.9.1</string>
    <key>FacebookAppID</key>
    <string>1679166828968529</string>
    <key>FacebookDisplayName</key>
    <string>Student Kitchen</string>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>fbapi</string>
        <string>fb-messenger-api</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>
    </array>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>akamaihd.net</key>
            <dict>
                <key>NSExceptionRequiresForwardSecrecy</key>
                <false/>
                <key>NSIncludesSubdomains</key>
                <true/>
            </dict>
            <key>facebook.com</key>
            <dict>
                <key>NSExceptionRequiresForwardSecrecy</key>
                <false/>
                <key>NSIncludesSubdomains</key>
                <true/>
            </dict>
            <key>fbcdn.net</key>
            <dict>
                <key>NSExceptionRequiresForwardSecrecy</key>
                <false/>
                <key>NSIncludesSubdomains</key>
                <true/>
            </dict>
        </dict>
    </dict>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
</dict>
</plist>

I have the proper skds for both Facebook and Parse imported into my project. In both my AppDelegate.swift file and the Viewcontroller.swift file i have imported the following at the top.
import UIKit
import Parse
import ParseFacebookUtilsV4
import FBSDKCoreKit
import FBSDKLoginKit

I have turned bitcode off. I have done everything i've read and this error still persists. Any help would be greatly appreciated.
I also would like to note that i am aware Facebook says this is an error that can be ignored. However this does not apply in my case. I am trying to launch the Facebook login screen to log into my app with, and the simulator starts up and goes to a white screen immediately, it does not switch to the Facebook login because of this error which is why i can't ignore it. I also can not try to run the app on my phone as it is an iPhone 4 and is running iOS 7 and i am trying to ensure this works for iOS 9. Also downgrading versions in either Facebook or parse sdks is not an option.
I have also reset the content and settings of the simulator multiple times.
Thank you in advance to whoever can help, i have seen many people with the same error but no proper solution, and I am sure they will all be grateful as will I.


text:
Q: for loop within a function to write multiple files I'm trying to write a function that will take all images in a file location and apply another function to them (specifically, apply gaussian blur with varying sigma to each image and then write each image to the same location).
require(EBImage)
blurpics=function(pics.location){
  x=list.files(pics.location)
  y=length(x)
  for (i in x)  {
    for (j in y)  {
      blurpic=function(x,y){
      pic=readImage(x)
      pic1=gblur(pic,sigma=16.9)
      pic2=gblur(pic,sigma=15.3)
      pic3=gblur(pic,sigma=13.75)
      pic4=gblur(pic,sigma=12.25)
      pic5=gblur(pic,sigma=10.8)
      pic6=gblur(pic,sigma=9.4)
      pic7=gblur(pic,sigma=8.05)
      pic8=gblur(pic,sigma=6.75)
      pic9=gblur(pic,sigma=5.5)
      pic10=gblur(pic,sigma=4.3)
      pic11=gblur(pic,sigma=3.15)
      pic12=gblur(pic,sigma=2.05)
      pic13=gblur(pic,sigma=1)
      writeImage(pic1,paste(y,"_01.jpg",sep=""),quality=70)
      writeImage(pic2,paste(y,"_02.jpg",sep=""),quality=70)
      writeImage(pic3,paste(y,"_03.jpg",sep=""),quality=70)
      writeImage(pic4,paste(y,"_04.jpg",sep=""),quality=70)
      writeImage(pic5,paste(y,"_05.jpg",sep=""),quality=70)
      writeImage(pic6,paste(y,"_06.jpg",sep=""),quality=70)
      writeImage(pic7,paste(y,"_07.jpg",sep=""),quality=70)
      writeImage(pic8,paste(y,"_08.jpg",sep=""),quality=70)
      writeImage(pic9,paste(y,"_09.jpg",sep=""),quality=70)
      writeImage(pic10,paste(y,"_10.jpg",sep=""),quality=70)
      writeImage(pic11,paste(y,"_11.jpg",sep=""),quality=70)
      writeImage(pic12,paste(y,"_12.jpg",sep=""),quality=70)
      writeImage(pic13,paste(y,"_13.jpg",sep=""),quality=70)
      #}
    }
  }
}

One problem is that the function only works with one image in the file location.--- UPDATE: the logical error was pointed out by baptiste
More importantly, how can I rewrite this function more efficiently so that I dont have to define each pic variable separately?

A: Just on the initial question, what you probably want for this kind of task is lapply() - it takes a list and applies a function to each element. You also, presumably, want to be able to factor the relative gaussian blur levels in, too. For that you'd want a list where each element contains two items; a file name, and a level of blur. So:
#List files
vector_of_file_names <- list.files(pics.location)

#List gaussian blur levels
gaussian_blur <- c(1,2,3,4)

#And now apply!
lapply(vector_of_file_names, function(x){

    #"x" is the filename
    pic <- readImage(x[[1]])

    for(i in seq_along(gaussian_blur)){

        #Apply gaussian blurring.
        pic = gblur(puc, sigma = gaussian_blur[i])

        #Write out
        writeImage(pic, paste(i, "blurred",x, sep = ""), quality = 70)
     }

})

Hope this helps. Generally the answer to "I have nested for-loops" is going to be "have a for loop/apply function running over a list of vectors, rather than a single vector".

A: Moving my solution from the OP: With baptiste's help, here is the solution I was originally seeking, and kudos to Ironholds for the alternative solution:
blurpic=function(pics.location){
 require(EBImage)
  require(tools)
   x=list.files(pics.location)
   sigma=c(16.9,15.3,13.75,12.25,10.8,9.4,8.05,6.75,5.5,4.3,3.15,2.05,1)
   for (i in seq_along(x))  {
     for(j in seq_along(sigma)) {
      pic=readImage(x[i])
      pic1=gblur(pic,sigma=sigma[j])
      #writeImage(pic1,paste(file_path_sans_ext(x[i]),j,".jpg",sep=""),quality=70)
      writeImage(pic1,paste(i,"_",j,".jpg",sep=""),quality=70)
    }
  }
}

Note: I've added two writeImage possibilities for naming according to the original filename or naming by sequence.


text:
Q: Undefined method and bad serialization with delayed job on lion I am getting some odd behavior on a newly set up mac with os x lion.  Our app runs fine in the development environment locally but in the test environment delayed job is not serializing correctly.  On my other machine (snow leopard) everything works fine from the same branch & commit.  Below you will see the job and error.
Any ideas on what would cause this?
BTW, I have no setup_load_paths.rb file.  The solution on a similar question won't work.
#<Delayed::Backend::ActiveRecord::Job:0x007fe3771343b0> {
            :id => 1,
      :priority => 0,
      :attempts => 0,
       :handler => "--- !ruby/struct:Delayed::PerformableMethod \nobject: !ruby/object:Class User\nmethod_name: :update_listed_package_states_for\nargs: \n- 2\n",
    :last_error => nil,
        :run_at => Tue, 02 Aug 2011 13:24:06 UTC +00:00,
     :locked_at => Tue, 02 Aug 2011 13:24:20 UTC +00:00,
     :failed_at => nil,
     :locked_by => "host:typhoon.local pid:84593",
    :created_at => Tue, 02 Aug 2011 13:24:06 UTC +00:00,
    :updated_at => Tue, 02 Aug 2011 13:24:06 UTC +00:00
}
#<NoMethodError: undefined method `update_listed_package_states_for' for #<Class:0x007fe3771118d8>>

A: What ended up fixing this for me was bumping up my gems and then resorting to bundle exec... to run cucumber & rspec.  Never really got to the bottom of the cause but this leads me to believe it was a stray gem being loaded that was causing the trouble.


text:
Q: Modern ui current navigation default expandable Is possible to expand Modern UI current navigation by default despite of clicking arrows icons  to expand it and collapsed it.

A: Currently this is not possible in SharePoint Online Modern experience by using OOTB functionalities.
You can read more about it on SharePoint Tech Community: Can you set the Quick Launch Menu as to default as collapsed with Modern Pages?.
Also, I found one UserVoice suggestion on SharePoint UserVoice, you can vote on it: Left menu/submenu expand and/or collapse default behavior setting.


text:
Q: Add a folder into a workspace by tasks in Visual Studio Code Is there a way to add a folder into a workspace by tasks?
Is it possible to add and remove (or hide) folders in a workspace on selecting options from input in tasks.json?
{
    "version": "2.0.0",
    "inputs": [
        {
            "id": "selectProject",
            "type": "pickString",
            "description": "Some decription",
            "options":
            [
               "PROJECT1",
               "PROJECT2"
            ]
        }
    ],
    "tasks": [
        {
            "label": "add into workspace",
            "type": "process",
            "command": "command-to-add-folder-into-workspace", // what do I need to put here?
            "args": [
                "${input:selectProject}"
            ]
        }
    ]
}

A: I've found a solution using code --add folder in tasks.
File .code-workspace
{
    "folders": [
        {
            "name": "wp",
            "path": "../wp" // folder has .code-workspace file
        }
    ],
    "settings": { /*...*/ },
    "tasks": {
        "inputs":[
                {
                    "id": "selectProject",
                    "type": "pickString",
                    "description": "select project",
                    "options":
                    [
                        "PROJECT1",
                           "PROJECT2"
                    ]
                }
        ],
        "version": "2.0.0",
        "tasks": [
            {
                "label": "Add project",
                "type": "shell",
                "command": "code", // usind command code --add folder
                "options": {
                    "cwd": "${workspaceFolder}"
                },
                "args": [
                    "--add",
                    "../${input:selectTest}"
                ],
                "presentation": {
                    "echo": false,
                    "reveal": "always",
                    "clear": false,
                    "showReuseMessage": false
                }
            }
        ]
    }
}


text:
Q: Set permissions for different namespaces in Azure DevOps using Rest API How can I use RestAPI to set permissions for Build definitions, Release definitions, git repo and team securities? When I was using TFS, I was able to do this using Tfsssecurity.exe tool.
Edited.
For example, I am trying to modify the project permissions of Contributors group. like Allow Contributors to rename team project etc.
enter image description here

A: Are you looking for the Security API page?
You probably need to manage group membership using Graph API.
The Get started page lists the libraries you can use and how to authenticate.

A: There isn't the REST API to change permission of release definition and git repo. Other contributors submit a user voice that you can vote Set version control permissions by REST API
For details,please refer to these links:
VSTS REST API to change security permissions on Release definition or Release definition environment
Use VSTS Rest API to set git repo permissions
Hope this helps.


text:
Q: Object Equality and Value Equality in javascript I am not able to understand how does javascript handles object equality.
Please can anybody explain me the below output?
1. var x = 3;
 2. var y = 3;
 3. var obj1 = {};
 4. var obj2 = {};
 5. var obj3 = obj1;
 6. x == y
 7. x === y
 8. obj1 == obj2
 9. obj1 === obj2
10. obj1 == obj3
11. obj1 === obj3

Output:

*true

*true

*false

*false

*true

*true

A: When you compare objects using either == or ===, the comparison is only true if the objects are the same object, not merely identically-constructed objects, but the very same object.
If you want to compare objects for whether they are identically constructed, you might want to look into something like LoDash: https://lodash.com/docs/4.17.5
Particular relevant here is the _.isEqual() function: https://lodash.com/docs/4.17.5#isEqual


text:
Q: Visual C# method calls using too much memory? I'm writing a game using the XNA 4.0 framework. I've written a set of methods that translates the 2D mouse coordinates to a line in the 3d world, then checks to see if that line intersects a plane, and if the intersection point is within the bounds of a face in that plane.
The math works, but for some reason when I do these calculations over 500 times a frame it brings the program to a halt. I can watch the memory usage climb from starting at 15 MB to about 130 MB before garbage collection decides to clean things up. I know specifically it is in this code because when I comment it out, everything else runs smoothly.
I'll paste my code below, any insight would be helpful and thank you!
The Loop:
            GraphicObject me = new GraphicObject();
            Intersection intersect;
            double? dist = null;

            foreach (GraphicObject obj in GraphicObjects)
            {
                intersect = obj.intersectMe(line);
                if (intersect.Distance != null)
                {
                    if (intersect.Distance < dist || dist == null)
                    {
                        dist = intersect.Distance;
                        me = obj;
                    }
                    else
                    {
                        obj.Highlight(false);
                    }
                }
                else
                {
                    obj.Highlight(false);
                }
            }

            if (dist != null)
            {
                me.Highlight(true);
            }

intersectMe:
    public override Intersection intersectMe(Ray _line)
    {
        GraphicHelper.Intersects(_line, rect.Vertices[0].Normal, rect.Vertices[0].Position, intersect);

        if (intersect.Distance != null)
        {
            if (!rect.PointOnMe(intersect.X - position.X, intersect.Y - position.Y, intersect.Z - position.Z))
            {
                intersect.Distance = null;
            }
        }

        return intersect;
    }

GraphicsHelper.Intersects:
    // _l = line, _n = normal to plane, _p = point on the plane
    public static void Intersects(Ray _l, Vector3 _n, Vector3 _p, Intersection _i)
    {
        _i.Distance = null;

        float num = (_n.X * (_p.X - _l.Position.X) + _n.Y * (_p.Y - _l.Position.Y) + _n.Z * (_p.Z - _l.Position.Z));

        float denom = (_n.X * _l.Direction.X + _n.Y * _l.Direction.Y + _n.Z * _l.Direction.Z);

        if (denom != 0 && num != 0)
        {
            float t = num / denom;

            if (t > 0)
            {
                _i.X = _l.Position.X + _l.Direction.X * t;
                _i.Y = _l.Position.Y + _l.Direction.Y * t;
                _i.Z = _l.Position.Z + _l.Direction.Z * t;

                _i.Distance = _i.X * _i.X + _i.Y * _i.Y + _i.Z * _i.Z;
            }
        }
    }

PointOnMe:
    public bool PointOnMe(float _x, float _y, float _z)
    {
        float ex = _x - Vertices[3].Position.X;
        float ey = _y - Vertices[3].Position.Y;
        float ez = _z - Vertices[3].Position.Z;

        float ae = a.X * ex + a.Y * ey + a.Z * ez;
        float be = b.X * ex + b.Y * ey + b.Z * ez;

        ex = _x - Vertices[1].Position.X;
        ey = _y - Vertices[1].Position.Y;
        ez = _z - Vertices[1].Position.Z;

        float ce = c.X * ex + c.Y * ex + c.Z * ez;
        float de = d.X * ex + d.Y * ey + d.Z * ez;

        if (ae > 0 && be > 0 && ce > 0 && de > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

A: Thank you all for taking some time to look at this for me. The error was actually in how I handle obj.Highlight(), TaW's kick in the butt to get a profiler setup helped me to figure that out.
    public override void Highlight(bool toggle)
    {
        if(toggle)
        {
            rect.Texture = new Texture2D(GraphicsManager.Graphics.GraphicsDevice, 1, 1);
            rect.Texture.SetData<Color>(new Color[] { Color.Yellow });
        }
        else
        {
            rect.Texture = new Texture2D(GraphicsManager.Graphics.GraphicsDevice, 1, 1);
            rect.Texture.SetData<Color>(new Color[] { squareColor });
        }
    }

Every frame all the obj's were having new textures generated. A terrible way to do things.


text:
Q: How do I add an Image/media field in Sitefinity? I am using mvc, and I have created a controller for the custom widget which will allow the user to choose the image that they watn displayed. How do I specify this field?
I have:
public class Test: Controller
    {
        public ImageSelector Image { get; set; }
}

A: You need the so called custom designer for your MVC widget.
Check this article for all the steps/details you need:
https://www.progress.com/documentation/sitefinity-cms/image-selector-mvc
UPDATE: Here is Github Gist with working code:
https://gist.github.com/VesselinVassilev/31b159a1985f272e85b4ff167e59c8d8
Note: the DemoController.cs file should be in the /mvc/controllers folder
the rest of the files should go to the /mvc/views/demo/ folder.


text:
Q: horizontally fill background color after div to end of screen I have an rtl react app. It means,

*

*any element I create is filled from right to left.

*to apply style to the left side of a div I have to use after selector, instead of before.

I want 2 partially overlapped divs, in which I can set a background color from the end of the second div, to the end of the screen. sth like this:

I've already done it, using these codes:
html:
<Grid container xs={12} lg={9} css={styles.grid}>

item 1

item 2

</Grid>

css:
  grid: css`
    display: grid;
    grid-template-columns: repeat(13, 1fr);
    margin: 0 auto;
  `,
  item1: css`
    min-height: 300px;
    grid-column: 1 / 8;
    background-color: #00ff5560;
    grid-row: 1/2;
  `,
  item2: css`
    position: relative;
    background-size: cover;
    grid-column: 7 / -1;
    grid-row: 1/2;
      background-color: #0365f260;
      &:after {
      content: "";
      position: absolute;
      top: 0;
      left: 100%;
      display: block;
      width: 100vw;
      height: 100%;
      background-color: #0365f2;
    }
  `

The problem is that, it makes my screen, bigger than it's real size, so it becomes scrollable horizontally:

Can you please help me to figure out how to fix it?


text:
Q: Inserting Norwegian letters into SQLite db through java program I'm trying to fill an SQLite database with data in my java program.
The data is read from an excel file using Apache POI. I have no trouble inserting the data into the db using normal methods.
However, when I check the database manually with the shell, all the Norwegian characters æ,ø,å are not displayed correctly. Whenever I fill out the database manually through the shell, they are displayed as they should.
Also, when printing out a java string in console containing these characters, they are displayed correctly.
The problem must occur when an action like this is performed:
String sql = "insert into db(name) values (æøå)";
stmt.executeUpdate(sql);

I have tried
byte[] b = sql.getBytes("utf-8");
sql = new String(b, "utf-8");

to no avail.
Any idea how to remedy the situation?
Thanks!

A: There is a very simple solution for you: Let Java and the SQLite driver do everything for you. You don't have to care about encodings and escaping of parameters.
How that is possible: Use a PreparedStatement:
String name = "æøå"
PreparedStatement prepStmt = conn.prepareStatement("insert into db(name) values (?)");
prepStmt.setString(1, name);
prepStmt.executeUpdate();

Furthermore this code fragment is secure against SQL injection attacks.
BTW: The second code fragment you posted is totally useless, it does nothing. Converting a String to byte[] and back to String does not change a single bit of the String.


text:
Q: CSS Grid No Longer Responsive I Have a project using CSS Grid and it was originally responsive, but isn't now.  When I use the developer tools, I can see they are symmetrically overflowing out of the grid.  I will attach the image.
Basically, I need to see how to make it responsive again.

This is using Ruby/Rails, but I hope its more of a general CSS question
my index.html.erb

Our Products

  <% if @products.any? %>

    <%= render "products/product-card" %>

  <% else %>

There are no products yet.

  <% end %>

  <% if current_user && current_user.admin %>

Admin Only

<%= link_to "Create new product", new_product_path %>

  <% end %>

  <%= will_paginate @products %>

The product card html.erb its rendering, above
    <% @products.each do |product| %>

<%= link_to product.name, product_path(product) %>

    <div class="stars" style="--rating: <%= product.average_review %>;" aria-label="Rating of this product is " <%= product.average_review %> " out of 5.">

$<%= product.price %>

Imported From <%= product.country  %>

    <% if product.product_photo.attached? %>
      <%= image_tag product.product_photo, class:"card-image" %>
      <% else %>
      <%= image_tag 'image_not_available.webp', class:"card-image-not-found", alt: 'Image Not Found ' %>
    <% end %>

<% end %>

My css, which I think is where the problem really lies:
    /*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
 * vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 */

//  app/assets/fonts/SnellRoundhandScriptV1.woff

// Custom Boostratp Variables must be imported before bootstrap
@import "bootstrap";

// custom Stylesheet Import links

// General Text Styles

@font-face {
  font-family:'SnellRoundhand';
  src: font-url('SnellRoundhandScriptV1.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@mixin headings {
  h1, h2, h3,
  h4, h5, h6 {
      @content;
  }
}

@include headings {
  font-family: 'SnellRoundhand';
}

a {
  color: #000000;
}

a span {
  color: #000000;
}

.center {
  text-align: center;
}

.flash {
  display: inline-block;
  background: #f9f8ea;
}

.flash-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
}

// Header styles

.header-container {
  position: relative;
}

.header-image {
  padding: 5px;
  border-radius: 10px;
  display: block;
  margin-left: auto;
  margin-right: auto;
  min-width: 400px;
  width: 100%;
  height: 400px;
  object-fit: cover;
  opacity: 0.35;
}

.header-top-left {
  position: absolute;
  padding-bottom: 100px;
  top: 34px;
  left: 16px;
  font-size: 6vw;
  line-height: 65px;
  min-width: 400px;
  font-family: 'SnellRoundhand', cursive;
}
.authentication-text {
  display: inline-block;
}

.authentication-position {
  position: absolute;
  top: 15px;
  right: 10px;
}

// Avatars

.avatar-tiny {
  width: 24px;
  height: 24px;
  padding: 1px;
  border-radius: 5px;
  object-fit: cover;
}

.avatar {
  width: 100px;
  height: 100px;
  padding: 1px;
  border-radius: 25px;
  object-fit: cover;
}

// non-card product images

.product-image {
  height: 100px;
  padding: 1px;
  border-radius: 10px;
  object-fit: cover;
}

// Footer Styles

// Navbar Styles

@media only screen and (max-width: 480px) {
  .hidden-xs-hover {
    visibility: hidden;
  }
}

// Home Page Styles

.welcome-sub-header {
  text-align: center;
}

.welcome-sub-header > h1 {
  font-size: 50px;
}

.welcome-sub-header > h4 {
  font-size: 30px;
  color: rgba(37, 37, 37, 0.416);
}

// UL to cards

.products {
  display: grid;
  // grid-template-columns: repeat(auto-fill, minmax(375px, 1fr));
  grid-template-columns: repeat(3, minmax(auto, 1fr));
  grid-gap: 10px;
  align-items: center;
  justify-content: center;
  // min-width: 375px;
  // min-height: 415px;

  & > h2 {
    grid-column: 1 / -1;
  }

  & > ul {
    list-style-type: none;
  }

  & > ul > li {
    font-family: 'SnellRoundhand';
    border: 1px solid #ccc;
    border-radius: .3rem;
  }

}

.card {
  // position: relative;
  padding: 10px;
  width: 375px;
  height: 415px;
  background-color: white;
  padding: 0% 0% 0% 0%;
  padding-bottom: 1px;
  border-radius: 5px;
  border: 1.5px solid #CBCBCB;
  border-top: 3px solid #419234;
  text-align: center;
  overflow: hidden;
  // min-width: none;
}

.card-image {
  padding: 1px;
  border-radius: 5px;
  width: 373px;
  height: 100%;
  object-fit: cover;
}

.card-image-not-found {
  padding: 1px;
  width: 200px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.card-image-not-found-sm {
  padding: 1px;
  height: 100px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

// Product Page Styles

.centered-header {
  text-align: center;
}

// User Forms

.user-form-grid-container {
  padding: 2rem;
  display: grid;
  grid-template-columns: auto;
  grid-template-rows: auto;
  grid-template-areas:
    "left-col right-col";
  // grid-template-columns: 1fr 1fr;
  grid-gap: 1rem;
}

.form-col-2 {
  grid-area: left-col;
  border: 1px;
}

.form-col-1 {
  grid-area: right-col;
  border: 1px;
}

// Reviews Styles

.reviews-container {
  white-space: nowrap;
}

.reviews-ul {
  list-style-type: none;
}

.reviews-li {
  display: inline-block;
}

.review-card {
  width: 500px;
  height: 100ps;
  border: 1px;
}

// Will Paginate Styling

.pagination {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width:fit-content;
  background: white;
  cursor: default;
  /* self-clearing method: */ }
  .pagination a, .pagination span, .pagination em {
    padding: 0.2em 0.5em;
    display: block;
    float: left;
    margin-right: 1px; }
  .pagination .disabled {
    color: #999999;
    border: 1px solid #dddddd; }
  .pagination .current {
    font-style: normal;
    font-weight: bold;
    background: #419234;
    color: white;
    border: 1px solid #419234; }
  .pagination a {
    text-decoration: none;
    color: #288a40;
    border: 1px solid #4d8647; }
    .pagination a:hover, .pagination a:focus {
      color: #152519;
      border-color: #152519; }
  .pagination .page_info {
    background: #419234;
    color: white;
    padding: 0.4em 0.6em;
    width: 22em;
    margin-bottom: 0.3em;
    text-align: center; }
    .pagination .page_info b {
      color: #152519;
      background: #4d8647;
      padding: 0.1em 0.25em; }
  .pagination:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden; }
  * html .pagination {
    height: 1%; }
  *:first-child + html .pagination {
    overflow: hidden;
}

// Star Rating

.rating {
  display: flex;
  flex-direction: row-reverse;
  justify-content: left;
}

.rating>input {
  display: none
}

.rating>label {
  position: relative;
  width: 1em;
  font-size: 6vw;
  color: #FFD600;
  cursor: pointer
}

.rating>label::before {
  content: "\2605";
  position: absolute;
  opacity: 0
}

.rating>label:hover:before,
.rating>label:hover~label:before {
  opacity: 1 !important
}

.rating>input:checked~label:before {
  opacity: 1
}

.rating:hover>input:checked~label:before {
  opacity: 0.4
}

// Partial Start Rating Average

:root {
  --star-size: 30px;
  --star-color: #fff;
  --star-background: #fc0;
}

.stars {
  --percent: calc(var(--rating) / 5 * 100%);

  display: inline-block;
  font-size: var(--star-size);
  font-family: Times; // make sure ★ appears correctly
  line-height: 1;

  &::before {
    content: '★★★★★';
    letter-spacing: 3px;
    background: linear-gradient(90deg, var(--star-background) var(--percent), var(--star-color) var(--percent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }
}


text:
Q: Projective Modules, Definition and Etymology Question that I have after reading some of the answers to this question about the etymology of projective modules. It goes as follows:
Let $P$ be an $R$-module, $R$ being some arbitrary ring. Is it the case that if there exists a free $R$-module $M$ such that $P$ is isomorphic to a submodule $P'$ of $M$, and a surjective map $f: M \rightarrow P'$ such that $f^2 = f$, then $P$ is necessarily a projective $R$-module?
EDIT: I have come to learn that this indeed is the case, though I still could very much use a formal proof.

A: Yes, although you need to phrase it differently.  Note that in order for "$f^2=f$" to even make sense, $f$ has to be a self-map.  So, rephrasing your question, is it the case that given $P$ as submodule of a free module $M$ and a map $f:M\to M$ such that $f(M)=P$ and $f^2=f$, then $P$ is a projective module?
The only way we can have $f^2=f$ is if $f$ is the identity on $P$, since suppose $z=f(y)$, then $f(z)=f^2(y)=f(y)=z$.  So $f$ is the identity on $P$, so the inclusion map splits the exact sequence $0\to \ker(f) \to M \to P \to 0$


text:
Q: Laravel 5.3 SQL Server Migration error I have a migration error with accessing a sql server using laravel 5.3.
*Using Windows 10 with WAMP, also need to point out that I have the necessary php extensions:

*

*php_pdo_sqlsrv_7_ts_x86

*php_sqlsrv_7_ts_x86

I dumped some data from the database in my view, meaning i have access to the database tables, but I cannot run migration commands. I finally found this article that can help me but the problem is that I am not familiar with SQL servers.. https://github.com/laravel/framework/issues/15841
The error when i run a migrate command in image below

I have done some reading and I know that sysobjects is like the main table that houses all information about the database.. and after reading the article i am i found the SQLGrammer class but I am still not sure what i am doing.. Can anyone help?
This is my .env

A: Do you have the pdo_mysql.so extension? Make sure it is enabled using phpinfo()
Be sure to configure the DEFAULT key in app/config/database.php and in .env file.
Make sure mysql is installed:
sudo apt-get install php5-mysql
sudo apt-get install php-mysql

If nothing works, it would be nice if you show us how your
app/config/database.php looks like and your .env.

A: Have you added the sqlsrv config to the connections array in config/database.php?
Since you've added the connections settings in your .env, it should have an entry after mysql / psql etc. similar to this:
'sqlsrv' => [
   'driver' => 'sqlsrv',
   'host' => env('DB_HOST', 'localhost'),
   'port' => env('DB_PORT', '3306'),
   'database' => env('DB_DATABASE', 'database'),
   'username' => env('DB_USERNAME', 'root'),
   'password' => env('DB_PASSWORD', ''),
   'prefix' => '',
],

You also have to specify the default connection in config/database.php:
'default' => env('DB_CONNECTION', 'sqlsrv'),

A: Thank you @Matt Gibson in the comments, for giving me this link. I just copied the SQL Server driver installed extensions in the 2 PHP.ini file, the 1 in apache and the other in PHP thanks a lot!!
php.ini - command line PHP and WAMP server access different files


text:
Q: Beginner Hardware development guides I'm looking to get started with Arduino and I wanted to know any good books out there. Any help would be appreciated

A: What is your experience level? What types of hardware?
I would probably put "Making Things Talk" close to the top of
the list.
Depending on your experience some general electronics books
like "The Art of Electronics" and "CMOS Cookbook". An
excellent free resource is http://www.allaboutcircuits.com

A: "Getting Started with Arduino" by Massimo Banzi, then
"Practical Arduino" by Jon Oxer and Hugh Blemings

A: Make: Arduino Bots and Gadgets

Arduino: A Quick-Start Guide by Maik Schmidt

A: This is a very good book for complete beginners:
Joe sent me a copy to see what I thought of it.
It's also available with a hardware kit.

A: The question of how best to get started with Arduino is an important topic. Before recommending books, let me suggest a three step approach:
1) Talk with the community. Since you posted here, you are already doing this step.
2) Get your hands dirty as soon as possible, and keep them dirty. Build kits - they allow you to make something cool without understanding all the parts, so you can focus on learning a particular aspect. As you get better, modify kits.
3) Read books and blogs. There is a lot out there for free, and you will soon be spending more than you intended on your new hobby :)
Books to start with is a very active topic on the Arduino News forum. (arduino.cc)
That discussion suggests http://earthshinedesign.co.uk, (go to bottom left, External Links, top link, "The complete Beginners Guide ...") which is a free download. I would suggest trying that.
I tried Getting started with Arduino, and found it OK, but "meh". There is better stuff nowadays. Making Things Talk is well worth the money and pretty basic, but not for complete beginners.

A: Forrest Mims' books on electronics are great for understanding the basics. For the digital stuff, I find the internet (Google, AVR Freaks, this site, Arduino forums) and the datasheet for your microcontroller to be the best guides.


text:
Q: Can I add IF clause to TRY & EXCEPT clause Please pardon me if I make any formatting issues here!
I am creating 2 variables, namely the mean and variance. Still working on the "variance" variable so please ignore that part.
Here's the background:
The mean and variance are int inputs. The mean can be of any value, on the other hand, the variance will need to be of value greater than 1. And whenever, the input prompts, and the users hit enter straightaway (without any inputs), the mean and variance will be 0 and 1 respectively.
I have attempted the question and want to integrate both the TRY & EXCEPT clause with the IF clause because to check of ValueError and to automatically stop the program if the users hit enter without any values...
I am not sure if this is doable, can anyone advise, please... Many thanks!
Here's my code:
mean = 0
variance = 1

valid_input = False
while valid_input == False:
    try:
        mean = int(input("Please enter the mean value: "))
        if mean == "":
            valid_input = True
            break
    except ValueError:
        print("Please enter a numeric value!")
    else:
        valid_input = True
print (mean, variance)

A: mean = 0
variance = 1
mean = input("Please enter the mean value: ")
try:
    mean = int(mean)
    print (mean, variance)
except ValueError:
    print("Please enter a numeric value!")

This works. If the input is not an int, Please enter a numeric value is printed and the program exits.
Or you can use the following code to determine if the user input is an integer, and if it is, you can convert it to int. You won't need the try-except block now. Ref
import re
# read value from keyboard
value = input("Enter a string\n")
# match the entered value to be a number
result = re.match("[-+]?\d+$", value)
# check if there was a match
if result is not None:
    print("Entered string is an integer")
    print(int(value))
else:
    # entered value contains letters also
    print("Entered string is not an integer")


text:
Q: Adding additional UITabbarItem to UITabbarController I am wondering if there is a way to add an additional UITabBarItem to my exisiting UITabBarController. It doesn't need to be in runtime.
All I want to do is when hitting this button I want to presentModalViewController: over my actually visible ViewController, which should either be the TabBarController or its controllers.
Hopefully this is clear enough, if not, feel free to ask.

A: As a result of my research you cannot add a UITabBarItem to a UITabBar that is managed by a UITabBarController.
Since you maybe have added your UITabBarItem by adding a list of view controller, this is also the way of your choice to add further custom UITabBarItems, as i will show now:
Pre-Conditions:
As i mentioned before, you maybe have added your UITabBarItems by adding a list of view controller:
tabbarController = [[UITabBarController alloc] init]; // tabbarController has to be defined in your header file

FirstViewController *vc1 = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:[NSBundle mainBundle]];
vc1.tabBarItem.title = @"First View Controller"; // Let the controller manage the UITabBarItem

SecondViewController *vc2 = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:[NSBundle mainBundle]];
vc2.tabBarItem.title = @"Second View Controller";

[tabbarController setViewControllers:[NSArray arrayWithObjects: vc1, vc2, nil]];

tabbarController.delegate = self; // do not forget to delegate events to our appdelegate

Adding custom UITabBarItems:
Now since you know how to add UITabBarItems through adding view controller, you can also use the same way to add custom UITabBarItems:
UIViewController *tmpController = [[UIViewController alloc] init];
tmpController.tabBarItem.title = @"Custom TabBar Item";
// You could also add your custom image:
// tmpController.tabBarItem.image = [UIImage alloc];
// Define a custom tag (integers or enums only), so you can identify when it gets tapped:
tmpController.tabBarItem.tag = 1;

Modify the line above:
[tabbarController setViewControllers:[NSArray arrayWithObjects: vc1, vc2, tmpController, nil]];

[tmpController release]; // do not forget to release the tmpController after adding to the list

All fine, now you have your custom button in your TabBar.
What about handling events of this custom UITabBarItem?
Its easy, look:
Add the UITabBarControllerDelegate to your AppDelegate class (or the class which is holding the tabbarController).
@interface YourAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> { }

Fit the protocol definition by adding this function:
- (void)tabBarController:(UITabBarController *)theTabBarController didSelectViewController:(UIViewController *)viewController {
  NSUInteger indexOfTab = [theTabBarController.viewControllers indexOfObject:viewController];

  UITabBarItem *item = [theTabBarController.tabBar.items objectAtIndex:indexOfTab];
  NSLog(@"Tab index = %u (%u), itemtag: %d", indexOfTab, item.tag);
  switch (item.tag) {
    case 1:
      // Do your stuff
      break;

    default:
      break;
  }
}

Now you have all you need to create and handle custom UITabBarItems.
Hope this helps.
Have fun....

A: Access the tabBar - property of your UITabBarController (reference), grab the elements array with the items - property (reference), add a new UITabBarItem to this array and use the tabBar's setItems:animated: - method to update your tab bar. Add an action to this tab bar to  display the modal view controller.


text:
Q: ComboBoxStyle QML QT Label not working I'm trying to customize the label on a combobox, but it doesn't seem to be working, I have the following code:
  ComboBox {
    id:tableName
    editable: true
    currentIndex: 0
    model: eventModel.getTables()
    anchors.left: parent.left; anchors.leftMargin: 20
    y: parent.height/10
    width: buttonWidth
    height: 70
    style: ComboBoxStyle {
        id:comboStyle
        background: Rectangle {
            id: rectCategory
            width: control.width
            height: control.height
            color: "#FFECECEC"
            Text {
                anchors.verticalCenter: parent.verticalCenter
                anchors.right: parent.right
                anchors.rightMargin: 2
                font.pointSize: 15
                font.family: "sans serif"
                color: control.hovered?"#FF6BC1E5":"#FF404040"
                text:"˅"
            }
        }

        label: Label{
                Rectangle{anchors.fill: tableName; color:"red"}
                anchors.right: parent.right
                anchors.rightMargin:10
                font.pointSize: 12
                font.family: "sans serif"
                color: "black"
                text:control.currentText
        }

        // drop-down customization here
        property Component __dropDownStyle: MenuStyle {
            __maxPopupHeight: 600

            __menuItemType: "comboboxitem"

            frame: Rectangle {              // background
                color: "#FFACACAC"
            }

            itemDelegate.label: Text {
                verticalAlignment: Text.AlignVCenter
                horizontalAlignment: Text.AlignHCenter
                font.pointSize: 12
                font.family: "sans serif"
                color: styleData.selected ?  "#FF6BC1E5" : "#FF404040"
                text: styleData.text
            }

            itemDelegate.background: Rectangle {  // selection of an item
                color: styleData.selected ?  "#FF404040" : "#FFECECEC"
            }

            __scrollerStyle: ScrollViewStyle { }
        }

    }

the dropdown customization seems to work pretty fine, but the label stays the same, this is the output I get:

thanks to jpnurmi, I found a style that worked:
ComboBoxStyle {
        id:comboStyle
        textColor:"blue"
        font{
            pointSize:15
            family:"sans serif"
        }

        background: Rectangle {
            id: rectCategory
            width: control.width
            height: control.height
            color: "#FFECECEC"

            Image {
                anchors.verticalCenter: parent.verticalCenter
                anchors.right: parent.right
                anchors.rightMargin: 5
                source:control.hovered?"images/select2.png":
                                        "images/select.png"
            }
        }

        __editor:
            Rectangle {
            anchors.fill: parent
            color: "#00000000"
        }

        // drop-down customization here
        property Component __dropDownStyle: MenuStyle {
            __maxPopupHeight: 600

            __menuItemType: "comboboxitem"

            frame: Rectangle {              // background
                color: "#FFACACAC"
            }
            itemDelegate.label: Text {
                verticalAlignment: Text.AlignVCenter
                horizontalAlignment: Text.AlignHCenter
                font.pointSize: 12
                font.family: "sans serif"
                color: styleData.selected ?  "#FF6BC1E5" : "#FF404040"
                text: styleData.text
            }
            itemDelegate.background: Rectangle {  // selection of an item
                color: styleData.selected ?  "#FF404040" : "#FFECECEC"
            }
            __scrollerStyle: ScrollViewStyle { }
        }

    }

A: The read-only label is for a non-editable ComboBox. Try this:
    style: ComboBoxStyle {
        font.pointSize: 12
        font.family: "sans serif"
        textColor: "black"
        background: Rectangle {
            ...
        }

        __editor: Rectangle {
            color: "red"
        }

        ...
    }


text:
Q: Rails endpoint for ajax request using json I want to build a endpoint that will accept an ajax request, update a record associated with that request, then create a new object based on the updated record and send it back to the client to be used.
def tested
     @prime = PrimeNumber.where(testNumber: id).first
     @prime.update_attributes(prime_params)

     next = PrimeNumber.where(wasTested: false).first
    if next != nil
        @toTest = needWork

    else
        lastNum =  PrimeNumber.last.testNumber
        nextNum = lastNum + 1
        newNum = PrimeNumber.new
        newNum.testNumber = nextNum
        newNum.wasTested = false
        newNum.isPrime = false
        newNum.save
        @toTest = PrimeNumber.last
    end
end

 private
    def prime_params
        params.require(:prime_number).permit(:testNumber, :isPrime, :wasTested, :id)
    end

everything worked when I was just using post and then reloading the view however i do not need to render any views or partial views. Ideally I would like to be able to send information back and forth in the background of my web app without it making any visible changes.

A: You can easily adapt your current method tested to return a JSON response if there is an AJAX request.
Just add something like this to the end of your code:
def tested
    // ...
    if request.xhr?
        render :json => @prime
    end
end

@prime would be returned as JSON.
And then in your view, change it so the request is done by AJAX (perhaps by setting remote: true on the form helper, depends on how you do things).
See this guide for details: Working with JavaScript in Rails

A: You can use 'remote: true' in your form_for tag, which makes it ajax request.
and In response you can create tested.js.erb file in your views.
In tested.js.erb you have @prime accessible and you can use it anywhere, append that in the table without reloading the page.
This link is going to be helpful for you.
http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html


text:
Q: On Windows paperclip uses "file" command in Ruby Devkit, but gives error "Errno::EEXIST in ArticlesController#create" On Ubuntu paperclip file upload works with builtin file command. On Windows I did both install Ruby Devkit or file.exe in PATH variable: None of this helps! I get:
File exists @ sys_fail2 - C:/Users/Lap127/AppData/Local/Temp/3e26e8e7aa5f147d0c6c7ae71efc007220170215-7312-1bv14wq.txt
Extracted source (around line #24):

def create
  @article = Article.new(article_params) #line 24 here

  if @article.save
    redirect_to @article

How do I upload attachments with paperclip on windows without getting error, that the new file already exists?

A: Ran into a similar issue with this before, and it took a bit of searching, but here's where the problem was for tempfiles and Ruby on Windows.
C:\<path_to_ruby_file>\lib\ruby\<version>\tempfile.rb
Based on this post: https://www.ruby-forum.com/topic/187311
Our team was able to find the problem.
While they have a solution, we ended up writing our own.
You want (~Line 204):
def unlink
  #----ADDED THIS LINE---#
  return if @unlinked
  #-----END ADDED LINE----#
  begin
    File.unlink(@tmpfile.path)
  rescue Errno::ENOENT
  rescue Errno::EACCES
    # may not be able to unlink on Windows; just ignore
    return
  end
  ObjectSpace.undefine_finalizer(self)
  @unlinked = true
end
alias delete unlink

If you are still getting this error, let me know! Additionally, if you could check that the content of the tempfile is what you expect, that might be useful.


text:
Q: How to pass django authtoken using ajax How to pass djangorest authtoken from AJAX request
I tried following code.but not working
$({
    type: 'POST',
    url: 'menu/menu/,
    beforeSend: function (request) {
        request.setRequestHeader("Authorization ", "Token " + token);
    },
});

A: Try serialize your authtoken
$.ajax({
        type: "POST",
        url: "/menu/menu/",
        data: JSON.stringify(data),
        sucess: function() { //do something },
        contentType: "application/json; charset=utf-8",
        //content type: application/x-www-form-urlencoded; charset=UTF-8
        dataType: "json",
        crossDomain:false,
        beforeSend: function(xhr, settings) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    });


text:
Q: Self-referential URLs What's the most reliable, generic way to construct a self-referential URL? In other words, I want to generate the http://www.site.com[:port] portion of the URL that the user's browser is hitting. I'm using PHP running under Apache.
A few complications:

*

*Relying on $_SERVER["HTTP_HOST"] is dangerous, because that seems to come straight from the HTTP Host header, which someone can forge.

*There may or may not be virtual hosts.

*There may be a port specified using Apache's Port directive, but that might not be the port that the user specified, if it's behind a load-balancer or proxy.

*The port may not actually be part of the URL. For example, 80 and 443 are usually omitted.

*PHP's $_SERVER["HTTPS"] doesn't always give a reliable value, especially if you're behind a load-balancer or proxy.

*Apache has a UseCanonicalName directive, which affects the values of the SERVER_NAME and SERVER_PORT environment variables. We can assume this is turned on, if that helps.

A: As I recall, you want to do something like this:
$protocol = 'http';

if ( (!empty($_SERVER['HTTPS'])) || ($_SERVER['HTTPS'] == 'off') ) {
    $protocol = 'https';
    if ($_SERVER['SERVER_PORT'] != 443)
        $port = $_SERVER['SERVER_PORT'];
} else if ($_SERVER['SERVER_PORT'] != 80) {
    $port = $_SERVER['SERVER_PORT'];
}
// Server name is going to be whatever the virtual host name is set to in your configuration
$address = $protocol . '://' . $_SERVER['SERVER_NAME'];
if (!empty($port))
    $address .= ':' . $port
$address .= $_SERVER['REQUEST_URI'];
// Optional, if you want the query string intact
if (!empty($_SERVER['QUERY_STRING']))
    $address .= '?' . $_SERVER['QUERY_STRING'];

I haven't tested this code, because I don't have PHP handy at the moment.

A: I would suggest that the only way to be sure and to be secure is to define a constant for the url in some kind of config file for the site. You could generate the constant with $_SERVER['HTTP_HOST'] as a default and replace with a hard coded definition on deployments where security really matters.
define('SITE_URL', $_SERVER['HTTP_HOST']);

and replace as needed:
define('SITE_URL', 'http://foo.bar.com:8080/');

A: The most reliable way is to provide it yourself.
The site should be coded to be hostname neutral, but to know about a special configuration file. This file doesn't get put into source control for the codebase because it belongs to the webserver's configuration. The file is used to set things like the hostname and other webserver-specific parameters. You can accomodate load balancers, changing ports, etc, because you're saying if an HTTP request hits that code, then it can assume however much you will let it assume.
This trick also helps development, incidentally. :-)

A: $_SERVER["HTTP_HOST"] is probably the best way, after some validation of course.
Yes, the user specifies it and so it cannot be trusted, but you can easily detect when the user is playing games with it.

A: One idea for validating that $_SERVER['HTTP_HOST'] is valid could be to validate it by DNS.  I've used this method in one or two cases without serious consequences to speed and I believe this method fails silently if provided a IP address.
http://www.php.net/manual/en/function.gethostbyname.php
Peusudo code might be:
define('SITEHOME', in_array(gethostbyname($_SERVER['HTTP_HOST']), array(... valid IP's)))
? $_SERVER['HTTP_HOST']
: 'default_hostname';

A: why {if you wish the user to continue using http:///host:port/ that they are on do you wish to generate full urls}
whan you can use relative urls instead of either
say on page http://xxx:yy/zzz/fff/
you culd use either
../graphics/whatever.jpg
{to go back one directory from current and get http://xxx:yy/zzz/graphics/whatever.jpg
or
/zzz/graphics/whatever.jpg
{to goto site root and work up the directories as specified}
these both avoid mentioning the host:port part and inherit it from the one currently in use


text:
Q: Disable location.reload() when click button to open modal I have a page that reloads to update information in a database. THe page will show a list of files with some information about each file. To show more detailed info about the file the user can click a button for that file and open a modal with more information.
My problem is that the reload function kicks in and closes the modal. The update interval needs to be 10 seconds but when the modal is open I would either disable the reload or change the time value to a few minutes instead. And after the modal is closed the timer should go back to 10 seconds.

And in the HTML part this opens the modal.
echo "<button data-id='".$orderNo."' class='orderinfo'>Read report</button>	";

I have tried different things but can't find a way to fix it.
Appreciate any help
Thanks

A: you can use clearTimeout() to stop .
     var t = 0;

    function timer_pause(){
        clearTimeout(t);
        console.log('pause');
    }

    function timer_start(){
        t = setTimeout(function(){
                    location.reload();
                    },5000);
    }

    $(document).ready(function(){
        timer_start();
        $('.orderinfo').click(function(){
            timer_pause();
       });
    // use #modalid or whatever modal selector you have
    // or if you have close function put resume in it
      $('.myModal').on('hidden.bs.modal', function () {
         timer_start();
      })

   })

this way when you modal open it will pause the timer and when modal is close it will reset it, you can make adjustment to continue the timer with previous time,
I wont suggest you reload the page too often, you can just reload the  content, if you are showing a table, use datatables, or just simple ajax.

A: Thank you Ahmed Sunny.
I almost got it working. It open the modal and stops the timer. So far so good.
But I don't get it to start the timer when closing the modal.
Here is how the code looks now.

In the HTML for the close button I have this:

<button type="button" class="button" data-dismiss="modal">Close</button>

I guess I'm not have the connection right here.
You have to excuse me I haven't done anything with this kind of stuff before. Just plain PHP, HTML and CSS
Thanks


text:
Q: Can a  return a value in c#? so i'm trying to decrypt a string using aes256 and dnlib, when trying to decrypt, the program will  run, but will not call the <Module> , i think that is because of the internal class of the <Module>
looking at the program through a decompiler :
using System;
using System.IO;

// Token: 0x02000001 RID: 1
internal class <Module>
{
    // Token: 0x06000001 RID: 1 RVA: 0x00002624 File Offset: 0x00000824
    public static string Decrypt_(string A_0)
    {
        string result;
        try
        {
            result = Aes256._GetString(A_0);
        }
        catch (Exception)
        {
            result = null;
        }
        return result;
    }
}

would it be possible to get a return value through a <Module>? just like in the code above
I'm using this but modified to aes256 : https://github.com/srn-g/EncryptStrings


text:
Q: Completely lock user into a single applications I'm planning an exhibition where I need to run an app which needs a keyboard, but no mouse. I want to lock the viewers into one fullscreen application. They should never be able to see anything except this one app. Nothing whatsoever.
So I'd set up a new user which will start the app (in fullscreen mode) as soon as the user logs in. The machine it's running on will be physically secured.
But they have access to the keyboard and could do unwanted things (even closing or switching applications is unwanted). Is there any way of preventing all keyboard based application switching, launching, shutting down, access to tty, login prompt... - such that the only way to leave the application (or simply see anything else) is using the power off button on the (secured) hardware?
The app is intended for Ubuntu 17.10.

A: As per derHugo's suggestion I've found a way to map key inputs to nothing.
I couldn't figure out how to do so within the application (Python), taking into account Super and Ctrl+Alt+F1 et cetera... But this answer on how to disable the Super key with Xmodmap (here is some documentation) can be extended to every key. I've decided to disable all the keys that aren't strictly necessary for my app (which is just [a-zA-Z0-9@.] alias e-mail addresses).
So, to summarize:

*

*Create a .Xmodmap: xmodmap -pke > ~/.Xmodmap

*Edit ~/.Xmodmap and remove the actions of unwanted keys (e.g. keycode  23 = Tab ISO_Left_Tab Tab ISO_Left_Tab to keycode 23 =)

*Optional: Test this by running xmodmap ~/.Xmodmap

*Log out and in again, keys should be disabled

*If you're on 17.10 with Gnome, they aren't yet. Manually apply with xmodmap ~/.Xmodmap and/or add this to your startup.

Careful: If you disable as many keys as I did, you're basically limited to the mouse!

A: Is it a touchscreen? If so, you can use an onscreen keyboard that limits what characters the user can choose. I used that in a museum application. Or don't use a keyboard at all with a touchscreen and just use gxmessage. I used that also. Startup person saw login screen that had instructions as to login name to enter and had onscreen keyboard. There were actually 2 users (runtime and "application administrator) with the second having a password but with no prompt to select that. Once login was done by the volunteer who started it, the onscreen keyboard (with limited choices of letters/numbers/special characters) disappeared and all the other prompts and choices were handled by gxmessage. No shutdown allowed. Power switch (physically secured) was only shutdown.


text:
Q: Overcome translation Workbench drawback I have requirement where I have Polish language to do double translation. Like say if User Language is Polish and User Profile 'A', I need to show my custom object 'X' as 'Y'. When User language is Polish and User Profile 'B' I need to show my custom object Name 'Z'. Is this achievable by some custom settings or so?
Translation workbench operates on only User language. Can I make it customized to operate on both User language and profile. Thus my custom object label will show 'Polish Object1' if User language and profile respectively is 'Polish' and 'Profile1' ; 'Polish Object 2' if User language and profile respectively is 'Polish' and 'Profile2'


text:
Q: Can I write a Keycloak Login page with Vue? As far as I know and tried, Keycloak comes with .ftl templates.
I want to use Vue and everything that comes with it, to create a login Page that is visually
consistent with the rest of my application.
Can I do that? If so how?
To Clarify: I know how to protect an application with keycloak, but I want to know how to use Vue for a Keycloak Login page.

A: It's possible - I would say it's hackish. See POC: https://github.com/jangaraj/vuetify-keycloak-theme/


text:
Q: Python can't write to cache file I'am currently working on a project using to spotify API in python. For this I'am using the spotipy library. In order for the program to work you need to have an access token. This is saved in a .cache-username file. The access token needs to be refreshed very hour. This happens automatically with the way I setup the code. The problem I'am having is that when I run the code on my windows 10 pc using python 3 it has no problem writing to the cache file and keeping the program alive, but when I run the program on my Raspberry PI also using python 3 it will crash after 30-60 minutes with the following error:
Couldn't write token to cache at: .cache-username.
I have already tried to give the cache file all the rights it needs by doing:
sudo chmod +rwx .cache-username
but that didn't solve the problem.
Does anyone know what could cause this problem and how to solve it?
The program itself:
import spotipy
import spotipy.util as util

clientID = "my_client_id"
clientSec = "my_client_secret_key"

# The scopes defines how much you are allowed
scope = "user-read-currently-playing"

username = "my_user_name"

# loop to keep updating
while True:
    # Gets a token for spotify and should keep it updated
    token = util.prompt_for_user_token(username, scope, client_id=clientID, client_secret=clientSec, redirect_uri="http://localhost/Spotify/callback.php")
    sp = spotipy.Spotify(auth=token)

    # Returns some data about the current playing song
    results = sp.currently_playing(market=None)

    # If there is a song playing than show the song name
    if results:

        # Song info
        songName = results["item"]["name"]

        # print(songName)
    time.sleep(0.4)

A: NEW method : add an cache path while OAuth -> cache_path='./tokens.txt'
example -
oauth = spotipy.oauth2.SpotifyOAuth(scope=scope, username=u, cache_path='./tokens.txt')

OLD method : add an cache path while prompt_for_user_token -> cache_path='./tokens.txt'
example - util.prompt_for_user_token(username, scope, client_id=clientID, client_secret=clientSec, redirect_uri="", cache_path="./tokens.txt")
(not sure if it works with the old method)


text:
Q: "Your communities" in site switcher menu should be a link This is not a link:

I think it should be a link.
(Specifically, I think it should link to the same place as the "# Accounts" header in the user profile summary does, i.e. http://stackexchange.com/users/<id>/<name>?tab=accounts.)

A: Great idea! This will go live in the next build.
We will also be linking "Current Community" to the home page of the site you're on mostly for consistency between all headers.


text:
Q: Read-only filesystem pod with Spring Boot application on Kubernetes I have a Docker container with Spring Boot 3.0.0 application running in the Kubernetes Deployment.
I have received a number of hardening rules that are required to be implemented, such as:

*

*do not mount emptyDir volumes to pods

*define runAsNonRoot in securityContext of pods

*pods must define, that their filesystem is mounted readonly using readOnlyRootFilesystem: true in securityContext
My application stores data in the database and does not need any write permissions to the filesystem, so I have tried to define securityContext in my Deployment using:
securityContext:
  runAsNonRoot: true
  readOnlyRootFilesystem: true

However, running the Deployment failed, and it seems that the Spring Boot is trying to create some temporary directory, which of course is not allowed:
[2023-02-01 15:12:31.762] ERROR [main] [org.springframework.boot.SpringApplication - 820]: Application run failed
org.springframework.context.ApplicationContextException: Unable to start web server
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:164)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:578)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.base/java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:95)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:58)
    at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:65)
Caused by: org.springframework.boot.web.server.WebServerException: Unable to create tempDir. java.io.tmpdir is set to /tmp
    at org.springframework.boot.web.server.AbstractConfigurableWebServerFactory.createTempDir(AbstractConfigurableWebServerFactory.java:208)
    at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:194)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:183)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:161)
    ... 16 common frames omitted
Caused by: java.nio.file.FileSystemException: /tmp/tomcat.8080.8311954706877871713: Read-only file system
    at java.base/sun.nio.fs.UnixException.translateToIOException(Unknown Source)
    at java.base/sun.nio.fs.UnixException.rethrowAsIOException(Unknown Source)
    at java.base/sun.nio.fs.UnixException.rethrowAsIOException(Unknown Source)
    at java.base/sun.nio.fs.UnixFileSystemProvider.createDirectory(Unknown Source)
    at java.base/java.nio.file.Files.createDirectory(Unknown Source)
    at java.base/java.nio.file.TempFileHelper.create(Unknown Source)
    at java.base/java.nio.file.TempFileHelper.createTempDirectory(Unknown Source)
    at java.base/java.nio.file.Files.createTempDirectory(Unknown Source)
    at org.springframework.boot.web.server.AbstractConfigurableWebServerFactory.createTempDir(AbstractConfigurableWebServerFactory.java:202)
    ... 19 common frames omitted

I was trying to find some relevant information on the web and this tells me that read-only containers are not supported in Spring Boot: https://github.com/spring-projects/spring-boot/issues/8578.
There are some proposed solutions, which I cannot apply, for example to use emptyDir mount, or pvc. It does not make sense for me to mount something just because Spring Boot needs to create temporary directory.
Does anyone has experience with that and can suggest a good solution how to create Deployment with Spring Boot pod that works when readOnlyRootFilesystem: true?


text:
Q: Laurent series for $\cot(\pi z)/z^2$ I'm looking for the series for $\frac{cot(\pi z)}{z^2}$ using the residue theory, where the function denotes a circle about the origin with a radius of $k+\frac{1}{2}$
I found that the residues of $\frac{cot(\pi z)}{z^2}$ are:
$R(f;0)= \frac{-\pi}{3}$
$R(f;n)=\frac{1}{\pi n^2}$, where $n$ are positive integers.
I know that the residue theory states that the integral of the function f(z) is  $2 \pi i$ $\sum Residues$ however I am unsure how to implement the fact that the radius is $k+\frac{1}{2}$
Because from my residue result I would assume the answer would be:
$2\pi i[\frac{-\pi}{3}+\frac{1}{\pi}\sum_{n=1}^k{\frac{1}{n^2}}]$
However the answer is
$2\pi i[\frac{-\pi}{3}+\frac{2}{\pi}\sum_{n=1}^k{\frac{1}{n^2}}]$
I'm not sure where the 2 before the sum cam from.
Thank you!


text:
Q: Can we use Mathematica for electronics design? A spoiler alert: I intend to answer my own question. I am posting this because I would like to share my excitement regarding the control theory tools in Mathematica, and also to promote further discussion.
I invite any and all to criticize what I post, correct any errors, and add to the discussion!

A: I've been exporting schematic designs from geda-gaf to Mathematica for many years using its "mathematica" exporter together with code that has a new home at https://github.com/noqsi/gEDAmath. This also works with Lepton-eda.
The notebook there shows how to create linear transfer function models for the kind of analysis you are doing. While this development predates Mathematica's system modeling machinery, it is easy to apply the new functionality here.

A: An example of electronics design is the design of amplifiers using operation amplifiers (op amps). One common configuration is the inverting amplifier depicted below in a schematic entered in LTSpice (a free spice tool from Linear Technology).

The amplifier makes use of an LT1365 op amp and is designed for a gain of -2. In this implementation, a 10pF capacitor Cp represents parasitic capacitance as may be found with some implementations. The op amp has a single pole in its transfer function. The effect of the added capacitance is to produce a second pole in the feedback path. The two poles therefore appear in the loop gain and threaten to add 180 degrees to the phase delay turning what was negative feedback into positive feedback -- producing instability and even threatening oscillation. What can be done? One method is to introduce a zero in the feedback path to improve the phase margin. We do that with Cf in parallel with Rf. How to choose its value?
First, we use the control theory tools to develop a transfer function model for the closed-loop system:
(* convenient shortcuts *)

(* circuit impedances in the s-domain *)
xl[l_] := s l; xc[c_] := 1/(s c); par[z1_, z2_] := (z1 z2)/(z1 + z2);

(* prefixes *)
k = 1000.; M = 1.*^6; u = 1.*^-6; p = 1.*^-12;

(* nominal values *)
nominals = {cp -> 10 p, ri -> 100 k, cf -> 0 p, rf -> 200 k,
   av -> -4500., pole -> 2 Pi 30000.};

(* the op amp has a one-pole roll off at 30kHz *)
lt1365 = av pole/(s + pole);

(* derive a closed-loop transfer function *)

(* node currents sum to zero into the inverting input node with \
voltage v *)
eq1 = (vin - v)/ri + (0 - v)/xc[cp] + (vout - v)/par[rf, xc[cf]] == 0;

(* equation for op amp gain *)
eq2 = vout == lt1365 v;

(* determine transfer function as vout/vin *)

temp = Eliminate[{eq1, eq2}, v];

tf = (vout /. Solve[temp, vout][[1]])/vin // Simplify;

tfm = TransferFunctionModel[tf, s];

(* nominal response of transfer function *)

nominalTFM = tfm /. nominals // Simplify;

The nominal transfer function has a value of zero for Cf -- that is no compensation. We see the effects of instability in both the frequency and transient response. The circuit is close to oscillation.
SetOptions[BodePlot, FeedbackType -> None,
  ScalingFunctions -> {{"Log10", "dB"}, {"Log10", "Degree"}},
  GridLines -> Automatic, ImageSize -> 300,
  FrameLabel -> {{"Frequency", "dB"}, {"Frequency", "Degrees"}},
  PhaseRange -> {-\[Pi], \[Pi]}, PlotRange -> Automatic];

plot[1] =
 BodePlot[nominalTFM, {2 Pi 10^4, 2 Pi 1*^8},
  PlotLabel -> "Nominal Response"]

(* the response to a negative pulse shows severe ringing *)
(* brought about by the parasitic capacitance *)

out = OutputResponse[
   nominalTFM, -UnitStep[t - 5 u] + UnitStep[t - 10 u], {t, 0, 15 u}];

plot[2] =
 Plot[out /. t -> tt u, {tt, 0, 15}, PlotRange -> Automatic,
  Frame -> True, FrameLabel -> {"\[Mu]s", None},
  PlotLabel -> "Pulse Response", PlotLegends -> {"Nominal"}]

We want to determine a value of Cf that will quench the ringing but still provide a fast transient response. The root-locus plot is the perfect way to do that.
(* The ringing can be reduced by placing a zero in the feedback using \
cf *)
(* check the root locus plot *)
(* without compensation the systen is almost oscillating *)
(* a value of cf = 0.478p brings the poles to the real axis *)
plot[3] = RootLocusPlot[tf /. cf -> cf1 /. nominals, {cf1, 0, 1 p},
  FeedbackType -> None,
  PlotRange -> {{-.3*^8, .1*^8}, All},
  AspectRatio -> .7, PlotLabel -> "Closed-Loop Poles",
  PoleZeroMarkers -> {"", Automatic, "",
    "ParameterValues" -> {0, .25 p, .45 p, .478 p, .5 p, .8 p}}]

We can see on the root-locus plot that with no compensation the two poles are nearly on the imaginary axis -- close to oscillation. Using a set of values for Cf we find the value that brings the poles down to the real axis.
We now have a smooth frequency response:
improvedTFM = tfm /. cf -> .478 p /. nominals;

plot[4] =
 BodePlot[improvedTFM, {2 Pi 10^4, 2 Pi 1*^8},
  PlotLabel -> "Improved Response"]

The transient response is just what we want:
out2 = OutputResponse[
   improvedTFM,
   -UnitStep[t - 5 u] + UnitStep[t - 10 u],
   {t, 0, 15 u}];

plot[5] =
  Plot[out2 /. t -> tt u, {tt, 0, 15}, PlotRange -> Automatic,
   Frame -> True, FrameLabel -> {"\[Mu]s", None}, PlotStyle -> {Red},
   PlotLabel -> "Pulse Response", PlotLegends -> {"Improved"}];

plot[6] = Show[plot[2], plot[5], PlotLabel -> "Pulse Response"]

It is interesting to compare this with an analysis in LTSpice. It will not be exact, Spice will use the actual op amp model, not just a 1 pole roll-off. But it is quite close. (And note that in Mathematica we get the use of root-locus as a tool.)
Uncompensated:

Compensated:

So I hope my fellow Mathematica fanatics find this interesting. For me -- who started out doing this stuff with slide rule and graph paper -- it is fantastic!
EDIT:
In response to the comment by andre314 that the label on the frequency axis on the bode plot should be radian frequency -- I agree. But I would really prefer frequency. I have tried to implement that using ScalingFunctions like this:
fscale = {Log10[#/2/Pi] &, 2 Pi 10^# &};
SetOptions[BodePlot, FeedbackType -> None,
  ScalingFunctions -> {{fscale, "dB"}, {fscale, "Degree"}},
  GridLines -> Automatic, ImageSize -> 300,
  FrameLabel -> {{"Frequency", "dB"}, {"Frequency", "Degrees"}},
  PhaseRange -> {-\[Pi], \[Pi]}, PlotRange -> Automatic];

However, when I evaluate BodePlot it returns an error that the value of option ScalingFunction is invalid. I suspect that BodePlot does not accept
the user-defined value for ScalingFunction as described in the documentation.
Does anyone know how to get BodePlot to plot in frequency rather than radians/sec?
**** This is answered in the comments!  BodePlot[tfm[2 Pi s]] plots in Hz ****
EDIT 2:
In continuing to look at this model I have come on an issue that concerns me greatly. To plot the response of the nominal system to a pulse, I converted the transfer function (s-domain) to a TransferFunctionModel and substituted into it the nominal values. I then used OutputResponse to plot the response to a pulse composed of UnitStep functions.
I have now done this another way. I start with the same transfer function and substitute into it the nominal values. I then multiply it by a pulse in the s-domain. That is the response in the s-domain. I then do an inverse Laplace transform to the time domain to obtain the response.
You see the results below. The output does not agree with the output obtained in the first method. But it does agree with the simulation in LTSpice. (The frequency of ringing is slightly different, but so are the op amp models.)
It might be that I have made some error. Or it might that the system is close enough to unstable that a slight difference in the numerical methods show a burst into oscillation (like after the falling edge in plot[2] ) in one method and not in the other.
Here is the work:
(* a negative pulse in the s domain *)
pulseS[t0_, t1_] := (-Exp[-s t0] UnitStep[t0] +
  Exp[-s t1] UnitStep[t1])/s

(* the same 10us pulse used for OutputResponse *)
pulse = pulseS[5 u, 10 u];

(* the nominal transfer function in the s domain *)
nominalTF = tf /. nominals // Simplify;

(* the output in the s domain *)
outSD = pulse nominalTF // Simplify;

(* the output as a function in the time domain *)
outTD[t_] = InverseLaplaceTransform[outSD, s, t];

plot[7] =
 Plot[Re[outTD[t u]], {t, 0, 15}, PlotRange -> Automatic,
  Frame -> True, FrameLabel -> {"\[Mu]s", None},
  PlotLabel -> "Pulse Response Using Laplace Transform"]

EDIT 3:
And here is a fix for this problem thanks to the comment from Andre 314:
(* And a fix thanks to Andre314 *)

out3 = OutputResponse[
   nominalTFM, -UnitStep[t - 5 u] + UnitStep[t - 10 u], {t, 0, 15 u},
   Method -> {"NDSolve", MaxStepSize -> 10^-8}];

plot[8] = Plot[out3 /. t -> tt u, {tt, 0, 15}, PlotRange -> Automatic,
  Frame -> True, FrameLabel -> {"\[Mu]s", None},
  PlotLabel -> "Pulse Response", PlotLegends -> {"Nominal"}]

The damping appears slightly stronger, but the overall characteristics are quite similar to the Laplace transform method.
I reduced the step size until the output no longer changed.
Here is the result at MaxStepSize->10^-10

EDIT 4: I have posted a summary of the convergence issue to Wolfram Community here.


text:
Q: How to hide image-url if no attachment? How can I hide the img-tag if there is no attacment?
(function is from this tutorial: http://wp.tutsplus.com/tutorials/automagic-post-thumbnails-image-management/)
<img src="<?php get_attachment_picture();?>" />

I need something like this:
<?php if ( get_attachment_picture()) { ?>
<img src="<?php get_attachment_picture();?>">
<?php } else { ?>
show nothing, not even av default image
<?php } ?>

Here is the function I use:
<!?php

/* Function to process your thumbnail & image
   Copy and paste the code below to your functions.php */

function get_attachment_picture(){
    global $post, $posts;
    $related_thumbnail =  get_post_meta($post->ID, 'image', $single = true);                            //read post meta for image url

    if($related_thumbnail == ""):
        $attachments = get_children( array(
                                    'post_parent'    => get_the_ID(),
                                    'post_type'      => 'attachment',
                                    'numberposts'    => 1,
                                    'post_status'    => 'inherit',
                                    'post_mime_type' => 'image',
                                    'order'          => 'ASC',
                                    'orderby'        => 'menu_order ASC'
                                    ) );
        if(!empty($attachments)):                                               //check if there an attachment or not
            foreach ( $attachments as $attachment_id => $attachment ) {
              if(wp_get_attachment_image($attachment_id) != ""):
                  $related_thumbnail = wp_get_attachment_url( $attachment_id );
              endif;
            }
        else:                                                           // if no attachment
            $first_img = '';
            ob_start();
            ob_end_clean();
            $output = preg_match_all('//i', $post->post_content, $matches);
            $first_img = $matches [1] [0];

            if(!empty($first_img)):
                $related_thumbnail = $first_img;
            else:
                $related_thumbnail = "images/default_thumbnail.jpg";                            //define default thumbnail, you can use full url here.
            endif;
        endif;
    endif;

    echo $related_thumbnail;
} ?>

A: Assuming you're following this tutorial:
http://wp.tutsplus.com/tutorials/automagic-post-thumbnails-image-management/
Replace the echo statement at the end of get_attachment_picture with a return, then change your image code.
Here is your new image code:
// get the URL of the image
$src = get_attachment_picture();

// if the url is not empty, display the image
if(!empty($src)){
    ?>
    <img src="<?php echo $src; ?>" />
    <?php
} else {
    // the url was empty, do not display the image
}

Here's the modified function:
function get_attachment_picture(){
    global $post, $posts;
    $related_thumbnail =  get_post_meta($post->ID, 'image', true);                          //read post meta for image url

    if($related_thumbnail == ""):
        $attachments = get_children( array(
                                    'post_parent'    => get_the_ID(),
                                    'post_type'      => 'attachment',
                                    'numberposts'    => 1,
                                    'post_status'    => 'inherit',
                                    'post_mime_type' => 'image',
                                    'order'          => 'ASC',
                                    'orderby'        => 'menu_order ASC'
                                    ) );
        if(!empty($attachments)):                                               //check if there an attachment or not
            foreach ( $attachments as $attachment_id => $attachment ) {
              if(wp_get_attachment_image($attachment_id) != ""):
                  $related_thumbnail = wp_get_attachment_url( $attachment_id );
              endif;
            }
        else:                                                           // if no attachment
            $first_img = '';

            $output = preg_match_all('//i', $post->post_content, $matches);
            $first_img = $matches [1] [0];

            if(!empty($first_img)):
                $related_thumbnail = $first_img;
            else:
                $related_thumbnail = "";
            endif;
        endif;
    endif;

    return $related_thumbnail;
}