text:
Q: How to display a MsgBox in case of error 1004 Created this code to change pivot fields in 4 different workbooks.
Option Explicit

Sub Account_Name()

    Workbooks.Open "C:\Book1.xlsm"
    Workbooks.Open "C:\Book2.xlsx"
    Workbooks.Open "C:\Book3.xlsx"
    Workbooks.Open "C:\Book4.xlsx"

    Dim workbookNames As Variant
    workbookNames = Array("Book1.xlsm", "Book2.xlsx", "Book3.xlsx", "Book4.xlsx")

    Dim i As Long
    For i = LBound(workbookNames) To UBound(workbookNames)

        Dim wb As Workbook
        Set wb = Workbooks(workbookNames(i))

        Dim ws As Worksheet
        Set ws = wb.Worksheets("Analysis")

        Dim rootAccount As String
        rootAccount = ws.Cells(1, 6).Value

        Dim pt As PivotTable
        For Each pt In ws.PivotTables
            With pt
                With .PivotFields("Root Account")
                    .ClearAllFilters
                    .CurrentPage = rootAccount
                End With
            End With
            Next pt
    Next i

End Sub

Code is working fine until Root Account is found in all 4 workbooks but if any Root Account is not available in any of the workbooks it gives Runtime Error 1004.  In such case, is it possible to clear filter from Root Account and display MsgBox that this Root Account is not available. TIA

A: On Error Resume Next When Single Statement
' Declare a Long variable to hold the error number.
Dim cpErrNum As Long

With .PivotFields("Root Account")
    .ClearAllFilters

    ' Attempt to...
    On Error Resume Next ' defer error trapping (ignore errors)
        .CurrentPage = rootAccount ' ... do this.
        cpErrNum = Err.Number ' store the error number in the variable
    On Error GoTo 0 ' disable error handling
    If cpErrNum <> 0 Then ' an error occurred
        MsgBox "Root Account is not available.", vbExclamation
    'Else ' no error occurred i.e. 'cpErrNum = 0'; do nothing
    End If

End With

*

*Note that objects are handled differently i.e. there is no need for the Long variable and you check if the object was not referenced with e.g. If obj Is Nothing Then.


text:
Q: Run sudo as another non-root user and save in this user's home directory I added a new group: ircuser and a new user: ircuser
In visudo I placed this line:
myuser localhost=(ircuser) NOPASSWD: /usr/bin/irssi

Created ircuser directory, where config files, caches, etc should be saved:
drwxrwx--- 2 ircuser ircuser 4096 Mar  2 10:28 ircuser

When issuing the command:
sudo -Hu ircuser /usr/bin/irssi

or
sudo -u ircuser /usr/bin/irssi

The program can't save the config file in the ircuser directory.
** ERROR **: Couldn't create /home/myuser/_web/ircuser/.irssi directory
aborting...
Aborted

But, it is being run as ircuser:
ps auxw | grep irssi
ircuser  11962  0.0  0.0  23684  2504 pts/6    S+   11:18   0:00 /usr/bin/irssi

So, albeit irssi is run by ircuser it can't write to a directory owned by the same user?
What do I need to change to allow it saving there?

A: The problem probably lies in not having eXecute permission in one of the parent directories leading up to ircuser's home directory.  In order for any user to traverse, not necessarily look into a directory, that user must have execute permission either via a group, or via other.  If you have these permissions:
drwxrwx--- 2 myuser myuser 4096 Mar  2 10:28 /home/myuser

And ircuser is not part of the myuser group, then ircuser can't access any file underneath even if it has permissions for that directory.  If you try this instead:
drwxrwx--x 2 myuser myuser 4096 Mar  2 10:28 /home/myuser

Then ircuser can't browse myuser's home directory, but it can potentially access some file beneath it such as /home/myuser/_web/ircuser
UPDATE: A few more details I left out from the above description.  Permissions are evaluated as you traverse the file system.  It's possible to be able to access a folder starting from the current directory that you can't access starting from the root directory.  If you change your working directory to somewhere else, you will loose your handle on the current directory and loose access to the files in it.  If you use something like sudo su - ircuser, su will switch to the home directory of ircuser before dropping root privileges.  At that point, you have a valid handle for ircuser's home directory because it's the current working directory.  If you start irssi, it will be running in ircuser's home directory as ircuser.  If you try to access .irssi, that will work because you have eXecute permission on the current direcory.  If you have to traverse a directory where you are lacking eXecute permission, iy will fail.  For example, opening up the file /home/myuser/_web/ircuser/.irssi or even starting from the current directory and using the relative path of ../../_web/ircuser/.irssi because it requires traversing /home/myuser where you have no eXecute permission.

A: Use the -H option which makes the command executed with sudo to consider 'home' the user's home directory. You can find more detailed explanation on sudo's man page: http://linux.die.net/man/8/sudo

A: Would you mind trying with
  sudo -iu ircuser /usr/bin/irssi ?
Additionally, as Patkos Csaba already stated check for the env_reset, env_keep Defaults set in your sudoers.
From the sudoers manpage:
As a special case, if sudo's -i option (initial login) is specified,
sudoers will initialize the environment regardless of the value of
env_reset.  The DISPLAY, PATH and TERM variables remain unchanged;
HOME, MAIL, SHELL, USER, and LOGNAME are set based on the target user.
On Linux and AIX systems the contents of /etc/environment are also
included.  All other environment variables are removed.

So sudo -i will initialize the environment getting around the values of these.
Edit: I've reproduced your setup on a Ubuntu box and even sudo -u ircuser /usr/bin/irssi works fine for me.
From my /etc/sudoers
<snipped>
Defaults    env_reset, log_output
<snipped>
testing LABUBU01=(ircuser) NOPASSWD: /usr/bin/irssi

Versions:
testing@LABUBU01:~$ sudo -V
Sudo version 1.8.3p1
pmplugin policy_plugin 5.6.0 (034)
pmplugin io_plugin 5.6.0 (034)
testing@LABUBU01:~$ uname -a
Linux LABUBU01 2.6.35-28-generic #50-Ubuntu SMP Fri Mar 18 19:00:26 UTC 2011 i686 GNU/Linux

testing@LABUBU01:~$ ls -lap /home/
total 64
drwxr-xr-x 16 root     root     4096 2012-03-02 15:57 ./
drwxr-xr-x 22 root     root     4096 2011-12-08 15:48 ../
drwxr-xr-x  3 ircuser  ircuser  4096 2012-03-02 15:57 ircuser/

/EDIT
EDIT2:
your error:

** ERROR **: Couldn't create /home/myuser/_web/ircuser/.irssi directory
  aborting...
  Aborted

states, it cannot create /home/myuser/_web/ircuser/.irssi which is in your home, not in ircuser's home directory.
/EDIT2

redpajama_set_name: RedPajamaStackExchange


text:
Q: NGXS maintain a map of states instead of arrays I'm looking into using NGXS for maintaining the current prices of tickers coming from the server. I might have a lot of symbols in the application so I'd rather be able to index into them using a hash key instead of an array.
what I would like would look like something like this.
export interface SymbolCurrentPriceModel {
  updateTime: number;
  symbol: string;
  currentPrice: number;
}

const SYMBOL_CURRENT_PRICES_TOKEN = new StateToken<Map<string, SymbolCurrentPriceModel>>('symbolCurrentPrices');

I can do it like this, however I don't want to dispatch the whole map on an action when one of the symbols changes values. Instead I would like to per symbol if that's possible.
On the selector side, I'm imagining something like this to access these values
  @Selector([SYMBOL_CURRENT_PRICES_TOKEN])
  static getCurrentPrice(state: Map<string, SymbolCurrentPriceModel>) {
    return (symbol: string) => {
      return state[symbol];
    };
  }

I can't seem to be able to find an example in the docs that would support this use case https://www.ngxs.io/concepts/state
In addition to this, I would like my selector to fetch the value if it isn't in the store. Is that a use case handled by NGSX?


text:
Q: bootstrap how to align content with navbar I am trying to align the content of the page with the "home" button of the navbar this is the result i have at the moment

As you can see the "Users" field and the searchbar are not well aligned with the home button.
Here is all the HTML of the page:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='index.css') }}">

                Home

        Sign in
        Sign up

Users

                <input type="text" class="form-control" placeholder="Search by username" aria-label="Search by username" aria-describedby="basic-addon2">

                    <button class="btn btn-outline-primary" type="button">Search</button>

                    <button type="button" class="btn btn-primary">Left</button>
                    <button type="button" class="btn btn-primary">Middle</button>
                    <button type="button" class="btn btn-primary">Right</button>

I am new to bootstrap so i dont really know that much on how to align elements.

A: One of the solution would be overriding of padding-left property of .container-fluid class:
.container-fluid.padding-left {
  padding-left: 0.3rem;
}

An example:

@media (min-width: 768px) {
  .container-fluid.padding-left {
    padding-left: 0.3rem;
  }
}

@media (max-width: 767px) {
  .container-fluid.padding-left {
    padding-left: 0;
  }
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='index.css') }}">

                Home

        Sign in
        Sign up

Users

                <input type="text" class="form-control" placeholder="Search by username" aria-label="Search by username" aria-describedby="basic-addon2">

                    <button class="btn btn-outline-primary" type="button">Search</button>

                    <button type="button" class="btn btn-primary">Left</button>
                    <button type="button" class="btn btn-primary">Middle</button>
                    <button type="button" class="btn btn-primary">Right</button>


text:
Q: Наследование от объединения (union) Здравствуйте.
Разъясните, пожалуйста, почему нельзя наследоваться от union?
union Uexample{
    int u1;
    int u2;
};
class Cexample : public Uexample {};

Ошибка:

error C2569: 'Uexample' : enum/union cannot be used as a base class

Хотя наследоваться от структуры возможно.
struct Sexample{
    int s1;
    int s2;
};
class Cexample : public Sexample {};

A: Структура и клас это почти одно и тоже за исключением того что отличаются доступом (public / private) по умолчанию, а вот объединение к ним никак не относится это всего лишь две или более переменных находящиеся в одном адресном пространстве, Вы же не будете делать наследование от обычной переменной.


text:
Q: Android - Fragment Abre antes dos dados estarem prontos Estou com problema de uma lista de objetos que vem em um JSON, eu consigo pegar os dados, ele chagam, eles devem ser apresentados num Fragment que possui um RecyclerView, o app abre e não mostra nada. Ao analisar os logs percebi que o Fragment abre antes dos dados estarem prontos.
Não sei como resolver isso.


