text:
Q: css how to make the div width just for the content I have this html:
<!DOCTYPE html>

    <title>Test Float</title>
    <link rel="stylesheet" href="Styles/style.css" />

            up

                Hello

            down

And this is my css style:
html, body {
margin:0px;
height:100%;
}
.header {
    width:100%;
    height:20%;
    background-color:red;
    border-radius:10px;
}
.footer {
    width:100%;
    height:20%;
    background-color:green;
}
.mainContent {
    width:100%;
    height:60%;
}
.slideBar {
    width:20%;
    height:100%;
    float:left;
    background-color:blue;
}
.content {
    width:80%;
    height:100%;
    float:right;
    background-color:yellow;
}
    .content .div1 {
        border:2px solid black;
        margin-left:10px;
    }

This is the result:

My problem
the border of the hello word goes to all the width. but I need it just to be surround the text

A:
 is a block-level element, so in order to get it to shrink around its content, you need to make it act like an inline element. Setting display: inline-block; on .content .div1 will make it behave more or less like an inline element, and so it will fit to contents. See example here: http://jsfiddle.net/6wZhe/
However, what you might want to do is change out your
 tag for a  tag, which is another multipurpose non-semantic container, except that is is an inline element, not a block-level element.
If you still want the linebreak after the
 you can add a
 element, or do it with floats.

A: Add display:inline-block;  to .content .div1    and in html add a
  above and below it:
http://jsfiddle.net/LYvft/2/

A: Add display: inline-block to it. http://jsfiddle.net/zhF4f/
Divs are "block elements"(display:block) which mean they take up 100% of their parent width. By setting inline-block, it only wraps the content.

A: You can write display: inline-block; for div with class = div1 or replace your div to span.
Div is block element on default. If you use a text it is better to use span - default inline element.


text:
Q: Android R.java gives error on Numeric (media) file name I have huge number of sound bytes which I want to use in my project. Unfortunately all files are named numerically like "001.m3 , 002.mp3 ...."
When I added files in raw folder, Android R file gives error.
How can I solve this problem. Can any one provide me link where android has mentioned naming conventions for resource files.

A: The problem that you are facing is because of your file names, since your file name is 001.mp3 or 002.mp3. Android creates R.java file automatically, and in that file(R.java) it will create a variable by that file name which is variable name "001". Having a numeric variable name is wrong . It will not allow such thing and instead throw an error.
If your file is 001.mp3 then R.java will have error in this line which is
Syntax error on token "001", invalid VariableDeclaratorId
public static final int 001=0x7f050000;

I request you to change your file names. May be follow the recommendations Are there conventions on how to name resources?

A: Every resources having entry in R.java file, If you see R.java file is nothing but like our normal class
public final class R {
    public static final class raw {
        public static final int 001=0x7f090005; // this will not accept as a variable name
    }

    public static final class drawable {
    }

    public static final class id {
        public static final int main=0x7f090001;
    }
}

You should follow the same Naming Convention like we do have for Variables i.e.
1) Must not start with number
2) Must not contain Special character except(_)
3) Must not used Reserved Keyword mentioned here
Solution: You have to rename you files, thats it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как сверстать два столбца внутри ? Как здесь поднять второй столбик?

.fon_plusov_producta {
  background-color: #f5f5f5;
}
.plusi_producta {
  padding-left: 464px;
  padding-top: 50px;
  font-size: 30px;
  font-family: Arial;
  color: #445161;
}
.perviy_stolbik {
  padding-top: 31px;
  padding-left: 50px;
  font-size: 16px;
  font-family: Arial;
  color: #333333;
}
.vtoroy_stolbik {
  padding-left: 640px;
  font-size: 16px;
  font-family: Arial;
  color: #333333;
}

    Dignity and pluses product

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

A: Добавьте
.vtoroy_stolbik {
  padding-top: 31px;
}

и уберите padding-left (настройте дальше как нужно)
Применяйте flexbox:
.sami_plusi {
  display: flex;
}

Дальше можно сделать width: 50% столбцам

A: Ну если не знаете flex, то хоть float-то Вы должны знать:

div {
  box-sizing: border-box;
}
.fon_plusov_producta {
  background-color: #f5f5f5;
  overflow: hidden;
}
.plusi_producta {
  padding-top: 50px;
  font-size: 30px;
  font-family: Arial;
  color: #445161;
  text-align: center;
}
.perviy_stolbik,
.vtoroy_stolbik {
  padding: 30px;
  font-size: 16px;
  font-family: Arial;
  color: #333333;
  float: left;
  width: 50%;
}

    Dignity and pluses product

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

A: Чтоб понять как работает технология flexbox, необходимо почитать чуть информации и немного попрактиковаться. Про свойство flex можно почитать тут:
Справочник CSS. flex
Далее, следующий способ ровнять блоки так как необходимо, это использование grid css.
Пример использования данной технологии как-то приводил (включая и flex):
Как разместить два блока на одной строке?
Далее про grid можно почитать тут:
CSS Grid Layout
Пример использования flex в этом коде:

