text:
Q: Rails carrierWave permit parameters I am having a problem in uploading an image in Rails 4.2.6 with ruby 2.3.0 and CarrierWave.
I have a podcast model, and when I am trying to create a new model from the form, providing name, description and a .jpg image, I get the following error: Missing template podcasts/create, application/create with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in: * "/Users/mychro94/Desktop/Prova/app/views" * "/Users/mychro94/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-i18n-1.6.1/app/views" * "/Users/mychro94/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-4.4.3/app/views"
If I remove the :image field in
def podcast_params
    params.require(:podcast).permit(:name, :description, :image)
end

I don't get that error anymore, but the image is not added to the object created.
The podcast create method is:
def create
   @podcast = current_user.podcasts.create(podcast_params)
   if @podcast.save
      redirect_to podcast_path(@podcast)
   end
end

and the new.html.erb file is
   <%= form_for(@podcast, html: { :multipart => true, id: "input-      container", class: "cf wrapper"}) do |f| %>

   <%= f.file_field :image, :required => true %>

    <%= f.text_field :name,:required => true , placeholder: "Insert Podcast title", class: "border-animation" %>

   <%= f.text_area :description, :required => true , placeholder: "Insert Podcast description", class: "border-animation"%>

    <%= f.submit "Create my podcast",class: "button button-highlight" %>

   <% end %>