text:
Q: How to auto-link boost libraries with CMake project(learn)

cmake_minimum_required(VERSION 3.11)

set(CMAKE_CXX_STANDARD 17)

if(${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
    message("Current OS is Linux")
    include_directories("/mnt/e/c++/boost_1_72_0")
    link_directories("/mnt/e/c++/boost_1_72_0/stage/lib")
    link_libraries(pthread boost_thread boost_fiber boost_context)
elseif(${CMAKE_SYSTEM_NAME} STREQUAL "Windows")
    message("Current OS is Windows")
    include_directories("E:/c++/boost_1_72_0")
    link_directories("E:/c++/boost_1_72_0/stage/lib")
endif(${CMAKE_SYSTEM_NAME} STREQUAL "Linux")

add_executable(learn_asio learn_asio.cpp)

learn_asio.cpp:
#include <boost/asio.hpp>
#include <boost/fiber/all.hpp>
#include <boost/thread.hpp>
#include <iostream>

using boost::asio::async_write;
using boost::asio::buffer;
using boost::asio::io_context;
using boost::asio::use_future;
using boost::asio::ip::make_address;
using boost::asio::ip::tcp;
using boost::fibers::async;
using boost::fibers::fiber;
using boost::system::error_code;

int main(){
  io_context ioc;
  tcp::socket socket(ioc);

  tcp::endpoint ep(make_address("192.168.1.20"), 80);

  auto ret_f = socket.async_connect(ep, boost::asio::use_future);

  boost::thread_group t;
  t.create_thread([&ioc]() {
    ioc.run();
    std::cout << "jfiejf" << std::endl;
  });

  ret_f.wait_for(std::chrono::seconds(3));

  t.join_all();

  return 0;
}

My library folder:

Accroding to the code above I can successfully build my code. But I hate the code:
link_libraries(pthread boost_thread boost_fiber boost_context)

on the linux platform. Why do I not need it on windows platforms? As I remember Linux can auto link the library too.
How can I achieve it?

A: Boost docs:

Auto-Linking
Most Windows compilers and linkers have so-called "auto-linking support," which eliminates the second challenge. Special code in Boost header files detects your compiler options and uses that information to encode the name of the correct library into your object files; the linker selects the library with that name from the directories you've told it to search.
The GCC toolchains (Cygwin and MinGW) are notable exceptions; GCC users should refer to the linking instructions for Unix variant OSes for the appropriate command-line options to use.

Note that the auto-linking feature has been known to fail on occasion (e.g. when your Boost libraries are installed using a non-standard setting). You can define BOOST_ALL_NO_LIB to disable the feature on Windows.
You shouldn't be hard-coding Boost paths into your CMakeLists.txt, though.  Better use the platform-independent find_package:
set( Boost_USE_STATIC_LIBS OFF )
set( Boost_USE_MULTITHREADED ON )
set( Boost_USE_STATIC_RUNTIME OFF )

find_package( Boost 1.72.0 COMPONENTS thread fiber context )

if ( Boost_FOUND )
    include_directories( ${Boost_INCLUDE_DIRS} )
    link_libraries( learn_asio ${Boost_LIBRARIES} )
else()
    message( FATAL_ERROR "Required Boost packages not found. Perhaps add -DBOOST_ROOT?" )
endif()


text:
Q: Django and Postgresql with DateTimeField model field giving different results I have defined a class for which I inherit form:
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)

In postgresql I see the entry created like:
2014-02-24 17:04:05.904248-05 (correct timezone)

And django spits it out like:
2014-02-24 22:04:05.904213+00:00 (incorrect)

In my settings.py I have,
TIME_ZONE = 'US/Eastern'
USE_TZ = True

I've also noticed a similar issue for the field date_done in djcelery's taskmeta table.
I've done some reading and I know it's quite tricky, just thought if anyone could help.


text:
Q: FAST function OpenCV Debug Assertion Faild when I try debug my project, I get Debug Assertion Failed, at the end of the execution up. You can see it below.

I think that the problem is related to FAST function from OpenCV, because when I comment out the line which contains this function, it works fine.
This is my code:
#pragma once
#include <opencv2/core/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
using namespace cv;
using namespace std;
int main()
{
    string table[2] = { "background_2.jpg","foreground_2.jpg" };
    Mat firstImage = imread(table[0], IMREAD_COLOR);
    Mat secondImage = imread(table[1], IMREAD_COLOR);
    Mat result;
    subtract(firstImage, secondImage, result);
    Mat resultGray, firstImageGray, secondImageGray;

    cvtColor(firstImage, firstImageGray, COLOR_BGR2GRAY);
    cvtColor(secondImage, secondImageGray, COLOR_BGR2GRAY);
    cvtColor(result, resultGray, COLOR_BGR2GRAY);

    Canny(firstImageGray, firstImageGray, 33, 100, 3);
    Canny(secondImageGray, secondImageGray, 33, 100, 3);
    Canny(resultGray, resultGray, 33, 100, 3);

    vector <KeyPoint> keyPoints;
    FAST(resultGray, keyPoints, 9, true);//Probably here is the problem.
    Mat resultKeyPoints;
    drawKeypoints(resultGray, keyPoints, resultKeyPoints, 156);

    return 0;
}

I build my project in Visual Studio 2015 Preview.
When I clicked "Retry" to break at that assertion, I got the following exception:
Unhandled exception at 0x00007FF851891B4B (ucrtbased.dll) in

OpenCVProject.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.

This is in xmemory0 file from VS in 120 line.

A: I found the answer. I changed in Property Pages in my project Platform Toolset from Visual Studio 2015 (v140) to Visual Studio 2013 (v120). Now it works fine. It seems that the problem wasn't in FAST function, but in this case, that I use VS 2015 with OpenCV 3.0. @drescherjm thank you for help me do this.


text:
Q: How to unit test an Angular component which uses CarouselModule I've created a custom component TorsoComponent which uses another custom component SponcerComponent which uses a carousel. I need to test TorsoComponent and not the carousel (Carousel is a dependency I installed from NPM). So I'm not concerned with that but it is blocking my Torso testing. Here is my code.
package.json
"dependencies": {
...
"ngx-owl-carousel-o": "^2.0.3"
}
app.module.ts
import { CarouselModule } from 'ngx-owl-carousel-o';
...
@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    CarouselModule,
    ...
  ]})

sponcers.component.ts
import { Component, OnInit } from '@angular/core';
import { OwlOptions } from 'ngx-owl-carousel-o';
@Component({
  ...
})
export class SponcersComponent {
  customOptions: OwlOptions = {
    ...
}

sponcers.component.html
<owl-carousel-o [options]="customOptions">
    <ng-template carouselSlide>

    </ng-template>
    <ng-template carouselSlide>

        </ng-template>
    <ng-template carouselSlide>
    ...
</owl-carousel-o>

Now comes the spec file where I need help.
torso.component.html
<app-sponcers></app-sponcers>

torso.component.spec.ts
import { TestBed, async } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { CarouselModule } from 'ngx-owl-carousel-o';
import { SponcersComponent } from '../sponcers/sponcers.component';
import { TorsoComponent } from './torso.component';

fdescribe('TorsoComponent', ()=> {

  beforeEach(async()=> {
    TestBed.configureTestingModule({
      declarations: [TorsoComponent, SponcersComponent, CarouselModule ],
      imports: [TranslateModule.forRoot()]
    }).compileComponents();
  })

  it('should create', () => {
    const fixture = TestBed.createComponent(TorsoComponent);
    const app = fixture.debugElement.componentInstance;
  })
})

I've been told strictly to avoid using CUSTOM_ELEMENTS_SCHEMA. Right now I'm getting this error:

Please point out my mistakes.

A: You should use imports to import the CarouselModule as below
import { TestBed, async } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { CarouselModule } from 'ngx-owl-carousel-o';
import { SponcersComponent } from '../sponcers/sponcers.component';
import { TorsoComponent } from './torso.component';

fdescribe('TorsoComponent', ()=> {

  beforeEach(async()=> {
    TestBed.configureTestingModule({
      imports: [CarouselModule], // <-- should be added here
      declarations: [TorsoComponent, SponcersComponent ],
      imports: [TranslateModule.forRoot()]
    }).compileComponents();
  })

  it('should create', () => {
    const fixture = TestBed.createComponent(TorsoComponent);
    const app = fixture.debugElement.componentInstance;
  })
})


text:
Q: How to download a file with resume support using Indy? I have already tried code from StackOverflow, f.e. Download, pause and resume an download using Indy components.
But when I try to use IdHttp1.Disconnect() in order to pause download and then resume it, the download does not resume. The file is downloaded from zero. So, what should I do in order to add resume support to my Delphi app?
BTW: the server allows download resuming, because IDM can resume the download.

A: You have to check the size of the remote file, and the size of the local file (if exists).
If the size of the remote file is larger than the size of the local file, then you have to set the Ranges property of the Request property of TIdHTTP to the starting point (the local file size).
For example, if the remote file size is 100000 bytes, and the local file size is 80000 bytes, then you have to set http.Request.Ranges to start at 80000.
Here is a fully working code for you to use:
function FileSize(const FileName: string): Int64;
var
  AttributeData: TWin32FileAttributeData;
begin
  if GetFileAttributesEx(PChar(FileName), GetFileExInfoStandard, @AttributeData) then
  begin
    Int64Rec(Result).Lo := AttributeData.nFileSizeLow;
    Int64Rec(Result).Hi := AttributeData.nFileSizeHigh;
  end
  else
    Result := -1;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  http: TIdHTTP;
  FS: TFileStream;
  file_url: String;
  file_path: String;
  web_file_size: Integer;
  local_file_size: Integer;
  IhaveToDownload: Boolean;
begin
  file_url := 'http://212.183.159.230/50MB.zip';
  file_path := 'C:\50MB.zip';
  IhaveToDownload := False;

  FS := nil;
  http := TIdHTTP.Create(nil);
  try
    //I will check if local file exists
    if FileExists(file_path) then
    begin
      //I have to run http.Head() to get the ContentLength of the remote file.
      http.Head(file_url);

      //web_file_size now has the remote file size in bytes
      web_file_size := http.Response.ContentLength;
      //local_file_size now has the local file size in bytes
      local_file_size := FileSize(file_path);