.fon_plusov_producta {
  background-color: #f5f5f5;
  font-family: Arial;
} /* для фона не нужно создавать отдельный блок */
.sami_plusi {
  display: flex;
   /* блоки особо не фиксил, тут суть показать, что flex необходимо применить к родителю */
}
.plusi_producta {
  padding: 50px;
  font-size: 30px;
  color: #445161;
}
.perviy_stolbik {
  padding: 50px;
  font-size: 16px;
  color: #333333;
}
.vtoroy_stolbik {
  padding: 50px;
  font-size: 16px;
  color: #333333;

    Dignity and pluses product

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

      impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

      perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

A: Для тех, кто в гробу видел эти ваши флексы, пихаемые где надо и не надо:

div {
    box-sizing: border-box;
}
.fon_plusov_producta {
    background-color: #f5f5f5;
    overflow: hidden;
}
.sami_plusi{
    font-size:0;  /* ооочень грязный хак */
}
.plusi_producta {
    padding-top: 50px;
    font-size: 30px;
    font-family: Arial;
    color: #445161;
    text-align: center;
}
.perviy_stolbik,
.vtoroy_stolbik {
    padding: 30px;
    font-size: 16px;
    font-family: Arial;
    color: #333333;
    width: 50%;
    display:inline-block;  /* блочно-строчная модель */
    vertical-align:top;  /* и тянем наверх */
}

        Dignity and pluses product

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

          impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

          perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

          impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

          perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

          impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

          perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

          impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

          perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

          impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

          perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

Delectus dolorem vero quae beatae quasi dolor deserunt iste amet atque,

          impedit iure placeat, ullam. Reprehenderit aliquam, nemo cum velit ratione

          perferendis quas, maxime, quaerat porro totam, dolore minus inventore.

P.S. Старайтесь не использовать float

A: .sami_plusi div {
       vertical-align: top;
}


text:
Q: Why does Ruby call the `call` method when I don't supply the method name? Given the following module:
module Foo
  def self.call
    'foo'
  end
end

I would of course expect the following to work:
puts Foo.call  # outputs "foo"

However, I did not expect this to work:
puts Foo.()    # outputs "foo"

Apparently when the method name is left off, Ruby assumes that I want to call the call method.  Where is this documented, and why does it behave that way?

A: Proc#call:

Invokes the block, setting the block's parameters to the values in params using something close to method calling semantics. Generates a warning if multiple values are passed to a proc that expects just one (previously this silently converted the parameters to an array). Note that prc.() invokes prc.call() with the parameters given. It's a syntax sugar to hide "call".

I did some research and found method #() is a syntactic sugar of the method #call..Look at the error as below :
module Foo
  def self.bar
    12
  end
end
Foo.()
#undefined method `call' for Foo:Module (NoMethodError)

As OP defined the #call method in module Foo class,Foo#call is called in an attempt of Foo.().
Here is some more examples :
"ab".method(:size).() # => 2
"ab".method(:size).call # => 2
"ab".() # undefined method `call' for "ab":String (NoMethodError)

See here what Matz said So compromise with object.() syntax introduced in 1.9...

A: Apparently, as Arup is saying, this is syntactic sugar introduced a while ago, possibly for the single cause of making Proc objects easier to work with. (You don't have to explicitly call them, but can just do prc.() instead).
I also concluded that this is definitely a Ruby 1.9+ feature. If I switch my JRuby to 1.8 mode, I get this instead:
SyntaxError: spam.rb:12: syntax error, unexpected tLPAREN2

So, somewhere in the changelogs for Ruby 1.9 it can probably be found, if someone really wants to dig it out from the caves... :)


text:
Q: Processing table data in Queue format The following is a main portion of the code from an SP that I am using to process table data in a FIFO queue order. The SP could be called by 100's of processes at the same time.
    create   TABLE #STAG(ident BIGINT)

    begin try

    begin tran
    insert into CaseLock (id,locktime,sessionid,lockid) output inserted.id into #STAG
    select top 1
         i.ident
        ,getutcdate()
        ,case when @sess is null then i.sessionid else @sess end
        ,newid()
      from QueueItem i WITH (ROWLOCK, READPAST)     where
        not exists(select 1 from CaseLock lck WITH (ROWLOCK, READPAST) where  lck.id = i.ident)
        and i.QUEUEIDENT    = @QUEUEIDENT
        and i.finished is null and (i.deferred is null or i.deferred < getutcdate())

    commit

    end try
    begin catch
       rollback
    end catch

    Select i.encryptid, i.id, i.ident, i.keyvalue, i.data, i.status, i.attempt
    from QueueItem i  WITH (ROWLOCK, READPAST)
    where EXISTS(SELECT 1 FROM #STAG WHERE [#STAG].[ident]=i.ident)

The data in the QueueItem table can not be deleted, we use the CaseLock table to lock the record that has been selected for processing. Once a record has been procesed the finished column get updated to current datetime.
I am getting

Violation of PRIMARY KEY constraint 'PK_CaseLock'. Cannot insert
  duplicate key in object 'dbo.CaseLock'.  The duplicate key value is
  (105).

My problem is the SP must always return a data, the application will crash if no data is returned from the sp.
How can I modify the code to resolve the Primary key violation error and it also returns a record?

A: execute the following in two separate sessions (ssms query windows):
declare @QUEUEIDENT  = 12345 --a queue value which has rows for processing

begin transaction
    select top 1
         i.ident

      from QueueItem i WITH (ROWLOCK, READPAST)     where
        not exists(select 1 from CaseLock lck WITH (ROWLOCK, READPAST) where  lck.id = i.ident)
        and i.QUEUEIDENT    = @QUEUEIDENT
        and i.finished is null and (i.deferred is null or i.deferred < getutcdate())

you will get the same value in both windows, that is why the primary key violation on CaseLock is raised (if the queries executed at the same time, they would try to insert the same primary key, one execution would succeed the other would fail).
The issue is with SELECT (ROWLOCK), the lock is not kept on the row after the row is read.
Another possible issue is with skipping any existing locks on CaseLock:
where not exists(select 1 from CaseLock lck WITH (ROWLOCK, READPAST)

....assuming you delete rows from caselock when queue items fail processing (those queue items need to be retried later) you could end up with a queue reader trying to insert an item whose CaseLock is "on the flight" to deletion (the reader READsPAST any CaseLock locks on the deleted row).
In order to solve those two possible issues, you could try keeping the lock on QueueItem when reading and check CaseLock without any locks :
UPDLOCK on QueueItem keeps the lock for the duration of the transaction,
NOLOCK on CaseLock makes sure that i.ident will NEVER be inserted if it exists

``
 ...   from QueueItem i WITH (ROWLOCK, UPDLOCK, READPAST)
 where
    not exists(select 1 from CaseLock lck WITH (NOLOCK) where  lck.id = i.ident)...

All this if you want to keep the existing implementation, checking the queue item processing status based on another table.
A simpler approach would be to have a process related column on QueueItem and update that column with READPAST (capturing the inserted.ident in turn etc).


text:
Q: How to put view in specific location in ZStack based on another view? I have a view in a ScrollView and base on an offset value. There is another view that needs to animate out.
This view is under the gray box but it places its base on a hardcoded value. How to pin the green box under the gray area without a hardcoded value? Using the hard coded value will not be consistent with other devices.
struct ContentView: View {
    @State private var contentOffset = CGFloat(0)

    var body: some View {
        NavigationView {
            ZStack {
                VStack(spacing: 0) {
                    TrackableScrollView { offset in
                        contentOffset = offset.y
                    } content: {
                        VStack(spacing: 0) {
                            Text("Hello World")
                                .padding()
                                .frame(maxWidth: .infinity)
                                .background(Color.gray)
                        }
                    }
                }

                Text("HELLO")
                    .frame(maxWidth: .infinity)
                    .background(Color.green)
                    .opacity(contentOffset < -16 ? 0 : 1)
                    .animation(.easeIn(duration: 0.2), value: contentOffset)
                    .offset(y: -280)
            }
            .ignoresSafeArea()
            .frame(maxHeight: .infinity, alignment: .top)
            .background(AccountBackground())
            .navigationBarHidden(true)
        }
    }
}

What it looks like:

When you scroll up the green box will disappear.

A: To do this you need to an overlay to your ZStack. If you have a navigation bar the offset that you need to give it is 0 as it will be placed automatically below it. The TrackableScrollView is a preference key that is commonly found online to track the scrolling position of the scroll view.
struct ContentView: View {
    @State private var contentOffset = CGFloat(0)
    @State private var offsetPositionValue: CGFloat = 0
    @State private var heightOfFrame: CGFloat = 0

    @State private var isShyHeaderVisible = false

    var body: some View {
        NavigationView {
            ZStack {
                TrackableScrollView { offset in
                    withAnimation {
                        contentOffset = offset.y
                    }
                } content: {
                    Text("Hello World")
                }
                .overlay(
                    ZStack {
                        HStack {
                            Text("Total number of points")
                                .foregroundColor(.white)
                                .lineLimit(1)

                            Spacer()

                            Text("20,000 pts")
                                .foregroundColor(.white)
                                .padding(.leading, 50)
                        }
                        .padding(.horizontal)
                        .padding(.vertical, 8)
                        .frame(width: UIScreen.main.bounds.width)
                        .background(Color.green)
                        .offset(y: contentOffset < -16 ? 0 : heightOfFrame - 5)
                        .opacity(contentOffset < -16 ? 1 : 0)
                        .transition(.move(edge: .top))
                    }
                    .frame(maxHeight: .infinity, alignment: .top)
                )
            }
            .navigationTitle("Hello")
            .navigationViewStyle(StackNavigationViewStyle())
            .navigationBarTitleDisplayMode(.inline)
            .frame(maxHeight: .infinity, alignment: .top)
            .background(AccountBackground())
        }
    }
}


text:
Q: UIKit TabBar with SwiftUI View I am updating my existing UIKit to use SwiftUI in some parts where I feel comfortable about being able to replace all of it with SwiftUI. It is a tab application, so there are 3 tabs and one of it are Settings, which I am replacing with SwiftUI.
My tab bar is configured to only show images and no titles (the issue I need help with would also occur with labels shown).
Now in UIKit I do this:
private let settingsViewController: UIViewController = UIHostingController<SettingsView>(SettingsView())
and later on before showing it:
settingsViewController.navigationItem.title = "Settings".
However from then on SwiftUI takes on with its view modifier: .navigationBarTitle("Text"), which I use for nested view controllers (pushed via NavigationLink), as UIKit cannot access those views to set a title.
The issue is however, that whenever .navigationBarTitle is used (same with setting the view's title property in UIKit, it sets the current tab bar items title. For UIKit there is always a way to set the navigationItem.title instead of title.
Is there any way to set the navigation bar title but not the tab bar title itself in SwiftUI?
Thanks

A: This is to be a bug in iOS. Please file a bug report to Apple.
I just discovered a workaround for this issue:
Create a custom subclass of UINavigationController and use it as the navigation controller containing your settingsViewController.
class WorkaroundUINavigationController: UINavigationController {
    override var title: String? {
       get { tabBarItem.title }
       set { navigationItem.title = newValue }
    }
}


text:
Q: How to override styles for two different mat-tab elements used in same page I have two different mat-tab section used in same component in my angular application.
How to override styles of mat-tab because i need to apply two different styles for both the tabs.
Say, I need to have mat-label as white color in one mat-tab and  in the other one, I need to have black color.
<mat-tab-group [selectedIndex]="selectedIndex" (selectedTabChange)="onChange($event)">
            <mat-tab label="Content 1">

            </mat-tab>
            <mat-tab label="Content 2">
            </mat-tab>
        </mat-tab-group>

<mat-tab-group [selectedIndex]="selectedIndex" (selectedTabChange)="onChange($event)">
            <mat-tab label="Content 3">

            </mat-tab>
            <mat-tab label="Content 4">
            </mat-tab>
        </mat-tab-group>

A: I would suggest using:
::ng-deep mat-tab {
  /*Your styles here*/
}

If this does not work, try using:
::ng-deep mat-tab {
  /*Your styles here*/ !important;
}

Although I would not advise the use of !important unless you have a very specific case.


text:
Q: unwind_frame cause a kernel paging error Background
Found a strange kernel Oops, Googled a lot, found nothing.
Background:

*

*The kernel version is 3.0.8

*There are two process let's say p1, p2

*p2 have lots of threads(about 30)

*p1 continuously calls system(pidof("name of p1"))
The kernel may Oops after running for a few days. the primary reason I found is that unwind_frame got a strange frame->fp(0xFFFFFFFF) from get_wchan
When executing this line
frame->fp = *(unsigned long *)(fp - 12);

The CPU will try to access 0xFFFFFFF3, and cause a paging error.
My question is:
How on earth the fp register saved before context switch becomes 0xFFFFFFFF ?

here is the CPU infomation
# cat /proc/cpuinfo
Processor       : ARMv7 Processor rev 0 (v7l)
processor       : 0
BogoMIPS        : 1849.75

processor       : 1
BogoMIPS        : 1856.30

Features        : swp half thumb fastmult vfp edsp vfpv3 vfpv3d16
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x3
CPU part        : 0xc09
CPU revision    : 0

Here is the Oops and pt registers:
[734212.113136] Unable to handle kernel paging request at virtual address fffffff3
[734212.113154] pgd = 826f0000
[734212.113175] [fffffff3] *pgd=8cdfe821, *pte=00000000, *ppte=00000000
[734212.113199] Internal error: Oops: 17 [#1] SMP
--------------cut--------------
[734212.113464] CPU: 1    Tainted: P             (3.0.8 #2)
[734212.113523] PC is at unwind_frame+0x48/0x68
[734212.113538] LR is at get_wchan+0x8c/0x298
[734212.113557] pc : [<8003d120>]    lr : [<8003a660>]    psr: a0000013
[734212.113561] sp : 845d1cc8  ip : 00000003  fp : 845d1cd4
[734212.113583] r10: 00000001  r9 : 00000000  r8 : 80493c34
[734212.113597] r7 : 00000000  r6 : 00000000  r5 : 83354960  r4 : 845d1cd8
[734212.113613] r3 : 845d1cd8  r2 : ffffffff  r1 : 80490000  r0 : 8049003f
[734212.113632] Flags: NzCv  IRQs on  FIQs on  Mode SVC_32  ISA ARM  Segment user
[734212.113651] Control: 10c53c7d  Table: 826f004a  DAC: 00000015

Here is the callstack:
[734212.117027] Backtrace:
[734212.117052] [<8003d0d8>] (unwind_frame+0x0/0x68) from [<8003a660>] (get_wchan+0x8c/0x298)
[734212.117079] [<8003a5d4>] (get_wchan+0x0/0x298) from [<8011f700>] (do_task_stat+0x548/0x5ec)
[734212.117099]  r4:00000000
[734212.117118] [<8011f1b8>] (do_task_stat+0x0/0x5ec) from [<8011f7c0>] (proc_tgid_stat+0x1c/0x24)
[734212.117158] [<8011f7a4>] (proc_tgid_stat+0x0/0x24) from [<8011b7f0>] (proc_single_show+0x54/0x98)
[734212.117196] [<8011b79c>] (proc_single_show+0x0/0x98) from [<800e9024>] (seq_read+0x1b4/0x4e4)
[734212.117215]  r8:845d1f08 r7:845d1f70 r6:00000001 r5:8ca89d20 r4:866ea540
[734212.117237] r3:00000000
[734212.117264] [<800e8e70>] (seq_read+0x0/0x4e4) from [<800c8c54>] (vfs_read+0xb4/0x19c)
[734212.117289] [<800c8ba0>] (vfs_read+0x0/0x19c) from [<800c8e18>] (sys_read+0x44/0x74)
[734212.117307]  r8:00000000 r7:00000003 r6:000003ff r5:7ea00818 r4:8ca89d20
[734212.117340] [<800c8dd4>] (sys_read+0x0/0x74) from [<800393c0>] (ret_fast_syscall+0x0/0x30)
[734212.117358]  r9:845d0000 r8:80039568 r6:7ea00c90 r5:0000000e r4:7ea00818
[734212.117388] Code: e3c10d7f e3c0103f e151000c 9afffff6 (e512100c)
[734212.113136] Unable to handle kernel paging request at virtual address fffffff3
[734212.113154] pgd = 826f0000
[734212.113175] [fffffff3] *pgd=8cdfe821, *pte=00000000, *ppte=00000000
[734212.113199] Internal error: Oops: 17 [#1] SMP

A: This bug was fixed by Konstantin Khlebnikov, details can be found in git commit log.


text:
Q: How to check a model object is persisted to DB or a new object? category = Category.new

This isn't persisted to DB yet, so how to distinguish form an object that is saved in the database?

A: c.persisted?  # => true if persisted
c.new_record? # => true if not persisted

:)

A: c.new_record? # true if new, false if saved


text:
Q: Count number of Node - Disjoint Paths between any two nodes in directed graph such that there distance is <=K How can we count number of node - disjoint paths between any two nodes such that distance between two nodes is maximum K?
Details about node - disjoint path can be found here.
We are given a directed graph where we have to count number of node - disjoint path from vertex u to v such that maximum number of nodes between them is K - 2 (u and v are decremented from K , therefore K - 2). Number of vertices in graph can be up to than 10^5 and edges can be 6 * 10^5. I thought of implementing BFS for every node until maximum distance from source node is less than K. But I am not getting idea for implementation. Anybody please help me?
If anybody have idea to solve it using DFS, please share it.

A: DFS  is the key to solve such problems. We can easily enumerate all the possible paths between 2 vertices using DFS, but we have to take care of the distance constraint.
My algorithm considers the number of edges traversed as a constraint. You can easily convert it to number of nodes traversed. Take that as an excercise.
We keep track of the number of edges traversed by variable e. If e becomes greater than K - 2, we terminate that recursive DFS call.
To maintain that a vertex has been visited we keep a boolean array visited. But if a recursive call terminates without finding a successful path, we discard any changes made to the array visited.
Only if a recursive DFS call is successful in finding a path, then we retain the visited array for the rest of the program.
So the pseudocode for the algorithm would be:
main function()
{
 visited[source] = 1
 e = 0//edges traversed so far.
 sum = 0// the answer
 found = false// found a path.
 dfs(source,e)
 print sum
 .
 .
 .
}

dfs(source,e)
{
 if(e > max_distance)
 {
  return
 }

 if(e <= max_distance and v == destination)
 {
  found = true
  sum++
  return
 }

 for all unvisited neighbouring vertices X of v
 {
  if(found and v != source)
   return;
  if(found and v == source)
  {
   found = false
   visited[destination] = 0
  }

  visited[X] = 1
  dfs(X , e + 1)
  if(!found)
   visited[X] = 1
 }

}


text:
Q: How to make server-side API requests? I'm working in javascript(React) to create a web app that makes use of multiple APIs(Spotify, Twitch, Youtube) and so far I have been using Axios to make
the REST calls successfully. But now I have begun running into Cross-Origin Resource Sharing (CORS) errors and I have been told
that I need to make calls to external APIs from a server instead of from my client. I've never made API calls from a server and
have some questions:

*

*Everything I am doing is currently running locally using Node and I dont have a "server" unless that's what Node counts as. Do I need to get a "server"?

*Should I be creating my own API and hosting it on some server so that I can call that API from my javascript code?

*How do I create my own API if that's what I should be doing?

*Is there a different language I will need to use to make server-side api calls?

A:
Everything I am doing is currently running locally using Node and I dont have a "server" unless that's what Node counts as. Do I need to get a "server"?

React comes with a bunch of development tools that use Node, including a development server. It isn't designed for production use though, so you shouldn't use it for that.

Should I be creating my own API and hosting it on some server so that I can call that API from my javascript code?

Yes.

How do I create my own API if that's what I should be doing?

Write some code which accepts an HTTP request, gets the data you want to respond to it with, and makes an HTTP response.
Express.js is a popular way to do this in Node. You can combine it with Next.js to apply server-side rendering for your React app (resulting in better performance, accessibility, reliability, and SEO).

Is there a different language I will need to use to make server-side api calls?

You can write your server-side code in any language you like.

A: *

*I assume you are hosting your application on a development nodeJS server, therefor you
will need an extra server.

*Yes. Create an API and call it from your frontend.

*Create a server which takes http requests and does your stuff according to the route
chosen.There are many examples on how to do this with for example nodeJS+Express on the
internet.

*The Language you use for the server side is your choice.


text:
Q: ffmpeg concat: 2nd video stream frozen, no image I'm trying to concatenate two video streams with the same econding into one:
ffmpeg -y -f concat -i parts.txt -c copy join.mkv

parts.txt
file part1.mkv
file part2.mkv

ffmpeg will concatenate them but the playback (any player) gives a still image if the playing position corresponds to the 2nd part.
I tried to switch part1.mkv and part2.mkv to see the results.
The 1st part (whichever part1 or part2) will play normally but when I seek the playback to the time corresponding the 2nd part the image won't show, only the audio plays.

What happens if i seek the playback to the 2nd part:

UPDATE:
FULL CONSOLE OUTPUT FOR ffmpeg -y -f concat -i parts.txt -c copy episode.mkv
ffmpeg version N-81118-gfb91850 Copyright (c) 2000-2016 the FFmpeg developers
  built with gcc 5.4.0 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-dxva2 --enable-libmfx --enable-nvenc --enable-avisynth --enable-bzlib --enable-libebur128 --enable-fontconfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libfreetype --enable-libgme --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-librtmp --enable-libschroedinger --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-libzimg --enable-lzma --enable-decklink --enable-zlib
  libavutil      55. 28.100 / 55. 28.100
  libavcodec     57. 50.100 / 57. 50.100
  libavformat    57. 44.100 / 57. 44.100
  libavdevice    57.  0.102 / 57.  0.102
  libavfilter     6. 49.100 /  6. 49.100
  libswscale      4.  1.100 /  4.  1.100
  libswresample   2.  1.100 /  2.  1.100
  libpostproc    54.  0.100 / 54.  0.100
[matroska,webm @ 000000000242bd40] Auto-inserting h264_mp4toannexb bitstream filter
Input #0, concat, from 'parts.txt':
  Duration: N/A, start: 0.000000, bitrate: N/A
    Stream #0:0: Video: h264 (High), yuv420p(tv, bt709), 1280x720, SAR 1:1 DAR 16:9, 23.97 fps, 23.97 tbr, 1k tbn, 47.95 tbc
    Metadata:
      BPS             : 1023638
      BPS-eng         : 1023638
      _STATISTICS_TAGS-eng: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES
      DURATION-eng    : 00:23:17.980000000
      NUMBER_OF_FRAMES: 33518
      NUMBER_OF_FRAMES-eng: 33518
      NUMBER_OF_BYTES : 178878340
      NUMBER_OF_BYTES-eng: 178878340
      _STATISTICS_WRITING_APP: mkvmerge v9.3.1 ('Mask Machine') 64bit
      _STATISTICS_WRITING_APP-eng: mkvmerge v9.3.1 ('Mask Machine') 64bit
      _STATISTICS_WRITING_DATE_UTC: 2016-07-30 17:28:29
      _STATISTICS_WRITING_DATE_UTC-eng: 2016-07-30 17:28:29
      _STATISTICS_TAGS: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES
      DURATION        : 00:22:13.164000000
[matroska @ 0000000000e7c920] Using AVStream.codec to pass codec parameters to muxers is deprecated, use AVStream.codecpar instead.
Output #0, matroska, to 'episode.mkv':
  Metadata:
    encoder         : Lavf57.44.100
    Stream #0:0: Video: h264 (High) (H264 / 0x34363248), yuv420p(tv, bt709), 1280x720 [SAR 1:1 DAR 16:9], q=2-31, 23.97 fps, 23.97 tbr, 1k tbn, 1k tbc
    Metadata:
      BPS             : 1023638
      BPS-eng         : 1023638
      _STATISTICS_TAGS-eng: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES
      DURATION-eng    : 00:23:17.980000000
      NUMBER_OF_FRAMES: 33518
      NUMBER_OF_FRAMES-eng: 33518
      NUMBER_OF_BYTES : 178878340
      NUMBER_OF_BYTES-eng: 178878340
      _STATISTICS_WRITING_APP: mkvmerge v9.3.1 ('Mask Machine') 64bit
      _STATISTICS_WRITING_APP-eng: mkvmerge v9.3.1 ('Mask Machine') 64bit
      _STATISTICS_WRITING_DATE_UTC: 2016-07-30 17:28:29
      _STATISTICS_WRITING_DATE_UTC-eng: 2016-07-30 17:28:29
      _STATISTICS_TAGS: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES
      DURATION        : 00:22:13.164000000
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
Press [q] to stop, [?] for help
[matroska,webm @ 0000000002605dc0] Auto-inserting h264_mp4toannexb bitstream filterpeed=1.87e+003x
frame=56417 fps=47467 q=-1.0 Lsize=  304604kB time=00:39:13.05 bitrate=1060.5kbits/s speed=1.98e+003x
video:304191kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.135798%


text:
Q: Regex Repeating Pattern Say you have a string:
string s = "GameObject.Find(\"obj\").GetComponent(\"comp\").GetMethod(\"method\").Get...";

The string can have any number of GetX() methods appended to it.
And you need to separate each method without the "." separator. Although, GameObject.Find can keep the (dot).
Here is my code so far :
Match match = Regex.Match(s, "(.+?\\(\".+?\"\\))(?:\\.??)*");

This produces only one group. What is the correct solution to this problem?
Edit :
Updated with non-capturing group.

A: First I'd recommend using verbatim string literals for writing regular expressions in C#. This cuts down the number of backslashes you need to write.
 @"(.+?\("".+?""\)\.??)*"

To get all the captures, inspect Match.Captures.
See it working online: ideone


text:
Q: creating some new columns based on old ones Create a new column Age. This is the current year (2019) minus the car's Year. If Age is 0, set it to 1.

Q1.Create a new column Age. This is the current year (2019) minus the
car's Year. If Age is 0, set it to 1. My codes are below:

df = pd.read_csv('car_train_data.csv',sep= ";",index_col= 0)
#method1
df["age"]= df[['age']].applymap(lambda x: 1 if pd(x) = 0)
#method2
df["age"]= (df["age"] == 0).all(1)

But it's failed...anyone can help with this??

A: I'm not sure what the data you have is, but try this.
import numpy as np
df['age'] = np.where(df['age']==0, 1, df['age'])

A: Toy example,
Input
    year    model
0   2019    a
1   2018    b
2   2017    c
3   2019    d

df=pd.DataFrame({
    'year':[2019, 2018, 2017, 2019],
    'model':['a','b','c','d']
})
df['age'] = np.where((2019 - df.year)==0,1,(2019 - df.year))
df

Output
    year    model   age
0   2019    a       1
1   2018    b       1
2   2017    c       2
3   2019    d       1


text:
Q: Refreshing a GLUT window Please, excuse my bad english.
I'm developing a program with OpenGL, GLUT and C++ that moves a block of polygons around the window. Well, first I used the GLUT timer function and it works fine. Now, I want to implement my own timer, so I wrote one. But when I use it in the same file, the animation works so slow. The timer create a thread to execute the function to move the block and I think the problem is that glutPostRedisplay don't refresh automatically the window and the timer continues doing calls to these function without consider if the winow was really updated or not.
My question is, is this the problem? How can solve it?
If is necesary, I can post the code, but is so large and hard to read...
Thanks.

A: glutPostRedisplay only sets the flag that means window needs to be updated, update will happen after glutSwapBuffers.


text:
Q: How to solve the equation $k = \frac{dv}{dt}(a + 2\int_0^t v(\tau) d\tau)^2$ I've been struggling a little on this problem for a while. I'm not sure what I'm missing. It goes like this:
$$k = \frac{dv}{dt}(a + 2\int_0^t v(\tau) d\tau)^2$$
Here $k, a$ are constants and $v, t$ represent velocity and time respectively. I want to know $v$ as a function of $t$. Is it possible to solve this? Any help would be appreciated!

A: Set $V(t)=\int_0^tv(s)ds$. Then your equation reads as
$$
k=V''(a+2V)^2.
$$
this can be separated and integrated once
$$
V''=\frac{k}{(a+2V)^2}\implies V'^2=c-\frac{k}{a+2V}.
$$
In principle you can now apply separation again, the resulting integral with square root might be difficult or impossible to solve.

A: If $v$ is velocity and is given by $v=\frac{ds}{dt}$ then
$$\int_0^tv(\tau)d\tau=\int_0^t\frac{ds}{d\tau}d\tau$$
By the fundamental theorem of calculus and Leibniz's rule:
$$\int_0^t\frac{ds}{dt}d\tau=\frac{d}{dt}\int_0^tsd\tau=\frac{d}{dt}st=s$$
Note: We are only allowed to do this because these specific limits of integration(zero at the left part, variable/parameter on the right part)
Substituting back in the original equation:
Which is 1st order in $v$
$$k=\frac{dv}{dt}(a+2s)^2$$
But because $v$ depends on $s$ we need to integrate it wrt. to $s$, then it's a 2nd order linear ODE:
$$k=\frac{d^2s}{dt^2}(a+2s)^2$$
$$\iint kdtdt=\iint(a+2s)^2dsds$$
$$k\frac{t^2}{2}=\int \frac{(a+2s)^3}{3a}ds+C=\frac{(a+2s)^4}{4a^2}+C$$
Now solve for $s$ and differentiate wrt. $t$ get back your solution to $v$.
Why doesn't distance depend on time?
To OP: try going through each step, i'll leave you to differentiate it on your own. Tell me if you got stuck.


text:
Q: Rational multiple of a line bundle In the paper http://arxiv.org/pdf/1207.5011.pdf of Chi Li and Song Sun, they say that "$D$ is a smooth divisor which is $\mathbb{Q}$-linearly equivalent to $−\lambda K_X$ for some $λ \in \mathbb{Q}$", and $X$ is a Fano manifold. I do not understand what is the meaning of "$\mathbb{Q}$-linearly equivalent".
In my opinion, if $L$ is linear equivalent to $-\frac{m_1}{m_2}K_X$, then we mean that $m_2 L$ is linear equivalent to $-m_1K_X$, for $m_1,m_2\in\mathbb{Z}^+$ and $m_1,m_2$ are prime with each other. Another question is whether $m_2$ here can be taken along all $\mathbb{Z}^+$? I wonder if $m_2$ is too large, whether there will be such line bundle $L$.


text:
Q: CSV to Custom XML with Java/Javascript i would like to convert from CSV to XML with Java/Javascript.
For example my CSV file is like this table:

| ID | OLO |
| 12345 | TLC |
| 12345 | VPN |
| 67890 | TLC |

I would like to have an XML file like this:
<?xml version='1.0' encoding='UTF-8'?>
<Custom name="Custom_ListaOLO">
  <Attributes>
    <Map>
      <entry key="12345">
        <value>
          <List>
            <String>TLC</String>
            <String>VPN</String>
          </List>
        </value>
      </entry>
      <entry key="67890">
        <value>
          <List>
            <String>TLC</String>
          </List>
        </value>
      </entry>
    </Map>
  </Attributes>
</Custom>

or:
<?xml version='1.0' encoding='UTF-8'?>
<Custom name="Custom_ListaOLO">
  <Attributes>
    <Map>
      <entry key="12345">
        <value>
          <List>
            <String>TLC</String>
            <String>VPN</String>
          </List>
        </value>
      </entry>
      <entry key="67890", value="TLC />
    </Map>
  </Attributes>
</Custom>

Can you help me?

A: you can fulfill the above requirement using JAXB marshaling with the MOXy implementation.
JAXB
Java Architecture for XML Binding (JAXB) is a software framework that provides way to map Java classes to XML representations. for more info
JAXB MARSHALING
converting the java objects to xml. for more info
MOXy
enable developers to handle the complex XML structures. for more info
firstly read the csv file and create java objects, then convert java objects to xml using jaxb marshaling with moxy implementation.
try with following solution,
create two java pojo classes (Custom and Entry) for represented <Custom> and <entry> elements of xml file,
Custom.java
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement(name="Custom")
public class Custom {

    private String name;
    private List<Entry> entry;

    public String getName() {
        return name;
    }

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

    public Custom() {
        entry = new ArrayList<Entry>();
    }

    @XmlPath("Attributes/Map/entry")
    public List<Entry> getEntry() {
        return entry;
    }

    public void setEntry(List<Entry> entry) {
        this.entry = entry;
    }
}

Entry.java
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAttribute;
import org.eclipse.persistence.oxm.annotations.XmlPath;

public class Entry {

    private String key;
    private List<String> string;

    public Entry() {
        string = new ArrayList<String>();
    }

    @XmlAttribute
    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    @XmlPath("value/List/String/text()")
    public List<String> getString() {
        return string;
    }

    public void setString(List<String> string) {
        this.string = string;
    }
}

read the csv file, create java objects and convert it to xml,
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.eclipse.persistence.jaxb.xmlmodel.ObjectFactory;

public class Demo {

    public static void main(String[] args) throws JAXBException {
        String line;
        String key = null;
        Custom custom = new Custom();
        Entry entry = null;
        int index = 0;

        try {
            BufferedReader br = new BufferedReader(new FileReader("inputCSV.csv")); //get csv file
            while ((line = br.readLine()) != null) {    //get every single line individually in csv file
                if(index > 0){  //skip the column's names (first line of csv file)
                    String[] value = line.split(",");   //collect the comma separated values (ID and OLO) into array
                    if(key == null || !key.equals(value[0])){   //first line of the csv file and when find the new key value, then create new entry
                        if(entry != null){
                            custom.getEntry().add(entry);   //add entry object into entry list of custom
                        }
                        key = value[0]; //assign the key value to variable (String key) for identify the new entry
                        entry = new Entry();    //create a new entry
                        entry.setKey(value[0]); //assign the key value to entry
                        entry.getString().add(value[1]);    //add string value String list of entry with new key
                    }else{
                        entry.getString().add(value[1]);    //add string value String list of entry under the same key
                    }
                }
                index++;
            }
            custom.setName("Custom_ListaOLO");  //set value to name attribute of custom element
            custom.getEntry().add(entry);   //add last entry into entry list of custom
        } catch (IOException e) {
            e.printStackTrace();
        }

        //marshaling with JAXB
        JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[]{Custom.class, ObjectFactory.class}, null);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(custom, new File("output.xml")); //generate the output xml file
        marshaller.marshal(custom, System.out);
    }
}

inputCSV.csv
ID,OLO
12345,TLC
12345,VPN
67890,TLC

output.xml
<?xml version="1.0" encoding="UTF-8"?>
<Custom name="Custom_ListaOLO">
   <Attributes>
      <Map>
         <entry key="12345">
            <value>
               <List>
                  <String>TLC</String>
                  <String>VPN</String>
               </List>
            </value>
         </entry>
         <entry key="67890">
            <value>
               <List>
                  <String>TLC</String>
               </List>
            </value>
         </entry>
      </Map>
   </Attributes>
</Custom>


text:
Q: charts js grid line not removing I am trying to remove gridlines from my chart that i have created using chrts.js but it is not working and verything seems right but i dont understand what is wrong, here's the code, i'll be grateful if someone could help me
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                gridLines: {
                    display: false,
                    drawOnChartArea: false,
                    drawTicks: false
                  },
            }]
        }
    }
});