this is what I get in the terminal when creating the podcast
Started POST "/podcasts" for ::1 at 2018-04-04 09:24:00 +0200
Processing by PodcastsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"wE57eKfcn/74znzOaQ4SBdYf5PSxPFBOZou9EOrhLNHmBzDNBa/nuw7+PJhIa5Lzqb3g55uIjqdhYmrSko+Wew==", "podcast"=>{"image"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007fc9043f4fd8 @tempfile=#<Tempfile:/var/folders/7y/kh7t8w9j2tzf54_vh32st63r0000gn/T/RackMultipart20180404-50589-qd7z9c.jpg>, @original_filename="pod.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"podcast[image][image]\"; filename=\"pod.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "name"=>"asdas", "description"=>"asdasd"}, "commit"=>"Create my podcast"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
 Unpermitted parameter: image
  (0.1ms)  begin transaction
 SQL (0.4ms)  INSERT INTO "podcasts" ("name", "description", "artist_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["name", "asdas"], ["description", "asdasd"], ["artist_id", 1], ["created_at", "2018-04-04 07:24:00.672689"], ["updated_at", "2018-04-04 07:24:00.672689"]]
  (0.9ms)  commit transaction
  (0.1ms)  begin transaction
  (0.0ms)  commit transaction
  Redirected to http://localhost:3000/podcasts/28
  Completed 302 Found in 11ms (ActiveRecord: 1.8ms)

For sure there is something wrong with this
"podcast"=>{"image"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007fc9043f4fd8

What can I do?

A: The error Missing template podcasts/create, application/create ... you are seeing is because you haven't handled the failure scenario in your create action. If @podcast.save returns false then it will, by rails convention, look for the template with same name as the action to render.
You can modify your action as below to redirect/render on failure. Most people prefer rendering the same form with errors displayed.
def create
  @podcast = current_user.podcasts.create(podcast_params)
  if @podcast.save
    redirect_to podcast_path(@podcast)
  else
    render :new     # Change this according to your will.
  end
end


text:
Q: Javascript programing on array Question is:
You live in the city of Cartesia where all roads are laid out in a perfect grid.
You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk.
The city provides its citizens with a Walk Generating App on their phones.
Everytime you press the button it sends you an array of one-letter strings representing directions to walk
(eg. ['n', 's', 'w', 'e']).
You know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.
Test case: [n,n,n,s,n,s,n,s,n,s] is true.
I am having difficulty to understand how to ensure that the person reached his starting point.
I know it must be a simple shortest path mathematics.
But I am really not getting starting point reached logic.
Please help.

A: Count the number of each characters. number of 'n' must be equal to the number of 's' and the number of 'e' must be equal to the number of 'w' and the total sum must be 10.
The example is wrong, because at the end you are 2 blocks north of your starting point so the answer should be false.

A: This may help
    function isValidWalk(walk) {
        let n = walk.filter(a => a =='n').length;
        let s = walk.filter(a => a=='s').length;
        let w = walk.filter(a => a=='w').length;
        let e = walk.filter(a => a=='e').length;

        return walk.length == 10 && n == s && w == e

    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Align single and double-line containers I have a header row where some of the header names are too long to fit on one line and have to be split. The headers are fixed height, sufficient for two lines. The text should be vertically centered.
Something like:

.container {
  width: 100%;
  height: 40px;
}
.pill {
  display: inline-block;
  width: 33%;
  background-color: red;
  text-align: center;
  height: 40px;
}

    Header One

    Header

Two

    Header Three

I can't figure out how to align all those headers correctly. Setting line-height to 40px makes the second header double-height; setting height to 40px throws them out of alignment.
Thanks!

A: So this is what I changed in your code:

*

*Add vertical-align: middle to align the pills

*Give line-height same as height for the pills other than split using the not selector:
.pill:not(.split) {
  line-height: 40px;
}

*In smaller displays the menu will wrap - so use float and clear them too.
Let me know your thoughts on this, thanks!

.container {
  width: 100%;
  height: 40px;
}
.pill {
  display: inline-block;
  vertical-align: middle;
  float: left;
  width: 33%;
  background-color: red;
  text-align: center;
  height: 40px;
}
.pill:not(.split) {
  line-height: 40px;
}
.pill:after{
  content: '';
  display: block;
  clear: both;
}

    Header One

    Header

Two

    Header Three

A: Flexbox can do that:

.container {
  width: 100%;
  height: 40px;
  display: flex;
}
.pill {
  display: flex;
  flex: 0 0 30%;
  margin: 0 1%;
  justify-content: center;
  align-items: center;
  text-align: center;
  background-color: red;
  height: 40px;
}

    Header One

    LONG HEADER TEXT GOES HERE

    Header Three

A: One option is change the way you are setting the elements side by side, so instead of inline-block:
Table-cell

.container {
  width: 100%;
  height: 40px;
}
.pill {
  padding:10px;
  border:1px solid white;
  display: table-cell;
  width: 33%;
  background-color: red;
  text-align: center;
  height: 40px;
  vertical-align:middle;
}

    Header One

    Header

Two

    Header Three

A: Add the following to your .pill css:
vertical-align:middle;

Here is an example


text:
Q: How to add additional header for cordova web view requests I'm using the Apache Cordova WebView. In the html I use img tags. For the HTTP requests of this images I would like to add a referer in the HTTP header.
I tried to use a own CordovaWebViewClient and intercepting with overriding shouldInterceptRequest or shouldOverrideUrlLoading:
public class CustomCordovaWebViewClient extends CordovaWebViewClient {

    public CustomCordovaWebViewClient(CordovaInterface cordova, CordovaWebView view) {
        super(cordova, view);
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

        Log.d("DEBUG", "AAAAAAAAAA Should intercept request" + url);
        //Implement your code
        return super.shouldInterceptRequest(view, url);
    }

    @Override
    public void onLoadResource(WebView view, String url) {
        Log.d("DEBUG", "AAAAAAAAAA onLoadResource" +url);
        //Implement your code
        super.onLoadResource(view, url);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        Log.d("DEBUG", "AAAAAAAAAA On page finished "+url);
        //Implement your code
        super.onPageFinished(view, url);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        Log.d("DEBUG", "AAAAAAAAAA should override url loading "+url);
        //Implement your code
        return super.shouldOverrideUrlLoading(view, url);

    }
}

The CustomCordovaWebViewClient I register by following code:
cwv = (CordovaWebView) findViewById(R.id.webView);
cwv.setWebViewClient(new CustomCordovaWebViewClient(getTabActivity(), cwv));
cwv.loadUrl("file:///android_asset/www/index.html");

No function will be called on any request.
Is there a better solution for adding http header?
The solution with loadUrl(url, extraHeaders) doesn't work with cordova.
I'm using Cordova 3.6.3


text:
Q: Are JSF Views shared between users? I've defined the # of logical views and views in session attributes in web.xml to 1, so that there is only a maximum of 1 view. Given that, I've a couple of questions:

*

*Is this # specific to a given user? Meaning, does this limit the # of views to 1 per user?
** If yes, could there be multiple view representations of the same JSP across multiple users?

*Is there a way to share the JSF view across users (given that the view is rather generic and does not contain any user specific data)?
Thanks!

A: If your generic definition of "an user" actually  equals to "a HTTP session", then yes, you're right. Views are basically stored in the HTTP session and referenced by a hidden HTML input field with the name javax.faces.ViewState. Different HTTP sessions will not share their views with each other, that would otherwise obviously have been a huge bug and security hole.
With setting the number of (logical) views in session to 1, you're however removing the possibility that the user can use multiple views containing POST forms in different windows/tabs in the same session. Everytime the enduser opens a new window/tab, the enduser will receive a ViewExpiredException whenever the enduser fires a POST request in a previous window/tab, because you've configured it to keep only one view in the session, which is the last opened one.


text:
Q: How to find and retrieve live photos from external or media storage in android? I want to retrieve all live photos from android device, any advices?

A: You can try this :
check if these permissions exists in your manifest :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Call this method to get all photos from the gallery :
public static ArrayList<Photo> getAllImages(Cursor cursor, Activity activity) {
       int i = 0;
       ArrayList<Photo> arrayList = new ArrayList<>();
       if (cursor == null) {
           ContentResolver resolver = activity.getContentResolver();
           cursor = resolver.query(
                   MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                   null,
                   null,
                   null,
                   null);
           if (cursor != null) {
               while (i < cursor.getCount()) {
                   cursor.moveToPosition(i);
                   int fieldIndex = cursor.getColumnIndex(MediaStore.Images.Media._ID);
                   Long id = cursor.getLong(fieldIndex);
                   Uri imageUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
                   Photo photo = new Photo();
                   photo.setName("");
                   photo.setUri(imageUri);
                   arrayList.add(photo);
                   i++;
               }
               cursor.close();
           }

       }
       return arrayList;
   }

Create a class and name it Photo :
public class Photo {
    private String name;
    private Uri uri;

    public String getName() {
        return name;
    }

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

    public Uri getUri() {
        return uri;
    }

    public Photo(String name, Uri uri) {
        this.name = name;
        this.uri = uri;
    }

    public Photo() {
    }

    public void setUri(Uri uri) {
        this.uri = uri;
    }
}


text:
Q: How to implement two similar views efficiently in UISegmentedControl I've two exactly similar views which I show in a two segmented control. Refer to image below. The differences between these two views is the parameter which I send to backend to fetch the values and the title. Even the returned values are same.
I've referred to some tutorial which cycles from one view to another when segment is selected .
I've ended up with two files with exactly same code. How to optimise this implementation so that I can implement with one piece of code only.
The two contained VCs have exactly same code to fetch values from backend and display. I've only one function which I've used in both VCs to fetch but there are other code sections such as Tableview delegations and other codes which are common to both.
In storyboard both are duplicate as well.
Is there anyway I can make it more efficient?

A: This could be a case for making your two view controllers be subclasses of a common superclass.
Or it could be even simpler: make them two instances of the same view controller class, which knows what to do because you pass a parameter at creation time telling it what to do.
For example, my Albumen app uses four view controllers, which differ primarily just in what query they perform on the user's music library. So I've elected to make them four instances of one view controller class, with an enum property saying which query it is, and any other varying functionality determined through switch statements on that enum.

A: I think you need to create only 1 VC ( In IB and code ) , put all the logic inside it and either
1- Add once instance / container of it to the MainVC and manage the process of selecting a segment to reload the content ( Recommended )
2- Add 2 instances of it to the MainVC and manage hide/show when the segment is selected


text:
Q: Postgres Datasource Definition - connection refused I'm trying to set up a quick datasource which will be used for integration tests, so rather than configuring it on the app server - Wildfly 10 - I'd prefer to deploy it on the fly.
This is how I configured it:
@DataSourceDefinitions({
    @DataSourceDefinition(
            name = "java:/datasources/testdb",
            className = "org.postgresql.xa.PGXADataSource",
            user = "testdb",
            password = "testdb",
            serverName = "localhost",
            portNumber = 5432,
            databaseName = "testdb",
            minPoolSize = 10,
            maxPoolSize = 50)
})
public class DatasourceDefinitions {}

I've tried with localhost, 127.0.0.1 and using the parameter url instead of the triple serverName, port and databaseName, but I always run into a Connection Refused error
Caused by: java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    at org.postgresql.core.PGStream.<init>(PGStream.java:62)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:76)
    ... 41 more

I have already checked user and password and they work just fine if I try to log in with pgAdmin.
Here is Postgres configuration:
# Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                peer
#host    replication     postgres        127.0.0.1/32            md5

I also enabled the line
listen_addresses = 'localhost'          # what IP address(es) to listen on;

in the configuration file postgresql.conf
Can anyone tell me what I'm missing and/or doing wrong?

A: Solved.
The problem was in Postgres configuration, namely in file /etc/postgresql/9.4/main/postgresql.conf.
I changed this
listen_addresses = 'localhost'

into this
listen_addresses = '127.0.0.1'

and now it works perfectly.


text:
Q: PIG LOAD filename I am just trying to load an unstructured input file and add the filename. So what I want to get is two fields :
filename:chararray, inputrow:chararray.
I can load the filename if I have a field delimiter using pigstorage(';','-tagfile') but I do not want to delimit fields at this point I just want the string and the filename. How can I do this ?
B

A: The way to load in files without applying a delimiter, is to choose a delimiter that does not (cannot) occur in the file.
For example, if your file is separated by ; and cannot contain tabs \t you could do:
pigstorage('\t','-tagfile')


text:
Q: OpenCV Python with Cuda low FPS on GPU I have built OpenCV with Cuda for Python and am using the following lines to use GPU.
net = cv2.dnn.readNetFromCaffe(proto_file, weights_file)
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)

However, my FPS with GPU is about 1.8 while it is about 0.8 with CPU. In the task manager, my GPU utilization is displayed as about 5%.
My GPU is Nvidia GeForce MX130. How can I increase my GPU utilization and hence, my FPS?
To verify that my OpenCV installation allows GPU processing, I have used the following statements with the respective outputs.
cv2.cuda.getCudaEnabledDeviceCount()

Output 1.
cv2.getBuildInformation()

Output:
'\nGeneral configuration for OpenCV 4.4.0 =====================================\n  Version control:               unknown\n\n  Extra modules:\n    Location (extra):            G:/opencv_contrib-4.4.0/opencv_contrib-4.4.0/modules\n    Version control (extra):     unknown\n\n  Platform:\n    Timestamp:                   2021-09-24T15:28:43Z\n    Host:                        Windows 10.0.19043 AMD64\n    CMake:                       3.21.1\n    CMake generator:             Visual Studio 16 2019\n    CMake build tool:            C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/MSBuild/Current/Bin/MSBuild.exe\n    MSVC:                        1929\n\n  CPU/HW features:\n    Baseline:                    SSE SSE2 SSE3\n      requested:                 SSE3\n    Dispatched code generation:  SSE4_1 SSE4_2 FP16 AVX AVX2 AVX512_SKX\n      requested:                 SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX\n      SSE4_1 (17 files):         + SSSE3 SSE4_1\n      SSE4_2 (2 files):          + SSSE3 SSE4_1 POPCNT SSE4_2\n      FP16 (1 files):            + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 AVX\n      AVX (5 files):             + SSSE3 SSE4_1 POPCNT SSE4_2 AVX\n      AVX2 (31 files):           + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2\n      AVX512_SKX (7 files):      + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX_512F AVX512_COMMON AVX512_SKX\n\n  C/C++:\n    Built as dynamic libs?:      YES\n    C++ standard:                11\n    C++ Compiler:                C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.29.30133/bin/Hostx64/x64/cl.exe  (ver 19.29.30133.0)\n    C++ flags (Release):         /DWIN32 /D_WINDOWS /W4 /GR  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:fast     /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /MP  /MD /O2 /Ob2 /DNDEBUG \n    C++ flags (Debug):           /DWIN32 /D_WINDOWS /W4 /GR  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:fast     /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /MP  /MDd /Zi /Ob0 /Od /RTC1 \n    C Compiler:                  C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.29.30133/bin/Hostx64/x64/cl.exe\n    C flags (Release):           /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:fast     /MP   /MD /O2 /Ob2 /DNDEBUG \n    C flags (Debug):             /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:fast     /MP /MDd /Zi /Ob0 /Od /RTC1 \n    Linker flags (Release):      /machine:x64  /INCREMENTAL:NO \n    Linker flags (Debug):        /machine:x64  /debug /INCREMENTAL \n    ccache:                      NO\n    Precompiled headers:         NO\n    Extra dependencies:          cudart_static.lib nppc.lib nppial.lib nppicc.lib nppicom.lib nppidei.lib nppif.lib nppig.lib nppim.lib nppist.lib nppisu.lib nppitc.lib npps.lib cublas.lib cudnn.lib cufft.lib -LIBPATH:C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v10.1/lib/x64\n    3rdparty dependencies:\n\n  OpenCV modules:\n    To be built:                 aruco bgsegm bioinspired calib3d ccalib core cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev datasets dnn dnn_objdetect dnn_superres dpm face features2d flann fuzzy gapi hfs highgui img_hash imgcodecs imgproc intensity_transform line_descriptor ml objdetect optflow phase_unwrapping photo plot python3 quality rapid reg rgbd saliency shape stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab world xfeatures2d ximgproc xobjdetect xphoto\n    Disabled:                    -\n    Disabled by dependency:      -\n    Unavailable:                 alphamat cnn_3dobj cvv freetype hdf java js julia matlab ovis python2 python2 sfm viz\n    Applications:                tests perf_tests apps\n    Documentation:               NO\n    Non-free algorithms:         NO\n\n  Windows RT support:            NO\n\n  GUI: \n    Win32 UI:                    YES\n    VTK support:                 NO\n\n  Media I/O: \n    ZLib:                        build (ver 1.2.11)\n    JPEG:                        build-libjpeg-turbo (ver 2.0.5-62)\n    WEBP:                        build (ver encoder: 0x020f)\n    PNG:                         build (ver 1.6.37)\n    TIFF:                        build (ver 42 - 4.0.10)\n    JPEG 2000:                   build Jasper (ver 1.900.1)\n    OpenEXR:                     build (ver 2.3.0)\n    HDR:                         YES\n    SUNRASTER:                   YES\n    PXM:                         YES\n    PFM:                         YES\n\n  Video I/O:\n    DC1394:                      NO\n    FFMPEG:                      YES (prebuilt binaries)\n      avcodec:                   YES (58.54.100)\n      avformat:                  YES (58.29.100)\n      avutil:                    YES (56.31.100)\n      swscale:                   YES (5.5.100)\n      avresample:                YES (4.0.0)\n    GStreamer:                   NO\n    DirectShow:                  YES\n    Media Foundation:            YES\n      DXVA:                      YES\n\n  Parallel framework:            Concurrency\n\n  Trace:                         YES (with Intel ITT)\n\n  Other third-party libraries:\n    Intel IPP:                   2020.0.0 Gold [2020.0.0]\n           at:                   G:/opencv-gpu-build/3rdparty/ippicv/ippicv_win/icv\n    Intel IPP IW:                sources (2020.0.0)\n              at:                G:/opencv-gpu-build/3rdparty/ippicv/ippicv_win/iw\n    Lapack:                      NO\n    Eigen:                       NO\n    Custom HAL:                  NO\n    Protobuf:                    build (3.5.1)\n\n  NVIDIA CUDA:                   YES (ver 10.1, CUFFT CUBLAS FAST_MATH)\n    NVIDIA GPU arch:             50\n    NVIDIA PTX archs:\n\n  cuDNN:                         YES (ver 7.6.5)\n\n  OpenCL:                        YES (NVD3D11)\n    Include path:                G:/opencv-4.4.0/opencv-4.4.0/3rdparty/include/opencl/1.2\n    Link libraries:              Dynamic load\n\n  Python 3:\n    Interpreter:                 G:/python-projects/human-pose-estimation/venv/Scripts/python.exe (ver 3.9.6)\n    Libraries:                   C:/Users/tmakp/AppData/Local/Programs/Python/Python39/libs/python39.lib (ver 3.9.6)\n    numpy:                       G:/python-projects/human-pose-estimation/venv/Lib/site-packages/numpy/core/include (ver 1.21.2)\n    install path:                G:/python-projects/human-pose-estimation/venv/Lib/site-packages/cv2/python-3.9\n\n  Python (for build):            G:/python-projects/human-pose-estimation/venv/Scripts/python.exe\n\n  Java:                          \n    ant:                         NO\n    JNI:                         NO\n    Java wrappers:               NO\n    Java tests:                  NO\n\n  Install to:                    G:/opencv-gpu-build/install\n-----------------------------------------------------------------\n\n'


text:
Q: Return values from Java Threads I have a Java Thread like the following:
   public class MyThread extends Thread {
        MyService service;
        String id;
        public MyThread(String id) {
            this.id = node;
        }
        public void run() {
            User user = service.getUser(id)
        }
    }

I have about 300 ids, and every couple of seconds - I fire up threads to make a call for each of the id. Eg.
for(String id: ids) {
    MyThread thread = new MyThread(id);
    thread.start();
}

Now, I would like to collect the results from each threads, and do a batch insert to the database, instead of making 300 database inserts every 2 seconds.
Any idea how I can accomplish this?

A: Store your result in your object.  When it completes, have it drop itself into a synchronized collection (a synchronized queue comes to mind).
When you wish to collect your results to submit, grab everything from the queue and read your results from the objects.  You might even have each object know how to "post" it's own results to the database, this way different classes can be submitted and all handled with the exact same tiny, elegant loop.
There are lots of tools in the JDK to help with this, but it is really easy once you start thinking of your thread as a true object and not just a bunch of crap around a "run" method.  Once you start thinking of objects this way programming becomes much simpler and more satisfying.

A: The canonical approach is to use a Callable and an ExecutorService.  submitting a Callable to an ExecutorService returns a (typesafe) Future from which you can get the result.
class TaskAsCallable implements Callable<Result> {
    @Override
    public Result call() {
        return a new Result() // this is where the work is done.
    }
}

ExecutorService executor = Executors.newFixedThreadPool(300);
Future<Result> task = executor.submit(new TaskAsCallable());
Result result = task.get(); // this blocks until result is ready

In your case, you probably want to use invokeAll which returns a List of Futures, or create that list yourself as you add tasks to the executor.  To collect results, simply call get on each one.

A: In Java8 there is better way for doing this using CompletableFuture. Say we have class that get's id from the database, for simplicity we can just return a number as below,
static class GenerateNumber implements Supplier<Integer>{

    private final int number;

    GenerateNumber(int number){
        this.number = number;
    }
    @Override
    public Integer get() {
        try {
            TimeUnit.SECONDS.sleep(1);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        return this.number;
    }
}

Now we can add the result to a concurrent collection once the results of every future is ready.
Collection<Integer> results = new ConcurrentLinkedQueue<>();
int tasks = 10;
CompletableFuture<?>[] allFutures = new CompletableFuture[tasks];
for (int i = 0; i < tasks; i++) {
     int temp = i;
     CompletableFuture<Integer> future = CompletableFuture.supplyAsync(()-> new GenerateNumber(temp).get(), executor);
     allFutures[i] = future.thenAccept(results::add);
 }

Now we can add a callback when all the futures are ready,
CompletableFuture.allOf(allFutures).thenAccept(c->{
   System.out.println(results); // do something with result
});

A: If you want to collect all of the results before doing the database update, you can use the invokeAll method. This takes care of the bookkeeping that would be required if you submit tasks one at a time, like daveb suggests.
private static final ExecutorService workers = Executors.newCachedThreadPool();

...

Collection<Callable<User>> tasks = new ArrayList<Callable<User>>();
for (final String id : ids) {
  tasks.add(new Callable<User>()
  {

    public User call()
      throws Exception
    {
      return svc.getUser(id);
    }

  });
}
/* invokeAll blocks until all service requests complete,
 * or a max of 10 seconds. */
List<Future<User>> results = workers.invokeAll(tasks, 10, TimeUnit.SECONDS);
for (Future<User> f : results) {
  User user = f.get();
  /* Add user to batch update. */
  ...
}
/* Commit batch. */
...

A: You need to store the result in a something like singleton. This has to be properly synchronized.
This not the best advice as it is not good idea to handle raw Threads.

A: You could create a queue or list which you pass to the threads you create, the threads add their result to the list which gets emptied by a consumer which performs the batch insert.

A: The simplest approach is to pass an object to each thread (one object per thread) that will contain the result later. The main thread should keep a reference to each result object. When all threads are joined, you can use the results.

A: public class TopClass {
     List<User> users = new ArrayList<User>();
     void addUser(User user) {
         synchronized(users) {
             users.add(user);
         }
     }
     void store() throws SQLException {
        //storing code goes here
     }
     class MyThread extends Thread {
            MyService service;
            String id;
            public MyThread(String id) {
                this.id = node;
            }
            public void run() {
                User user = service.getUser(id)
                addUser(user);
            }
        }
}

A: You could make a class which extends Observable.  Then your thread can call a method in the Observable class which would notify any classes that registered in that observer by calling Observable.notifyObservers(Object).
The observing class would implement Observer, and register itself with the Observable.  You would then implement an update(Observable, Object) method that gets called when Observerable.notifyObservers(Object) is called.


text:
Q: How can I group routes Route::group(['controller' => [AdminController::class], 'middleware' => ['role:administrator']], function () {
    Route::get('/admin', 'index');
});

It doesn't recognize the AdminController

A: Route::controller(AdminController::class)
    ->middleware('role:administrator'))
    ->group(function () {
        Route::get('/admin', 'index');
    });

More information about route controller groups in https://laravel.com/docs/9.x/routing#route-group-controllers


text:
Q: Prolog - Constraint Library - Variable Scope I'm working on trying to solve an LSAT logic problem with Prolog. I'm trying to get Prolog to tell me whether possible values for actors in a line are valid.
I wrote the following:
:- use_module(library(clpfd)).

actor("Jeff",A) :-
        A #>= 0,
        A #<5.
actor("Rich",C) :-
        C #>= 0,
        C #<5,
        actor("Jeff",A),
        A #< C.

When I query:
?- actor("Rich",0).
false.

Which is right since Jeff is < than Rich and Jeff is => 0 so Rich cannot be 0.
But, when I query:
?- actor("Jeff",1), actor("Rich",1).
true

I also get true, which is impossible because Rich > Jeff.
I feel the problem is because of something going on with my variable. I don't understand how
actor("Jeff",A),
A #< C.

is evaluating. It seems to me that actor("Jeff",A) should be set to actor("Jeff",1) and then 1 #< 1 should fail.

A: Variables within a clause or local to that clause.
In your case, to understand the issue, consider first the following query:

?- actor("Rich", C),
   C = 1.
C = 1.

This does not tell us a lot, so we apply the following purely algebraic reasoning: For the goal actor("Rich", C), we substitute the body of the single matching clause:

?- C #>= 0,
   C #< 5,
   actor("Jeff",A),
   A #< C,
   C = 1.

The answer is:

C = 1,
A = 0.

This shows that when C is 1, then A is 0. However, on the toplevel, you did not see this because this variable only occurs within the clause for "Rich". Making this explicit shows that there is a solution that satisfies the constraint within that clause, but it is not linked to the variable we want.
There are several ways out. One of them is to make A available as an argument so that you can explicitly refer to it from the toplevel. In general, to link the relevant entities together, you will have to introduce arguments for each of your clauses, so that you can refer to the variables you need to reason about, instead of introducing new ones within each clause.
For example, in your case, this could look as follows:

actor("Jeff", A, _) :-
        A #>= 0,
        A #< 5.

actor("Rich", A, C) :-
        C #>= 0,
        C #< 5,
        actor("Jeff", A, C),
        A #< C.

I have used A to refer to Jeff, and C to refer to Rich.
While we are at at, let us tidy up the code, and use the following essentially equivalent version:

actor(jeff, A, _) :- A in 0..4.
actor(rich, A, C) :- C in 0..4, actor(jeff, A, C), A #< C.

Make sure you understand the following answer:

?- actor(jeff, 1, C), actor(rich, C, 1).
C = 0.

Your original example now yields false, exactly as expected:

?- actor(rich, 1, 1).
false.

Thus, you should be able to solve your task in principle.
However, there is a much simpler way to solve all this, which avoids the reification overload.
Instead of painstakingly keeping track of connections between names and corresponding variables, let us use the variables directly with the intended names. For example, what do you say about this:

?- Jeff in 0..4,
   Rich in 0..4,
   Jeff #< Rich.

This uses Prolog variables to denote the people, and makes the work a lot simpler. In this representation, your query becomes:

?- Jeff in 0..4,
   Rich in 0..4,
   Jeff #< Rich,
   Jeff = 1,
   Rich = 1.

And this obviously results in false.


text:
Q: How to modify class data through tests? I have this luigi task with its required input being 'test_file.txt'. I want to change the required input through testing the class. I need to change the input so that I can test the functionalities of the class with a file. I tried the code below, but the printed result is still the initial path-'test_file.txt'. How can I change the path only in testing? (to get 'data.json' as the printed result.
import pytest
import luigi

class LuigiToBeTested(luigi.ExternalTask):
    def requires(self):
        return luigi.LocalTarget("test_file.txt")

def test_Luigi():
    class_instance = LuigiToBeTested()
    class_instance.requires().path = 'data.json'
    print('/////', class_instance.requires().path) #to get data.json

A: Here are 3 solutions for you

*

*test_luigi_1 - Intercept (via function) all calls to initialize a new object of luigi.LocalTarget and replace the input file name.

*test_luigi_2 - Same with 1, but via subclass

*test_luigi_3 - Instead of patching as done in 1 and 2, redesign your source code to be testable by allowing dependency injection. This is the more extensible way and also more future proof.
a. Ask for things, Don't look for things (aka Dependency Injection / Law of Demeter)
b. Fixing the Client API: Dependency Injection
c. And many many more references on why this is the preferred way.
import luigi
import pytest

class LuigiToBeTested(luigi.ExternalTask):
    def requires(self):
        return luigi.LocalTarget("test_file.txt")

class LuigiToBeTested2(luigi.ExternalTask):
    def requires(self, file_name):
        return luigi.LocalTarget(file_name)

@pytest.fixture
def amend_local_target_func_based(mocker):  # The <mocker> fixture is from pytest-mock. Install via <pip install pytest-mock>.
    orig = luigi.LocalTarget

    def fake(file_name):
        print(f"Intercepted initialization of luigi.LocalTarget via function. The file {file_name} might be replaced.")

        # If you only want to replace 'test_file.txt' but not the other files, then use this.
        # Otherwise, remove this if and just read from 'data.json' always.
        if file_name == 'test_file.txt':
            file_name = 'data.json'

        return orig(file_name)

    mocker.patch('luigi.LocalTarget', new=fake)

@pytest.fixture
def amend_local_target_class_based(mocker):
    class LocalTargetStub(luigi.LocalTarget):
        def __init__(self, file_name):
            print(f"Intercepted initialization of luigi.LocalTarget via subclass. The file {file_name} might be replaced.")

            # If you only want to replace 'test_file.txt' but not the other files, then use this.
            # Otherwise, remove this if and just read from 'data.json' always.
            if file_name == 'test_file.txt':
                file_name = 'data.json'

            super().__init__(file_name)

    mocker.patch('luigi.LocalTarget', new=LocalTargetStub)

def test_luigi_1(amend_local_target_func_based):
    class_instance = LuigiToBeTested()
    print('/////', class_instance.requires().path) #to get data.json

def test_luigi_2(amend_local_target_class_based):
    class_instance = LuigiToBeTested()
    print('/////', class_instance.requires().path) #to get data.json

def test_luigi_3():
    class_instance = LuigiToBeTested2()
    print('/////', class_instance.requires('data.json').path) #to get data.json

$ pytest -q -rP
================================================================================================= PASSES ==================================================================================================
______________________________________________________________________________________________ test_luigi_1 _______________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
Intercepted initialization of luigi.LocalTarget via function. The file test_file.txt might be replaced.
///// data.json
______________________________________________________________________________________________ test_luigi_2 _______________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
Intercepted initialization of luigi.LocalTarget via subclass. The file test_file.txt might be replaced.
///// data.json
______________________________________________________________________________________________ test_luigi_3 _______________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
///// data.json
3 passed, 1 warning in 0.07s


text:
Q: Can't turn off Mail grammar checking Leaving aside that there's nothing the matter with the grammar that's been flagged in the attached screenshot, you can see that Check grammar is turned off.  I've also turned off System Preferences > Keyboard > Text > Correct spelling automatically, just in case.  Before I report it as a bug, (which is, I suppose, the thing to do), I wonder if Stack Exchange has any other solutions, please.
I'm running macOS 12.5.1 on a 2021 14" M1 MacBook Pro
Additional information:  I discovered, half by accident, that if I ask Mail to check the grammar of a different e-mail then it flags additional 'problems'.  If you turn off grammar checking it reverts to just flagging this particular one.

A: Generally, the grammar in the example sentence is quite poor, but the checker is actually technically suggesting a spelling change, not grammar.
Apple's grammar checker is generally terrible & will let many things pass.
Its spell-checker makes similar mistakes and often will suggest incorrect replacements. Off/of is a common one.
I tend to leave both checkers on just for a visual guide, but I never let it make automatic corrections, just because of its propensity for changing correct words to incorrect ones.
[Also known as "Damn You Auto Correct", or DYAC for short ;)
Normally you would see squiggly lines underneath - which we're not seeing here because "check as you type" is switched off. Green is grammar, red is spelling.
In this particular sentence, though, both the grammar and spell checker will flag it, but with two different explanations underneath. The one in your image is the spelling reason, grammar says "consider 'of' instead" - which is, of course, just as wrong, but that's how we can clearly show the difference…
Spelling…

Grammar…

A: Seems like this is a bug and that it's been there since Mojave.  I stumbled my way to this:
https://discussions.apple.com/thread/8573939
My previous Mac had been running High Sierra, which explains why I've only just come across it.
My thanks to everyone who's got involved in this thread.


text:
Q: Using Salesforce Flow to create mutiple child records I am working on a solution for the following:
We have a multi-select picklist on the Opportunity that (currently) has four values: value1, value2, value3, value4
When a new value is selected and saved, it will need to create a child record; let's call the object valueChildRecord__c.
This is easy enough to do using Process Builder if it was for a single-select picklist. However, if the Opportunity is saved with value1, value2, and value3 selected, it will need to create 3 child records with each respective value stored in a field in its corresponding record.
The next part is slightly more complicated. If the Opportunity is edited and value3 is deselected and saved, the child record that corresponds to value3 needs to be updated with a timestamp. This goes for each value, and only if the value is deselected. If, in the future, value3 is selected and saved, it should create a new record.
I understand that I will need to use Process Builder and have a Flow trigger off of it. However, I have no idea where to begin with creating the Flow. A lot of the Salesforce help pages are very shallow, whereas I need a very indepth step-by-step guide to do something like this.
Can someone verify that using a process and flow in this way is the right approach? Any assistance in the actual building of the flow or a point in the right direction is appreciated!

A: A flow inside of PB is the correct way to do this. There's a Trailhead module that covers this particular topic called Lightning Flow. It's one of the more recent ones and should give you enough to get you started on what you're trying to do. I'd also highly recommend looking at the Automation Champion Blog for additional help on the topic. He really knows this material inside out.


text:
Q: Geoserver - Replacing log4j 1.2.17 with 2.15.0? I have a geoserver on my webserver that uses log4j v 1.2.17 (log4j-1.2.17.jar).
I've downloaded the latest (safe?) version (2.15.0) from the log4j download site and checksummed the download.
I'm now confused as to which .jar I should try and use?
The version on my website is called log4j-1.2.17.jar, but the .jars in the download are all called something like e.g. log4j-web-2.15.0.jar
The geoserver's web server is jetty if that makes any difference.
What to do?

A: There is a way to deactivate the log4j logging:
https://docs.geoserver.org/stable/en/user/configuration/logging.html

[Updated]
https://osgeo-org.atlassian.net/browse/GEOS-10333

A: There are significant changes in the way logging is done in the switch from log4j v1 (the one GeoServer uses) and log4j v2 (the one with the latest CVE). While GeoServer is immune to the RCE vulnerability mentioned in the question, there are still some small risks in using the old (and EOL) version we do use.
So as a temporary mitigation Andrea Aime has made a fork of the current log4j v1 trunk removing the network elements that might be abused by an attacker that has access to your GeoServer machine. See https://github.com/aaime/log4j for the tree you will need to clone and build. This will generate a new jar called log4j-1.2.17-norce.jar which you should replace log4j-1.2.17.jar with. You can now download that jar prebuilt from https://repo.osgeo.org/repository/geotools-releases/log4j/log4j/1.2.17/log4j-1.2.17-norce.jar
If you make use of GeoServer then you might like to contribute to the developers (or via the OSGEO foundation) to help support the work involved in reducing the technical debt of the project like updating the logging library.

A: I've been looking into this myself for the same reasons and from I can gather you need to use log4j-1.2-api-2.15.0.jar based on the following read:

Perhaps the simplest way to convert to using Log4j 2 is to replace the log4j 1.x jar file with Log4j 2's log4j-1.2-api.jar.

source
I would like to point out that this shouldn't be the accepted answer but I wanted to give an answer for those who are trying to grasp the situation.
[Edit]
It would seem that log4j-1.2-api-2.15.0.jar is not enough. It helps with migrating Geoserver to the newer log4j version whilst still using the previous main package but it fails to reference to the newer version. As such I also added log4j-api-2.15.0.jar to the mix to complete the pathing.
After this it seems to work again and the version has been updated.
I could validate this by using the api of Geoserver (/geoserver/rest/about/manifest.xml) specifically. If you search for log4j before upgrading you'll see 1.2.17 and afterwards 2.15.


text:
Q: how to handle Pandas read_json Error: ValueError: Unmatched ''"' when when decoding 'string' I am getting an error while reading a big file, around 3 Million lines, using read_json function from Pandas.
The error that i get is given below for reference,
ValueError: Unmatched ''"' when when decoding 'string'

I was able to identify the issue here. And the issue was there was an incomplete line in the file and that was giving me the error. the line is given below for reference,
{"Asset":"

The correct line would look something like this,
{"Asset":"somesite", "Stream":"Company", "Tag":"SomeTag"}

I read the big file using read_json like this:
for lines in pd.read_json(file_name, lines=True, convert_dates=False, chunksize=100000):
        do some processing on lines

I am not able to use try: catch after for loop because the error happens at the for loop line.
Just want to know if there is an effective way to handle this error without correcting the line in the big json file.


text:
Q: How to fix this error which happens when eclipse program starts? Recently, when I start eclipse program, always got below error. I did not see this issue before, seems the error started after I update the Android SDK. Could you please help?

I got some answers from here. They recommend me to uninstall some images from android sdk 5.1.1. I didn't install these images and even I cannot find them under 5.1.1 version as below.

A: delete this guy
the solution to above problem is to just delete(uninstall) the package Android Wear ARM EABI v7a system image available under Android 5.1.1 (API 22) if it's installed. (No need to uninstall whole 5.1.1 package). May be there is some eclipse bug with this package.
Finally restart eclipse to see your changes.
If the problem still exists, try removing other Android Wear package also (i.e Android Wear Intel x86 Atom System Image)


text:
Q: How to create a variable from xarray dataset coordinates? Based on a xarray dataset containing latitude and longitude coordinates and several variables I would like to create a new variable containing objects based on the latitude and longitude coordinates.
For example, from the following dataset:
<xarray.Dataset>
Dimensions:    (time: 100, x: 1000, y: 840)
Coordinates:
  * x          (x) float64 2.452e+06 2.458e+06 2.462e+06 ... 7.442e+06 7.448e+06
  * y          (y) float64 1.352e+06 1.358e+06 1.362e+06 ... 5.542e+06 5.548e+06
  * time       (time) datetime64[ns] 2015-01-01 ... 2015-01-05T03:00:00

... I would like to simply create a point object for each grid cell based on the respective latitude and longitude coordinates.
Pseudocode:
ds['points'] = (('y', 'x'), point_creation_function(ds.y, ds.x))

(How) Can I apply a function that requires the coordinate values as inputs such, that the result can be directly added as new variable?
A horrible implementation after an initialization of ds.points would be:
for x_value in ds.x:
    for y_value in ds.y:
        ds.points.loc[dict(x=x_value, y=y_value)] = (x_value, y_value)

I assume there is an elegant and computation-efficient solution available, but searching the documentation I did not understand how to use apply, reduce or other functions to achieve it.

A: If I undestand you question correctly, I think this is the answer:
import numpy as np
import xarray as xr

# Create some example data
data = np.random.rand(10,5,6)

# Make the dataset.
ds = xr.Dataset({"my_var": (["time", "x", "y"], data)})

# Create a MultiIndex
ds = ds.stack(points=("x", "y"))


text:
Q: Getting Error on Clicking Catalog -> Manage Categories in Magento Admin Panel I am getting following error when I click on Catalog -> Manage Categories in Magento Admin Panel
There has been an error processing your request
Exception printing is disabled by default for security reasons.

Error log record number: 481584870868

I saw in var/report in file 481584870868 for message...
following is the content of the file:
a:5:{i:0;s:100:"Source model "prima/system_config_source_ppagetmp" not found for attribute "ppage_template_override"";i:1;s:4101:"#0 /home/harmonic/public_html/app/code/core/Mage/Eav/Model/Entity/Attribute/Abstract.php(387): Mage::exception('Mage_Eav', 'Source model "p...')

 #1 /home/harmonic/public_html/app/code/core/Mage/Adminhtml/Block/Widget/Form.php(201): Mage_Eav_Model_Entity_Attribute_Abstract->getSource()

 #2 /home/harmonic/public_html/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Attributes.php(113): Mage_Adminhtml_Block_Widget_Form->_setFieldset(Array, Object(Varien_Data_Form_Element_Fieldset))

 #3 /home/harmonic/public_html/app/code/core/Mage/Adminhtml/Block/Widget/Form.php(144): Mage_Adminhtml_Block_Catalog_Category_Tab_Attributes->_prepareForm()

 #4 /home/harmonic/public_html/app/code/core/Mage/Core/Block/Abstract.php(918): Mage_Adminhtml_Block_Widget_Form->_beforeToHtml()

 #5 /home/harmonic/public_html/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tabs.php(140): Mage_Core_Block_Abstract->toHtml()

 #6 /home/harmonic/public_html/app/code/core/Mage/Core/Block/Abstract.php(293): Mage_Adminhtml_Block_Catalog_Category_Tabs->_prepareLayout()

 #7 /home/harmonic/public_html/app/code/core/Mage/Core/Model/Layout.php(456): Mage_Core_Block_Abstract->setLayout(Object(Mage_Core_Model_Layout))

 #8 /home/harmonic/public_html/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Edit/Form.php(55): Mage_Core_Model_Layout->createBlock('adminhtml/catal...', 'tabs')

 #9 /home/harmonic/public_html/app/code/core/Mage/Core/Block/Abstract.php(293): Mage_Adminhtml_Block_Catalog_Category_Edit_Form->_prepareLayout()

 #10 /home/harmonic/public_html/app/code/core/Mage/Core/Model/Layout.php(456): Mage_Core_Block_Abstract->setLayout(Object(Mage_Core_Model_Layout))

 #11 /home/harmonic/public_html/app/code/core/Mage/Adminhtml/Block/Widget/Form/Container.php(93): Mage_Core_Model_Layout->createBlock('adminhtml/catal...')

 #12 /home/harmonic/public_html/app/code/core/Mage/Core/Block/Abstract.php(293): Mage_Adminhtml_Block_Widget_Form_Container->_prepareLayout()

 #13 /home/harmonic/public_html/app/code/core/Mage/Core/Model/Layout.php(456): Mage_Core_Block_Abstract->setLayout(Object(Mage_Core_Model_Layout))

  #14 /home/harmonic/public_html/app/code/core/Mage/Core/Model/Layout.php(472): Mage_Core_Model_Layout->createBlock('adminhtml/catal...', 'category.edit')

   #15 /home/harmonic/public_html/app/code/core/Mage/Core/Model/Layout.php(239): Mage_Core_Model_Layout->addBlock('adminhtml/catal...', 'category.edit')

  #16 /home/harmonic/public_html/app/code/core/Mage/Core/Model/Layout.php(205): Mage_Core_Model_Layout->_generateBlock(Object(Mage_Core_Model_Layout_Element), Object(Mage_Core_Model_Layout_Element))

  #17 /home/harmonic/public_html/app/code/core/Mage/Core/Model/Layout.php(210): Mage_Core_Model_Layout->generateBlocks(Object(Mage_Core_Model_Layout_Element))

  #18 /home/harmonic/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(344): Mage_Core_Model_Layout->generateBlocks()

  #19 /home/harmonic/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(269): Mage_Core_Controller_Varien_Action->generateLayoutBlocks()

  #20 /home/harmonic/public_html/app/code/core/Mage/Adminhtml/Controller/Action.php(275): Mage_Core_Controller_Varien_Action->loadLayout(NULL, true, true)

  #21 /home/harmonic/public_html/app/code/core/Mage/Adminhtml/controllers/Catalog/CategoryController.php(201): Mage_Adminhtml_Controller_Action->loadLayout()

   #22 /home/harmonic/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_Catalog_CategoryController->editAction()

   #23 /home/harmonic/public_html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(254): Mage_Core_Controller_Varien_Action->dispatch('edit')

   #24 /home/harmonic/public_html/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))

    #25 /home/harmonic/public_html/app/code/core/Mage/Core/Model/App.php(365): Mage_Core_Controller_Varien_Front->dispatch()

    #26 /home/harmonic/public_html/app/Mage.php(684): Mage_Core_Model_App->run(Array)

    #27 /home/harmonic/public_html/index.php(83): Mage::run('', 'store')

    #28 {main}";s:3:"url";s:84:"/index.php/murcielago13/catalog_category/index/key/3728137de42712df515ed0ee8fad43a4/";s:11:"script_name";s:10:"/index.php";s:4:"skin";s:5:"admin";}


text:
Q: Can't get data in table form using Selenium Python Am new to scraping using selenium python. So i could retrieve some of the data, but i want it in table form as is displayed on the web page:
Here is what i have so far:
url='https://definitivehc.maps.arcgis.com/home/item.html?id=1044bb19da8d4dbfb6a96eb1b4ebf629&view=list&showFilters=false#data'

browser = webdriver.Chrome(r"C:\task\chromedriver")
browser.get(url)
time.sleep(25)

rows_in_table = browser.find_elements_by_xpath('//table[@class="dgrid-row-table"]//tr[th or td]')
for element in rows_in_table:
    print(element.text.replace('\n', ''))

result snippet:
Hospital NameHospital TypeCityState AbrvZip CodeCounty NameState Name
Phoenix VA Health Care System (AKA Carl T Hayden VA Medical Center)VA HospitalPhoenixAZ85012MaricopaArizona040130401362620000.001
Southern Arizona VA Health Care SystemVA HospitalTucsonAZ85723PimaArizona04019040192952952202.002
VA Central California Health Care SystemVA HospitalFresnoCA93703FresnoCalifornia060190601954542202.003
VA Connecticut Healthcare System - West Haven Campus (AKA West Haven VA Medical Center)VA HospitalWest HavenCT6516New HavenConnecticut09009090092162161102.004

I will really appreciate a help form an expert on this. Thanks.

A: The data is loaded dynamically using Javascript. You can use requests module to simulate those requests:
import json
import requests

config_url = 'https://definitivehc.maps.arcgis.com/sharing/rest/portals/self?culture=en-us&f=json'
page_url = 'https://services7.arcgis.com/{_id}/arcgis/rest/services/Definitive_Healthcare_USA_Hospital_Beds/FeatureServer/0/query?f=json&where=1%3D1&returnGeometry=false&spatialRel=esriSpatialRelIntersects&outFields=*&orderByFields=OBJECTID%20ASC&resultOffset={offset}&resultRecordCount=50&cacheHint=true&quantizationParameters=%7B%22mode%22%3A%22edit%22%7D'

_id = requests.get(config_url).json()['id']

offset = 0
while True:
    data = requests.get(page_url.format(_id=_id, offset=offset)).json()

    # uncommnet this to print all data:
    # print(json.dumps(data, indent=4))

    for i, f in enumerate(data['features'], offset+1):
        print(i, f['attributes'])
        print('-' * 160)

    if i % 50:
        break

    offset += 50

Prints all 6624 records:
...

6614 {'OBJECTID': 6614, 'HOSPITAL_NAME': 'Walter E Washington Convention Center Field Hospital (Temporarily Open due to COVID-19)', 'HOSPITAL_TYPE': 'Short Term Acute Care Hospital', 'HQ_ADDRESS': '801 Mount Vernon Pl Nw', 'HQ_ADDRESS1': None, 'HQ_CITY': 'Washington', 'HQ_STATE': 'DC', 'HQ_ZIP_CODE': '20001', 'COUNTY_NAME': 'District of Columbia', 'STATE_NAME': 'District of Columbia', 'STATE_FIPS': '11', 'CNTY_FIPS': '001', 'FIPS': '11001', 'NUM_LICENSED_BEDS': None, 'NUM_STAFFED_BEDS': None, 'NUM_ICU_BEDS': 0, 'ADULT_ICU_BEDS': 0, 'PEDI_ICU_BEDS': None, 'BED_UTILIZATION': None, 'Potential_Increase_In_Bed_Capac': 0, 'AVG_VENTILATOR_USAGE': None}
----------------------------------------------------------------------------------------------------------------------------------------------------------------
6615 {'OBJECTID': 6615, 'HOSPITAL_NAME': 'Joint Base Cape Cod Field Hospital (Temporarily Open due to COVID-19)', 'HOSPITAL_TYPE': 'Short Term Acute Care Hospital', 'HQ_ADDRESS': 'Connery Ave', 'HQ_ADDRESS1': None, 'HQ_CITY': 'Buzzards Bay', 'HQ_STATE': 'MA', 'HQ_ZIP_CODE': '2542', 'COUNTY_NAME': 'Barnstable', 'STATE_NAME': 'Massachusetts', 'STATE_FIPS': '25', 'CNTY_FIPS': '001', 'FIPS': '25001', 'NUM_LICENSED_BEDS': None, 'NUM_STAFFED_BEDS': None, 'NUM_ICU_BEDS': 0, 'ADULT_ICU_BEDS': 0, 'PEDI_ICU_BEDS': None, 'BED_UTILIZATION': None, 'Potential_Increase_In_Bed_Capac': 0, 'AVG_VENTILATOR_USAGE': None}
----------------------------------------------------------------------------------------------------------------------------------------------------------------
6616 {'OBJECTID': 6616, 'HOSPITAL_NAME': 'UMass Lowell Recreation Center Field Hospital (Temporarily Open due to COVID-19)', 'HOSPITAL_TYPE': 'Short Term Acute Care Hospital', 'HQ_ADDRESS': '322 Aiken St', 'HQ_ADDRESS1': None, 'HQ_CITY': 'Lowell', 'HQ_STATE': 'MA', 'HQ_ZIP_CODE': '1854', 'COUNTY_NAME': 'Middlesex', 'STATE_NAME': 'Massachusetts', 'STATE_FIPS': '25', 'CNTY_FIPS': '017', 'FIPS': '25017', 'NUM_LICENSED_BEDS': None, 'NUM_STAFFED_BEDS': None, 'NUM_ICU_BEDS': 0, 'ADULT_ICU_BEDS': 0, 'PEDI_ICU_BEDS': None, 'BED_UTILIZATION': None, 'Potential_Increase_In_Bed_Capac': 0, 'AVG_VENTILATOR_USAGE': None}
----------------------------------------------------------------------------------------------------------------------------------------------------------------
6617 {'OBJECTID': 6617, 'HOSPITAL_NAME': 'Miami Beach Convention Center Field Hospital (Temporarily Open due to COVID-19)', 'HOSPITAL_TYPE': 'Short Term Acute Care Hospital', 'HQ_ADDRESS': '1901 Convention Center Dr', 'HQ_ADDRESS1': None, 'HQ_CITY': 'Miami Beach', 'HQ_STATE': 'FL', 'HQ_ZIP_CODE': '33139', 'COUNTY_NAME': 'Miami-Dade', 'STATE_NAME': 'Florida', 'STATE_FIPS': '12', 'CNTY_FIPS': '086', 'FIPS': '12086', 'NUM_LICENSED_BEDS': None, 'NUM_STAFFED_BEDS': None, 'NUM_ICU_BEDS': 0, 'ADULT_ICU_BEDS': 0, 'PEDI_ICU_BEDS': None, 'BED_UTILIZATION': None, 'Potential_Increase_In_Bed_Capac': 0, 'AVG_VENTILATOR_USAGE': None}

...

A: This is an updated version to what @Andrej answered, this code will download the table and instead of printing, saves it as an excel document.
import json
import requests
import pandas as pd
from pandas.io.json import json_normalize

config_url = 'https://definitivehc.maps.arcgis.com/sharing/rest/portals/self?culture=en-us&f=json'
page_url = 'https://services7.arcgis.com/{_id}/arcgis/rest/services/Definitive_Healthcare_USA_Hospital_Beds/FeatureServer/0/query?f=json&where=1%3D1&returnGeometry=false&spatialRel=esriSpatialRelIntersects&outFields=*&orderByFields=OBJECTID%20ASC&resultOffset={offset}&resultRecordCount=50&cacheHint=true&quantizationParameters=%7B%22mode%22%3A%22edit%22%7D'

_id = requests.get(config_url).json()['id']
required=[]
offset = 0
while True:
    data = requests.get(page_url.format(_id=_id, offset=offset)).json()

    # uncommnet this to print all data:
    #pprint(json.dumps(data, indent=4))

    for i, f in enumerate(data['features'], offset+1):
        required.append(f['attributes'])

    if i % 50:
        break

    offset += 50

df=json_normalize(required)
with pd.ExcelWriter('dataFunction.xlsx', mode='A') as writer:
    df.to_excel(writer)

I tried this and uploaded the excel sheet HERE(LINK TO EXCEL SHEET)!


text:
Q: Can someone help me with my ajax code? I wanted to change the visibility of the thumbnail to visible right after when I click the button what should I do? please help me on this one because I cannot figure it out by myself because I do not know so much about ajax and web programming. Thanks in advance.

function ha(){
 $('#tabExe').click(function(event){
   $.ajax({
      url:'backEnd/ROOMS.php',
      success:function(result){
        $('#room1').css({ // this is just for style
          "visibility" : "visible",
        });
      }
    });
  });
}

<button style="border-radius:0px;" type="submit" name="tabExe" onClick="function ha();" id="tabExe" href="#Exec" class="btn btn-primary">
  Executive Room
</button>

A: If you just need to show the thumbnail (and you're not concerned about the response), include a beforeSend callback, like this:
$('#tabExe').click(function(event){
    $.ajax({
        url:'backEnd/ROOMS.php',
        beforeSend: function() {
            $('#room1').css({ // this is just for style
                "visibility" : "visible",
            });
        },
        success:function(result){

        }
    });
});

This will call before making the ajax request. success and error only are called when the request completes.
Here's a fiddle demonstrating:
http://jsfiddle.net/jpattishalljr/rzr5mrL1/
EDIT:
IF you need the thumbnail to show when a response comes back, then you'll want to look into the ajax response and see why success is not being called. One way to test is to add complete, something like this:
$('#tabExe').click(function(event){
    $.ajax({
        url:'backEnd/ROOMS.php',
        beforeSend: function() {
            $('#room1').css({ // this is just for style
                "visibility" : "visible",
            });
        },
        success:function(result){

        },
        complete: function(results) {
            alert(results.status);
        }
    });
});

http://jsfiddle.net/jpattishalljr/rzr5mrL1/1/
Should alert (404)
Good luck.


text:
Q: Scrollview disappers when clicking Checkbox My problem is that when I click my Checkboxthe ScrollView disappears. The checkbox uses a OnCheckChangedListener
This is a part of my layout file:
<ScrollView
        android:id="@+id/drawingScrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fillViewport="true"
        android:paddingTop="300dp" >

    <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0dp" >

        <ImageButton
                android:id="@+id/eraseButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/rubber" />

        <CheckBox
                android:id="@+id/unschaerfeFilterCheckBox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Unschärfefilter AN/AUS"
                android:textSize="12sp" />

        <ImageButton
                android:id="@+id/undoButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/undo" />

    </FrameLayout>

</ScrollView>

When I check and uncheck the checkbox the Layout should change:
unschaerfeFilterCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            // ab 6.2. Zeile
            CheckBox unschaerfeFilterCheckBox = (CheckBox) findViewById(R.id.unschaerfeFilterCheckBox);
            TextView radiusTextView = (TextView) findViewById(R.id.radiusTextView);
            TextView radiusTextMin = (TextView) findViewById(R.id.radiusMinTextView);
            SeekBar unschaerfeSeekBar = (SeekBar) findViewById(R.id.unschaerfeSeekbar);
            RadioButton unschaerfeCheckBox1 = (RadioButton) findViewById(R.id.unschaerfeCheckBox1);
            RadioButton unschaerfeCheckBox2 = (RadioButton) findViewById(R.id.unschaerfeCheckBox2);
            RadioButton unschaerfeCheckBox3 = (RadioButton) findViewById(R.id.unschaerfeCheckBox3);
            RadioButton unschaerfeCheckBox4 = (RadioButton) findViewById(R.id.unschaerfeCheckBox4);

            ScrollView drawingScrollView = (ScrollView)findViewById(R.id.drawingScrollView);
            View view = (View)findViewById(R.id.vorschauView);

            if (isChecked) {

                drawingScrollView.invalidate();
                drawingScrollView.requestLayout();

                view.invalidate();
                view.requestLayout();

                radiusTextView.setVisibility(View.VISIBLE);
                radiusTextMin.setVisibility(View.VISIBLE);
                unschaerfeSeekBar.setVisibility(View.VISIBLE);
                unschaerfeCheckBox1.setVisibility(View.VISIBLE);
                unschaerfeCheckBox2.setVisibility(View.VISIBLE);
                unschaerfeCheckBox3.setVisibility(View.VISIBLE);
                unschaerfeCheckBox4.setVisibility(View.VISIBLE);

                unschaerfeWertIsSet = true;
                unschaerfeLayoutIsSet = true;

                short abstandDurchsichtigkeitsTextOben = (short)(abstandStrichDickeTextOben + strichdickeTextHeight + konstanterAbstand);
                short height = (short)(drawingScrollView.getPaddingTop());

                short abstandUnschaerfeCheckBoxOben = (short)(abstandDurchsichtigkeitsTextOben + durchsichtigkeitsTextHeight + konstanterAbstand /*+ height*/);
                Log.d("abstandUnschaerfeCheckBoxOben", "abstandUnschaerfeCheckBoxOben " + abstandDurchsichtigkeitsTextOben + "|" + abstandUnschaerfeCheckBoxOben + "|" + height); // 64 bei Galaxy s2

                unschaerfeCheckBoxLayout.setMargins(0, abstandUnschaerfeCheckBoxOben, 0, 0);
                unschaerfeFilterCheckBox.setLayoutParams(unschaerfeCheckBoxLayout);

                short abstandRadiusTextLinks = (short)(unschaerfeCheckBoxWidth + konstanterAbstand);
                short abstandRadiusTextOben = (short)(abstandUnschaerfeCheckBoxOben + konstanterAbstand / 2);
                radiusTextViewLayout.setMargins(abstandRadiusTextLinks, abstandRadiusTextOben, 0, 0);
                radiusTextView.setLayoutParams(radiusTextViewLayout);

                short abstandRadiusMinTextLinks = (short)(abstandRadiusTextLinks + radiusTextViewWidth + konstanterAbstand);
                radiusMinTextViewLayout.setMargins(abstandRadiusMinTextLinks, abstandRadiusTextOben, 0, 0);
                radiusTextMin.setLayoutParams(radiusMinTextViewLayout);

...
The ScrollView is still disappered even when I uncheck the Checkbox. Everything works great in Emulator (API 16). The next thing is, that the position is incorrect on my mobile phone (API 19) but in Emulator the position is correct.
For illustration here are a few pictures:
(1): before pressing checkbox (mobile phone)

(2): after pressing checkbox (mobile phone) -> no ScrollView anymore, wrong position

(3): after pressing checkbox (emulator) -> everything all right

Let me know, when you need more java / xml

A: ScrollView view = (ScrollView)findViewById(R.id.scrollView);
view.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
view.setFocusable(true);
view.setFocusableInTouchMode(true);
view.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.requestFocusFromTouch();
        return false;
    }
});


text:
Q: An unexpected errors occured with Yarn 1.13.0 on Xubuntu 16 I managed to get the latest Yarn v1.13.0 installed on Xubuntu 16 with their curl installation instruction.
Now I'm getting this errors trying to install a project's dependencies.

An expected error occurred:
  "https://registry.yarnpkg.com/event-stream/-/event-stream-3.3.6.tgz:
  Request failed \"404 Not Found\

Same 'Not Found' message is displayed by the error url.
Seems to be caused by the security issue https://github.com/dominictarr/event-stream/issues/116?utm_content=educational&utm_campaign=2018-11-28&utm_source=email-sendgrid&utm_term=13952972&utm_medium=833442
How do I fix it? How do I find the project deps that use the corrupted version of event-stream?

A: Seemingly was caused by an older version of Nodemon prolly affected by the security issue above. Updating it to the latest version in package.json seemed to have helped.


text:
Q: WPF 2 Grid - hide 1 and the other should expand I have the following form.

These rows reside in a Grid and the darker blue areas, section 1 and section 2, are Grids themselves.
How do I have Grid 2 expand and fill the row when Grid 1 has been collapsed? I attempted a StackPanel but that only moved Grid 2 up and left it the same size.
I'd like it to look like this when Grid 1 has been collapsed:

Any suggestions on how to do this?
Thanks again!

A: You need to make sure Grid2 is set up to fill the available space.  If you have one Grid that contains Grid1, Grid2, and everything else, just make sure the RowHeight for the row containing Grid2 is set to * and everything else set to auto:
<Grid Name="MainGrid">
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="auto"/>
    </Grid.RowDefinitions>
    <Grid Name="Grid1" Grid.Row="0"/>
    <Grid Name="Grid2" Grid.Row="1"/>
    <Grid Name="EverythingBelow" Grid.Row="2"/>
<Grid>

A: Turn on/off the Visibility="Collapsed" with this XAML
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <Grid Grid.Row="0" Background="Red" Visibility="Collapsed" >
        <TextBlock Height="50" Text="Grid1" />
    </Grid>

    <Grid Grid.Row="1" Background="Yellow">
        <TextBlock Text="Grid2" />
    </Grid>

</Grid>


text:
Q: Free software to command line login to Windows from Linux I have a feeling the answer to this is "it's not possible", as I have googled a fair bit already. However, as I do cross platform development I would like to simultaneously work on my Linux laptop in the sitting room, beside the fire,  and use the command prompt on my Windows XP machine which is in  a different room, the study (colder!). This is because as I change code on Linux I would like to test regularly on Windows.
If I had installed Windows on the laptop I could have used ssh into Linux, but it is a low spec machine so I installed lubuntu instead. So, as James T Kirk would say "there's got to be a way".

A: install cygwin on windows and start ssh daemon on it. you will then be able to ssh into windows and get a familiar console window


text:
Q: Memory increases when merging multiple high resolution images into single image, iOS I have to merge multiple images in to single (all of high resolution), It acquires lots of memory. I saved original images to local directory and set resized images to imageviews, placed on different locations on main image. Now at the time of saving final merged image, I then read the original images from local directory. here the memory increases, that cause error (crash due to memory) for higher number of images.
here is code: retrieving original image from local directory
UIImage *originalImage = [UIImage imageWithContentsOfFile:[self getOriginalImagePath:imageview.tag]];

Is there any other way to get images from local directory without loading it into memory.
Thanks in advance

A: There is no way to load an image without it going into memory. With some image formats you could, in theory, implement your own reader that scales the image down while reading the file, so that the original size never ends up in memory, but that would require a lot of work for little gain.
Overall you would be better off just saving the different sizes of images as separate files and loading only the correct size (you seem to be scaling them based on the screen size, so there are not that many different versions required).
If you do keep to resizing them on the fly, try to ensure that you get rid of the original versions as soon as possible, i.e., don't keep any image reference no longer required, and perhaps wrap the whole thing in @autoreleasepool (assuming ARC is being used):
@autoreleasepool {
    UIImage *originalImage = [UIImage imageWithContentsOfFile:[self getOriginalImagePath:imageview.tag]];
    UIImage *pThumbsImage = [self scaleImageToSize:CGSizeMake(AppScreenBound.size.width, AppScreenBound.size.height) imageWithImage:pOrignalImage];
    originalImage = nil;
    imageView.image = pThumbImage;
    pThumbImage = nil;
    // … ?
}

Similarly treat any other image handling that creates intermediate versions, i.e., get rid of references no longer required as soon as possible (such as by assigning nil or having them fall out of scope), and put @autoreleasepool { … } around subsections that may generate temporary objects.

A: Found a solution, posting it as an answer to my own question, might help other people. reference from Image I/O Programming Guide
An alternative to "imageWithContentsOfFile:", one can use an Image Source
here is a code how I use it.
UIImage *originalWMImage = [self createCGImageFromFile:your-image-path];

the method createCGImageFromFile: get an image content without loading it to memory
-(UIImage*) createCGImageFromFile :(NSString*)path
{
    // Get the URL for the pathname passed to the function.
    NSURL *url = [NSURL fileURLWithPath:path];
    CGImageRef        myImage = NULL;
    CGImageSourceRef  myImageSource;
    CFDictionaryRef   myOptions = NULL;
    CFStringRef       myKeys[2];
    CFTypeRef         myValues[2];

    // Set up options if you want them. The options here are for
    // caching the image in a decoded form and for using floating-point
    // values if the image format supports them.
    myKeys[0] = kCGImageSourceShouldCache;
    myValues[0] = (CFTypeRef)kCFBooleanTrue;
    myKeys[1] = kCGImageSourceShouldAllowFloat;
    myValues[1] = (CFTypeRef)kCFBooleanTrue;

    // Create the dictionary
    myOptions = CFDictionaryCreate(NULL, (const void **) myKeys,
                                   (const void **) myValues, 2,
                                   &kCFTypeDictionaryKeyCallBacks,
                                   & kCFTypeDictionaryValueCallBacks);

    // Create an image source from the URL.
    myImageSource = CGImageSourceCreateWithURL((CFURLRef)url, myOptions);
    CFRelease(myOptions);

    // Make sure the image source exists before continuing
    if (myImageSource == NULL){
        fprintf(stderr, "Image source is NULL.");
        return  NULL;
    }

    // Create an image from the first item in the image source.
    myImage = CGImageSourceCreateImageAtIndex(myImageSource,
                                              0,
                                              NULL);

    CFRelease(myImageSource);

    // Make sure the image exists before continuing
    if (myImage == NULL){
        fprintf(stderr, "Image not created from image source.");
        return NULL;
    }

    return [UIImage imageWithCGImage:myImage];
}

A: Here is code: resized image and simply assigned to imageview. Then i perform scaling and rotation on imageview.
UIImage *pThumbsImage = [self scaleImageToSize:CGSizeMake(AppScreenBound.size.width, AppScreenBound.size.height) imageWithImage:pOrignalImage];
    [imageView setImage:pThumbImage];

here when saving:this code is within for loop: (upto number of images to merge on main image)
// get size of the second image
    CGFloat backgroundWidth = canvasSize.width;
    CGFloat backgroundHeight = canvasSize.height;

    //Image View: to be merged
    UIImageView* imageView = [[UIImageView alloc] initWithImage:stampImage];
    [imageView setFrame:CGRectMake(0, 0, stampFrameSize.size.width , stampFrameSize.size.height)];

    // Rotate Image View
    CGAffineTransform currentTransform = imageView.transform;
    CGAffineTransform newTransform = CGAffineTransformRotate(currentTransform, radian);
    [imageView setTransform:newTransform];

    // Scale Image View
    CGRect imageFrame = [imageView frame];

    // Create Final Stamp View
    UIView  *finalStamp = nil;
    finalStamp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, imageFrame.size.width, imageFrame.size.height)];

    // Set Center of Stamp Image
    [imageView setCenter:CGPointMake(imageFrame.size.width /2, imageFrame.size.height /2)];
    [finalImageView addSubview:imageView];

    // Create Image From image View;
    UIGraphicsBeginImageContext(finalStamp.frame.size);
    [finalStamp.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIImage *pfinalMainImage = nil;

    // Create Final Image With Stamp
    UIGraphicsBeginImageContext(CGSizeMake(backgroundWidth, backgroundHeight));
    [canvasImage drawInRect:CGRectMake(0, 0, backgroundWidth, backgroundHeight)];
    [viewImage drawInRect:CGRectMake(stampFrameSize.origin.x , stampFrameSize.origin.y , stampImageFrame.size.width  , stampImageFrame.size.height) blendMode:kCGBlendModeNormal alpha:fAlphaValue];
    pfinalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

everything is okay here. the problem occurs while saving it or generating merged image.

A: This is an old question, but I had to face something like that recently... so there is my answer.
I had to merge a lot of images into one, and had the same problem. The memory increased until the app crashes. The functions that I created, returned UIImage and that was the problem. The ARC was not releasing at time, so I had to change to return CGImageRef and release them at properly time.


text:
Q: which log files can be deleted in sql server My hard drive is filling up. Is it safe to delete SQL Server dump files and error log files? It looks like files in multiple folders can be deleted.
Following are the paths where the log and dump files growing, Is it ok to delete these files to free up space? The dump folder has over 30gb.
Log File Location:

C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\Log\Polybase\dump

C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\Log

C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\Log\Polybase

A: As mentioned in the comments, the Transaction Logs are important because they are for database recovery, by keeping track of all transactions that occur. Transaction Logs allow you to recover your database to any point in time (within the granularity of how often you backup the Transaction Logs).
If your Transaction Logs are eating up your disk space, you may not be backing them up frequently enough (or at all, as some people don't realize they need to be backed up). A backup marks the Transaction Log file for reuse, so it won't continue growing.
If your database doesn't need granular level point in time recovery, and you're willing to lose data as much as your last Full or Differential Backup, then you can switch your database's Recovery Model to Simple Recovery Model. This will allow the Transaction Log to automatically be overwritten as soon as any active transactions are committed. That way the Transaction Log will re-use the space it has allocated already, minimizing any Transaction Log growth.

A: Seems you want clean the Error logs and Polybase dump, but before cleaning up try to check why they growing up and fix it, otherwise no matter the number of times you clean, it grow again!

*

*Polybase Dumps: You might have installed knowingly/unknowingly all features of SQL Server, and Polybase is one of them, pls follow these steps to fix the Polybase dumps creation issue

*SQL-Error-Log: It's always best practice to cycle-error-log which you can automate with following configuration (via SSMS)

15 is suitable number in my environment, you can set the number as per your requirement


text:
Q: ggplot and RGB mode I am trying to prepare figures for a publication.
The journal guidelines say that figures need to be in RGB mode.
I was wondering if the default ggplot() and ggsave() plots are in RGB mode or not.

A: I don't think you understand the plotting model in R. And I don't think that description in the journal guidelines is very helpful either, since "rgb mode" does not really describe a particular file format. The ggplot object is a complex description of how a plot is to be drawn using the 'grid' plotting engine that then gets sent to a plotting device that creates the file to be distributed. You have a variety of plotting devices to choose from. Type:
?Devices

You will notice that ggsave has as one of its parameters,...device = default_device(filename), (although that is no longer the default option as of Feb 2019), and another important one for journal publication is ... dpi = 300, and many journals will specify they want 1200 dpi if they request bitmapped graphics.
Most color specifications are done in sRGB at the device level. Journals will sometimes indicate a preference for either bitmap(tiff or jpg, where dpi will matter) or vector graphics (pdf or SVG, where dpi would not matter). There is an additional aspect of colors encoded in the transparency bytes and the fact that you do not mention that level of color values makes me wonder if transparency is supported.

A: Printer formats traditionally used CMYK, and RGB was long considered specifically for computer monitors and televisions.
Its more likely to find CMYK with offset printers and very high-quality inkjets, and RGB with (relatively) low-cost, laser printers. CMYK tends to be more expensive as offsets require setup and inkjets get costly.
Also, because publishing is now often done by personal computer, its become more common to ask for the image format to be in RGB instead of CMYK. Unfortunately, image quality of RGB is very poor compared to CMYK. Its not great but generally okay to convert from CMYK to RGB, but not the other way around.
As far as image formats, PNG, JPG, and GIF are RGB compatible but do not support CMYK. TIFF supports CMYK, RGB, LAB and other indexed formats.
Adobe has some color profile embedding to mimic CMYK in RGB, but its not an open-standard.
If a journal is requesting 1200dpi, its probably for a black & white image that doesn't have any halftoning (grey scaling).
By default, GGPLOT2 saves PNG and PDF.
To be safe, specify the image as a 300dpi PNG and avoid PDF.
Correction: Adobe's PDF supports a proprietary vector based format. I've never seen a PDF actually used within page layout software except as a bundling/transport for the final product to the printer. When using vector based imagery, its commonly as an EPS format. In the workflows that I'm familiar with, the EPS is then extracted from the PDF and used independently.


text:
Q: cvsnakeimage in opencv2.2 I want to use the cvsnakeimage function for active contours from opencv.
The problem is that i cannot find this function under opencv2.2, have the name been changed or what is the problem.
Thanks in advance!

A: Function cvSnakeImage reside in legacy module. (opencv2/legacy/legacy.hpp at line 818)
/* Updates active contour in order to minimize its cummulative
   (internal and external) energy. */
CVAPI(void)  cvSnakeImage( const IplImage* image, CvPoint* points,
                           int  length, float* alpha,
                           float* beta, float* gamma,
                           int coeff_usage, CvSize  win,
                           CvTermCriteria criteria, int calc_gradient CV_DEFAULT(1));


text:
Q: A reference-tracked object changed reference during deserialization This is the code to replicate the issue. Basically it fails on deserialization, with error "A reference-tracked object changed reference during deserialization". It's kind of interesting, if I remove the following line from IExecEnv setup:
metaType.AsReferenceDefault = true;

then the test passes. But this sounds odd. Is it a limitation of Protobuf-net?
using ProtoBuf;
using ProtoBuf.Meta;

namespace QRM.Analytics.Serialization.Commit.Tests;

public class UnitTest1
{
    private interface IExecEnv
    {
        int GetId();
    }

    [Immutable]
    private class ExecEnv : IExecEnv
    {
        public static readonly ExecEnv DefaultEnv = new ExecEnv(1);
        private readonly int _id;

        private ExecEnv(int id)
        {
            _id = id;
        }

        public int GetId()
        {
            return _id;
        }
    }

    [Serializable]
    private sealed class ExecEnvSurrogate
    {
        [ProtoConverter]
        public static IExecEnv FromSurrogate(ExecEnvSurrogate surrogate)
        {
            if (surrogate == null)
                return null;

            return ExecEnv.DefaultEnv;
        }

        [ProtoConverter]
        public static ExecEnvSurrogate ToSurrogate(IExecEnv env)
        {
            if (env == null)
                return null;

            return new ExecEnvSurrogate();
        }
    }

    private class WithExecEnv
    {
        private IExecEnv _env;

        public WithExecEnv(IExecEnv env)
        {
            _env = env;
        }

        public IExecEnv Env => _env;
    }

    private void SetupModel()
    {
        var metaType = RuntimeTypeModel.Default.Add(typeof(IExecEnv), false);
        metaType.AsReferenceDefault = true;

        var metaType3 = RuntimeTypeModel.Default.Add(typeof(WithExecEnv), false);
        metaType3.UseConstructor = false;
        metaType3.AddField(1, "_env");

        var metaType4 = RuntimeTypeModel.Default.Add(typeof(ExecEnvSurrogate), false);
        metaType4.UseConstructor = false;

        metaType.SetSurrogate(typeof(ExecEnvSurrogate));
    }

    [Test]
    public void CloneExecEnvWithSurrogate()
    {
        SetupModel();

        var withExecEnv = new WithExecEnv(ExecEnv.DefaultEnv);
        using (var stream = new MemoryStream())
        {
            Serializer.Serialize(stream, withExecEnv);

            stream.Seek(0, SeekOrigin.Begin);
            var clone = Serializer.Deserialize<WithExecEnv>(stream);

            Assert.NotNull(clone);
            Assert.Equal(withExecEnv.Env.GetId(), clone.Env.GetId());
        }
    }
}

A: Yes, reference-tracking is ... a massive PITA; it works in some limited scenarios, but there are situations where it becomes unreliable. It also isn't part of the core protobuf specification, but is hacked on top at the library level. For these reasons, it is not recommended, and is deprecated going forward; it cannot be made reliable, and I'd rather not encourage people to get into dangerous territory.


text:
Q: Any character in the last row and column of the table in sql How to display using postgresql any character (e.g. @) in the last column and last row of the sql result table? And only there!

column1
c2
c3
c4
last column

row1
1
1
1

row2
2
2
2

row3
3
3
3

row4
4
4
4

last row
5
5
5
@


text:
Q: ListView PageScrollPhysics snapping based on children width / PageView with viewportFraction < 1 align left I have a PageView/ListView with a viewportFraction of 0.8 to show a preview of the next slide. It looks something like this:

It seems like it is not possible to have the current slide aligned to the left, as shown below. Is that correct?

I found this solution. Using a horizontally scrolling ListView with PageScrollPhysics(), at first looked promising however, this way the page snapping is based on the screen width (?) and not on the ListView children, so the snapping is off by quite a bit.
Is there a way to have the page snapping based on the size of the children?

A: My answer comes a bit late but it might help others looking for the same thing.
the PageScrollPhysics uses the screen width. You need to create your own ScrollPhysics that uses your item width to paginate.
here is an example:
ListView.builder(
    physics: PagingScrollPhysics(itemDimension: YOUR_ITEM_WIDTH),
    itemCount:items.length,
    scrollDirection: Axis.horizontal,
    itemBuilder: (context, index) {
        return YOUR_CHILD();
    }
)

And the new ScrollPhysics:
import 'package:flutter/material.dart';

class PagingScrollPhysics extends ScrollPhysics {
  final double itemDimension;

  PagingScrollPhysics({required this.itemDimension, ScrollPhysics? parent}) : super(parent: parent);

  @override
  PagingScrollPhysics applyTo(ScrollPhysics? ancestor) {
    return PagingScrollPhysics(itemDimension: itemDimension, parent: buildParent(ancestor));
  }

  double _getPage(ScrollMetrics position) {
    return position.pixels / itemDimension;
  }

  double _getPixels(double page) {
    return page * itemDimension;
  }

  double _getTargetPixels(ScrollMetrics position, Tolerance tolerance, double velocity) {
    double page = _getPage(position);
    if (velocity < -tolerance.velocity) {
      page -= 0.5;
    } else if (velocity > tolerance.velocity) {
      page += 0.5;
    }
    return _getPixels(page.roundToDouble());
  }

  @override
  Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) {
    if ((velocity <= 0.0 && position.pixels <= position.minScrollExtent) || (velocity >= 0.0 && position.pixels >= position.maxScrollExtent)) return super.createBallisticSimulation(position, velocity);
    final Tolerance tolerance = this.tolerance;
    final double target = _getTargetPixels(position, tolerance, velocity);
    if (target != position.pixels) return ScrollSpringSimulation(spring, position.pixels, target, velocity, tolerance: tolerance);
    return null;
  }

  @override
  bool get allowImplicitScrolling => false;
}

A: I modified the code of Alaa Eddine Cherbib's answer in order to show smoothly scrolling for all elements when it is a fixed-size list. Now instead of passing item dimension, you should pass the item count and the view size (usually the screen width itself). The item dimension is not needed because it will be calculated internally.
Now always the items will be snaped at the beginning of the view and when scrolling to the last item it will do it smoothly.
import 'package:flutter/material.dart';

class PagingScrollPhysics extends ScrollPhysics {
  const PagingScrollPhysics(
      {required this.itemCount, required this.viewSize, super.parent});

  final double viewSize;

  final int itemCount;

  @override
  PagingScrollPhysics applyTo(ScrollPhysics? ancestor) => PagingScrollPhysics(
      itemCount: itemCount, viewSize: viewSize, parent: buildParent(ancestor));

  double _getPage(double current, double itemDimension) =>
      current / itemDimension;

  double _getTargetPixels(
      ScrollMetrics position, Tolerance tolerance, double velocity) {
    // plus view size because the max scroll extent is about where the screen
    //  starts not where the screen ends.
    final pixels = position.maxScrollExtent + viewSize;
    final itemDimension = pixels / itemCount;
    var page = _getPage(position.pixels, itemDimension);
    if (velocity < -tolerance.velocity)
      page -= 0.5;
    else if (velocity > tolerance.velocity) page += 0.5;
    final pageRound = page.round();
    final itemsPerPage = viewSize ~/ itemDimension;
    final showingLastItem = pageRound == itemCount - itemsPerPage;
    if (showingLastItem) return pixels - viewSize;

    return pageRound * itemDimension;
  }

  @override
  Simulation? createBallisticSimulation(
      ScrollMetrics position, double velocity) {
    if ((velocity <= 0.0 && position.pixels <= position.minScrollExtent) ||
        (velocity >= 0.0 && position.pixels >= position.maxScrollExtent))
      return super.createBallisticSimulation(position, velocity);
    final Tolerance tolerance = this.tolerance;
    final double target = _getTargetPixels(position, tolerance, velocity);
    if (target != position.pixels)
      return ScrollSpringSimulation(spring, position.pixels, target, velocity,
          tolerance: tolerance);
    return null;
  }

  @override
  bool get allowImplicitScrolling => false;
}


text:
Q: Is it possible to trace copy-pasted code to a website that it was retrieved from? If a person takes code from a website and pastes it in something like visual C++ and works on it and forms a finished working product. Could someone who has the source file take the source code from that finished product and trace the website that the leftover bits and traces of code were taken from?
When you copy and paste typed up code from a forum-esque website into something like visual C++ or eclipse does it hold within it an address of where it was copied from?

A: No, it doesn't.
Unless the source code says "Hey, I came from this web site", there are no hidden, invisible bits anywhere in any source code that covertly indicate where it comes from.


text:
Q: Subtract 2 datetime lists dd/mm/YYYY in pandas So, Basically, I got this 2 df columns with data content. The initial content is in the dd/mm/YYYY format, and I want to subtract them. But I can't really subtract string, so I converted it to datetime, but when I do such thing for some reason the format changes to YYYY-dd-mm, so when I try to subtract them, I got a wrong result. For example:
Initial Content:
a: 05/09/2022
b: 30/09/2021
result expected: 25 days.

Converted to DateTime:
a: 2022-05-09
b: 2021-09-30 (For some reason this date stills the same)
result: 144 days.

I'm using pandas and datetime to make this project.
So, I wanted to know a way I can subtract this 2 columns with the proper result.
--- Answer
When I used
pd.to_datetime(date, format="%d/%m/%Y")

It worked. Thank you all for your time. This is my first project in pandas. :)

A: df = pd.DataFrame({'Date1': ['05/09/2021'], 'Date2': ['30/09/2021']})
df = df.apply(lambda x:pd.to_datetime(x,format=r'%d/%m/%Y')).assign(Delta=lambda x: (x.Date2-x.Date1).dt.days)
print(df)

       Date1      Date2  Delta
0 2021-09-05 2021-09-30     25

A: I just answered a similar query here subtracting dates in python
import datetime
from datetime import date
from datetime import datetime
import pandas as pd

date_format_str = '%Y-%m-%d %H:%M:%S.%f'

date_1 = '2016-09-24 17:42:27.839496'
date_2 = '2017-01-18 10:24:08.629327'

start = datetime.strptime(date_1, date_format_str)
end =   datetime.strptime(date_2, date_format_str)

diff = end - start

# Get interval between two timstamps as timedelta object
diff_in_hours = diff.total_seconds() / 3600
print(diff_in_hours)

# get the difference between two dates as timedelta object
diff = end.date() - start.date()
print(diff.days)

Pandas
import datetime
from datetime import date
from datetime import datetime
import pandas as pd

date_1 = '2016-09-24 17:42:27.839496'
date_2 = '2017-01-18 10:24:08.629327'

start = pd.to_datetime(date_1, format='%Y-%m-%d %H:%M:%S.%f')
end = pd.to_datetime(date_2, format='%Y-%m-%d %H:%M:%S.%f')

# get the difference between two datetimes as timedelta object
diff = end - start

print(diff.days)


text:
Q: Facing gargle error while running R script while running this code:
gs4_auth(email = 'sandeep.maxxxx@xxx.com')

I got the following error:

gs4_auth(email = 'sandeep.maxxx@xxx.com')
getting below error:
trying token_fetch()
trying credentials_service_account()
Error caught by token_fetch():
Argument 'txt' must be a JSON string, URL or file.
trying credentials_external_account()
aws.ec2metadata not installed; can't detect whether running on EC2 instance
trying credentials_app_default()
trying credentials_gce()
trying credentials_byo_oauth()
Error caught by token_fetch():
inherits(token, "Token2.0") is not TRUE
trying credentials_user_oauth2()
Gargle2.0 initialize
attempt to access internal gargle data from: googlesheets4
adding "userinfo.email" scope
loading token from the cache
matching token found in the cache