      //check if remote file is bigger than local file (so I have to resume download)
      if (web_file_size > local_file_size) and (http.Response.AcceptRanges = 'bytes') then
      begin
        //remote file is bigger than local file, so I will resume download.
        http.Request.Ranges.Add.StartPos := local_file_size;
        FS := TFileStream.Create(file_path, fmOpenReadWrite);
        FS.Position := local_file_size;
        IhaveToDownload := True;
      end
      else if web_file_size <> local_file_size then
      begin
        //remote file is not equal with local file, so I will restart download.
        FS := TFileStream.Create(file_path, fmCreate);
        IhaveToDownload := True;
      end;
    end
    else
    begin
      //File does not exist locally. I will create a new local file
      FS := TFileStream.Create(file_path, fmCreate);
      IhaveToDownload := True;
    end;

    if IhaveToDownload then
      http.Get(file_url, FS);
  finally
    FS.Free;
    http.Free;
  end;
end;


text:
Q: How can I remove same word from the list? I want to delete the same word score  from the all elements in list:
scorelist = ['100score', '200score', '300score']

scorelist = ['100', '200', '300']

A: According to your comments, you're using Python. How about .replace()?
scorelist = ['100score', '200score', '300score']
newlist = []
for score in scorelist:
  newlist.append(score.replace('score',''))

print(newlist)

Try it here!
In python, strings are immutable - that means they can't be changed. Just doing score.replace('score', '') isn't enough - this function returns a string that we can then capture and use.
Good luck!

A: In PHP
function test_alter(&$item1, $key, $prefix)
{

    //  replace string
    $item1= str_replace($prefix, "", $item1);

}

array_walk($scorelist, 'test_alter', 'score');


text:
Q: Function that creates a file in a directory I have 4 directories: dir1 dir2 dir3 dir4. I want to create a file in each directory. I know I can do this: touch file1.txt and then move it to dir1, then touch file2.txt then move it to dir2 but it takes ages. How can I create a function that creates a text file in each of the directories? Thanks

A: You don't need to create and then move files - you can touch them in place ex.
touch dir1/file1.txt dir2/file2.txt dir3/file3.txt

It won't really save you any time (or typing) but you can of course create a shell function for this - a minimal implementation would be
mkfile() { touch "$1"/"$2"; }

which you can invoke as
mkfile dir1 file1.txt

although of course it should really include some checking / error handling (such as what to do if $1 is not a directory, or doesn't exist).
If your file and directory structure is always of the form dirN/fileN.txt then there are some better ways to automate the creation such as
seq 1 3 | xargs -I{} touch dir{}/file{}.txt

or even (using GNU parallel and brace expansion)
parallel touch dir{}/file{}.txt ::: {1..3}

A: Not sure what you regard as 'ages'. There's no function that would create 4 files in parallel for you. Assuming you're using bash or similar the 'easiest' way is probably a loop. e.g.:
DIR=dir
for i in 1 2 3 4
do
  touch "${DIR}i"
done

That's pretty quick on any machine I use. If you want an atomic 4 file create, I'm afraid there's no real way to do this.
Note that if there's content in the 4 files, the 'quickest' way in terms of lag between the first file appearing and the last one would be create the files elsewhere and then mv them.


text:
Q: Как сделать кнопку постоянно активной? Делаю переключение языков на сайте через 2 кнопки, есть отельный файл с переводами каждого класса, при нажатии на кнопку язык переключает без ошибок, но всего на долю секунды. Как решить?
buttonUA.addEventListener('click', changeURLLanguageUA);
buttonEN.addEventListener('click', changeURLLanguageEN);

// Перенаправляет URL с указанием языка
function changeURLLanguageUA(){
 let lang = buttonUA.value;
 location.href = window.location.pathname + '#'+lang;
 location.reload();
}
function changeURLLanguageEN(){
 let lang = buttonEN.value;
 location.href = window.location.pathname + '#'+lang;
 location.reload();
}

// Функции перевода
buttonUA.addEventListener('click', function() {
 hash = buttonUA.value
 for (let key in langland) {
    document.querySelector('.lng-' + key).innerHTML = langland[key][hash];
  }
});
buttonEN.addEventListener('click', function() {
 hash = buttonEN.value
 for (let key in langland) {
    document.querySelector('.lng-' + key).innerHTML = langland[key][hash];
  }
});

A: У вас два обработчика клика на каждую из кнопок. Один обработчик переводит данные, другой - перенаправляет.  Получается, что вначале успевает один сработать, потом происходит перезагрузка страницы. Вы определитесь что вы хотите. Скорее всего вам надо перевод данных делать не по клику на кнопку а после перезагрузки страницы, т.е. на событии DOMContentLoaded
document.addEventListener("DOMContentLoaded", function(event) {
    ... тут код
    ... считываем хэш из URL
    ... вызываем функцию перевода с передачей туда значение хэша
    ... ПРИ ЭТОМ ФУНКЦИЯ ПЕРЕВОДА ОСТАНЕТСЯ ОДНА....этого достаточно
});


text:
Q: How to change the kendo dropdownlist default display text by value? I've a kendo dropdownlist which displays a primary location. I want the dropdown to set to this primary location as the default location when I click on reset.
I'm using this:
$("#dropDownList").val(20);
$("#dropDownList").trigger("change");

It's internally changing the value, but the display text does not change.
I tried the following options but nothing seems to be changing the default text:
$('#dropDownList option[Value=20]').attr('selected', 'selected');
$('select#dropDownList').val('20');

A: For a kendoDropDownList control, you need to do the following:
                var data = [
                    { text: "Black", value: "1" },
                    { text: "Orange", value: "20" },
                    { text: "Grey", value: "3" }
                ];

                // create DropDownList from input HTML element
                $("#dropDownList").kendoDropDownList({
                    dataTextField: "text",
                    dataValueField: "value",
                    dataSource: data,
                    index: 0,
                    change: onChange
                });

                var dropDownList= $("#dropDownList").data("kendoDropDownList");

                dropDownList.select(function(dataItem) {
                    return dataItem.value === "20"; //20 is selected now
                });
                dropDownList.trigger("change");

A: You basically want this then which sets the selected option to the value you want.
$('#dropDownList').on('change', function(){
     $('#dropDownList option:selected').val('20');
});


text:
Q: how to unmap a network driver when a user logs out of my vb6.0 project software? this Code will map my PC to a Network drive within the LAN that my PC is connected to. now what i want is to undo the mapping that this code does.
can you provide any sample code/suggestion?
Dim WshNetwork As Object
Set WshNetwork = CreateObject("WScript.Network")
WshNetwork.MapNetworkDrive "Y:", "\\172.16.11.240\pmva_dtr"

A: You can use RemoveNetworkDrive:
WshNetwork.RemoveNetworkDrive "Y:"


text:
Q: Is this exercise on proofs mathematically correct? I was doing some exercises on proof techniques from the book "Proofs and Fundamentals: A first course in abstract mathematics" and then I saw this exercise which is as far as I know incorrect. The exercise says:
Let c be an integer. Suppose that c ≥ 2, and that c is not a prime number. Prove that there is an integer b such that b ≥ 2, that b|c and that b≤√c
If the number c is not prime then it can't be equal to 2 or am I missing something here? Because this affects also the rest of the proof the way that I have thought about it at least.


text:
Q: SharePoint External Sharing: Enabled in Admin Center, but not possible anyway in our SharePoint-Online tenant, external sharing isn't possible anymore from one day to another.
No one changed something in the admin settings and the settings should be set correctly:

The enduser sharing dialogue looks like this since a few days:

External sharing isn't disabled on sharePoint site collection level, it's not possible on all sharePoint site collections: team sites and communication sites.
Has someone experienced something similar? Was there an update from microsoft who could have something to do with this?
Thank you for your help!

A: First have a try to use powershell to set sharing ability. If this works for a certain site, you can apply this for all the site collections in your tenant
connect-sposervice -url https://<domain>-admin.sharepoint.com -cred(get-credential)
set-sposite -identity <siteURl> -SharingCapability ExternalUserAndGuestSharing

A: you can do this from SharePoint admin center.
Navigate to SPO Admin Center >>  Active sites >> select site from list of active site
On top bar you will see Sharing command click that.


text:
Q: I can't seem to get --py-files on Spark to work I'm having a problem with using Python on Spark. My application has some dependencies, such as numpy, pandas, astropy, etc. I cannot use virtualenv to create an environment with all dependencies, since the nodes on the cluster do not have any common mountpoint or filesystem, besides HDFS. Therefore I am stuck with using spark-submit --py-files. I package the contents of site-packages in a ZIP file and submit the job like with --py-files=dependencies.zip option (as suggested in Easiest way to install Python dependencies on Spark executor nodes?). However, the nodes on cluster still do not seem to see the modules inside and they throw ImportError such as this when importing numpy.
File "/path/anonymized/module.py", line 6, in <module>
    import numpy
File "/tmp/pip-build-4fjFLQ/numpy/numpy/__init__.py", line 180, in <module>
File "/tmp/pip-build-4fjFLQ/numpy/numpy/add_newdocs.py", line 13, in <module>
File "/tmp/pip-build-4fjFLQ/numpy/numpy/lib/__init__.py", line 8, in <module>
    #
File "/tmp/pip-build-4fjFLQ/numpy/numpy/lib/type_check.py", line 11, in <module>
File "/tmp/pip-build-4fjFLQ/numpy/numpy/core/__init__.py", line 14, in <module>
ImportError: cannot import name multiarray

When I switch to the virtualenv and use the local pyspark shell, everything works fine, so the dependencies are all there. Does anyone know, what might cause this problem and how to fix it?
Thanks!

A: First off, I'll assume that your dependencies are listed in requirements.txt. To package and zip the dependencies, run the following at the command line:
pip install -t dependencies -r requirements.txt
cd dependencies
zip -r ../dependencies.zip .

Above, the cd dependencies command is crucial to ensure that the modules are the in the top level of the zip file. Thanks to Dan Corin's post for heads up.
Next, submit the job via:
spark-submit --py-files dependencies.zip spark_job.py

The --py-files directive sends the zip file to the Spark workers but does not add it to the PYTHONPATH (source of confusion for me). To add the dependencies to the PYTHONPATH to fix the ImportError, add the following line to the Spark job, spark_job.py:
sc.addPyFile("dependencies.zip")

A caveat from this Cloudera post:

An assumption that anyone doing distributed computing with commodity
  hardware must assume is that the underlying hardware is potentially
  heterogeneous. A Python egg built on a client machine will be specific
  to the client's CPU architecture because of the required C
  compilation. Distributing an egg for a complex, compiled package like
  NumPy, SciPy, or pandas is a brittle solution that is likely to fail
  on most clusters, at least eventually.

Although the solution above does not build an egg, the same guideline applies.

A: *

*First you need to pass your files through --py-files or --files

*

*When you pass your zip/files with the above flags, basically your resources will be transferred to temporary directory created on HDFS just for the lifetime of that application.

*Now in your code, add those zip/files by using the following command
sc.addPyFile("your zip/file")

*

*what the above does is, it loads the files to the execution environment, like JVM.

*Now import your zip/file in your code with an alias like the following to start referencing it
import zip/file as your-alias
Note: You need not use file extension while importing, like .py at the end
Hope this is useful.

A: To get this dependency distribution approach to work with compiled extensions we need to do two things:

*

*Run the pip install on the same OS as your target cluster (preferably on the master node of the cluster). This ensures compatible binaries are included in your zip.

*Unzip your archive on the destination node. This is necessary since Python will not import compiled extensions from zip files. (https://docs.python.org/3.8/library/zipimport.html)

Using the following script to create your dependencies zip will ensure that you are isolated from any packages already installed on your system.  This assumes virtualenv is installed and requirements.txt is present in your current directory, and outputs a dependencies.zip with all your dependencies at the root level.
env_name=temp_env

# create the virtual env
virtualenv --python=$(which python3) --clear /tmp/${env_name}

# activate the virtual env
source /tmp/${env_name}/bin/activate

# download and install dependencies
pip install -r requirements.txt

# package the dependencies in dependencies.zip. the cd magic works around the fact that you can't specify a base dir to zip
(cd /tmp/${env_name}/lib/python*/site-packages/ && zip -r - *) > dependencies.zip

The dependencies can now be deployed, unzipped, and included in the PYTHONPATH as so
spark-submit \
  --master yarn \
  --deploy-mode cluster \
  --conf 'spark.yarn.dist.archives=dependencies.zip#deps' \
  --conf 'spark.yarn.appMasterEnv.PYTHONPATH=deps' \
  --conf 'spark.executorEnv.PYTHONPATH=deps' \
.
.
.

spark.yarn.dist.archives=dependencies.zip#deps
distributes your zip file and unzips it to a directory called deps
spark.yarn.appMasterEnv.PYTHONPATH=deps
spark.executorEnv.PYTHONPATH=deps
includes the deps directory in the PYTHONPATH for the master and all workers
--deploy-mode cluster
runs the master executor on the cluster so it picks up the dependencies

A: Try to use  --archives  to archive your anaconda dir to each server
 and use --conf spark.yarn.appMasterEnv.PYSPARK_PYTHON=  to tell your spark server where is your python executor path in your anaconda dir.
Our full config is this:
--conf spark.yarn.appMasterEnv.PYSPARK_PYTHON=./ANACONDA/anaconda-dependencies/bin/python

--archives <S3-path>/anaconda-dependencies.zip#ANACONDA

A: You can locate all the .pys you need and add them relatively.
see here  for this explanation:
import os, sys, inspect
 # realpath() will make your script run, even if you symlink it :)
 cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
 if cmd_folder not in sys.path:
     sys.path.insert(0, cmd_folder)

 # use this if you want to include modules from a subfolder
 cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
 if cmd_subfolder not in sys.path:
     sys.path.insert(0, cmd_subfolder)

 # Info:
 # cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
 # __file__ fails if script is called in different ways on Windows
 # __file__ fails if someone does os.chdir() before
 # sys.argv[0] also fails because it doesn't not always contains the path

A: Spark will also silently fail to load a zip archive that is created with the python zipfile module. Zip archives must be created using a zip utility.

A: As Andrej Palicka expained in the comments,

"the problem lies in the fact, that Python cannot import .so modules
from .zip files (docs.python.org/2/library/zipimport.html)".

A solution that I found is to add the non .py files one by one to py-files separated by comas:
spark-submit --py-files modules/toolbox.cpython-38-x86_64-linux-gnu.so,modules/product.cpython-38-x86_64-linux-gnu.so spark_fro

m_cython.py


text:
Q: client server communication in Java I am trying to set up a webserver on an old machine of mine. I have installed ubuntu server edition and aim to use it for the following:
I want to run a java program on the server. I want to be able to retrieve data from the program from another computer/phone using an internet connection. I also want to be able to give the program data, and get a response saying whether or not the data has been received correctly.
So for example:

*

*A .jar program runs on my server and holds a variable x

*I want to be able to query the value of x from another device (over the internet).

*I want to be able to set the value of x remotely from another device, and get a response saying it was successful in altering the value.

What are my options here? I would like to try and keep things simple. It is perhaps worth mentioning that I will be the only one using the system. The server will be used exclusively for dealing with the two requests outline above.
Is it simply the case of creating a java program that listens out for incoming requests and running that on the server?

A: *

*As you mentioned, you can start with custom ServerSocket wrapper which will decode incoming requests and do as it's bid. Currently, whole frameworks are done to encapsulate common code of this task -- see my 3rd point.

*Old-school java solution: use RMI. See RMI tutorial.

*New-school java solution: devise some simple text-based protocol with 2 commands:

*

*Read()

*Set(newVal)
Then implement that protocol over some new trendy Java framework, like Apache MINA, which is created specifically to facilitate quick development of network apps in Java.

I, personally, started with RMI for such kind of tasks. Since RMI is considered Core Java technology, it's wise to learn it.


text:
Q: Unknown type name 'instancetype' - Xcode I have two Xcode projects on my computer. Each of them has a declaration with return type 'instancetype', but somehow one project can compile while another is showing error: Unknow type name 'instancetype'.
I tried to find the reason by comparing two projects' build settings, but even everything is set to the same, the problem still not solved.
My projects are using Apple LLVM7.0, which I think already supports 'instancetype'. please tell me what are the potential causes of this.

A: To answer my own question: It seems I have incorrectly used 'instancetype' in a declaration like: instancetype methodA(args...), without a + or @interface.


text:
Q: Revising a PS installed programs retrieval script to show PC names I've been writing a script to let me know what programs people have installed on their computers that I'm not "cool" with. To accomplish this, im using this code:
$allowed = @"
Microsoft Office Shared 64-bit Setup Metadata MUI (English) 2016
64 Bit HP CIO Components Installer
Dolby Digital Plus Home Theater
Intel(R) Chipset Device Software
Intel(R) Management Engine Components
...
NVIDIA Install Application
NVIDIA nView 148.47
NVIDIA WMI 2.29.0
Symantec Endpoint Protection
"@ -split [System.Environment]::NewLine

$path = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\"

(Get-ChildItem -Path $path |
    Get-ItemProperty -Name DisplayName -EA SilentlyContinue).DisplayName |
    Where-Object {$_ -notin $allowed} | Sort | Out-File '"path"' -Width 60

and running it as a logon script from the domain controller.
It does work, and it works very well indeed. However, it doesn't show me which computer name it took the information from, so I just have a long list of programs, but I don't know what computer they are installed at.


text:
Q: How to retrive data from another DataTable than the one bind to DataGrid.ItemsSource I use SQLiteDatabase.
I create table and fill to DataTable in C#.
I have DataTable for every table in database.
In WPF programming,
I bind DataTable to DataGrid.ItemsSource
then I can do every task such as List, Add, Edit, Delete.

but the problem is
I don't know how to do something like "left outer join".
such as
I have table "Product" that have ID, Name.
and table "Order" that have ProductID.
so if I bind "Order" to DataGrid.ItemsSource
I can show just the "ProductID" not the Name of it.
I think about "Converter".
I try to search in the internet,
I can just Convert value to something no need outside data.
I don't know how to get Product DataTable from my object.


text:
Q: local variables in a function I know that variables are properties of other objects. For example:
var myVar = 'something';

is a property of the window object (if it is in the global scope of course).
if I want to find the variable's object, I just use the this variable. But:
function f() {
    var myVar2 = 'something';
}

Which object does myVar2 belongs to? (myVar belongs to window object, but what about myVar2?)
I would like to know that, thanks.

A: It doesn't belong to an object.  It belongs to the scope of the function f.  You access it by doing myVar within f.  You cannot access it outside of f.
If you did
function f() {
  this.myVar = 1;
}

now you can do
var myF = new f();
myF.myVar

indeed, this how user defined objects are sometimes defined.

A: myVar2 belongs to the local scope (of f), and myVar the global scope.

A: var does some interesting things. var statements are hoisted to the top of their functional scope. The var's functional scope is whatever function it happens to be in.
JavaScript doesn't have block-level scope, which means that:
(function () { //a closure to create new scope
    var foo;
    foo = 1;
    if (condition) {
        var bar;
        bar = 3;
    }
}());

...is equivalent to...
(function () {
    var foo,
        bar;
    foo = 1;
    if (condition) {
        bar = 3;
    }
}());

If the var statement has no parent, it will instead add the variable as a property to the global context, which in web browsers happens to be window.
This is the only time that using var will create a property. If want to create a property of an object, you simply have to set it:
(function () {
    var foo;
    foo = {};
    foo.bar = 'baz'; //this creates the `bar` property on `foo`
}());

JavaScript is a prototypal language with prototypal inheritance. Functions are first-class objects (because JavaScript isn't racist against functions). This means that functions can be used just like any other object.
You can set them:
(function () {
    var foo;
    //foo is now a function
    foo = function () {
        alert('Hello World');
    };
}());

You can set properties on them:
(function () {
    var foo;
    foo = function () {
        alert('Hello World');
    };
    foo.bar = 'baz'; //this works just fine
}());

You can even pass them as parameters:
(function () {
    var foo,
        bar;
    foo = function () {
        alert('Hello World');
    };
    bar = function (c) {
        c();
    };
    bar(foo); //guess what this does?
}());

Another cool thing that functions do, is they act as constructors. All functions are inherently constructors, you just need to call them using the new keyword:
(function () {
    var foo; //case sensitive
    //it doesn't matter whether you use `function Foo`
    //or `var Foo = function...`
    function Foo() {
        alert('Hello World');
    }
    foo = new Foo();
    foo.bar = 'baz';
}());

The important detail in using constructors is that the function's context (this) will be set to the object created by the constructor. This means that you can set properties on the object within the constructor:
(function () {
    var foo;
    function Foo() {
        this.bar = 'baz';
    }
    foo = new Foo();
    alert(foo.bar); //'baz'
}());


text:
Q: Is it possible to edit Sphinx needtable contents? For example, if I had this table:
.. needtable:: names of people
   :style: datatables
   :types: english
   :columns: names, age, birth

and it looks like this:
|Name      |Age |Birth   |
-------------------------
|John man  |20  |England |
|Jen Smith |30  |America |

Is it possible to manipulate the data so that only first names are shown?
|Name      |Age |Birth   |
-------------------------
|John      |20  |England |
|Jen       |30  |America |

Thought about using regex or :filter-func: but it doesn't work.


text:
Q: Android camera fails taking a picture every second Let me start by saying that if image shooting interval is anything more than 1 second it works. For example taking a picture every 2 seconds works perfectly fine. But taking a picture every second sometimes throws java.lang.RuntimeException: takePicture failed. What could be causing this kind of a behaviour?
Here is the code I use and it is in Service:
@Override
public void onCreate()
{
    super.onCreate();
    prefs = getSharedPreferences("general",Context.MODE_PRIVATE);
    handler = new Handler();

    shotInterval = prefs.getInt(getString(R.string.prefs_int_imageShootingFrequency),1);

    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG).show();
    } else {
        cameraId = findBackFacingCamera();
        if (cameraId < 0) {
            Toast.makeText(this, "No front facing camera found.",Toast.LENGTH_LONG).show();
        } else {
            camera = Camera.open(cameraId);
        }
    }

    cameraParameters = camera.getParameters();
    cameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); //set camera to continuously auto-focus
    camera.setParameters(cameraParameters);

    pictureTaker.run(); // Start looping
}

Runnable pictureTaker = new Runnable() {
    @Override
    public void run() {
        try {
            takePicture();
        } finally {
            // 100% guarantee that this always happens, even if
            // your update method throws an exception
            handler.postDelayed(pictureTaker, shotInterval*1000);
        }
    }
};

private void takePicture(){
    SurfaceView view = new SurfaceView(this);
    try {
        camera.setPreviewDisplay(view.getHolder());
        camera.startPreview();
        camera.takePicture(null, null,new PhotoHandler(getApplicationContext()));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

A: You should launch postDelayed() from the onPictureTaken() callback. You can check the system timer on call to takePicture() and reduce the delay respectively, to keep 1000ms repetition, but maybe once in a while, this delay will reach 0.


text:
Q: Finding previous month end date From date 10/31/2018, I want to obtain 09/30/2018.
I tried:
PREV.PROD.DATE<-seq.Date(from=as.Date(chron("10/31/2018")),length=2,by="-1 months")

but it returns:

"2018-10-31" "2018-10-01"

How can I obtain 09/30 instead of 10/01?
Notes: I would like to avoid to use an external package, and I would like the solution to work for any end of month date.

A: The integer units of Date are days, so you can do:
seq.Date(from=as.Date("2018-10-31"), length=2, by="-1 months") - c(0,1)
# [1] "2018-10-31" "2018-09-30"

If you want arbitrary prior-last-date:
(d <- as.POSIXlt(Sys.Date()))
# [1] "2018-11-08 UTC"
d$mday <- 1L
as.Date(d) - 1
# [1] "2018-10-31"

Replace Sys.Date() with whatever single date you have. If you want to vectorize this:
(ds <- Sys.Date() + c(5, 20, 50))
# [1] "2018-11-13" "2018-11-28" "2018-12-28"
lapply(as.POSIXlt(ds), function(a) as.Date(`$<-`(a, "mday", 1L)) - 1L)
# [[1]]
# [1] "2018-10-31"
# [[2]]
# [1] "2018-10-31"
# [[3]]
# [1] "2018-11-30"

A: I like to floor the date - making it the first day of its month, and then subtract 1 to make it the last day of the previous month:
x = as.Date("2018-10-31")
library(lubridate)
floor_date(x, unit = "months") - 1
# [1] "2018-09-30"

Here's a version without using other packages:
as.Date(format(x, "%Y-%m-01")) - 1
# [1] "2018-09-30"

A: I don't use function chron. But I think the function duration from lubridate helps you.
You don't need use floor_date to confuse you.
library(lubridate)
#>
#> 载入程辑包:'lubridate'
#> The following object is masked from 'package:base':
#>
#>     date
library(tidyverse)
better_date <-
    str_split("10/31/2018",'/') %>%
    .[[1]] %>%
    .[c(3,1,2)] %>%
    str_flatten(collapse = '-') %>%
    as.Date()
(better_date - duration('1 months')) %>%
    as.Date()
#> [1] "2018-09-30"

Created on 2018-11-09 by the reprex package (v0.2.1)


text:
Q: prevent tabs to be seen while window reloading I have a page which has 4 jquery UI tabs. The first tab just displays a message saying "HELLO".  The 2nd, 3rd and 4th tabs have some html and php scripts running. All the pages are getting displayed properly. But say for example I am executing the php script on the 3rd tab by submitting a button. It does get executed but when the page reloads, I see the first tab flicker for a second and then the 3rd tab gets displayed. Same is the case for all the tabs. The first tab always gets displayed for a seconds and then it goes. Could you please let me know to add some code so that the 1st tab (or the div in which it is written ) is bypassed when other tab executes some php script.
My Javascript is as follows :


text:
Q: Loading spinner not showing up in React JS web app I'm trying to include a loading spinner in my react web app to show the loading animation when the API is fetching the data. Below is the code:
import Head from "next/head";
import React, { useState } from "react";
import styles from "./index.module.css";
import Spinner from 'react-bootstrap/Spinner';

export default function Home() {
  const [bookInput, setBookInput] = useState("");
  const [result, setResult] = useState();
  const [isLoading, setIsLoading] = useState(false);

  async function onSubmit(event) {
    setIsLoading(true);
    event.preventDefault();
    try {
      const response = await fetch("/api/generate", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ book: bookInput }),
      });

      const data = await response.json();
      if (response.status !== 200) {
        throw data.error || new Error(`Request failed with status ${response.status}`);
      }
      setResult(data.result);
      setIsLoading(false);
      //setBookInput("");
    } catch(error) {
      // Consider implementing your own error handling logic here
      console.error(error);
      alert(error.message);
      setIsLoading(false);
    }
  }