A: If you want to remove all gridlines from the chart area, you should define the option gridLines.drawOnChartArea: false for the y-axis and the x-axis.
Please have a look at your amended code below.

var myChart = new Chart('myChart', {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        gridLines: {
          drawOnChartArea: false
        },
        ticks: {
          beginAtZero: true,
          stepSize: 5
        }
      }],
      xAxes: [{
        gridLines: {
          drawOnChartArea: false
        },
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="80"></canvas>


text:
Q: Changing the input I receive from a program from a int to a string beginner I wrote a program that is supposed to simulate grading quizzes, but I want to change the input I receive from a int to a string, so I can type in a, b, c, d, as the answer to a quiz.  How should I do this?
import java.util.Scanner;
public class Quizzes1
{
    public static void main(String[] args)
    {

        int Questions;
        int answers;
        int Quizzes;
        int numOfQs = 0;
        String phrase= "";
        Scanner scan = new Scanner(System.in);

        System.out.println("How many questions are in the quizz?");
        Questions = scan.nextInt();

        char[] key = new char[numOfQs];

        int[] canswers = new int[Questions];
        for (int i=0; i<canswers.length; i++)
     {
  System.out.println("Please give the correct answers " + (i+1) + ": ");
  canswers[i] = scan.nextInt();
     }

        while (!phrase.equals("n"))
        {

            double Correct = 0;
            double Incorrect = 0;
            for (int i=0; i<canswers.length; i++)
            {
            System.out.println("What are the answers that the students put");
            answers = scan.nextInt();
            if (answers == canswers[i])
                Correct++;
            else
                Incorrect++;
            }

            System.out.println("There are " +Correct + " correct answers and " +Incorrect
                +" incorrect answers");
            double Percent = ((Correct / (Correct + Incorrect)) * 100);
            System.out.println("The percentage correct is " +Percent +"%");
            phrase = scan.nextLine();
            System.out.println("Would you like to grade another quiz y/n");
            phrase = scan.nextLine();
        }
    }
}

A: as a,b,c and d are singls letters, why don't you read characters instead of int or even string?
Just try
scanner.nextLine().charAt(0);

using characters, you can still use this part of your code:
if (answers == canswers[i])
    Correct++;
else
    Incorrect++;
}

That's pretty similar to dasblinkenligh's answer


text:
Q: VB6 Byte array in VB.NET I have some image comparison DLL, and documentation for VB6, but I want to use it in ASP.NET/VB.NET
In documentation is stated following:

iDLLoadImage
Description : Load the captured image (in raw format), preparing for
  face detection.
Declaration : iDLLoadImage (pByte As Byte, iWidth As Long, iHeight As
  Long,  iColor As Long)
Parameters : pByte    : byte array which stored the (raw) captured image
  (in) iWidth   : for setting raw image width (in) iHeight  : for setting
  raw image height (in) iColor  : 1 for Gray image, 3 for RGB image (in)
Return Values : 0 : Successful
  -1    : This library is not enabled.
  -2    : pByte is NULL.
  -3    : Failed to initialize internal parameters

But, when I try to pass it byte array in VB.NET it says it expects byte.
Is there any solution for this?
(And here's screenshot) http://i.stack.imgur.com/giORJ.png
Thanks.

A: Try these things:

*

*A Dabblernl said, try using image(0) as a parameter. Since it is byref, it may pass the memory location and from there process the entire array.

*You may be able to declare the function as an alias, and change the first parameter to pByte As Byte().


text:
Q: how to change profile picture on yii2 backend advanced I am using yii2 advanced app . In that we have static profile pic in backend side. how to change that pic dynamically?? just like we change our profile pic in facebook and other social media. can we do this?
backend\views\layouts\left.php

                <img src="<?= $directoryAsset ?>/img/user2-160x160.jpg" class="img-circle" alt="User Image"/>

how to change this image dynamically?


text:
Q: Keras Convolution1D input shape I am trying to build a simple Convolutional NN with:

*

*340 samples,

*260 rows per sample

*16 features per row.

I thought the order of the shape is (batch_size, steps, input_dim), which would mean (340, 16, 260) I believe.
Current code:
model = Sequential()
model.add(Conv1D(64, kernel_size=3, activation='relu', input_shape=(340, 16, 260)))
# model.add(Conv2D(64, 2, activation='relu'))
model.add(MaxPooling1D())
# model.add(Conv2D(128, 2, activation='relu'))
model.add(Conv1D(64, kernel_size=3, activation='relu'))
model.add(GlobalAveragePooling1D())
model.add(Dense(1, activation='linear'))

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

model.summary()

model.fit(xTrain, yTrain, batch_size=16, epochs=1000)

I am getting an error:

ValueError: Input 0 is incompatible with layer conv1d_1: expected ndim=3, found ndim=4

I am very lost and believe that my shapes are off. Could someone help me?
Thank you!

A: As mentioned in this answer, layers in Keras, accept two arguments: input_shape and batch_input_shape. The difference is that input_shape does not contain the batch size, while batch_input_shape is the full input shape, including the batch size.
Based on this, I think the specification input_shape=(340, 16, 260) tells keras to expect a 4-dimensional input, which is not what you want. The correct argument would be batch_input_shape=(340, 16, 260).


text:
Q: AngularJS RouteProvider Single When-Condition For All Route/Path/URL I'm using $routeProvider to change a page (telmplate) and controller when user click a link.
Like this:
$routeProvider.when('/profile/', {
        templateUrl: '/app/views/profile.html',
        controller: 'ProfileCtrl'
    }).when('/timeline/', {
        templateUrl: '/app/views/timeline.html',
        controller: 'TimelineCtrl'
    }).when('/chat/:username', {
        templateUrl: function(param){
          if(param){
            return '/app/views/chat.html?' + param;
          }
           return '/';
        },
        controller: 'ChatCtrl'
    }).otherwise({ redirectTo: '/' });

The problem is there are so many pages on my app and I need to register every single url on .when condition repetitively, whereas the template url and controller name is loaded based on link path.
My question is: Can I generalized all those when condition into a single when statement?
Like this:
$routeProvider.when(url, {
    templateUrl: '/app/views/' + url + '.html',
       controller: url + 'Ctrl'
});

Thanks in advance :)

A: You can try something like below:
angular.module('myapp', ['myapp.filters', 'myapp.services', 'myapp.directives']).
    config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/page/:name', {
        templateUrl: function(urlattr){
            return '/pages/' + urlattr.name + '.html';
        },
        controller: urlattr.name+'Ctrl.js'
      });
     }
]);

Please try it. In this case I am assuming your html page name is same as Controller name and have 'Ctrl' as suffix.


text:
Q: C# to VB.net delegate conversiom I'm trying convert C# code to VB.net and delegate stopped me.
origial code is:
using (var source = new ETWTraceEventSource(sessionName, TraceEventSourceType.Session))
        {
            Action<TraceEvent> action = delegate (TraceEvent data)
            {
                var taskName = data.TaskName;
                var EventName = data.EventName;

Row Action<>... is problem for me.
Some example will be appreciated.
Thanks, Jerry

A: Using the 'delegate' keyword in this way is outdated legacy C# (pre-lambda operator). The modern C# way is to use the lambda operator:
Action<TraceEvent> action = (TraceEvent data) =>

The VB equivalent for both is:
Option Infer On

Using source = New ETWTraceEventSource(sessionName, TraceEventSourceType.Session)
    Dim action As Action(Of TraceEvent) = Sub(data As TraceEvent)
        Dim taskName = data.TaskName
        Dim EventName = data.EventName
    End Sub
End Using


text:
Q: Google Play Services Location throwing NullPointerException I am trying to run a service that tracks a users location using the Google Play Location Services. I've followed the [Android Developers Google Play] (http://developer.android.com/google/play-services/setup.html) instructions but currently have a crashing app.
I am using the android emulator AVD with a Google API target (17).
I have
1) Installed the Google Play Services SDK
2) Made a copy of the Google Play services library project, imported it into my Eclipse workspace, and referenced it in my current app, using these [instructions] (http://developer.android.com/tools/projects/projects-eclipse.html#ReferencingLibraryProject)
I am not sure whether or not I have to add anything to the Manifest
Some background on my app structure: I have created a Location Services class with all of the error handling, and am calling that class' methods via a service. My app is currently crashing when I call the:
GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
command which is in the servicesConnected() which is the first instance I call anything Google Play related. So basically, where I am at: I am trying to call the method checking if Google Play services is available, and the app is crashing on:
 08-19 03:51:19.464: E/AndroidRuntime(1112): java.lang.RuntimeException: Unable to start service
      com.scarr025.zwilio.AdventureService@40d24920 with Intent { flg=0x4
      cmp=com.scarr025.zwilio/.AdventureService (has extras) }: java.lang.NullPointerException

Please help!!
Code is below:
Google Play Services Class
public class AdventureLocator extends FragmentActivity implements
            GooglePlayServicesClient.ConnectionCallbacks,
            GooglePlayServicesClient.OnConnectionFailedListener {

protected void onCreate(Bundle savedInstanceState) {
    mLocClient = new LocationClient(this, this, this);
    mContext = this;
}

public void startConnection() {
    mLocClient.connect();
}

public Location getLastLocation() {
    return mLocClient.getLastLocation();
}

// Method that encapsulates the check for Google Play services
public boolean servicesConnected() {
    // Check that Google Play services is available
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode) {
        // In debug mode, log the status
        Log.d("$$AdventureLocator$$", "In servicesConnected; Google Play services is available (returned true).");
        // Continue
        return true;
    // Google Play services was not available for some reason
    } else {
        // Get the error code
        // Get the error dialog from Google Play services
        Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
                resultCode,
                this,
                CONNECTION_FAILURE_RESOLUTION_REQUEST);

        // If Google Play services can provide an error dialog
        if (errorDialog != null) {
            // Create a new DialogFragment for the error dialog
            ErrorDialogFragment errorFragment = new ErrorDialogFragment();
            // Set the dialog in the DialogFragment
            errorFragment.setDialog(errorDialog);
            // Show the error dialog in the DialogFragment
            errorFragment.show(getSupportFragmentManager(), "Location Updates");
        }
        return false;
    }
    ...

Manifest File
...
        <service
        android:name=".AdventureService"
        android:label="@string/title_adventure_service" >
    </service>
    <activity
        android:name=".AdventureLocator"
        android:label="@string/title_adventure_locator" >
    </activity>
</application>

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

A: Left out the library referencing in the Manifest File
"After you've added the Google Play services library as a dependency for your app project, open your app's manifest file and add the following tag as a child of the  element:
<meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version" />

Once you've set up your project to reference the library project, you can begin developing features with the Google Play services APIs."


text:
Q: Using BCryptAddContextFunction and BCryptRemoveContextFunction to prioritize Schannel Cipher Suites for TLS 1.2 I have a list of cipher suits which should be acceptable on my server.
For example: I would like to handling only those suites in system
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"
I tried to use samples from
https://msdn.microsoft.com/en-us/library/windows/desktop/bb870930(v=vs.85).aspx#adding__removing__and_prioritizing_cipher_suites
but... this works only theoretically
// for visual c++
#include <stdio.h>
#include <windows.h>
#include <bcrypt.h>
#pragma comment(lib, "Bcrypt.lib")
#ifndef NT_SUCCESS
#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)
#endif

void addToTop(LPWSTR wszCipher){

    SECURITY_STATUS Status = ERROR_SUCCESS;
    wprintf_s(wszCipher);
    printf_s("\r\n");
    Status = BCryptAddContextFunction(
        CRYPT_LOCAL,
        L"SSL",
        NCRYPT_SCHANNEL_INTERFACE,
        wszCipher,
        CRYPT_PRIORITY_TOP);
    if (FAILED(Status))
    {
        printf_s("\n**** Error 0x%x returned by BCryptAddContextFunction\n", Status);
    }

}

void printCipherSuites()
{
    HRESULT Status = ERROR_SUCCESS;
    DWORD   cbBuffer = 0;
    PCRYPT_CONTEXT_FUNCTIONS pBuffer = NULL;

    Status = BCryptEnumContextFunctions(
        CRYPT_LOCAL,
        L"SSL",
        NCRYPT_SCHANNEL_INTERFACE,
        &cbBuffer,
        &pBuffer);
    if (FAILED(Status))
    {
        printf_s("\n**** Error 0x%x returned by BCryptEnumContextFunctions\n", Status);
        goto Cleanup;
    }

    if (pBuffer == NULL)
    {
        printf_s("\n**** Error pBuffer returned from BCryptEnumContextFunctions is null");
        goto Cleanup;
    }

    for (UINT index = 0; index < pBuffer->cFunctions; ++index)
    {
        printf_s("\n%S", pBuffer->rgpszFunctions[index]);
    }
Cleanup:
    if (pBuffer != NULL)
    {
        BCryptFreeBuffer(pBuffer);
    }
    getchar();
}

int removeSth()
{
    printf_s("\nRemoving TLS_RSA_WITH_AES_128_CBC_SHA256");
    LPWSTR wszCipher = L"TLS_RSA_WITH_AES_128_CBC_SHA256";
    SECURITY_STATUS Status = ERROR_SUCCESS;

    Status = BCryptRemoveContextFunction(
        CRYPT_LOCAL,
        L"SSL",
        NCRYPT_SCHANNEL_INTERFACE,
        wszCipher);
    if (FAILED(Status))
    {
        printf_s("\n**** Error 0x%x returned by BCryptRemoveContextFunction\n", Status);
    }
    return 0;
}
void main()
{
    addToTop(L"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
    addToTop(L"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256");
    addToTop(L"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384");
    printCipherSuites();
}

You can see - calling BCryptAddContextFunction does not change anything in system. I do not have failed Status for this call, however - when I list all cipher suites - there is no TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, LS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 on the list
I cannot find a working WinAPI sample. What should I change in my code to prioritize Schannel Cipher Suites?
edit:
I discovered an interesting thing... WinApi remove/add functions returns STATUS_SUCCESS - but SSL Cipher Suites list is not updated.
We also cannot see the results of BCryptAddContextFunction/BCryptRemoveContextFunction in
gpedit.msc, Computer Configuration -> Administrative Templates -> Network -> Local Group Policy Editor -> SSL Cipher Suite Order


text:
Q: How to download a package with dependency manually? I am going to install following package: gcc-4.9-aarch64-linux-gnu
But apt is unable to find it. I downloaded the .deb manually and installed it using dpkg. but there is some missing dependency. When I use apt to fix the problem it said:
$ sudo apt-get install gcc-4.9-aarch64-linux-gnu
        Reading package lists... Done
        Building dependency tree
        Reading state information... Done
        gcc-4.9-aarch64-linux-gnu is already the newest version (4.9.3-13ubuntu2cross1).
        You might want to run 'apt --fix-broken install' to correct these.
        The following packages have unmet dependencies:
         gcc-4.9-aarch64-linux-gnu : Depends: cpp-4.9-aarch64-linux-gnu (= 4.9.3-13ubuntu2cross1) but it is not installable
                                     Depends: binutils-aarch64-linux-gnu (>= 2.26)
                                     Depends: gcc-4.9-aarch64-linux-gnu-base (= 4.9.3-13ubuntu2cross1) but it is not installable
                                     Depends: libgcc-4.9-dev-arm64-cross (= 4.9.3-13ubuntu2cross1) but it is not installable
                                     Depends: libmpfr4 (>= 3.1.3) but it is not installable
                                     Recommends: libc6-dev-arm64-cross (>= 2.13-0ubuntu6) but it is not going to be installed
        E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

What does it mean by but it is not installable ? Why I can not install it? I have been added all 4 main repositories from Ubuntu. I am using ubuntu 18.04.
EDIT: I have seen this link. BUT I want to install it anyway. How I can? The problem with manual installation is its many dependency packages. Should I download and install all of them manually? Not less tedious way?!

A: You can manually find the packages by searching packages.ubuntu.com.  For instance you can follow the links to get to a downloadable deb of one of the dependecies from here: https://packages.ubuntu.com/en/xenial/cpp-4.9-aarch64-linux-gnu.
There might be an easier way though.  Since this appears to be from Xenial, if you turn off all repos in /etc/apt/sources.list and only have the main and universe repos enabled for Xenial (eg. deb http://us.archive.ubuntu.com/ubuntu/ xenial main universe), then perhaps apt-get install gcc-4.9-aarch64-linux-gnu will work.  Make sure to do apt remove gcc-4.9-aarch64-linux-gnu first.  Also, be careful, make sure that only the dependencies you want are getting pulled in.  Sometimes this kind of thing can end up trying to install the Xenial glibc, which could break your system.


text:
Q: What is the role of arg in variable argument function defined as int function(int arg, ...)? I am learning about variable argument functions in C and i came across different codes which uses different named argument (injector message as per some websites). int function(int count, ...), int function(char *string, ...).I tried running below code.
#include <stdio.h>
#include <stdlib.h>

#include <stdarg.h>
#include <string.h>

int addition(int count, ...)
{
    va_list values;
    va_start(values, count);

    int sum = 0;

    for (int i = 0; i < count + 2; i++)
    {
        sum += va_arg(values, int);
    }

    return sum;
}

int main(void)
{
    int sum = average(3,12,23,43,65,12);

    printf("%d\n", sum);
    return 0;
}

It ran successfully again. By writing above code i have no intention to get the addition but just to understand the role of named argument(count) there are few points which made me skeptical.
I thought named argument is the number of arguments passed to the variadic function. But after encountring a function int function(char *string, ...) and using above code i am clear this isn't its role.
In above function i can pass count+2 in for loop to find the sum, and i can get the same result as intended, So clearly importance of named argument depends on functionality of the code.
There are many instances one wants to pass a variable count to a variadic function like taking average or passing a char* to create a input function like scanf. But on the same place there can be some cases where there is no need of any named argument (i don't know any example but i believe there may be some cases)
I thought the reason to use a named argument may lie in the inability of a compilor to figure out if the argument passed is named argument or not. But by removing named argument in average function int average(...), i am getting compiler error that there is no named argument passed. So compiler can distinguish between a named argument and a variable argument. This can also be illustrated by changing the declaration of the addition function to int addition(int count, int another, ...), by doing this compiler will give error that int count is not the last named argument.
The only thing i don't understand is this, why named argument is necessary even though it is not necessarily going to affect the working of the program (as per my knowledge). As compiler can distinguish between a named argument and a variable argument, one can use this ability to create a function which takes only variable arguments and a variadic function with named argument at the same time.
va_start is taking named argument as 2nd argument and on this website it states  void va_start (va_list ap, paramN); Initializes ap to retrieve the additional arguments after parameter paramN. As i understand this, it means that 2nd argument is to tell compiler that arguments after paramN are variable arguments, But i think compiler already knows which argument is which.


text:
Q: Finding the eigenvalues of $A^2$ and $A^{-1}$ from the characteristic polynomial of $A$ In my question we are given a characteristic polynomial $x^3 - 4x^2 + x + 6$ for a matrix A and are told to find eigenvalues for both $A^{-1}$ and $A^2$. I just want to confirm that I am approaching this correctly. So I found the eigenvalues for matrix $A$, which are $x = -1, x = 2, x = 3$. Looking at the equation $A^n = P^{-1} D^n P$, where D is known because we have the eigenvalues, to find the eigenvalues of $A^2$ would we just have to do $(-1)^2, 2^2, 3^2$ ? and then a similar approach for $A^{-1}$.
Thank you.

A: HINTS
 Characteristic polynomial of $ A^{-1 }$is the polynimial whose roots are recripocal to roots of the given polynomial.


text:
Q: Highlight all words in jTextField that the user puts into search for Hey all the following code below works with highlighting the supplied word to search for but if there are more than just one (1) of that word in the sentence then it wont find it. It just stops at finding one (1) match.
private JFrame frame;
private static JTextField textField;
private static JTextField txtWorld;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                CaretDemo window = new CaretDemo();
                window.frame.setVisible(true);

                String text = "hello world. How are you?";

                textField.setText(text);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public CaretDemo() {
    initialize();
}

private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    textField = new JTextField();
    textField.setBounds(21, 11, 350, 36);
    frame.getContentPane().add(textField);
    textField.setColumns(10);

    txtWorld = new JTextField();
    txtWorld.setColumns(10);
    txtWorld.setBounds(21, 156, 350, 36);
    frame.getContentPane().add(txtWorld);

    JButton btnNewButton = new JButton("New button");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Highlighter highlighter = textField.getHighlighter();
            HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.pink);
            int p0 = textField.getText().indexOf(txtWorld.getText());
            int p1 = p0 + txtWorld.getText().length();

            try {
                highlighter.removeAllHighlights();
                highlighter.addHighlight(p0, p1, painter);
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        }
    });

    btnNewButton.setBounds(221, 203, 128, 29);
    frame.getContentPane().add(btnNewButton);
}