  return (

        <title>Quickread</title>
        <link rel="icon" href="/book.png" />

QuickRead

        <form onSubmit={onSubmit}>
          <input
            type="text"
            name="book"
            placeholder="Enter a Book Title"
            value={bookInput}
            onChange={(e) => setBookInput(e.target.value)}
          />
           {isLoading ? <Spinner animation="border" role="status"/> : <input type="submit" value="Summarize" />}
        </form>

{result}

  );
}

I am using the react-bootstrap library for the loading spinner but not sure why is it not showing when the API is fetching the data. Appreciate if someone can help me on this.


text:
Q: Linux - Control Flow in a linux kernel module I am learning to write kernel modules and in one of the examples I had to make sure that a thread executed 10 times and exits, so I wrote this according to what I have studied:
#include <linux/module.h>
#include <linux/kthread.h>

struct task_struct *ts;
int flag = 0;
int id = 10;

int function(void *data) {
  int n = *(int*)data;
  set_current_state(TASK_INTERRUPTIBLE);
  schedule_timeout(n*HZ); // after doing this it executed infinitely and i had to reboot
  while(!kthread_should_stop()) {
    printk(KERN_EMERG "Ding");
  }
  flag = 1;
  return 0;
}

int init_module (void) {
  ts = kthread_run(function, (void *)&id, "spawn");
  return 0;
}

 void cleanup_module(void) {
   if (flag==1) { return; }
   else { if (ts != NULL) kthread_stop(ts);
   }
   return;
 }