The above code looks like this when ran and supplied the word "world" to find.

But now if I add to the sentence and add another "world" then hit the button this is what it looks like:

As you see, it still has the same highlighted word without also highlighting the second (2) "world".
UPDATE 1
I have attempted using regex in order to loop and find the needed word.
btnNewButton_3.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        System.out.println("hi");
        String theSentence = txtTheSentence.getText();
        String WordToFind = txtWordToFind.getText();
        Highlighter h = txtWordToFind.getHighlighter();

        Pattern pattern = Pattern.compile("\\b"+WordToFind+"\\b", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(theSentence);

        if(matcher.find()){
            String extractedWord = matcher.group(0);
            System.out.println(extractedWord);
        }
    }
});

But this does not produce even one word found.

A:
it still has the same highlighted word without also highlighting the second (2) "world" -

Well that is exactly what your code does.
First you remove all the highlights and then add back a single highlight.
If you want multiple words to be highlighted then you need to:

*

*first remove all the highlights and then

*write a loop and process all the text in the string.

You can use the String.indexOf(text, fromIndex) method to continue the search from a new index once you find the matching text.

A: Got it finally!
btnNewButton_3.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        System.out.println("hi");
        String theSentence = txtTheSentence.getText();
        String theWord = txtWordToFind.getText();
        Highlighter h = txtWordToFind.getHighlighter();
        Pattern pattern = Pattern.compile(theWord, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(theSentence);

        while (matcher.find()) {
            String extractedWord = matcher.group();
            System.out.println(extractedWord);
        }
}


text:
Q: How do I build a trap? So I'm trying to build a trap on the bridge leading into sanctuary.
I placed a pressure plate and a tesla trap, then I wired them up to power.  Once I exited the workshop menu I 'activated' the pressure plate by interacting with it and it disappeared.
What did I do wrong?

A: Traps work exactly as you'd expect - basically in an identical manner to lights and other electrical devices. If you've had a pressure plate fall through the floor I'd call this a bug. It's likely it didn't agree with you placing it exactly on the floor and some clipping issue occurred when you stood on it.
The other thing I came across is that you can effortlessly break these traps (especially the tesla trap) just by having it on. To repair a broken trap in Workshop mode, press E with the item selected.

The things to notice are only the "metal" section of the pressure plate depresses, when it does the red light goes green. When there is no pressure the green light will go red. While the light is green, power will pass to connected devices. While the light is red, it won't.


text:
Q: Недостаточно системных ресурсов при загрузке словаря Добавляю к spellchecker'у словарь:
        spellChecker1.Dictionaries.Clear();

        DevExpress.XtraSpellChecker.SpellCheckerOpenOfficeDictionary openOfficeDictionaryRussian =
            new DevExpress.XtraSpellChecker.SpellCheckerOpenOfficeDictionary();
        openOfficeDictionaryRussian.DictionaryPath = @"Dictionaries\russian-aot.dic";
        openOfficeDictionaryRussian.GrammarPath = @"Dictionaries\russian-aot.aff";
        openOfficeDictionaryRussian.Culture = new System.Globalization.CultureInfo("ru-RU");
        spellChecker1.Dictionaries.Add(openOfficeDictionaryRussian);