MODULE_LICENSE("GPL");

What I want to know is :
a) How to make thread execute 10 times like a loop
b) How does the control flows in these kind of processes that is if we make it to execute 10 times then does it go back and forth between function and cleanup_module or init_module or what exactly happens?

A: If you control kthread with kthread_stop, the kthread shouldn't exit until be ing stopped (see also that answer). So, after executing all operations, kthread should wait until stopped.
Kernel already implements kthread_worker mechanism, when kthread just executes works, added to it.
DEFINE_KTHREAD_WORKER(worker);

struct my_work
{
    struct kthread_work *work; // 'Base' class
    int n;
};

void do_work(struct kthread_work *work)
{
    struct my_work* w = container_of(work, struct my_work, work);

    printk(KERN_EMERG "Ding %d", w->n);

    // And free work struct at the end
    kfree(w);
}

int init_module (void) {
    int i;
    for(i = 0; i < 10; i++)
    {
        struct my_work* w = kmalloc(sizeof(struct my_work), GFP_KERNEL);
        init_kthread_work(&w->work, &do_work);
        w->n = i + 1;
        queue_kthread_work(&worker, &w->work);
    }
    ts = kthread_run(&kthread_worker_fn, &worker, "spawn");
    return 0;
}

void cleanup_module(void) {
    kthread_stop(ts);
}


text:
Q: Trouble matching XML elements that has namespace attribute How would the conditional statement look like if I'm to insert a section of text into the xml below using xslt?
<items xmlns="http://mynamespace.com/definition">
    <item>
        <number id="1"/>
    </item>
    <item>
        <number id="2"/>
    </item>
    <!-- insert the below text -->
    <reference>
        <refNo id="a"/>
        <refNo id="b"/>
    </reference>
    <!-- end insert -->
</items>

This is how my xsl looks like at the moment (the condition is wrong...):
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns="http://mynamespace.com/definition"
    version="1.0">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:param name="addRef">
        <reference>
            <refNo id="a"/>
            <refNo id="b"/>
        </reference>
    </xsl:param>
    <xsl:template match="node()|@*" name="identity">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <!-- here is where the condition got stuck... -->
    <xsl:template match="/items[namespace-url()=*]/item[position()=last()]">
        <xsl:call-template name="identity"/>
        <xsl:copy-of select="$addRef"/>
    </xsl:template>
</xsl:stylesheet>

I wanted to add the reference section after the bottom-most , but I got stuck with how to get around matching an element that has a (explicit) namespace.
Thanks.

A: A better, and more elegant, way to solve this would be to use a prefix for your namespace. I prefer working with a null default namespace and using prefixes for all defined namespaces.
Matching on  fn:local-name() would match on the local name of the node in all namespaces. All that's needed in your matching condition if using a prefix for your namespace is my:item[last()].
Input:
<?xml version="1.0" encoding="UTF-8"?>
<items xmlns="http://mynamespace.com/definition">
  <item>
    <number id="1"/>
  </item>
  <item>
    <number id="2"/>
  </item>
</items>

XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
  xmlns:my="http://mynamespace.com/definition">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

  <xsl:param name="addRef">
    <!-- We set the default namespace to your namespace for this
         certain result tree fragment. -->
    <reference xmlns="http://mynamespace.com/definition">
      <refNo id="a"/>
      <refNo id="b"/>
    </reference>
  </xsl:param>

  <xsl:template match="node()|@*" name="identity">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="my:item[last()]">
    <xsl:call-template name="identity"/>
    <xsl:copy-of select="$addRef"/>
  </xsl:template>

</xsl:stylesheet>

Output:
<?xml version="1.0" encoding="UTF-8"?>
<items xmlns="http://mynamespace.com/definition">
  <item>
    <number id="1"/>
  </item>
  <item>
    <number id="2"/>
  </item>
  <reference>
    <refNo id="a"/>
    <refNo id="b"/>
  </reference>
</items>

A: Try this:
match="//*[local-name()='items']/*[local-name()='item'][position()=last()]"


text:
Q: Windows/.NET Load Distribution & Balancing Is there a vetted Windows-friendly, or even .NET-native, load-distributing/load-balancing utility out there along the lines of HA Proxy? We have a .NET stack product, and the one piece that we step out of the stack is for load-balancing.
We need something with configurable rules for distribution -- perhaps subdomain-driven -- that NLB alone doesn't seem to offer. If it integrates directly with .NET, or offers an exposed API callable by webservices, so much the better!
Thanks in advance!
Clarification: we need to logically part over boxes. This is not just a cluster/failover/replication scenario.
Further clarification: we are a WCF house. We already have a custom router and inspectors on our grid. We need distribution on the frontend however, which is where HA Proxy currently lives in our architecture. However, we need something we don't have to write then test the heck out of, as we're about to wrap a release and no one has cycles to test something up to the level of an HA Proxy.
Candidate solution: I was previously unaware of IIS7+ Application Request Routing (ARR) which uses the URLRewrite module. I'm not familiar with anyone who can speak to ARR's performance and stability, perhaps a Stacker can help me out?

A: I've been using Application Request Routing for several months now, though more for reverse proxying than load-balancing or farm management at this point in time.
It's certainly convenient when you're 100% Microsoft stack to begin with.
I can't speak to performance yet, at least not in any broad sense. Using it as a proxy introduces no user-noticeable performance hit, but it does introduce very occasional 502s, apparently when the content server takes longer to respond than the ARR controller is configured for timeout.
ARR appears to be fairly extensible, for integration with custom affinity providers, integration with third-party equipment like Citrix or F5, but I haven't fully explored this.
I've seen no "definite," no "regular" stability issues, but there has been some IIS flakiness that may be ARR-related. Inexplicable errors that go away with an app pool recycle, or server restart.
None of the minor issues encountered have prevented going to production. None of the minor issues encountered have been showstoppers for clients.

A: With .NET 4.0 we get the WCF Routing Service which looks to be a software based proxy we get out of the box, which could possibly be used to distribute load.  It can do content based routing, protocol mediation (tcp/ip->http or https->http) and is likely extensible in some fashion.
Some resources to get started:

*

*WCF Routing Service in .NET 4.0
channel 9 video.

*.NET 4.0 Training
Kit for some .NET 4.0 samples

You can always start rolling your own using these articles by Bustamante:

*

*Building a WCF Router, Part 1

*Building a WCF Router, Part 2
HTH,
Z


text:
Q: How to deploy python flask application on linux web app service through azure portal? I am trying to deploy my flask application on Linux web apps.
I want to set a azure pipeline for my code which is pushed on an azure repository.
I have made all the configuration changes in my python code and created a web app with runtime stack of Python 3.7
As soon as I go to deployment center to deploy my code, after selecting the azure repository as the source of my code, I am redirected to an option of azure pipelines where we have to configure our build settings.
But the build does not gives any option for Python. It just gives me four build options such as Node, Ruby, Asp.Net and php.
I cannot use :
- Docker
- Git
With such limitations I have found no suitable tutorial to do the same.
Can someone tell me some way to set the pipeline for my python project ?

A: Azure DevOps CI/CD works with any language, platform and cloud. Just for Python application, you may need add additional steps to achieve the deployment from Azure Devops CI/CD.

*

*CI
Since the python is an interpreted language, do not need the compilation. If none of other step, like test, just need use 2 tasks in CI pipeline: Archive Files task and Publish Build Artifacts task.

The Archive Files task used to pack the python application source folder into a zip package to use it in CD. And Publish Build Artifacts task will publish this zip package to Release pipeline.
BUT,
If your project contains and needs test, please add another Command line task to run the test by using pytest.
But, in azure devops, you need configure the python environment with some tasks if you want to use python component like pytest.
Here please refer to this blog.
Note: Since the stack you are using is Python 3.7, please specify the python version as 3.x in the Using Python task.

*

*CD
Since you have create the app service in Azure portal, just skip step 4(Add Azure CLI task) in Exercise 3: Configure Release pipeline which shown in this blog, because Step 4 just used to create a new Azure Resources.
1. To deploy the python application, you need add the Azure App Service manage task first to install the corresponding python version site extension in release pipeline:

It would install set of corresponding tools to support to manage your app service.
2. Next you could use Azure App Service deploy to deploy the zip package which created in the Build pipeline, to the app service you configured in Azure portal.
After specified the subscription in this task, the app service will automatically display in the drop list of App Service name:

Then specified the path which you configured in the publish task of the build pipeline. Replace $(Build.ArtifactStagingDirectory) as $(System.DefaultWorkingDirectory), and replace $(Build.BuildId) as * to search the zip package by using the fuzzy search.


text:
Q: android jsoup Parsing html Hello i am developing a post tracking application and my main tracking info query is based on parsing the info from html url connection using jsoup however i am facing a small issue. when i establish connection to the url and getting the entire text from the website i get result of "please wait while tracking info is retrieved" it is probably because the connection is immidiate but in my case i need to connect and wait a few seconds until the info is retrieve.so my question is What is the right approach for this?
thanks in advance
 public class gettracking extends AsyncTask<Void,Void,Void> {
    String status,TAG="trackingquery";

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
    }

    @Override
    protected Void doInBackground(Void... voids) {

        try {

            Document doc = Jsoup.connect("http://www.israelpost.co.il/itemtrace.nsf/mainsearch?OpenForm&L=HE&itemcode=RR123456789IL").get();

            status =doc.text();
            Log.d(TAG,status);
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }
}

}


text:
Q: Google maps draws circle at wrong position I'm showing marker and drawing circle using the same coordinates. Don't know why but my marker is offset a little bit to the top. How do you think what is the problem?

override func viewDidLoad() {
    super.viewDidLoad()

    let camera = GMSCameraPosition.camera(withLatitude: 37.36, longitude: -122.0, zoom: 13.0)

    setupMapWith(cameraPosition: camera)
    showMarker(position: camera.target)
    circleWith(position: camera.target)
}

func showMarker(position: CLLocationCoordinate2D) {
    let marker = GMSMarker()
    marker.position = position
    marker.title = "Palo Alto"
    marker.snippet = "San Francisco"
    let markerView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
    markerView.backgroundColor = .red
    marker.iconView = markerView
    marker.map = mapView
}

func circleWith(position: CLLocationCoordinate2D) {

    let circ = GMSCircle(position: position, radius: 1000)
    circ.fillColor = UIColor.MapAreaFilter.areaFilterColor
    circ.map = mapView
}

A: Try setting your marker's groundAnchor property:
marker.groundAnchor = CGPoint(x: 0.5, y: 0.5)


text:
Q: Spark Structured Streaming - Graceful shutdown using a touch file I am working on spark Structured Streaming which is pretty easy use case.
I will be reading data from Kafka and persist in hdfs sink after parsing JSON.
I have almost completed the part. Now problem is we should have good way of shutting down the streaming job without having to close abruptly (ctrl+c or yarn -kill).
I have used the below options
sparkConf.set("spark.streaming.stopGracefullyOnShutdown","true") but no use.
My requirement is when streaming job is running, it should get stop when some touch file is created in hdfs or Linux EN path.
https://jaceklaskowski.gitbooks.io/spark-structured-streaming/spark-sql-streaming-demo-StreamingQueryManager-awaitAnyTermination-resetTerminated.html
In this above link, they create thread for fixed duration. But I need something like that which comes out of execution when some dummy file is created.
I am a newbie, so please need your help for that.
Thanks in advance.

A: I am not sure if actually works currently sparkConf.set("spark.streaming.stopGracefullyOnShutdown","true"). Some claim it does work, though some don't.

*

*In any event it is about direct kill or graceful stopping.

*You need to kill the JVM though, or if in Databricks they have a whole lot of utilities.
But you will not lose data due to check-pointing and write ahead logs that Spark Structured Streaming provides. That is to say ability to recover state and offsets without any issues, Spark maintains own offset management. So, how you stop it seems less of an issue which may explain the confusion & the "but no use".


text:
Q: .Net Csvhelper header not found I have a class
 public class AccCsv
    {

        public string IdNumber { get; set; }

        public string Firstname { get; set; }

        public string Lastname { get; set; }

        public string AccountNumber { get; set; }
}

I am trying to read these values from an excel document. My service for reading the doc looks like so
 public List<debtorCsv> GetAllDebtorImportedData(string path)
        {
            List<AccCsv> records;

            using (var reader = new StreamReader(path))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                records = csv.GetRecords<AccCsv>().ToList();

            }
            return records;
        }

However, when I run it I run into an error that says "Header with name IdNumber[0] was not found" (for all headers). I do have headers in my excel doc.
Does anyone who has used CSVhelper know what my error could be Thanks
Snap of my data: sample data

A: Have you tried to apply the decoration like this: [Name("IdNumber")] to your POCOS (as docs says : https://joshclose.github.io/CsvHelper/getting-started/) ?
something like:
 public class AccCsv
    {

        [Name("IdNumber")]
        public string IdNumber { get; set; }

        [Name("Firstname")]
        public string Firstname { get; set; }

        [Name("Lastname")]
        public string Lastname { get; set; }

        [Name("AccountNumber")]
        public string AccountNumber { get; set; }
}

A: I found that similar issue may occur if you do not have a public, parameter-less constructor defined for your model class.


text:
Q: Python opens in script instead of python-3.9.5.amd64 Up until now whenever I downloaded an ipynb file it would open in
C:\WinPython\WPy64-3950\python-3.9.5.amd64\lib\site-packages\jupyter_server\transutils.py:13
and the old downloaded ipynb files still do, but the newer ones open in
C:\WinPython\WPy64-3950\scripts>
so I get an error saying: ".ipynb" cannot be processed syntactically at this point.
What can I do to fix this?
Note: I am using Windows 11


text:
Q: SQL: conditional string split then group by Min value then join again I'm new to the programing languages and SQL, and trying my best to explain my issue in a good way.
I'm working in large planning department where I arrange the maintenance of rented equipments for more than one client, my only source to get all different equipment's and different clients with maintenance schedules and details is a "READ ONLY" access to the DB from our main branch .
The return is like this
    Col1          |          Col2          | Col3      |     Col4
------------------+------------------------+-----------+-----------------------
  equipment type  | Identification/Plate # | Client ID |Mech_3_mailage/1.6_60%/
                  |                        |           |Elec_2_mailage/1.6_20%/
                  |                        |           |Elec_2_Year_-10%/
                  |                        |           |Tyrs_1_OFF_Road/1.6_-45%
------------------+------------------------+-----------+-------------------------

My issue is with COL4 where i get all the schedules and calculations in one cell for each equipment.
The only thing can help is the pattern
(maintenance shop)_(Procedure)_(Calculation)_(percentage%)

what make it harder is that there is more than one calculation for each procedure and shop so sometime I get same equipment and same shop and same procedure but different calculations, beside sometime in the calculation I get '/' , so I have to use '%' as the delimiter and after I have to remove '/' if present of the return value, and the
I tried this code:
SELECT
    Col1, Col2, Col3,
    (CASE
        WHEN LEFT (value, 1) = '/'
           THEN RIGHT (value, (LEN(value) - 1))
     END)
FROM
    dbo.clients
CROSS APPLY
    STRING_SPLIT (Col4, '%')
WHERE
    value IS NOT NULL

I did some searches and try myself but my knowledge's did not help me to get the table as below :
    Col1          |          Col2          | Col3      | Mech_3| Elec_2 |Tyrs_1 |
------------------+------------------------+-----------+-------+--------+-------+
  equipment type  | Identification/Plate # | Client ID | 60%   |  -10%  | -45%  |

I tried to declare table variable since my access is ready only, but once I add the string split to add its return to the variable table I get error

'STRING_SPLIT' is not a recognized built-in function name

I am using SQL Server 2016 (SP2-CU14; v13.0.5830.85 - X64).
I really appreciate any help or guidance to get this done.
Thanks


text:
Q: Django - Dynamic Tables - Add rows and columns I am trying to dynamically add columns to my DB.
For example. When the user clicks "Add Column" in the UI, Django adds a column in the database.
Are there tutorials on how I can accomplish this?

A: For doing this, it's more efficient to use NoSql databases.
Also if you want to use RDBMS, you can use JSONField or use below model:
class Column(models.Model):
    name = models.CharField(max_length=500)
    # more options

class Value(models.Model):
    column = models.ForeignKey(Column, on_delete=models.CASCADE)
    value = models.CharField(max_length=500)
    # more options


text:
Q: how to get all events from fullcalendar I have the following code where I am trying to retrieve all the events that are in fullcalendar:
<!DOCTYPE html>

  <title>Fullcalendar Demo</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@5.5.0/main.min.css"/>

  <button onclick="getEvents()">Click me</button>

When I click the button at the top of the page, in order to call the getEvents() function to console.log the events, I am currently getting the error "Uncaught ReferenceError: getEvents is not defined", which I can understand given where the function is placed, but if I place it outside the document.addEventListener('DOMContentLoaded', function() block then the calendar variable won't be in scope and thus I won't be able to call the getEvents() method of the calendar. Does anyone know how else I could retrieve the events? (I later want to make a call to a post route using the data of the events when I click the button)

A: You can give an id that button and listen click event by adding an addEventListener
Live Demo:

    document.addEventListener('DOMContentLoaded', function() {
      var calendarEl = document.getElementById('calendar');
      var calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'timeGridWeek',
        editable: true,
        headerToolbar: {
            start: 'prev,next today',
            center: 'title',
            end: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        selectable: true, //can click to set event
        selectMirror: true, // so it's solid
        unselectAuto: false, //if you click outside calendar, event doesn't disappear, but if you click inside calendar, event still disappears
        eventStartEditable: true,
        eventResizableFromStart: true,
        eventDurationEditable: true,
        select: function(selectionInfo) {
            calendar.addEvent({
              title: 'dynamic event',
              start: selectionInfo.start,
              end: selectionInfo.end //need these and not endTime/startTime, otherwise they won't re-render
            });
            calendar.unselect();
        },
        eventClick: function(eventClickInfo) {
            eventClickInfo.event.remove();
        }

      });
      calendar.render();

      function getEvents() {
        console.log(calendar.getEvents());
      }

      document.getElementById('getevent').addEventListener('click', getEvents);

    });
<!DOCTYPE html>

  <title>Fullcalendar Demo</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@5.5.0/main.min.css"/>

  <button id="getevent">Click me</button>


text:
Q: Let $X_n$ be a one-dimensional random walk with $p \neq 0.5$. Show that $P(\lim_{n \rightarrow \infty} \frac{1}{n} X_n = 0)$ equals $0$. Let $X_n$ be a one-dimensional random walk on the integers that starts at $0$ (as normally) but has $p \neq \frac{1}{2}$, i.e. so that it moves to its right neighbor with probability $p$ and left neighbor with probability $1-p$ at each step. In other words, the walk is biased to left or right and should therefore be "located" infinitely far to the left or right respectively when an infinite amount of time has passed, informally speaking. So how do I prove that $P(\lim_{n \rightarrow \infty} \frac{1}{n} X_n = 0)$ equals $0$, i.e. that the there is zero probability that $\lim_{n \rightarrow \infty} \frac{1}{n} X_n = 0$?

A: Consider $n$ random variables $Y_i$ for $i = [1,n]$ where, WLOG, $Y_i = 1$ if we go to the right and $Y_i = -1$ otherwise. These $n$ variables are independent Bernoulli trials with (WLOG) $Pr(Y_i = 1) = p > 0.5$.
Then we have that $X_n = \sum_{i=1}^{n} Y_i$. This can be interpreted as the final co-ordinate after completion of the random walk.
The expected value of the final co-ordinate is given by $$E[X_n] = \mu = \sum_{i=1}^{n} E[Y_i] = \sum_{i=1}^{n} (1\times p -1\times (1-p)) = (2p-1)n$$
Via Chernoff Bounds we have that
$$Pr(X_n > (1 + \delta)\mu) \le e^{\frac{-\mu \delta^2}{3}}, 0 < \delta \le 1 $$
$$ = e^{-n\frac{(2p - 1)\delta^2}{3}}$$
Now observe that $p > 0.5 \implies E[X_n] > 0$, i.e. we expect to finish the random walk on a non-zero co-ordinate.
Now observe that the probability of the random variable $X_n$ deviating from the expected value by some small factor of $\delta$ is bounded above by an exponentially decreasing function in $n$. Thus, as $n \to \infty$ we have that $e^{-n\frac{(2p - 1)\delta^2}{3}} \to 0$
This can be interpreted as the probability of the finishing point $X_n$ deviating away from its expected value is zero as the size of the walk gets larger. Therefore $\lim_{n\to\infty}X_n = n(2p-1)$
Thus
$$\lim_{n\to\infty}\frac{1}{n}X_n = \lim_{n\to\infty}\frac{1}{n}(2p-1)n = 2p-1 \not= 0$$
$$\implies Pr(\lim_{n\to\infty}\frac{1}{n}X_n = 0) = 0$$
Q.E.D.
Alternatively
We saw that $E[X_n] = (2p-1)n > 0$.
By the law of large numbers, we have that as $\lim_{n\to\infty}X_n =E[X_n]$.
Thus
$$\lim_{n\to\infty}\frac{1}{n}X_n = \lim_{n\to\infty}\frac{1}{n}(2p-1)n = 2p-1 \not= 0$$
$$\implies Pr(\lim_{n\to\infty}\frac{1}{n}X_n = 0) = 0$$
Q.E.D.


text:
Q: How to create line extension of a button I would like to ask if this is possible, I'm trying to achieve this design which
has a curve line extension of a button/ or <a> tag. my first choice is to export this line image and insert it after the button. but is there any ways of CSS styling that can make this possible,

Any suggestion would be greatly appreciated! Thank you

A: It certainly is possible, I'm just not sure whether it's advisable. Anyway, you can use an absolutely positioned pseudo element but as always with absolute positioning, you have to be careful when it comes to responsiveness. In the example, I'm using quite a lot of magic numbers which I don't really like.
I would probably rather use JavaScript and SVG to make the line properly positioned/sized on all devices.
Anyway, here's a CSS solution:

body {
  padding: 200px 50px;
}

button {
  position: relative;
  background-color: #92701b;
  border-radius: 999px;
  font-size: 1rem;
  color: #fff;
  border: 0;
  font-weight: 600;
  padding: 14px 25px;
  letter-spacing: 0.5px;
}

button:after {
  content: "";
  position: absolute;
  bottom: 21px;
  left: 100%;
  width: 200px;
  height: 200px;
  border-radius: 0 0 30px 0;
  border: 4px solid #d76f46;
  border-top: none;
  border-left: none;
}
<button>Polyethylene</button>


text:
Q: Open website and edeting the html with python am a little stuck. The program is supposed to open a website and read save it in a file. Then it is supposd to read everything up til it finds a string and delete everything before it and save it again in a new file. But when i run it i get the first file with the html in and the second file i am trying to make turns out to be blank. Anyone that can point me in the right direction?
import fileinput
import re
import requests
import sys

#linkToGet=sys.argv[1]                  //Hvordan hente link fra terminalen
#r = requests.get(linkToGet)

#nameOfFile=sys.argv[2]

#Hent nettsiden og lagre kildekoden som en textfil
r = requests.get('https://www.bibel.no/Nettbibelen?query=ud8MMrJeKwHNJdqN05oJoRgo89+A24MHmKzQYWJRSygk2+FVqgPK3UvcYb+xB3j7')  #Bare sånn jeg kan builde enkelt fra Atom
print (r.text)
f= open("kap3.txt","w+")
f.write(r.text)
f.close

#Fjern all tekst frem til en linje

TAG = """50 """

tag_found = False
with open('kap3.txt') as in_file:
    with open('kap3ren.txt', 'w') as out_file:
        for line in in_file:
            if not tag_found:
                if line.strip() == TAG:
                    tag_found = True
            else:
                out_file.write(line)

A: It looks like you are only calling out_file.write(line) if you HAVE found the line you are looking for, your else satement should be indented to be for the inner if.
for line in in_file:
    if not tag_found:
        if line.strip() == TAG:
            tag_found = True
        else:
            out_file.write(line)

Of course this makes the outer if basically useless so it can be simplified to this:
for line in in_file:
    if line.strip() == TAG:
        # you're done here so you can break the loop
        break
    else:
        out_file.write(line)


text:
Q: biztalk wcf integration issue I am trying to access a wcf service through a biztalk sendport(wcf-custom) with
establishsecuritycontext = false . My application generates 80 orch instances and everytime only 2 of them give the following error and all others work properly.further if i increase the retrycount =1 then the two orch instances give a warning in the first attempt to connect to the service and complete successfully in the 2nd attempt.
the error message
Error Description: System.TimeoutException: Client is unable to finish the security negotiation within the configured timeout (00:10:00).  The current negotiation leg is 1 (00:10:00).  ; System.TimeoutException: The request channel timed out while waiting for a reply after 00:10:00. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.;
 System.TimeoutException: The HTTP request to 'webservice-address' has exceeded the allotted timeout of 00:10:00. The time allotted to this operation may have been a portion of a longer timeout. ; System.Net.WebException: The operation has timed out

A: What is probably happening is that your Biztalk server is overloading your downstream WCF service with too many concurrent calls.
Your WCF service will only accept a finite number of concurrent connections depending on the processing capability of the WCF service (e.g. number of servers, number of threads in the app pools etc).
Quick and Dirty, but not recommended
There are knobs on the BizTalk WCF adapter to reduce the number of concurrent messages on the send ports. If your orchestrations are triggered by batches of incoming messages then you can also look at adjusting the receive adapters and also the BizTalk throttling settings on your receive host, in order to reduce the amount of messages absorbed.
Singletons
The recommended approach however is to modify your orchestration to become a singleton, or Seroter's 'N-ton' so that it limits the number of concurrent messages that it processes (typically by correlating messages so that they stack up in the message box).
You could also look improving the performance of the WCF service - e.g. look at indexing if it uses a database, caching if it fetches data etc.

A: Another couple of options...
Set Ordered Delivery on the physical send port. This will impact performance, as the messages will be effectively serialized, but is really quick to test and may/may not turn out to be suitable in your situation...
Set Delivery Notification Transmitted on the logical send port and catch DeliveryFailureException. Then you can wait a predefined/configurable amount of time and retry the orchestration. This is a bit more involved, but gives you the most flexibility.
Good luck!


text:
Q: Checking all checkboxes in list by single checkbox click On my webpage, I have a CheckBoxList and a single checkbox. When I click on the check box, all the Check Boxes in the CheckBoxList should get checked. My CheckBoxList has to be under Bodycontent placeholder because that's how the layout of webpage is, and I kept the script in the same placeholder.
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

        <asp:CheckBoxList ID="CheckBoxList1" runat="server"
            RepeatDirection="Horizontal" RepeatLayout="Flow">
            <asp:ListItem>Item A</asp:ListItem>
            <asp:ListItem>Item B</asp:ListItem>
            <asp:ListItem>Item C</asp:ListItem>
        </asp:CheckBoxList>

            <asp:CheckBox ID="allCheck" onclick="select(this)" runat="server" Text="Select all" />

</asp:Content>

The above doesn't do anything. On clikcing on the checkbox nothing happens! I have been stuck on this small issue from quite long and not able to do the same. Any suggestions what's wrong?

A: change the name of your function to something else; it will work
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

        <asp:CheckBoxList ID="CheckBoxList1" runat="server"
            RepeatDirection="Horizontal" RepeatLayout="Flow">
            <asp:ListItem>Item A</asp:ListItem>
            <asp:ListItem>Item B</asp:ListItem>
            <asp:ListItem>Item C</asp:ListItem>
        </asp:CheckBoxList>

            <asp:CheckBox ID="allCheck" onclick="select1(this)" runat="server" Text="Select all" />

</asp:Content>

A: try like this..
function UnCheckAll(isCheck) {
            var theForm = document.forms['yourFormName'];
            if (!theForm) {
                theForm = document.form1;
            }
            var length = theForm.elements.length;
            for (var i = 0; i < length; i++) {
                if (theForm.elements[i].type == "checkbox") {
                    if (theForm.elements[i].id != "allCheck") {
                        if (theForm.elements[i].disabled == false) {
                            theForm.elements[i].checked = isCheck.checked;
                        }
                    }
                }
            }
        }


text:
Q: nested ajax parent completed before child had finished $.ajax(
        {
            type: 'POST',
            url: '@Url.Action("EkranListeleSektor")',
            dataType: 'json',
            async: false, //added async later, no changes
            data: { sektorID: $("#ekranSektorID").val() },

            success: function (items) {
                $.each(items, function (i, ekranlar) {

                    $.ajax({
                        type: 'POST',
                        url: '@Url.Action("IlAdGetir")',
                        dataType: 'json',
                        data: { id: ekranlar.il },
                        success: function (ilAd) {
                            strIlAd = ilAd;
                        },
                        error: function (ex) {
                            alert('İl isim çekilemedi.' + ex);
                        }
                    });

                    $.ajax({
                        type: 'POST',
                        url: '@Url.Action("IlceAdGetir")',
                        dataType: 'json',
                        data: { id: ekranlar.ilce },

                            success: function (ilceAd) {
                                alert(ilceAd);
                            strIlceAd = ilceAd;
                        },
                        error: function (ex) {
                            alert('İlce isim çekilemedi.' + ex);
                        }
                    });

                    divContent += '' +
                        ' ' +
                        '<input type="checkbox" id="' + ekranlar.ekranID + '" name="' + ekranlar.ekranAd + '" value="' + fiyat +
                                    '" class="styledCheck">' + '
Ekran İsim: ' + ekranlar.ekranAd +
                                    '
' + 'Günlük Fiyat' + ': ' + fiyat + '
Ekran Boyutu: '
                                    + ekranlar.ekranBoyutID + '"
' +
                                    '' + strIlAd + '
 ' + strIlAd + ' ';

                    $("#imgDiv").append(divContent);
                });
            }, error: function (ex) {
                alert('Ekranlar Çekilemedi.' + ex);
            }
        });
    }

my action part worked correctly i can see coming data with alert and debugger but "EkranListeleSektor" completed before nested "IlAdGetir" or "IlceAdGetir" starting so when i trying to print output to div, strIlAd and strIlceAd print undefined.

A: You should STRONGLY consider using deferred objects here to solve your problem.  Let me give you an example for how you should work this based on jQuery's convenient when() method:
// This would be code in success handler for your outermost $.ajax() call.
// start "nested" ajax calls wrapped in when()
$.when(
    $.ajax({
        type: 'POST',
        url: '@Url.Action("IlAdGetir")',
        dataType: 'json',
        data: { id: ekranlar.il }
    }),
    $.ajax({
        type: 'POST',
        url: '@Url.Action("IlceAdGetir")',
        dataType: 'json',
        data: { id: ekranlar.ilce },
    })
).done(function(firstCall, secondCall) {
    // This is triggered when both calls are successful
    // set variables
    strIlAd = firstCall[0];
    strIlceAd = secondCall[0];
    divContent += '' +
    ' ' +
    '<input type="checkbox" id="' + ekranlar.ekranID + '" name="' + ekranlar.ekranAd + '" value="' + fiyat +
    '" class="styledCheck">' + '
Ekran İsim: ' + ekranlar.ekranAd +
    '
' + 'Günlük Fiyat' + ': ' + fiyat + '
Ekran Boyutu: '
    + ekranlar.ekranBoyutID + '"
' +
    '' + strIlAd + '
 ' + strIlAd + ' ';
    $("#imgDiv").append(divContent);
}).fail(function(){
    // your failure handler, triggered when either ajax call fails
});

You can see that this really consolidates your code, getting all success handling and failure handling for both ajax request in a single place.
Performance-wise and user-experience-wise, you will likely find this preferable to using synchronous ajax calls which will block the user's browser from doing anything else while you iterate through each record from outer ajax call and make two nested calls for each.

A: I already post my answer in comments anyway I can think in 2 ways to try solving your issue:

*

*Add async: false, to your nested calls

*Try moving your div print out to the last (the second one) nested "success" call, but first verify all the calls are being executed using debug tools (debug tools -> network).


text:
Q: Java build has started failing - Fatal error compiling: java.lang.IllegalAccessError: class lombok.javac.apt.LombokProcessor We have a Java 11 server on EC2 that has just started failing to build with the following error:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile)
on project showhow-server: Fatal error compiling: java.lang.IllegalAccessError: class lombok.javac.apt.LombokProcessor (in unnamed module @0x49d0e934) cannot access class
com.sun.tools.javac.processing.JavacProcessingEnvironment (in module jdk.compiler) because module jdk.compiler
does not export com.sun.tools.javac.processing to unnamed module @0x49d0e934 -> [Help 1]
[ERROR]

The build is from BitBucket pipelines.
Any idea what it could be?

A: Upgrade lombok dependency to 1.18.20

A: I use java 11 too and fixed the problem by adding this to the POM plugins section.
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
                <fork>true</fork>
                <!-- this is to fix bitbucket pipeline build error due to Lombok processing -->
                <compilerArgs>
                    <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED</arg>
                    <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED</arg>
                    <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED</arg>
                    <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED</arg>
                    <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED</arg>
                    <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED</arg>
                    <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED</arg>
                    <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED</arg>
                    <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED</arg>
                    <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED</arg>
                </compilerArgs>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                        <version>${lombok.version}</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>

The java.verion is 11, lombok.version is 1.18.18

A: Using maven i managed to build using this (changed source and target to match my java version):
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
    <source>16</source>
    <target>16</target>
    <fork>true</fork>
    <compilerArgs>
        <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED</arg>
        <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED</arg>
        <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED</arg>
        <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED</arg>
        <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED</arg>
        <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED</arg>
        <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED</arg>
        <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED</arg>
        <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED</arg>
        <arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED</arg>
    </compilerArgs>
    <annotationProcessorPaths>
        <path>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </path>
    </annotationProcessorPaths>
</configuration>

Source, lomboks github

A: i had faced same issue due to vulnerabilities in current lombok version. please verify vulnerability status of current version and if required, please upgrade it to latest working version.