Далее добавляю проверку орфографии
private void Form1_Load(object sender, EventArgs e) {
        spellChecker1.SpellCheckMode = DevExpress.XtraSpellChecker.SpellCheckMode.AsYouType;
        spellChecker1.Check(memoEdit1);
    }

В результате при загрузке приложения и его попытке загрузить словарь получаю ошибку

Additional information: Недостаточно системных ресурсов, чтобы загрузить словарь ru-RU.

Windows 10 Pro 1703, 16 ГБ ОЗУ
Проверка орфографии в Outlook и Word работает без проблем.
Подскажите, пожалуйста, что я делаю не так?


text:
Q: Get middleware mount point from request in Express I have an Express application with a router, here is the example of the router:
const router = require('express-promise-router')();

const users = require('./users');
const validate = require('./validate');

router.get('/users', users.list);
router.get('/users/:id', users.get);
// other routes here

module.exports = router;

Now I want to add a middleware that validates each query, like that (this is not the working example, it's just to show the idea of what I want to accomplish):
const schemas = {
    '/users': 'some validation schema',
    '/users/:id': 'another validation'
}

module.exports = (req, res, next) => {
    const url = req.originalUrl; // This is where I'm stuck.

    if (!schemas[url]) {
        // throw new error that validation failed
    }

    // validating somehow
    if (!req.validate(schemas[url])) {
        // throw new error that validation failed
    }

    return next();
}

And for this, I need to get the middlelware mount folder (like '/users/:id' for '/users/557'). I've tried to use req.originalUrl, but it returns the full URL path instead of the mount folder.
How can I achieve this? And if there's no way, how can I write my validation middleware another way to make it work?

A: Inside req.route you will get the path of API.
Check this screenshot


text:
Q: Bootstrap4 adding scrollbar to div I am using stacked pills inside a div. The problem is, sometimes the div contains a lot of pills. How can I add a scrollbar for it?

    Active

    Link

    Link

    Disabled

Can I add a class for the div to make stacked pills scrollable?

A: Yes, It is possible,
Just add a class like anyclass
and give some CSS style. Live
.anyClass {
  height:150px;
  overflow-y: scroll;
}

.anyClass {
  height:150px;
  overflow-y: scroll;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>

      Active

      Link

      Link

      Link

      Link

      Link

      Link

      Link

      Link

      Link

      Link

      Disabled

A: Use the overflow-y: scroll property on the element that contains the elements.
The overflow-y property specifies whether to clip the content, add a scroll bar, or display overflow content of a block-level element, when it overflows at the top and bottom edges.
Sometimes it is interesting to place a height for the element next to the overflow-y property, as in the example below:

    Active

    Link

    Link

    Disabled

A:

.Scroll {
  height:600px;
  overflow-y: scroll;
}
<!DOCTYPE html>

Smooth Scroll

Section 1

Click on the link to see the "smooth" scrolling effect.

Note: Remove the scroll-behavior property to remove smooth scrolling.

Section 2

Knowing how to write a paragraph is incredibly important. It's a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you're writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.

Section 3

Knowing how to write a paragraph is incredibly important. It's a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you're writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.

Section 4

Knowing how to write a paragraph is incredibly important. It's a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you're writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.

Section 5

    Click Me to Smooth Scroll to Section 1 Above

Section 6

Knowing how to write a paragraph is incredibly important. It's a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you're writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.

Section 7

    Click Me to Smooth Scroll to Section 1 Above

A:

        Column 0

        Column 1

        Column 2

        Column 3

        Column 4

        Column 5

        Column 6

        Column 7

        Column 8

        Column 9

        Column 10

        Column 11

        Column 12

        Column 13


text:
Q: Apache - Redirecting from one URL to another with a new domain I'd like to redirect a list of URLs to another list in a new domain, like this:
myoldsite.com/page1 => mynewsite.com/the-new-page-1

The base of my .htaccess file is likek this
Redirect 301 /v2/test https://newdomain.com/foo
Redirect 301 /v2/hello https://newdomain.com/bar

But when I access http://myoldsite.com/v2/test I don't get redirected to https://newdomain.com/foo. FYI the source site has a .htaccess on /v2 folder.

A: If your .htaccess file is inside the v2 folder already, then you don't need the /v2/ part and the redirects should be something like this:
Redirect 301 test https://newdomain.com/foo
Redirect 301 hello https://newdomain.com/bar

A: if the .htaccess file is in the folder ./v2/ you should omit "/v2" from your rewrite rule
or you move the rules to a .htaccess file in the document root


text:
Q: Integer to int[] conversion in Java Problem:

Given an array of integers nums sorted in ascending order, find the
  starting and ending position of a given target value.
Example:Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]

My code:
class Solution34{
public int[] searchRange(int[] nums, int target) {
    ArrayList<Integer> index=new ArrayList<>();
    for(int i=0;i<nums.length;i++){
        if(nums[i]==target){
            index.add(i);
        }
    }
    Integer[] index_arr = new Integer[index.size()];
    index_arr = index.toArray(index_arr);

    System.out.println(index);
  return index_arr;
}
}

System.out.println(index) - My code gave me desired output.(If I omit return statement ).
I got an error in last line return index_arr. Error: Incompatiable types:Required int[] Found Java.lang.Integer.
Then I searching how to convert Integer to int and found .int.Value use to convert Integer to int. When I use it in my code I got another error unrecognizable command. How could I convert Integer to int[]?

A: I would start with a firstIndex and a lastIndex initialized to -1. Then iterate the nums array searching for target. When found, if the firstIndex is -1 initialize both it and the lastIndex - otherwise update only the lastIndex. Return a new array at the end. Like,
public static int[] searchRange(int[] nums, int target) {
    int firstIndex = -1, lastIndex = -1;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == target) {
            if (firstIndex == -1) {
                lastIndex = firstIndex = i;
            } else {
                lastIndex = i;
            }
        }
    }
    if (firstIndex == -1) {
        return new int[] { -1 };
    }
    return new int[] { firstIndex, lastIndex };
}

A: You are trying to return an array of Integer[] but your method returns int[], hence the compilation error.
To fix it you should change the return type of searchRange(...) to Integer[].

A: return type of searchRangeis int array, but you are returning Integer array.

Convert ArrayList<Integer> to int[] by using java-8 streams and return

 public int[] searchRange(int[] nums, int target) {
        ArrayList<Integer> index=new ArrayList<>();
        for(int i=0;i<nums.length;i++){
            if(nums[i]==target){
                index.add(i);
            }
        }
        System.out.println(index);
      return index.stream().mapToInt(Integer::intValue).toArray();

A: One approach would be to stream the list, convert the Integers to ints and collect to an array:
return index.stream().mapToInt(Integer::intValue).toArray();

A:
How could I convert Integer to int[]?

You cann't do that. If you want to convert Integer[] to int[], try do it like this in java8:
int[] intArray = Arrays.stream(index_arr).mapToInt(Integer::intValue).toArray();

Update:
just for the leetcode 34, try this code with a time complexity of O(lgn), in which the binary search is employed.
class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] res=new int[]{Integer.MAX_VALUE,Integer.MIN_VALUE};
        binarySearch(nums,0,nums.length-1,target,res);
        if(res[0]==Integer.MAX_VALUE&&res[1]==Integer.MIN_VALUE)
            return new int[]{-1,-1};
        else
            return res;
    }

    private void binarySearch(int[] nums,int lo,int hi,int t,int[] res){
        if(hi<lo)
            return;
        int mid=lo+(hi-lo)/2;
        if(nums[mid]==t){
            if(mid<res[0])
                res[0]=mid;
            if(res[1]<mid)
                res[1]=mid;
            binarySearch(nums,lo,mid-1,t,res);
            binarySearch(nums,mid+1,hi,t,res);
        }else if(nums[mid]<t){
            binarySearch(nums,mid+1,hi,t,res);
        }else if(t<nums[mid]){
            binarySearch(nums,lo,mid-1,t,res);
        }
    }

}

A: Hi you can change your Integer array to String and then to charArrays and finally to int[] that your method wants it as return value.  Like this :
 public int[] searchRange(int[] nums, int target) {
    ArrayList<Integer> index = new ArrayList<Integer>();
    for (int i = -0; i < nums.length; i++) {
        if (nums[i] == target) {
            index.add(i);
        }
    }
    Integer[] index_arr = new Integer[index.size()];
    index_arr = index.toArray(index_arr);
    String i = index_arr.toString();
    char[] characters = i.toCharArray();
    int[] list = new int[characters.length];

    for (int z = 0; z < characters.length; z++) {
        list[z] = characters[z];
    }

    System.out.println(index);
    return list;
}

A: If you are using old version of you can do like this
package com.stackoverflow;
import java.util.ArrayList;
public class Solution34 {
public int[] searchRange(int[] nums, int target) {
    ArrayList<Integer> index = new ArrayList<>();
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == target) {
            index.add(i);
        }
    }
    Integer[] index_arr = new Integer[index.size()];
    index_arr = index.toArray(index_arr);

    System.out.println(index);

    int[] int_index_arr = new int[index_arr.length];

    for (int i = 0; i < index_arr.length; i++) {
        int_index_arr[i] = index_arr[i];
    }

    return int_index_arr;
}

public static void main(String[] args) {
    int[] nums = { 5, 7, 7, 8, 8, 10 };
    int target = 8;

    Solution34 s34 = new Solution34();
    int[] result = s34.searchRange(nums, target);
    for (int i : result) {
        System.out.println(i);
    }
}

}

A: if you are using java 8 or above,you can use this code
package com.stackoverflow;
import java.util.ArrayList;
public class Solution34 {
public int[] searchRange(int[] nums, int target) {
    ArrayList<Integer> index = new ArrayList<>();
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == target) {
            index.add(i);
        }
    }

    return index.stream().mapToInt(x -> x).toArray();
}

public static void main(String[] args) {
    int[] nums = { 5, 7, 7, 8, 8, 10 };
    int target = 8;

    Solution34 s34 = new Solution34();
    int[] result = s34.searchRange(nums, target);
    for (int i : result) {
        System.out.println(i);
    }
}

}


text:
Q: How to stop jackson timezone conversion and not apply local offset In my java dto i am converting json date ("dispOn": "11/28/2020",) to java.util.Date.since i am not sending any timezone jackson is taking UTC as default time zone but when desterilizing it is taking the offset of CST(My local time)as a result, date in my code(11/27/2020) is one day behind
import java.util.Date;
@JsonFormat(pattern = "MM/dd/yyyy")
private Date dispOn;

How can i get the same date sending in json into my code

A: As Andreas mentioned in his comment, it is sufficient to change from Date to LocalDate.
For additional info, I used LocalDateTime to show you how the format should be configured. I'm also using Lombok's annotations on class-level for logging and getter/setter generation.
Keep in mind that LocalDate and LocalDateTime are only available since Java 8.
Below a complete example of a DTO in which I parse a JSON
@Slf4j
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true) // optional annotation
public class MyMessage implements Deserializer<MyMessage> {

    @JsonProperty("EVENT_TIMESTAMP")
    @JsonFormat(shape = JsonFormat.Shape.STRING,
                pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS")
    private LocalDateTime eventTimestamp;
    @JsonProperty("MESSAGE")
    private String message;

    @Override
    public void configure(Map<String, ?> configs, boolean isKey) {
        Deserializer.super.configure(configs, isKey);
    }

    @Override
    public MyMessage deserialize(String s, byte[] bytes) {
        ObjectMapper mapper = new ObjectMapper();
        MyMessage event = null;
        try {
            event = mapper
                    .registerModule(new JavaTimeModule())
                    .readValue(bytes, MyMessage.class);
        } catch (Exception e) {
            log.error("Something went wrong during the deserialization of the MyMessage: {}", e.getMessage());
        }
        return event;
    }

    @Override
    public MyMessage deserialize(String message, Headers headers, byte[] data) {
        return Deserializer.super.deserialize(message, headers, data);
    }

    @Override
    public void close() {
        Deserializer.super.close();
    }

And the JSON I'm sending:
{
"EVENT_TIMESTAMP": "2022-03-15T14:14:05.945",
"MESSAGE": "Test 123"
}


text:
Q: How can I convert a date / time I get in as part of a json object into a date only? My json is returning:
json.Modified = "28/09/12 18:42"

is there a way I can convert this into:
"28/09/12"

A: var date = "28/09/12 18:42"
date = date.split(" ");
final = date[0];

A: Please use the below code
var date = "28/09/12 18:42";
var arr =data.split(" ");
var newDate = arr[0];

A: You may try this
var d=json.Modified.split(' ')[0];
alert(d); // 28/09/12

DEMO.

A: You can use the substr function if your string always matches the same pattern.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substr
var cleanedDate = dateAndHours.substr(0,8);

A: var dateOnly = json.Modified.substring(0, 8);


text:
Q: Gradle + Git - enforcing a version change upon merge to master I am leading a team of developers creating a Java library.  We are following the standard Semantic Versioning model.  The code is versioned with Git.  Artifacts are built and pushed to an artifact server using Gradle.
As is the standard, the artifact version, when published, is determined in build.gradle with the line version 'xxx.xxx.xxx'.  I want to enforce a policy that all merges to the master branch require that this version be changed.  This is to ensure we don't accidentally publish a new artifact over an old version, which could cause a dependency nightmare for downstream users of our library.
It looks to me like the Git Client Side Hooks may hold the answer, but the methodology for scanning through the changes in a merge and looking for a particular one eludes me.
Note that I do not need the hook to do any intelligence around the changes to the version line.  I trust the developers increment the values correctly.  This is just about making sure a forgetful dev (which will undoubtedly be me) is reminded that the version needs to be changed.


text:
Q: AVA: setup different timeout for each test case I writing asynchronous tests using AVA, and need to setup custom timeout for each test cases. I've not found out any information about this possibility and my tests seems like this:

import test from 'ava';

test.cb('super test', t => {
    setTimeout(() => {
        t.is(1, 1);
        t.end();
    }, 10000);

    setTimeout(() => {
        t.fail("Timeout error!");
        t.end();
    }, 100);
});

Does anybody know another way to implement this in AVA?

A: There's an open issue to support this in AVA itself: https://github.com/avajs/ava/issues/1565
Until that lands you'll have to manage a timer yourself. Don't forget to clear it once your normal test completes.

A: I don't know if AVA has something like this built in. I suspect not, as it seems like quite an unusual use-case.
But you could create a utility function that implements some kind of a "timeout test":
import test from 'ava';

function timeout (ms, fn) {
   return function (t) {
       setTimeout(() => {
           t.fail("Timeout error!")
           t.end()
       }, ms)
       fn(t)
   }
}

test.cb('super test', timeout(10000, t => {
    t.is(1, 1);
}));


text:
Q: Redirect with Ajax / JQuery / PhoneGab I use PhoneGab for my firstime, and something wrong...
I woodlike use the window.location.href method when I receive 'data' (json response from PHP before an Ajax request(cross domain)).
But when I test this think on my mobile(Android), the redirection doesn't work...
ps: everything is usually fine on web browser.
Does anyone see the problem?
That's my code :

    <title>Ajax Cross-Origin</title>

        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <link rel="stylesheet" href="css/bootstrap/css/bootstrap.min.css" />

Inscription

        <form class="FormInscription" method="POST">
            Nom
            <input type="text" name="nom" id="nom" placeholder="nom"/>
            Prénom
            <input type="text" name="prenom" id="prenom" placeholder="prénom"/>
            Email
            <input type="email" name="email" id="email" placeholder="xyz@email.com"/>
            Mot de passe
            <input type="password" name="password1" id="mdp1" placeholder="xxx123"/>
            Confirmer votre mot de passe :
            <input type="password" name="password2" id="mdp2" placeholder="xxx123"/>
            <button id="saveLogin" >
                Suivant
             </button>
        </form>

A: The updated cordova version doesn't allow you to redirect via javascript. You need to follow the instructions in order to make the javascript redirect work.
Add the "Cordova Whitelist Plugin" in your config.xml
<gap:plugin name="cordova-plugin-whitelist" spec="1.1.0" />

Or simply
<plugin name="cordova-plugin-whitelist" spec="1.1.0" />

Try putting the following in your config.xml
<content src="index.html" />

is the path to your HTML file inside the source directory.
<access origin="*" />

will allow you to redirect to any of the external page using JS. If you want to restrict your app to just a single domain then use it like this.
<access origin="http://yourdomain.com" />

At the end, put the following intents
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />