text:
Q: Pivot table creations I have a doubt that can one sheet have multiple Pivot tables? If so is there any way to define their names in the sheet?
I wrote the below code to update/Refresh the Pivot tables defined on different sheets,but gettings following error:
 Dim objExcel1,strPathExcel1
 Dim objSheet1,objSheet2,objSheet3

 Set objExcel1 = CreateObject("Excel.Application")
 strPathExcel1 = "D:\AravoVB\Copy of Original    Scripts\CopyofGEWingtoWing_latest_dump_21112012.xls"

objExcel1.Workbooks.open(strPathExcel1)
Set objSheet1 = objExcel1.ActiveWorkbook.Worksheets("Business Process Matrix")
Set objSheet2 = objExcel1.ActiveWorkbook.Worksheets("Workflow Status Matrix")
Set objSheet3 = objExcel1.ActiveWorkbook.Worksheets("Business Hierarchy Martix")

objSheet1.PivotTables(1).PivotCache.Refresh
objSheet2.PivotTables(1).PivotCache.Refresh
objSheet3.PivotTables(1).PivotCache.Refresh

ERROR : Subscript out of range
Can you help me here?
UPDATE
I have a data Excel sheet in the below format:
Name   Fruits    Condition of Fruits
=====  ======    ====================

Ram    Apple       Good

Jadu   Apple       Bad

Tina   Orange      Good

Ram    Orange      Good

Tina   Apple       Bad

Ram    Apple       Bad

Output of the Pivot program in the other sheet of the same excel, say in sheet(2) should be
like this:
Name  Fruits   Condition of Fruits
====  ======   ===================
               Good       Bad    Total
               ====      =====  ======
Ram   Apple     1           1     2
Ram   Orange    1           0     1
Tina  Apple     0           1     1
Tina  Orange    1           0     1
jadu  Apple     0           1     1
===================================
Grand Total     3           3     6
===================================

The above format needs to be present in the Excel in the sheet(2), whenever sheet(1) will be having source data within it as shown in the first table.
I want Macro program to create using Excel pivot table concept.
Can you suggest any code settings, for the above Pivot creation?
Thanks

A: You can have multiple Pivot tables in one single sheet. Create them, then right-click them, select "Pivot Table Options ..." and view/change their names. Normally you don't need to do this, as Excel automatically names the tables [PivotTable*N*] with N being 1, 2, 3, ...
However you should avoid having multiple Pivots in a single sheet if you often change their look (e.g. add or remove columns and/or rows)
EDIT: in response to your comment ... yes you can ... in Excel2010.VBA the relevant objects/methods are
ActiveWorkbook.PivotCaches.Create(SourceType:=..., SourceData:= ..., Version:=...).CreatePivotTable TableDestination:=..., TableName:=..., DefaultVersion:=...

The Source data is defined through the PivotCache object, destination defined through the concatenated CreatePivotTable method.
Later on you use
ActiveSheet.PivotTables(...).PivotFields(...).Orientation and .position

and
ActiveSheet.PivotTables(...).AddDataField ...PivotFields(...), "header", xlSum

to specify your Pivot table design.
Best is to start recording a macro, create a Pivot table, stop the recorder and examine the generated code.


text:
Q: C++ How check characters in real time with _getch() i need in my loop get character in realtime and check it by conditions. If user press whatever except enter, program works fine. Can anyone help me ? thanks !
   while (read != '\n')
            {
                cout << "Enter character:\n";
                read = _getwch();
                if (read == '\n') {
                    cout << "You pressed : ENTER\n";
                }
                else {
                    cout << "Your character is: \"" << read << "\"\n\n";
                    read = '\0';
                }
            }

A: include
using namespace std;
int main()
{
cout << "Press the ENTER key";

if (cin.get() == '\n')

{
       cout << "Good job.\n";
}
else
{
       cout << "I meant ONLY the ENTER key... Oh well.\n";
}

return 0;
}
This code will help in detecting the ENTER key when pressed.
Hope this helps you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: как реализовать цикл прослушивания с микрофона в kivy с дальнейшим распознанием и т.п Создаю голосового помощника на Python и хотелось бы обернуть его в графический интерфейс. Использовал kivy.  При нажатии кнопки, которая запускает запись звука и распознавания(посредством цикла), графическое окно зависает и работает только консоль. Вопрос: возможно ли реализовать то, что я хочу в kivy, если да, то как? если нет, то какую оболочку для графического интерфейса использовать в данной задаче? (чтобы работали циклы, или чем их заменить и как?)
В коде ниже убрал всё лишнее, оставил только саму суть проблемы.
import json, pyaudio
from vosk import Model, KaldiRecognizer
from kivy.config import Config
Config.set('kivy','keyboard_mode','systemanddock')
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=8000)
stream.start_stream()

model_ru_small = Model('C:/1/Python/voice_helper/model_ru_small')
rec_ru_small = KaldiRecognizer(model_ru_small, 16000)

def listen():
    while True:
        data = stream.read(4000, exception_on_overflow=False)
        if (rec_ru_small.AcceptWaveform(data)) and (len(data)>0):
            answer_ru = json.loads(rec_ru_small.Result())
            if answer_ru['text']!='':
                yield answer_ru['text']

def m_n():
    for text in listen():
        print(text)
        if text!='':
            if text=='привет':
                print('привет')
                ## далее идут другие команды..

class MyApp(App):

    def btn_pressed(self, *args):
        m_n()

    def build(self):
        self.title = 'Голосовой помощник'
        box=BoxLayout()
        btn=Button(text='Запуск')
        btn.bind(on_press=self.btn_pressed)
        label=Label(text='Голосовой \n помощник \n 1.0')
        box.add_widget(label)
        box.add_widget(btn)
        return box

if __name__=='__main__':
    MyApp().run()

A: def btn_pressed(self, *args):
    thread = Thread(target=m_n)
    thread.start()

При нажатии на кнопку открываю новый поток, который содержит в себе бесконечный цикл прослушки.


text:
Q: When typing long texts, textview appends empty spaces proportional to the input the empty space on the endI am taking the size of my text view text (the text view that I am writing on) and setting it equal to the size of the text view that I am displaying it. But it if write longer text it shows longer empty space in my text view when I post it. I made the code for the size of my text view by measuring the content.height of the textV that i AM writing on.
} else if identifier == "save" {
        print("Save button tapped")

        if textViewWrite.text == "" {
            print("text empty")
        }
        else{

            print("\(textViewWrite.contentSize.height)")

            let size: CGSize = textViewWrite.sizeThatFits(CGSize.init(width: textViewWrite.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
            let insets: UIEdgeInsets = textViewWrite.textContainerInset;
            let relevantHeight = size.height - insets.top - insets.bottom;

            let text = Post(texts: "String", textHeight: relevantHeight, textWidth: textViewWrite.contentSize.width)
            PostService.create(text: self.textViewWrite.text!, height: Int(textViewWrite.contentSize.height), width: Int(view.frame.width) )
            print("\(textViewWrite.contentSize.height)")

            // 1
            let HomeViewController = segue.destination as! HomeViewController
            // 2
            HomeViewController.posts.append(text)

        }
        textViewWrite.text = ""
    }
}

A: I have seen the method you are using used before, however for your purposes, I think it's best to use layout constraints. It's a lot easier in my opinion.
What you want to do is use layout constraints to constrain the height property of the receiving text view.
In your receiving text view try setting up layout constraints like so...
let captionContainer: UIView = {
    let c = UIView()
    c.translatesAutoresizingMaskIntoConstraints = false
    c.backgroundColor = UIColor.lightGray
    c.layer.cornerRadius = 6
    return c
}()

let caption: UITextView = {
    let c = UITextView()
    c.textAlignment = .left
    c.font = .systemFont(ofSize: 14)
    c.isScrollEnabled = false
    c.translatesAutoresizingMaskIntoConstraints = false
    return c
}()

func setupCaption() {

    view.addSubview(captionContainer)
    view.addSubview(caption)

    //Container Constratins
    captionContainer.widthAnchor.constraint(equalToConstant: 250).isActive = true
    captionContainer.heightAnchor.constraint(equalTo: caption.heightAnchor, multiplier: 1).isActive = true
    captionContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    captionContainer.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

    //Caption Constraints
    caption.widthAnchor.constraint(equalToConstant: 250).isActive = true
    caption.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    caption.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

    // This constraint controls the maximum height the caption can have.
    NSLayoutConstraint(item: caption, attribute: .height, relatedBy: .lessThanOrEqual, toItem: view, attribute: .height, multiplier: 0.25, constant: 0).isActive = true
}

Then set the caption text to whatever the textfield or textview you are using for user input.
Good luck.


text:
Q: Simulating CPU-intensive Task having fixed amount of work I am simulating a CPU-Bound task. Each CPU-bound task calculate factorial of 800. Each CPU-bound task is a Runnable object executed by Thread. When i increases number of threads(Each thread runs a Runnable tak) then i found some threads runs so fast in such a way that service times tends to Zero.I could not understand this behaviour.The codes are as follows.
import java.math.BigInteger;
public class CpuBoundJob  implements Runnable {
    public void run() {
         BigInteger factValue = BigInteger.ONE;
            long t1=System.nanoTime();
            for ( int i = 2; i <= 800; i++){
              factValue = factValue.multiply(BigInteger.valueOf(i));
            }
        long t2=System.nanoTime();
        System.out.println("Service Time(ms)="+((double)(t2-t1)/1000000));
    }
}

public class TaskRunner extends Thread {
    CpuBoundJob job=new CpuBoundJob();
    public void run(){

    job.run();
    }
}

public class Test {
int numberOfThreads=5;
public Test(){
    for(int i=1;i<=numberOfThreads;i++){
        TaskRunner t=new TaskRunner();
        t.start();
        }
}
public static void main(String[] args) {
    new Test();
    }
}

In case of 5 Threads the output is as below.
Service Time(ns)=28.765821
Service Time(ns)=33.489663
Service Time(ns)=29.19727
Service Time(ns)=34.259404
Service Time(ns)=37.347448

In case of 10 Threads the output is as below.
Service Time(ns)=45.647232
Service Time(ns)=3.972654
Service Time(ns)=23.494475
Service Time(ns)=12.210069
Service Time(ns)=19.382478
Service Time(ns)=15.34706
Service Time(ns)=54.769652
Service Time(ns)=20.646827
Service Time(ns)=3.28936
Service Time(ns)=29.809905
Service Time(ns)=60.798897
Service Time(ns)=50.718839
Service Time(ns)=2.727253
Service Time(ns)=2.882779
Service Time(ns)=63.864835
Service Time(ns)=42.601425
Service Time(ns)=4.029496
Service Time(ns)=4.339761
Service Time(ns)=79.396239
Service Time(ns)=2.923832
Service Time(ns)=5.773848
Service Time(ns)=3.064359
Service Time(ns)=2.446592
Service Time(ns)=2.205802
Service Time(ns)=2.212513
Service Time(ns)=2.265408
Service Time(ns)=82.51073
Service Time(ns)=2.200276
Service Time(ns)=2.289487
Service Time(ns)=2.322645
Service Time(ns)=2.201459
Service Time(ns)=2.217644
Service Time(ns)=2.197908
Service Time(ns)=2.252381
Service Time(ns)=13.564814
Service Time(ns)=2.238171
Service Time(ns)=2.199486
Service Time(ns)=2.179355
Service Time(ns)=2.237381
Service Time(ns)=2.593041
Service Time(ns)=2.444225
Service Time(ns)=2.42054
Service Time(ns)=38.745219
Service Time(ns)=81.232565
Service Time(ns)=19.612216
Service Time(ns)=22.31381
Service Time(ns)=59.521916
Service Time(ns)=59.511258
Service Time(ns)=54.439255
Service Time(ns)=11.582434

i could not understand service times of 2.4 etc and sometimes service times drop to 0.8 . why does threads running a fixed amount of work executes so fastly?

A: How are you starting these tests?  If you are running starting them cold each time, I suspect the JVM is "warming up" and Just In Time compiling the code.  If this is the case, the tests with a few threads are running as interpreted code, and later runs are compiled, and even later runs are optimized based upon previous runs.  The JVM is magic that way.
Ideas to make the optimizations less likely to hit:

*

*use a random number as a working parameter (and not the loop index)

*use the time as a working parameter (ditto)

*throw in some string concatenation

*vary the length of the loop by with the working parameters

A: It is possible that at some point the JIT kicks in and optimizes the code. Try running the experiment by first "warming up" the system i.e. for N iterations (you will need to experiment what is a good value of N) run the system without measuring - then measure e.g:
public class Test {

private int numberOfThreads;
private int warmUpIterations;

public Test(int numberOfThreads, int warmUpIterations) {
    this.numberOfThreads = numberOfThreads;
    this.warmUpIterations = warmUpIterations;
}

public void runTests() {
    for (int i = 0; i < warmUpIterations; i++) {
        test(); // don't collect timing here
    }

    test(); // collect timing here
}

private void test() {
    for (int i = 0; i < numberOfThreads; i++) {
        TaskRunner t = new TaskRunner();
        t.start();
    }
}

public static void main(String[] args) {
    new Test(10, 10000).runTests();
}

}
Also printing the statistics from within run() is problematic, consider accumulating them in some collection and print them once the test is done.

A: Most likely the timing functions are too inaccurate to measure such a quick operation. Try the factorial of 100000 or something similar.
The docs of the nanotime method say that it's not guaranteed to provide nanosecond accuracy:

This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) - no guarantees are made except that the resolution is at least as good as that of currentTimeMillis().


text:
Q: Unable to deploy MobileFirst app to MobileFirst container on Bluemix via MobileFirst CLI As per https://mobilefirstplatform.ibmcloud.com/blog/2015/08/14/ibm-mobilefirst-platform-server-bluemix-net-5-minutes/
When I try to deploy a locally developed MobileFirst app to MobileFirst container on Bluemix via MobileFirst CLI, I keep getting below error:
Couldn't connect to server BluemixServer at http://x.x.x.x:9080.
failed to retrieve runtime information: Unexpected token E: HTTP 404 - Not Found
Here's what I'm passing as parameters:

*

*Enter name of new server definition: BluemixServer

*Enter the fully qualified URL of this server: http://...:9080 (Bluemix public URL of MFP server container)

*Enter the MFP admin login id: admin

*Enter the MFP admin password: *****

*Save admin password for this server?: Yes

*Enter the context root of the MobileFirst administration services: MobileFirstStarter
I think problem is with "parameter 1" above: I tried passing it as both BluemixServer as well as the IBM container name for MobileFirst image that I created but it fails with same error in both cases.
Any thoughts?

A: Agreed with Vivin, the issue is probably for sure step 6.
"MobileFirstStarter" is the name of the image used for the container. That's fine. But the value that should be used in step 6 is "worklightadmin", like in the example given in the blog post linked to in the question.


text:
Q: Possible Paths across a Rectangular Grid Consider a rectangular grid of 4×3 with lower  left corner named as A and upper right corner named B. Suppose that starting point is A and you can move one step up(U) or one step right(R) only. This is continued until B is reached.

*

*How many different paths from A to B possible ?

*calculate best path according to possible combinations?

*how to implement php and javascript?


text:
Q: [Python argparse]set the behaviour of an argument to be interactive if no value is given I wonder if it is possible to change the behaviour of an argument depending if a value was given or not.
Typically, I want to provide an interactive way to enter a password.
example usages:

$script.py => use the default argument value for argument 'p'
$script.py -p mypass => use 'mypass' as value for 'p'
$script.py -p => get password interactively

A: import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-p", nargs='?', const="mypass", default="default")

args = parser.parse_args()

if args.p:
    print args.p

You can then check for the value of p and get the password interactively

A: A simple class:
class AskUser:
    def __init__(self, type, func, *args, **kwargs):
        self.type = type
        self.func = func
        self.args = args
        self.kwargs = kwargs
    def __call__(self, value):
        if value == '':
            value = self.func(*self.args, **self.kwargs)
        return self.type(value)

which you can plug directly into argparse:
parser = argparse.ArgumentParser()
parser.add_argument('user', nargs='?', type=AskUser(str, input, 'Enter user name: '), default='')
parser.add_argument('file', nargs='?', type=AskUser(Path, filedialog.asksaveasfilename,
    title='Select a file', filetypes=(('CSV files', '*.csv'),), defaultextension='.csv'), default='')
args = parser.parse_args()


text:
Q: simple_html_dom timer? I am trying to get the contents of a webpage but the page loads in 2 times.
there seems to be some kind of timer, at first it loads some content and then after 10 seconds it loads the other part of the content that have the content that i am trying to get.
Is there a way to achieve this?
Ty ;)

A: You need to use a headless browser engine to do this. cURL and wget are HTTP libraries; they speak HTTP and download documents as text. They don't have a concept of a DOM or a JavaScript engine that would help them understand that a page is doing AJAX OR JS Timer . So to download the HTML, you need something that acts more like a browser, by parsing a DOM and executing JS. I recommend  http://simile.mit.edu/wiki/Crowbar, which uses a Mozilla engine.


text:
Q: Make a full screen alertDialog I tried to make a full screen alert dialog. But I have get this ScreenShot. Please help me to improve it, to full fill the screen. I have read a lot of questions, but I couldn't solve this problem.
Here is my code:
    // AlertDialog Builder
    AlertDialog.Builder bmneu = new AlertDialog.Builder(this, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);

    // Inflate
    LayoutInflater inflate = this.getLayoutInflater();

    // View
    View v = inflate.inflate(R.layout.help_archive, null);

    // Assign view to AlertDialogBuilder
    bmneu.setView(v);

    // Alert Dialog
    AlertDialog alertHelp = bmneu.create();

    // Show AlertDialog
    alertHelp.show();

xml code (help_archive.xml):
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#40e9e2f7" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txtHelpArchive1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="در این قسمت بایگانی از موارد خمسی ذخیره شده را مشاهده می کنید."
        android:gravity="right"
        android:padding="10dp"
        android:textColor="#ffffff"
        android:background="@android:color/transparent" />

    <ImageView
        android:id="@+id/imgHelpArchive1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/help_archive1"
        android:padding="10dp" />

    <TextView
        android:id="@+id/txtArchive2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="تاریخ سال خمسی با مشخص بودن، شمسی و یا قمری بودن سال، مشخص شده است. در سمت چپ تصویر نیز برای حذف، تعبیه شده است."
        android:gravity="right"
        android:padding="10dp"
        android:textColor="#ffffff"
        android:background="@android:color/transparent" />

    <ImageView
        android:id="@+id/imgHelpArchive2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/help_archive2"
        android:padding="10dp" />

    <TextView
        android:id="@+id/txtHelpArchive3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="با فشردن کلیدهای زیر می توانید، می توانید مواردی را که قبلا ذخیره کرده اید، مشاهده و یا ارسال کنید."
        android:gravity="right"
        android:padding="10dp"
        android:textColor="#ffffff"
        android:background="@android:color/transparent" />

    <ImageView
        android:id="@+id/imgHelpArchive3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/help_archive3"
        android:padding="10dp" />

</LinearLayout>
</ScrollView>

Thanks.

A: What you can do is create a custom Dialog extending DialogFragment and on your onStart() method to the following:
  @Override
    public void onStart() {
        super.onStart();

        int height = (int)(getResources().getDisplayMetrics().heightPixels);
        int width = (int)(getResources().getDisplayMetrics().widthPixels);

        getDialog().getWindow().setLayout(width, height);
    }

Hope this helps! Let me know if I wasn't clear enough.

A: Maybe this will be useful:
            AlertDialog.Builder bmneu = new AlertDialog.Builder(this, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);

            // Inflate
            LayoutInflater inflate = getLayoutInflater();

            // View
            View v = inflate.inflate(R.layout.help_archive, null);

            // Assign view to AlertDialogBuilder
            bmneu.setView(v);

            // Alert Dialog
            AlertDialog alertHelp = bmneu.create();

            // Show AlertDialog
            alertHelp.show();

            ScrollView.LayoutParams params = (ScrollView.LayoutParams) v.getLayoutParams();
            params.height = getResources().getDisplayMetrics().heightPixels;
            params.width = getResources().getDisplayMetrics().widthPixels;
            v.setLayoutParams(params);

The last block of code sets the width and height of the view (inside a dialog)
So, put the following code after show alertHelp.show() (remember that v is your layout):
            ScrollView.LayoutParams params = (ScrollView.LayoutParams) v.getLayoutParams();
            params.height = getResources().getDisplayMetrics().heightPixels;
            params.width = getResources().getDisplayMetrics().widthPixels;
            v.setLayoutParams(params);


text:
Q: How to Log which AVPlayerItem is playing in AVQueuePlayer? I'm using the AVQueuePlayer to play many audio files in sequence.
I need to log every AVPlayerItem that is playing.
How to do that?

A: AVQueuePlayer has currentItem property. just log it every time item changed.


text:
Q: In-App-Purchase not working in iOS 5 i have successfully integrated in app purchase in my app.i have follow this tutorial for in app purchase.it working fine with iOS 6. but when i try to test it on ios 5.1 simulator than every time i try to login to buying the product i just get the bellow error.
Transaction error: An unknown error has occurred
and yes my mac keyboard is also not working when i am testing it on ios 5.1 simulator i have to input from simulator keypad.

A: You cannot reliably test In App Purchase in the iOS5 Simulator. You need to test it on a device.
And the keyboard not working for In App Purchase login used to be bloody annoying.


text:
Q: Getting an interface reference inside a lambda function Consider the following code:
val hwnd = Handler()
hwnd.postDelayed(object : Runnable {
        override fun run()
            hwnd.postDelayed(this, 5000)
        }
}, 5000)

This way, I can post the same Runnable to the Handler by using this (which refers to the Runnable) in the run() method. But how could I do the same using only a lambda expression?
val hwnd = Handler()
hwnd.postDelayed({
    //How to get "this" here?
}, 5000)

Is that even possible?

A: It is not possible like that. You can refer to this discussion: Is "this" accessible in SAMs?

this in a lambda refers to the instance of the containing class, if
  any. A lambda is conceptually a function, not a class, so there is no
  such thing as a lambda instance to which this could refer.
The fact that a lambda can be converted into an instance of a SAM
  interface does not change this. Having this in a lambda mean different
  things depending on whether the lambda gets SAM-converted would be
  extremely confusing.

You can create a workaround (for example as suggested in the discussion): Create an extension function:
inline fun runnable(crossinline body: Runnable.() -> Unit) = object : Runnable {
    override fun run() = body()
}

then you can call it like
hwnd.postDelayed(runnable { hwnd.postDelayed(this, 5000) }, 5000)

A: Since default lambda conversion gives you lambda with signature of () -> Unit, that means underlying Runnable is completely hidden.
You have to either deal with manual object creation, or write a wrapper extension function  that will consume lambda with another signature:
// custom extension function for handler
inline fun Handler.postDelayed(delayMilis: Long, crossinline runnable: (Runnable) -> Unit) = postDelayed(object : Runnable{
    override fun run() {
        runnable(this)
    }
}, delayMilis)

Then at calling side you will be provided with Runnable object as lambda parameter (only parameter: it):
hwnd.postDelayed(5000){
    // it : Runnable
    hwnd.postDelayed(it, 5000)
}

Or if you want to get really fancy, change extension parameter to Handler.(Runnable) -> Unit, then you will be able to call:
hwnd.postDelayed(5000){
    // this : Handler, it : Runnable
    postDelayed(it, 5000)
}

A: are you referring to the "qualified this" as described here:
https://kotlinlang.org/docs/reference/this-expressions.html


text:
Q: Keep only the text of a label In a text which have formating labels such as
data.frame(id = c(1, 2), text = c("something here
my text
 also
Keep it
", "
title
 another here"))

How can someone keep with a comma separate option only the text exist inside in

:
data.frame(text = c("my text, Keep it", "title"), id = c(1, 2))

A: We can use str_extract_all.  Using regex lookaround, get the characters after the tag, then loop over the list output and paste the extracted strings
library(stringr)
data.frame(text = sapply(str_extract_all(df1$text, "(?<=
)[^<]+"),
      paste, collapse=", "), id = df1$id)
#               text id
#1 my text, Keep it  1
#2            title  2

A: You can use the web scraping skill.
library(rvest)

sapply(df$text, function(x) {
  read_html(x) %>% html_nodes(css = "h1") %>% html_text %>% toString
}, USE.NAMES = F)

# [1] "my text, Keep it"
# [2] "title"

A: If you want to use quanteda for this, you can process convert this to a corpus, and then process it via two corpus_segment() calls, one to get the text before , and the second to then just select the text after .  Then you can re-group the text using texts(x, groups = docid()), specifying the spacer = ", ".
Here's how, with your desired output:
library("quanteda")
## Package version: 2.1.1

df <- data.frame(
  id = c(1, 2),
  text = c("something here
my text
 also
Keep it
", "
title
 another here")
)

charvec <- corpus(df, docid_field = "id") %>%
  corpus_segment("
", pattern_position = "after") %>%
  corpus_segment("
", pattern_position = "before") %>%
  texts(groups = docid(.), spacer = ", ")

Then to convert this into the data.frame that you want:
data.frame(text = charvec, id = names(charvec))
##               text id
## 1 my text, Keep it  1
## 2            title  2


text:
Q: php Copying images from one directory to another I have tried to image copy one directory to another directory but it is not working for me.
Here is my code:
<?php

$old_sub_dir = '/media/import';

$new_sub_dir = '/media/catalog/product/image';

//get directory contents
$contents = array();

$dir = opendir($_SERVER['DOCUMENT_ROOT'] . $old_sub_dir);

while (false !== ($file = readdir($dir))) {
       $contents[] = $file;
}
closedir($dir);

//get only jpeg contents
$jpeg_contents = array();

foreach($contents as $file){
    if (eregi('.jpg{1}$', $file)){
        $jpeg_contents[] = $file;
    }
}

// copy each jpeg from directory 'a' to directory 'b'
foreach($jpeg_contents as $file){
    copy($_SERVER['DOCUMENT_ROOT'] . $old_sub_dir . '/' . $file, $_SERVER['DOCUMENT_ROOT'] . $new_sub_dir . '/' . $file);
}

?>

and the error I'm getting is:
Uncaught Error: Call to undefined function eregi()

Any help would be appreciated.
Thanks.

A: eregi() is depricated function from PHP version 5.3. Use preg_match() function istead.


text:
Q: Não consigo eliminar avisos do ESLint Estou aprendendo react-native, nunca tive muita experiência com JavaScript, instalei a extensão ESLint e estou tentando seguir a risca buscando a melhor sintaxe.
Porém tem dois avisos que não consegui eliminar e nem consigo entender o porque.
O primeiro sempre que coloco um alert() sem importar o conteúdo
[eslint] 'alert' is not defined. (no-undef)
function alert(message?: any): void

O segundo no require
<Image source={require('./imgs/logo.png')} />

Também sem importar o conteúdo
[eslint] Unexpected require(). (global-require)
function require(name: string): any

O app funciona ok mesmo com estes avisos porém gostaria de entendê-los

A: No Eslint tens um ficheiro de configuração, aí podes dizer ao eslint os ambientes em que trabalhas para ele contar com algumas variáveis globais como o alert e require (*).
Assim, no ficheiro de configuração .eslintrc.js coloca o que precisares:
env: {
    browser: true,
    commonjs: true,
    es6: true,
    node: true
},

* - ver documentação aqui


text:
Q: How to position Google Maps Infowindow box near the top and style as error I have developed this plunker sample:
Click on "View Canada Map with Message" to see the infowindow.
I want the infowindow to be positioned near the top of the map boundary or in the middle of the upper part. Also, I want to style the infowindow to appear as error message with error indicator icon.
See sample code below:
<!DOCTYPE html>

    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">

    <input type="button" value="Init Map" onclick="initMap()">
    <input type="button" value="View Canada Map with Message" onclick="viewCanadaWithMessage()">

    ");
    //-->
    </script>

How to calculate the position (lat, lng) which will be close to the upper side, and how I can style the infowindow to look like an error message?

A: I did some analysis, and realized that I can find the approximate midpoint between the top and the center using this code snippet:
var center = JSON.parse(JSON.stringify(map.getCenter()));
var boundaries = JSON.parse(JSON.stringify(map.getBounds()));
var newPosition = {lat: center.lat + Math.abs(boundaries.north - center.lat) / 2.75, lng: center.lng};
infoWindow.setContent('How I can locate this info window to be near the top, approx in the middle between the top point and the middle point? I want this window to display error message with error indicator icon.');
infoWindow.setPosition(newPosition);

See plnker sample here.
I hope that this is the right way. Please let me know if you better solution.
Now, I need to style the infowindow to appear as error. Appreciate your help.


text:
Q: What shall be the logical conclusion out of the following? Each question has a main statement, followed by four statements labeled A,B,C and D. Choose the ordered pair of statements, where the fisrt statement implies the second, and the two statements are logically consistent with the main statement.
All irresponsible bosses shout if their workers do not fall in line.
(A) All irresponsible bosses do not shout.
(B ) Workers fall in line.
(C) Workers do not fall in line.
(D) All irresponsible bosses shout.
(a) AB
(b) BA
(c) CA
(d) none of these.
{since it's an "If A then B" type, answer should be (a) that is AB, but it's wrong; in answer key it shows (b) as an answer. I'm not able to understand why.
the two valid conclusions of 'if P then Q' statment are: Q'P' or PQ itself.
So here: clause 'workers do not fall in line' is P since it's followed by word 'if' and clause 'all irresponsible bosses shout' becomes Q.
So shouldn't the answer be BA from the options, i.e. all irresponsible bosses do not shout, workers fall in line?

A: I'm afraid I don't agree with you or your answer key.  The statement itself is CD, which isn't one of the options.  But the contrapositive also isn't one of the options, since the negation of "All irresponsible bosses shout" is "Not all irresponsible bosses shout" or "Some irresponsible bosses don't shout".  Those are different statements than "All irresponsible bosses don't shout", at least in English.

A: X if Y means if Y then X, so your axiom is $C \implies D$.  The contrapositive of that is $\lnot D \implies \lnot C$, which is $A \implies B$.  This would say the answer is a in agreement with you.
The wording of the question is poor.  It should say "the first statement implies the second based on the main statement."  All of $A,B,C,D$ are compatible with the main statement depending on the truth value of other statements in the list.


text:
Q: Strange values when using Memoization for Grid Traveler problem? I'm learning dynamic programming and I've just started with some simple problems. I'm doing a grid traveler problem where you start in the top-left corner of a grid and you can only move left or down. You need to return the amount of unique paths to get from the top-left corner to the bottom-right corner of the grid.
I'm getting some strange return values when I try some bigger grids. For example, when I try (18,18) it goes to -> -1961361076 instead of 2333606220
Can anyone see something wrong with my code?
'''
import java.util.HashMap;

public class Test{

    public static void main(String[] args){
        HashMap<String, Integer> memo = new HashMap<>();
        System.out.println(gridTraveler(2,2,memo));
        System.out.println(gridTraveler(18,18,memo));
    }

    public static int gridTraveler(int m, int n, HashMap<String, Integer> memo){

        String key = "" + m + "," + n;
        //base case
        if(m == 1 || n == 1)
            return 1;

        //base case
        if(m == 0 || n == 0)
            return 0;

        if (memo.containsKey(key))
            return memo.get(key);

        //Set value of the key memo[key]
        memo.put(key, gridTraveler(m-1, n, memo) + gridTraveler(m, n-1, memo));

        return memo.get(key);
    }
}

A: This is because the maximum value of an Integer has been reached. When you try to add a value to it, it overflows, and "wraps around" to the negative.
If you change to Long instead of Integer it will work: -
public static void main(String[] args){
    HashMap<String, Long> memo = new HashMap<>();
    System.out.println(gridTraveler(2,2,memo));
    System.out.println(gridTraveler(18,18,memo));
}

public static Long gridTraveler(long i, long j, HashMap<String, Long> memo){

    String key = "" + i + "," + j;
    //base case
    if(i == 1 || j == 1)
        return (long) 1;

    //base case
    if(i == 0 || j == 0)
        return (long) 0;

    if (memo.containsKey(key))
        return memo.get(key);

    //Set value of the key memo[key]
    memo.put(key, gridTraveler(i-1, j, memo) + gridTraveler(i, j-1, memo));

    return memo.get(key);
}
}


text:
Q: Basic multiple if statement logic flow syntax in PowerShell I can't seem to understand how to continue to another IF statement. What I'm trying to do is:

*

*IF Action 1 succeed then do X AND go to Action 2, else log it and RETURN to the next loop

*If Action 2 succeed then do X AND go to Action 3, else log it and RETURN to the next loop

I am having issues with "AND go to Action 2" after action 1. I tried various ways but obviously the script below does not work. It can do Action 1 the test-connection, and if it succeeds will export the log else it will log a failure and RETURN to the next loop. HOWEVER, I cannot make it do the next action if successful.
$hostname = Import-Csv C:\Users\jackie.cheng\Desktop\TestComputers.csv

$hostname | % {

if (Test-Connection $_.hostname -count 1)

{Write-Host "$($_.hostname) Test-Connection Succeeded"
            $array += [pscustomobject]@{
                Name = $currentobject.hostname
                Status = "Test-Connection Success"}
}

else  {Write-Host "$($_.hostname) Test-Connection Failed"
            $array2 += [pscustomobject]@{
                Name = $currentobject.hostname
                Status = "Failed Test-Connection"}
       } return

if (Test-Connection $_.hostname -count 1)

{Write-Host "Second action ran"}

else {Write-Host "Second action failed"} return

}

A: Within the script block of a Foreach-Object, which is the full name of the command with the alias %, you can in fact use return to skip any statements after the return, and continue on to the next loop.
In your case you simply need to move your return into your else blocks like this:
If (Success Condition){
   Actions to do on success
}
else{
   Actions to do on fail
   return
}

If (Success Condition 2){
   ...
}
else{
   ...
   return
}

As mentioned in the comments to your question, be sure to read up on how return works in PowerShell as it is somewhat unusual and behaves differently in different contexts.

A: I would do it this way, just output the objects for either case.  Notice the indenting to help see the structure of the code.  Return is usually not needed. -ea 0 means "-erroraction silentlycontinue".
Import-Csv TestComputers.csv |
% {
  if (Test-Connection $_.hostname -count 1 -ea 0) {
    [pscustomobject]@{
      Name = $_.hostname
      Status = $true}
  }
  else {
    [pscustomobject]@{
      Name = $_.hostname
      Status = $false}
  }
}

Name          Status
----          ------
yahoo.com       True
microsoft.com  False


text:
Q: how to GET a variable from a url without a variable I am trying to GET the int from the following string

member.php?3-bradthor

I have tried using the following code
    $query = parse_url($str, PHP_URL_QUERY);
$intval = preg_replace("/[^0-9]/","",' $query');

However I don't think this is a fool proof solution?
what Imporovements could I make to this code/what code should I use to get the integer from the above string.
Thanks for the help :)

A: Check this,
$str = 'member.php?3-bradthor';
$query = parse_url($str, PHP_URL_QUERY);

$intval = preg_replace("/[^0-9]/","",$query);// remove single quotes.

echo $intval;

Working demo

A: Because of how integers are parsed in PHP you can simple use
$query = parse_url('member.php?3-bradthor', PHP_URL_QUERY);
$intval = intval($query);

if will work only when number in the begining of string.
Less dirty solution is to use for example mod_rewrite.


text:
Q: Coding a discrete fourier transform on python WITHOUT using built in functions Here's what I have
import math
import numpy as np
from cmath import sqrt

# Ask the user for the number of elements in the sequence
n = int(input("n: "))

# create a matrix full of n elements
x = [0]*n
for i in range(0,n):
    x[i] = int(input(f"x{i}: "))

j= sqrt(-1)

y = [0]*n
for k in range(0,n):
    for l in range(0,n):
        y[k] += x[l]*(np.exp((-np.pi *j* k*2)/n))

# Print out the answers
for i in range(0,n):
print(f"y{i} = {y[i]}")

Example 1
The answers I get when I use x = {0,1,2,3} is:
y0 = (6+0j)
y1 = (3.6739403974420594e-16-6j) WRONG
y2 = (-6-7.347880794884119e-16j) WRONG
y3 = (-1.102182119232618e-15+6j) WRONG

It should be: 6, -2+2j, -2, -2-2j as partially derived here:

Example 2
If n is 2 and x = {1,2}
Then the expected answers are: 3/sqrt(2) and -1/sqrt(2)
Example 3`
if n is 4 and x = {1,1,0,0}
Then the answers are 2, 1-j, 0 and 1+j

Here's a fix, yet when I do the x={1,2} part, I don't get the theoretical answers... They are very different
import math
import numpy as np
from cmath import sqrt
n = int(input("n: "))

x = [0]*n

#Create a matrix for n amount of inputs
for i in range(0,n):
    x[i] = int(input(f"x{i}: "))

#Empty matrix for the answers for later

y = [0]*n
# define j so that it can be used later
j = sqrt(-1)
for k in range(0,n):
    for l in range(0,n):
        # Carry out the summation
        y[k] += x[l]*(np.exp((-np.pi *j*l* k*2)/n))

for i in range(0,n):
    print(f"y{i} = {y[i]}")

A: A much faster method to get the DFT X of a sample sequence xn of length N is to use the concise matrix form of the DFT. It is easily implemented with a numpy array and the matmul product function:
# Custom matrix
import numpy as np
k = np.arange(N)
M = np.exp(-2j * np.pi * k[:, None] * k / N)
X = np.matmul(xn, M)

The python for loops are replaced by faster C loops internal to numpy and possibly vectorization features of the CPU.
There is a scipy function, named dft which returns the same array, so you can save one line of code:
# Built-in matrix
import scipy.linalg as sl
M = sl.dft(N)
X = np.matmul(xn, M)

The next piece of code shows the perfect matching these methods and FFT:

import numpy as np
import matplotlib.pyplot as plt

def show_peak_frequencies(ax, ff):
    lims = ax.get_xlim()
    tax = ax.twiny()
    ticks = np.hstack([-ff, ff])
    tax.set_xticks(ticks)
    tax.set_xlim(lims)
    tax.grid()

mag = lambda X: abs(sf.fftshift(X))
omega = lambda f: 2*np.pi * f

# Sampling parameters
N = 70
fs = 10
Ts = 1 / fs
max_t = (N-1) * Ts

# Signal components
ff = np.array([1, 2.5, 3.5]) # frequencies Hz
w1, w2, w3 = omega(ff)

# Continuous signal
t = np.linspace(0, max_t, 200)
x = lambda t: 2 * np.cos(w1*t) + np.cos(w2*t) + 0.5 * np.cos(w3*t)
xt = x(t)

# Actual samples
n = np.arange(N)
xn = x(n*Ts)

fig, axes = plt.subplots(ncols=2, squeeze=True, figsize=(9, 3), layout='constrained')

ax = axes[0]
ax.plot(t, xt, c='gray')
ax.stem(n*Ts, xn)
ax.set_title(f'Signal sampled at {1/Ts:0.2f}Hz')
ax.set_xlabel('t (s)')

# Built-in fft
import scipy.fft as sf
X1 = sf.fft(xn)
f = sf.fftfreq(N, Ts)
f = sf.fftshift(f)

# Built-in matrix
import scipy.linalg as sl
M2 = sl.dft(N)
X2 = np.matmul(xn, M2)

# Custom matrix
k = np.arange(N)
M3 = np.exp(-2j * np.pi * k[:, None] * k / N)
X3 = np.matmul(xn, M3)

ax = axes[1]
ax.plot(f, mag(X1), label='FFT', c='lime', lw=7, alpha=0.5)
ax.plot(f, mag(X2), label='scipy matrix', c='navy', lw=4, ls='--')
ax.plot(f, mag(X3), label='custom matrix', c='magenta')
show_peak_frequencies(ax, ff)
ax.set_xlabel('f (Hz)')
ax.legend()


text:
Q: How to implement  I have a trouble with <mvc:annotation-driven />. I would like to use for JSR-303 annotation.
Check this image.
http://s7.postimg.org/cz7itmiuj/Beze_jm_na.png

A: Try adding an xmlns:mvc="http://www.springframework.org/schema/mvc attribute as well as adding http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd within the xsi:schemaLocation of your opening beans element.
Something like:
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

Obviously, keep the additional namespaces that you have in your current configuration that you're using but are not in the sample above, such as the xmlns:jee if you need it.


text:
Q: Concatenated strings in sqlDataReader query string introduce spurious 'N' character I am using a SqlDataReader in .net 4.0
Dim wSQL = "Select (LastName + N',b' + FistName) as CustomerName from Customers"
Dim wSQLDataReader as SQLDataReader = wSQLConnection.ExecuteReader(wSQL)

[I am using the letter b to denote a space character.]
I am getting results like 'SmithN,bJohn'
I get the same result if I omit the N qualifier from within the wSQL string.
If the wSQL string is changed to
"Select (LastName + N',bb' + FistName) as CustomerName from Customers"

(with two spaces following the comma).
I get result 'Smith,bbJohn' with the two spaces (of course) but the N has disappeared.
Is this a known .Net bug? Is there a known work around to avoid the extra space?
Both the above select statements run fine in SQL Server Management Studio.

A: Try removing the + sign before N..you may also need a comma after LastName.. Like this:
Dim wSQL = "Select (LastName N',b' + FistName) as CustomerName from Customers"
Dim wSQLDataReader as SQLDataReader = wSQLConnection.ExecuteReader(wSQL)

I have a query that is similar (but more complex) maybe it will help you it is:
SELECT
'All Users' as QuestionOption,
Stuff( (SELECT N'; ' + email FROM users where email>='  ' FOR XML PATH(''),TYPE)
.value('text()[1]','nvarchar(max)'),1,2,N'') as QuestionOptionValue

It may look something like:
 Dim wSQL = "Select 'CustomerName' as CustomerName, Stuff( (SELECT LastName N', ' +     FirstName FROM CustomerName FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'') as Customer_Full_Name


text:
Q: How to print a string within a for loop but only once? I am new to Python and wanted to implement a simple for loop:
phone_number = input("Please print phone number: ")
for i in phone_number:
    if i=="-":
        continue
    print(i, end="")

so as you can see, the point of the program is to print the inputted phone number (111-222-3333) without "-" so the output is: 1112223333.
But I want the output to be "Your phone number is: 1112223333." I do not know how to implement the part that reads
print("Your phone number is: ")

I have tried to put this statement within the for loop but because of the end="" put in
print (i, end="")

I get a response that reads like
Your phone number is:
Your phone number is:1
Your phone number is:1
Your phone number is:1,...

I only want the statement to be printed once. What should I do???

A: Instead of iterating over the characters of the string and printing each character separately, we can remove the '-' by using str.replace(...):
phone = '111-222-3333'
print(f"Your phone number is: {phone.replace('-','')}")

A: Using your for loop method, you can do the following to achieve your goal:
phone_number = input("Please print phone number: ")

print("Your phone number is: ", end="")
for i in phone_number:
    if i == "-":
        continue
    print(i, end="")
print()

Note how I've added an indent before the line print(i, end="") so that it is done once per loop, rather than after the for has finished.
I also moved the "your phone number is" part to before the loop, so that it is only printed once before any of the numbers are printed.

If you wanted, you could also invert the if condition to achieve the same result in 1 less line:
for i in phone_number:
    if i != "-":
        print(i, end="")
print()


text:
Q: Get rows of first and last datetime records based on a column I have a df with several columns and can't figure out in Python how to get only the rows with the first and last date/time (columns is in pandas datetime64[ns] Dtype) entry for each id. And also how to create a new df with the datetime difference in days?
Here's a df slice:

user_id
length
datetime

d8366132199
20
2021-03-31 17:55:44

d8366132199
40
2021-05-12 13:55:48

d8366132199
10
2021-04-09 16:55:47

d8366132199
70
2021-06-25 17:58:47

d8366132199
80
2021-06-28 18:55:49

e8172920273
10
2021-03-28 18:55:44

e8172920273
50
2021-03-30 18:55:45

e8172920273
60
2021-05-26 18:55:46

e8172920273
90
2021-05-26 18:55:47

Expected output:

user_id
length
datetime

d8366132199
20
2021-03-31 17:55:44

d8366132199
80
2021-06-28 18:55:49

e8172920273
10
2021-03-28 18:55:44

e8172920273
90
2021-05-26 18:55:47

New df with datetime difference, expected output:

user_id
date_diff

d8366132199
276

e8172920273
60

Many thanks!

A: You can get the idxmin/idxmax per group, then use the values to slice the original dataset:
# get the indices of min/max per group, then flatten as array
idx = df.groupby('user_id')['datetime'].agg(['idxmin', 'idxmax']).values.ravel()
# array([0, 4, 5, 8])

# slice
df.loc[idx]

output:
        user_id  length            datetime
0  d8366132199       20 2021-03-31 17:55:44
4  d8366132199       80 2021-06-28 18:55:49
5  e8172920273       10 2021-03-28 18:55:44
8  e8172920273       90 2021-05-26 18:55:47

A: For the first question, you can use .nth()
ndf = df.sort_values('datetime').groupby('user_id',as_index = False).nth([0,-1])

Output:
       user_id  length            datetime
5  e8172920273      10 2021-03-28 18:55:44
0  d8366132199      20 2021-03-31 17:55:44
8  e8172920273      90 2021-05-26 18:55:47
4  d8366132199      80 2021-06-28 18:55:49

From there, to answer the second question, you can subtract the last row from the first row.
(ndf.groupby('user_id',as_index = False)
 .agg(date_diff = ('datetime',lambda x: (x.iloc[-1] - x.iloc[0]).days)))

Output:
       user_id  date_diff
0  d8366132199         89
1  e8172920273         59


text:
Q: How to do a task only once every 200 milliseconds I need to post ie 25 requests to webserver in a for loop. The webserver is limited to only 5 calls per second for some reason. So I need to make sure 200 miliseconds have passed since the last request. I have this code below as a demo (the actual code is inside a WCF service), but I believe Thread.Sleep is not the best way to go. Are there any alternatives, Theaded or otherwise?
class Program
{
    private static long lastRun = DateTime.Now.Ticks;

    static void Main(string[] args)
    {
        for (int i = 0; i < 25; i++) { PostData(); }

        Console.WriteLine("Hit any key...");
        Console.ReadLine();
    }

    static void PostData()
    {
        var elapsedMilliseconds = (int)TimeSpan.FromTicks(DateTime.Now.Ticks - lastRun).TotalMillliseconds;

        if (elapsedMilliseconds < 200)
        {
            var pause = 200 - elapsedMilliseconds;
            Console.WriteLine("Pausing for " + pause);

            // pause
            Thread.Sleep(pause);
        }
// HttpPost here

        lastRun = DateTime.Now.Ticks;
        Console.WriteLine("Job done at {0}.{1}", DateTime.Now, DateTime.Now.Millisecond);
    }
}

A: Given that this is a console application, Thread.Sleep() will actually work quite well.  It blocks, but there really isn't any other work to be done while this is blocking, so there's little downsides.
If this were a GUI app, service, or other scenario where blocking is bad, however, then I would recommend using asynchronous methods, and await Task.Delay(pause) instead, which would allow the UI to continue processing messages.  This doesn't matter in a console application, though, so there is little or no downside to your current approach.
This would involve making your main method asynchrnous
static async Task PostDataMultipleTimes(int times)
{
     for (int i=0;i<times;++i)
     {
         var sw = Stopwatch.StartNew();
         PostData(); // PostData doesn't need to sleep/wait/etc anymore

         var ms = (int)sw.ElapsedMilliseconds;
         if (ms < 200)
             await Task.Delay(200 - ms);
     }
}

Note that PostData no longer needs any logic related to blocking - it would just post your relevant data.
This would likely be possible to accomplish in .NET 4. with task continuations, but I'd likely just use Sleep as the logic gets fairly ugly, very quickly.


text:
Q: ASP.NET - OpenIdConnect - The redirect URI is not well-formed When I use OpenIdConnect I have a problem in a OpenIdConnectHandler (394 line)
So, I use a cyrillic domain http://грант-лев.рф (just for example) and redirect URI in OpenIdConnectHandler looks incorrect:
The redirect URI is not well-formed. The URI is: 'http://грант-лев.рф:5000/connect/authorize?client_id=RosgrantService&redirect_uri=http%3A%2F%2Fxn----7sbhbm9amwu.xn--p1ai%3A5002%2Fsignin-oidc&
Seems, punycode like here redirect_uri=http%3A%2F%2Fxn----7sbhbm9amwu.xn--p1ai
would be good, but I dont know where I can handle it.
Moreover, after this warning I catch an exception in kestrel
System.InvalidOperationException: Invalid non-ASCII or control character in header: 0x0433
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameHeaders.ThrowInvalidHeaderCharacter(Char ch)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameHeaders.ValidateHeaderCharacters(String headerCharacters)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameHeaders.ValidateHeaderCharacters(StringValues headerValues)
    ....

So, how can I turn my cyrillic domain to punycode to prevent warning and a Kestrel craching in OpenIdConnectHandler?
UPDATE:
It could be useful
https://github.com/aspnet/Security/issues/1646
Also I've solved a problem by using some workaround
http://amilspage.com/set-identityserver4-url-behind-loadbalancer/

A: Issue is with internationalised domain name you are using.
tldr; OpenID Connect does not allow IDN in redirect URI.
Explanation
OpenID Connect is built on top of OAuth 2.0. Because of that, it inherit key protocol definitions from OAuth 2.0. Below is an extraction of the definition for redirect endpoint
3.1.2.  Redirection Endpoint

The redirection endpoint URI MUST be an absolute URI as defined by
RFC3986 Section 4.3.

According to OAuth 2.0 definition, you cannot use internationalised redirect endpoint since its definition is based on RFC3986 (as shown above)
Now here is the extraction from RFC3986 about characters allowed in URI,
Characters

The ABNF notation defines its terminal values to be non-negative integers (codepoints) based on the US-ASCII coded character set [ASCII].  Because a URI is a sequence of characters, we must invert that relation in order to understand the URI syntax.  Therefore, the integer values used by the ABNF must be mapped back to their corresponding characters via US-ASCII in order to complete the syntax rules.

If you want to convert IDN to valid ASCII, you may use IdnMapping class to do the mapping. This question explains how to use it.
Issues with IDN for OpenID Connect/OAuth 2.0
In OAuth 2.0, you need to validate the redirect URI. So if you are using a IDN, you need to convert it and store it at authorization server. This way you solve one issue, you authorization server would accept redirect uri comes in.
But response for authorization request could be problematic. From your client application, you are using a IDN. But you have registered ASCII value of your redirect endpoint to comply with protocol definition. When authorization server respond back, your client application cannot receive the response as there is no redirection endpoint matching to ASCII value.
If your authorisation server could handle punycode conversions, then problem could be solved in customised manner. But if it can't, only option is to use ASCII based redirection endpoint.


text:
Q: Can't get more than two sections objects in tableview I wanna learn about sections in tableview. Ive been following Jared Davidson youtube tutorial. But i can only add two strings into the objects below the section title. Its like theres somekind of limit?

A: In tableView(_:numberOfRowsInSection:), you need to return the number of rows in the section. Right now you're returning the number of sections (which is what you should, and do, return from numberOfSectionsInTableView(_:)).
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return objectsArray[section].sectionObjects.count
}

A: Its because in your numberOfRowsInSection and numberOfSectionsInTableView delegate functions you get the count of the Objects array which only has two objects in it. Your sections is the object count but your rows are sectionsObject array you are putting in each object in the objects array.


text:
Q: Wikipedia-like references in answers Would it be possible to introduce a feature where we can reference other websites in our answers?
For example, if we answered a question on how to use a method in a library, we could link to the specific part of documentation explaining it on the official website.
Then all the references in that question, or all of the questions, could be found at the bottom of the page like Wikipedia does. You could extend the link code, although links and references should be different, to look something like this...
[Somelink in answer][1]
[ref {
    1: http://www.example.com
    title: A link to the documentation explaining the method
    date: 22/06/2010
}]

This would promote good, well researched answers with evidence to back things up. So users can visit these references perhaps helping them with other questions in the future.
This is poorly explained, but you see my point. Making Stack Overflow more like a wiki will make it a better resource for programmers.

A: Unless I'm missing something, most of this is already there:
Unless I'm missing something, [most of this][1] is already there:

  [1]: https://meta.stackoverflow.com/editing-help
      (link to the documentation explaining the method, retrieved 22/7/2010)

When you say, "like Wikipedia does", are you asking for an auto-generated "list of references" displayed at the bottom of the document (vs. hidden in the source)? That wouldn't necessarily require any changes to syntax, but it might be seen as just additional clutter... And getting people to fill in the additional information would be difficult either way - heck, some folks have enough trouble just understanding how to create links as-is!
See also: jjnguy's answer

A:
Unless I'm missing something, most of this[1] is already there:

Unless I'm missing something, most of this[<sup>\[1\]</sup>][1] is already there:

  [1]: https://meta.stackoverflow.com/editing-help
      (link to the documentation explaining the method, retrieved 22/7/2010)
You can do this already with the given syntax.
Inspiration for this post came from @Shog9's answer.

A: Seconded. A good answer usually comes with references, and this would be a better way of organizing them than in-text links.

A: Thirded? This would further differentiate SE from other Q&A type forums.
Having forms  following a bibliographical standard that an answerer could fill out for both online and offline references would increase the value of the body of sites. As pointed out, references and notes can be done in a hodge podge way by the experts that answer questions, but having a formalized way would encourage the use of references and thus increase the perceived value of the property--and the answers themselves.


text:
Q: How to accept any kind of number into a function as an argument in C#? c#: How do I accept any kind of number into a function as an argument?
Currently my AddDataInt32() asks specifically for Int32, but how I can accept any number, byte, ints signed or unsigned, so I can pass it on to BitConverter.GetBytes()? It's seems silly to write same funct's for each type :(
public void AddDataInt32(Int32 i)
{
    Data = ConcatTwoByteArrays(Data, BitConverter.GetBytes(i));
}

A: You can just overload the method...
public void AddData (Int32 i)
{...}

public void AddData (Int16 i)
{...}

etc. One for each number type. When you make the call to the procedure, it will take any form of number that you've coded, with the same procedure name.

A: Well, you could automate it with reflection and generics, but IMO overloads are the better choice - very much like your existing code.
Reflection / generics example - although I don't really recommend this route:
static void Main()
{
    byte[] bytes = GetBytes(123);
}
static byte[] GetBytes<T>(T value) {
    return Cache<T>.func(value);
}
static class Cache<T> {
    public static readonly Func<T, byte[]> func;
    static Cache() {
        MethodInfo method = typeof(BitConverter)
            .GetMethod("GetBytes", new Type[] { typeof(T) });
        if (method == null) {
            func = delegate { throw new ArgumentException(
                "No GetBytes implementation for " + typeof(T).Name); };
        } else {
            func = (Func<T, byte[]>)Delegate.CreateDelegate(
                typeof(Func<T, byte[]>), method);
        }
    }
}

You would then mix that with an AddData<T> generic method that calls GetBytes<T> etc.

A: public void AddData(object data )
{
}

or
public void AddData<T>( T data )
{
}

Although I think I would prefer overloaded methods.


text:
Q: Parse yaml files in Ansible I have got multiple yaml files on remote machine. I would like to parse those files in order to get information about names for each kind (Deployment, Configmap, Secret) of object, For example:
...
kind: Deployment
metadata:
  name: pr1-dep
...

kind: Secret
metadata:
  name: pr1
...

....
kind: ConfigMap
metadata:
  name: cm-pr1
....

Ecpected result:
3 variables:

*

*deployments = [pr1-dep]

*secrets = [pr1]

*configmaps = [cm-pr1]

I started with:
- shell: cat "{{ item.desc }}"
with_items:
  - "{{ templating_register.results }}"
register: objs

but i have no idea how to correctly parse item.stdout from objs

A: Ansible has a from_yaml filter that takes YAML text as input and outputs an Ansible data structure.  So for example you can write something like this:
- hosts: localhost
  gather_facts: false
  tasks:
    - name: Read objects
      command: "cat {{ item }}"
      register: objs
      loop:
        - deployment.yaml
        - configmap.yaml
        - secret.yaml

    - debug:
        msg:
          - "kind: {{ obj.kind }}"
          - "name: {{ obj.metadata.name }}"
      vars:
        obj: "{{ item.stdout | from_yaml }}"
      loop: "{{ objs.results }}"
      loop_control:
        label: "{{ item.item }}"

Given your example files, this playbook would output:
PLAY [localhost] ***************************************************************

TASK [Read objects] ************************************************************
changed: [localhost] => (item=deployment.yaml)
changed: [localhost] => (item=configmap.yaml)
changed: [localhost] => (item=secret.yaml)

TASK [debug] *******************************************************************
ok: [localhost] => (item=deployment.yaml) => {
    "msg": [
        "kind: Deployment",
        "name: pr1-dep"
    ]
}
ok: [localhost] => (item=configmap.yaml) => {
    "msg": [
        "kind: ConfigMap",
        "name: pr1-cm"
    ]
}
ok: [localhost] => (item=secret.yaml) => {
    "msg": [
        "kind: Secret",
        "name: pr1"
    ]
}

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Creating the variables you've asked for is a little trickier. Here's
one option:
- hosts: localhost
  gather_facts: false
  tasks:
    - name: Read objects
      command: "cat {{ item }}"
      register: objs
      loop:
        - deployment.yaml
        - configmap.yaml
        - secret.yaml

    - name: Create variables
      set_fact:
        names: >-
          {{
            names|combine({
              obj.kind.lower(): [obj.metadata.name]
            }, list_merge='append')
          }}
      vars:
        names: {}
        obj: "{{ item.stdout | from_yaml }}"
      loop: "{{ objs.results }}"
      loop_control:
        label: "{{ item.item }}"

    - debug:
        var: names

This creates a single variable named names that at the end of the
playbook will contain:
{
    "configmap": [
        "pr1-cm"
    ],
    "deployment": [
        "pr1-dep"
    ],
    "secret": [
        "pr1"
    ]
}

The key to the above playbook is our use of the combine filter, which can be used to merge dictionaries and, when we add list_merge='append', handles keys that resolve to lists by appending to the existing list, rather than replacing the existing key.

A: Include the dictionaries from the files into the new variables, e.g.
    - include_vars:
        file: "{{ item }}"
        name: "objs_{{ item|splitext|first }}"
      register: result
      loop:
        - deployment.yaml
        - configmap.yaml
        - secret.yaml

This will create dictionaries objs_deployment, objs_configmap, and objs_secret. Next, you can either use the dictionaries
    - set_fact:
        objs: "{{ objs|d({})|combine({_key: _val}) }}"
      loop: "{{ query('varnames', 'objs_') }}"
      vars:
        _obj: "{{ lookup('vars', item) }}"
        _key: "{{ _obj.kind }}"
        _val: "{{ _obj.metadata.name }}"

, or the registered data
    - set_fact:
        objs: "{{ dict(_keys|zip(_vals)) }}"
      vars:
        _query1: '[].ansible_facts.*.kind'
        _keys: "{{ result.results|json_query(_query1)|flatten }}"
        _query2: '[].ansible_facts.*.metadata[].name'
        _vals: "{{ result.results|json_query(_query2)|flatten }}"

Both options give
  objs:
    ConfigMap: cm-pr1
    Deployment: pr1-dep
    Secret: pr1


text:
Q: El archivo program.exe tiene un hash calculado distinto al especificado en el manifiesto Este es el problema que tenía, busque por internet pero no encontré nada, pero ahora que lo pude solucionar hago la pregunta para auto responderme y lleva la solución que esta tan simple cómo borrar un archivo.
La activación de C:\Users..\Session1.application dio como resultado una excepción. Se detectaron los siguientes mensajes de error:

*

*El archivo Session1.mdf tiene un hash calculado distinto al especificado en el manifiesto.

A: la solución es muy simple solo debes de borrar el archivo .pfx, en el ejemplo de la imagen es TemporaryKey.pfx
y volver hacer los pasos para crear el instalador.


text:
Q: ImportError: cannot import name '_path' matplotlib When importing matplotlib by import matplotlib.pyplot as plt I'm getting the following error:
Traceback (most recent call last):   File "mode.py", line 1, in <module>
    import matplotlib.pyplot as plt   File "C:\Users\yuhan\AppData\Roaming\Python\Python36\site-packages\matplotlib\pyplot.py", line 32, in <module>
    import matplotlib.colorbar   File "C:\Users\yuhan\AppData\Roaming\Python\Python36\site-packages\matplotlib\colorbar.py", line 32, in <module>
    import matplotlib.artist as martist   File "C:\Users\yuhan\AppData\Roaming\Python\Python36\site-packages\matplotlib\artist.py", line 16, in <module>
    from .path import Path   File "C:\Users\yuhan\AppData\Roaming\Python\Python36\site-packages\matplotlib\path.py", line 25, in <module>
    from . import _path, rcParams ImportError: cannot import name '_path'

I tried reinstalling the whole matplotlib library, tried re-installing Python 3.6 etc. I really do not know what is wrong and since I don't have a backup.

A: py -m pip uninstall matplotlib

then:
py -m pip install matplotlib

worked for me for that error as well.
Then I had a problem of kiwisolver not being found, and did the same
uninstall, install for kiwisolver and now:
import matplotlib.pyplot as plt works.

A: This problem can pop up when you copy libraries from place to place (at least that's what happend with me :P)
Make sure that in .../Python37/Lib/site-packages there is a file named:
matplotlib-3.0.2-py3.7-nspkg.pth
with the correct version of Python and matplotlib
(in this example I am using python 3.7.1 and matplotlib 3.0.2)
If that's not the case, reinstall matplotlib like other users suggested.
Make sure also that you are targeting the correct directory (sometimes I've seen that the problem might be the wrong version of pip)


text:
Q: I have the following code about the current date and time so, how do I add day in current time? <script>
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
</script>

A: Try this:
tomorrow = new Date(today.getTime() + 1000 * 60 * 60 * 24)

One day equals 24h = 24 * 60 minutes = 24 * 60 * 60 seconds = 24 * 60 * 60 * 1000 miliseconds
Edit: I might have misunderstood the question, but if what you want to achieve is adding 1 day to your variable, this will work.

A: You can use toLocaleString() Date method to get that format

let actualDate = new Date().toLocaleString();           // Output: d/m/yyyy h:mm:ss
console.log(actualDate)

A: If you're looking for the day of the week, then today.getDay() will return a numerical day of the week from 0-6. You could then use an array with the day names in to refer to the text for the day of the week.
For example:
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];

var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate()+'-'+days[today.getDay()];

A: A nextDay function...
const nextDay = () => { return new Date(parseInt(new Date().getTime()) + 60*60*24*1000).toLocaleString() };

const nextDay = () => { return new Date(parseInt(new Date().getTime()) + 60*60*24*1000).toLocaleString() };
console.log(nextDay());


text:
Q: Fix this phong shader for me where to put the lights or vertex position with custom baked normals My goal is to create a bevel effect for a flat 2d sprite. Where the edges are the start of non transparent pixels.
I've tried this approach Create a bevel effect on non-rectangular shapes in Javascript. And figured I would go with a phong shader.
I copied code from this example http://www.cs.toronto.edu/~jacobson/phong-demo/.
I built normals from custom math along with distance to transparent pixels.
I am not sure I am putting the values correctly but light position and vertex position are uniforms so I can tweak them. Vertex position not sure what it corresponds to but I use texture coordinates, which is pretty close for a quad texture.
I get results like this:

But they get pretty off lightining, but seems pretty close. I figure if I set those at the right position this will show bevel highlight on the edges like I wanted.
precision mediump float;

varying vec2 vTextureCoord;
uniform sampler2D uSampler;
uniform vec4 filterArea;

//uniform float transformX;
//uniform float transformY;

const float transformX = 10.0;
const float transformY = 10.0;

bool isalpha(vec2 uv, vec2 offset) {
  vec4 color = texture2D(uSampler, uv - offset);

  return color.a < 0.001;
}

float getdistancetoedge(vec2 uv) {
  float mindistance = 1.0;
  vec2 dir = vec2(1.0 / filterArea) * vec2(transformX, transformY);

  for (int i=0; i <= 20; i++) {
    vec2 vdist = dir * 0.05 * float(i);
    bool alpha = isalpha(uv, vdist);

    if (alpha) {
      mindistance = min(float(i) * 0.05, mindistance);
    }
  }
  return mindistance;
}

const float Kd = 1.0;
const float Ks = 20.0;
const vec3 specularColor = vec3(1.0);
const float shininessVal = 4.0;

uniform vec3 lightPos;
uniform float vertZ;

void main(void) {
  vec4 color = texture2D(uSampler, vTextureCoord);

  vec3 vertPos = vec3(-vTextureCoord, vertZ);

  float dist = getdistancetoedge(vTextureCoord);
  float na = 3.1415 * 0.5 + atan(0.5, dist);

  mat2 rotation = mat2(cos(na), -sin(na), sin(na), cos(na));
  vec2 x_axis = vec2(1.0, 0.0);
  vec2 u_normal = rotation * x_axis;

  vec3 N = vec3(u_normal, 1.0);
  vec3 L = normalize(lightPos - vertPos);
  float specular = 0.0;
  float lambertian = max(dot(N, L), 0.0);

  vec3 R;
  vec3 V;
  float specAngle;
  if (lambertian > 0.0) {
    R = reflect(-L, N);
    V = normalize(-vertPos);
    specAngle = max(dot(R, V), 0.0);
    specular = pow(specAngle, shininessVal);
  }

  color = vec4(Kd * lambertian * color.rgb + Ks * specular * specularColor, 1.0);
  gl_FragColor = vec4(color.rgb * color.a, color.a);
}


text:
Q: Blueprints plugin for Cytoscape, Gephi etc I'm building UI to visualize and edit graph which is present in a gremlin store.
Which framework is better Cytoscape.js vs Gephi.js Vs other?
Do these frameworks have Blueprints plugin available? I want to avoid writing  module to convert the gremlin output to the framework compatible format.
Please advice. Thanks.

A: Answer from the Cytoscape development team...
Well, there are a number of ways you can use Cytoscape with TinkerPop, but I would think that the best way would be to use the REST interface to Cytoscape and inject your graph directly into it.  You could save your graph as a Neo4j database and use the Neo4j app to pull it into Cytoscape or save your graph as a GraphML or some other common graph format and read it in that way.  Neither Cytoscape or Gephi are UI frameworks, though -- both are standalone applications that are designed to import, visualize, analyze and manipulate very large graphs.
A good place to start is on the Cytoscape Automation topic in the Cytoscape manual: http://manual.cytoscape.org/en/stable/Programmatic_Access_to_Cytoscape_Features_Scripting.html

A: No matter which library you use for graphs on the web, you're going to have to convert your model to the JSON format used by the library (e.g. the Cytoscape JSON format if you use Cytoscape desktop or Cytoscape.js).


text:
Q: JavaFX with FXML Tableview not displaying I've been searching all over for what I'm doing wrong but somehow I'm missing something. I've commented out and rewrote so much code that it's starting to be a mess (totally my fault) so hopefully I can find a solution.
I am using a FXML form to make a list of Attack class objects. The form pulls up, I type the required entries, hit the add attack button and the table does not populate.  Here is the pertinent code:

Classes involved
 public class Attack {

       import javafx.beans.property.SimpleStringProperty;

public class Attack {

    private final SimpleStringProperty weapon = new SimpleStringProperty("");
    private final SimpleStringProperty range= new SimpleStringProperty("");
    private final SimpleStringProperty damage= new SimpleStringProperty("");
    private int attackBonus;

    public String getRange(){return range.get();}
    public String getName(){return weapon.get();}
    public String getDamage(){return damage.get();}
    public int getAttackBonus(){return attackBonus;}

    public void setRange(String newRange){range.set(newRange);}
    public void setWeapon(String newName){weapon.set(newName);}
    public void setAttackBonus(int atkBonus){this.attackBonus = atkBonus;}
    public void setDamage(String dmg){damage.set(dmg);}

    Attack(String nameIn, int AB, String rangeIn, String damageIn){

      setWeapon(nameIn);
      setDamage(damageIn);
      setRange(rangeIn);
      setAttackBonus(AB);

    };

    Attack(){
       this("", 0, "", "");
    }
}

Controller Class
package sample;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.Stage;

public class AddNPC{

    @FXML
    private Button save, addAttack;

    @FXML
    private TextField ac, hp, init, initBonus, fort, will, ref, weapon, attackBonus, damage;
    @FXML
    private RadioButton melee, touch, ranged, rangedTouch;
    @FXML
    private ToggleGroup range;

    @FXML
    private NPC monster;

    @FXML
    private Stage dialogStage;

   @FXML
    private final TableView<Attack> attackTableView = new TableView<>();

    @FXML
    private TableColumn<Attack, String> weaponColumn;
    @FXML
    private TableColumn<Attack, String> attackColumn;
    @FXML
    private TableColumn<Attack, String> rangeColumn;
    @FXML
    private TableColumn<Attack, String> damageColumn;

    Dice d = new Dice(1, 3, 1);

   /* @FXML
    private final ObservableList<Attack> atk = FXCollections.observableArrayList();

    public ObservableList<Attack> getAtk(){
        return atk;
    }*/

    //public AddNPC(){};

    @FXML
    public void initialize(){

        getAttack();

    }

    public ObservableList<Attack> getAttack(){
        ObservableList<Attack> attacks = FXCollections.observableArrayList();

        attacks.add(new Attack("Unarmed", 0, "melee", "1d3"));
        return attacks;
    }

    @FXML
    private void handleButtonAction(ActionEvent event){

        //event for save here but not shown

        if(event.getSource() == addAttack){

            String weaponIn = weapon.getText();
            int bonusIn = Integer.parseInt(attackBonus.getText());
            String rangeIn = range.getSelectedToggle().getUserData().toString();
            String damageIn = damage.getText();

            Attack attack = new Attack(weaponIn, bonusIn, rangeIn, damageIn);

            attackTableView.getItems().add(attack);

            attackBonus.clear();
            weapon.clear();
            damage.clear();

        }

    }

}

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.RadioButton?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.ToggleGroup?>
<?import javafx.scene.control.cell.PropertyValueFactory?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.shape.Line?>
<?import javafx.scene.text.Font?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="541.0" prefWidth="453.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.AddNPC">
   <children>
      <TextField fx:id="name" layoutX="70.0" layoutY="74.0" prefHeight="25.0" prefWidth="127.0" promptText="Name" />
      <TextField fx:id="hp" layoutX="71.0" layoutY="114.0" prefHeight="25.0" prefWidth="38.0" promptText="HP" />
      <TextField fx:id="ac" layoutX="125.0" layoutY="114.0" prefHeight="25.0" prefWidth="38.0" promptText="AC" />
      <TextField fx:id="init" layoutX="179.0" layoutY="114.0" prefHeight="25.0" prefWidth="68.0" promptText="Initiative" />
      <TextField fx:id="initBonus" layoutX="261.0" layoutY="114.0" prefHeight="25.0" prefWidth="98.0" promptText="Initiative Bonus" />
      <TextField fx:id="fort" layoutX="71.0" layoutY="153.0" prefHeight="25.0" prefWidth="38.0" promptText="Fort" />
      <TextField fx:id="will" layoutX="125.0" layoutY="153.0" prefHeight="25.0" prefWidth="38.0" promptText="Will" />
      <TextField fx:id="ref" layoutX="181.0" layoutY="153.0" prefHeight="25.0" prefWidth="57.0" promptText="Reflex" />
      <Button fx:id="save" layoutX="202.0" layoutY="502.0" mnemonicParsing="false" onAction="#handleButtonAction" text="Save" />
      <Button fx:id="addAttack" layoutX="185.0" layoutY="293.0" mnemonicParsing="false" onAction="#handleButtonAction" text="Add Attack" />

      <TextField fx:id="weapon" layoutX="65.0" layoutY="224.0" promptText="Weapon Name" />
       <TextField fx:id="attackBonus" layoutX="232.0" layoutY="224.0" prefHeight="25.0" prefWidth="47.0" promptText="Bonus" />
      <TextField fx:id="damage" layoutX="292.0" layoutY="224.0" prefHeight="25.0" prefWidth="83.0" promptText="damage" />
      <RadioButton fx:id="melee" contentDisplay="TOP" layoutX="69.0" layoutY="253.0" mnemonicParsing="false" prefHeight="35.0" prefWidth="75.0" selected="true" text="Melee" textAlignment="CENTER" userData="melee">
         <toggleGroup>
            <ToggleGroup fx:id="range" />
         </toggleGroup></RadioButton>

      <RadioButton fx:id="touch" layoutX="144.0" layoutY="262.0" mnemonicParsing="false" text="Touch" toggleGroup="$range" userData="touch" />
      <RadioButton fx:id="ranged" layoutX="214.0" layoutY="262.0" mnemonicParsing="false" text="Range" toggleGroup="$range" userData="ranged" />
      <RadioButton fx:id="rangedTouch" layoutX="279.0" layoutY="262.0" mnemonicParsing="false" text="Ranged Touch" toggleGroup="$range" userData="rangedTouch" />
      <Line endX="100.0" layoutX="222.0" layoutY="204.0" startX="-100.0" />
      <TableView fx:id="attackTableView" layoutX="18.0" layoutY="332.0" prefHeight="154.0" prefWidth="418.0">
        <columns>
          <TableColumn fx:id="weaponColumn" prefWidth="107.0" text="Weapon">
            <cellValueFactory>
               <PropertyValueFactory property="weapon" /></cellValueFactory>
          </TableColumn>
          <TableColumn fx:id="attackColumn" prefWidth="69.0" text="Atk Bonus">
            <cellValueFactory>
              <PropertyValueFactory property="attackBonus" /></cellValueFactory>
            </TableColumn>
           <TableColumn fx:id="rangeColumn" prefWidth="59.0" text="Range">
            <cellValueFactory>
              <PropertyValueFactory property="range" /></cellValueFactory>
            </TableColumn>
           <TableColumn fx:id="damageColumn" prefWidth="181.0" text="Damage">
            <cellValueFactory>
              <PropertyValueFactory property="damage" /></cellValueFactory>
            </TableColumn>
        </columns>

      </TableView>
   </children>
</AnchorPane>

Hopefully I'm not missing anything.


text:
Q: Hosting site Asp.net MVC and SQL Server Compact 4 In my ISP, they must hire service SQL Server to host a  sql server compact framework?
The fact that MVC requires the host to have some extra service? Or a simple hosting plan already supports asp.net MVC?

A: You can bin-deploy SQL CE 4. Just make sure you are using the RTM version because there was a problem with bin-deployment in betas. Also see Scott Gu's blog post about it.
ASP.NET MVC 3 can also be bin-deployed if your hosting provider doesn't have the assemblies installed in the GAC. All that's need is .NET 4.0.
This being said SQL CE is an embedded database and not designed to work in a heavy multithreaded environments such as ASP.NET. It is good for development and light-usage scenarios.  For high-volume sites and applications you'll probably want to migrate it to use SQL Server Express or SQL Server.


text:
Q: How to join these two tables to get results as api resource? am having two tables one is the main client table and the other one is a sub-client table, The sub-clients is a client of the main client that is the primary key of the main client is in sub-client table how can i join these two tables and take the output in controller to pass over the resource as JSON for API ??
This is my model of the main client :
 namespace App;

    use Illuminate\Database\Eloquent\Model;

        class Clients extends Model
            {
                  //
                    }

This is my Controller of the main client :
namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use App\Clients;
    use App\Http\Resources\Client as ClientResource;

        // use Illuminate\Http\Response;

    class Clients_controller extends Controller
        {
          /**
             * Display a listing of the resource.
           *
            * @return \Illuminate\Http\Response
                 */
         public function index()
          {
                   //get clients

                       $clients = Clients::paginate(15);

                   //Return collection of clients as a resource
                   return ClientResource::collection($clients);
              }
                    }

This is my model of the Sub client :
 namespace App;

            use Illuminate\Database\Eloquent\Model;

            class Sub_clients extends Model
            {
                //
            }

This is my Controller of the sub-client :
 namespace App\Http\Controllers;

            use Illuminate\Http\Request;
            use App\Sub_clients;
            use App\Http\Resources\Sub_client as SubclientResource;

            class Sub_client extends Controller
            {
               /**
               * Display a listing of the resource.
              *
                 * @return \Illuminate\Http\Response
              */
          public function index()
           {
                //get Sub_clients

                 $subclients = Sub_clients::paginate(15);

                 //Return collection of sub clients as a resource
                  return SubclientResource::collection($subclients);
             }
                }

Can anyone please help since am new to laravel

A: I joined using Query Builder
  $client = DB::table('clients')
          ->join('sub_clients', 'clients.c_id', '=', 'sub_clients.c_id')
          ->select('clients.*', 'sub_clients.password', 'sub_clients.username as name')
          ->where('sub_clients.c_id','=',$c_id)
          ->get();


text:
Q: Pgfplots: How do I change plot line width independently of axis line width? I can use something like \pgfplotsset{every axis/.append style={line width=1pt}} to make all lines 1pt thick, but I would like to make only the plot lines thicker.
I can do this on a per-plot-basis with \addplot [thick] ..., but how can I set it for all plots?

A: I found this non-obvious to find out, but there is a plot "type" or whatever the name is, which means, this will work:
\begin{tikzpicture}[every plot/.append style={very thick}]

Or
\begin{tikzpicture}[every axis plot/.append style={very thick}]

Or
\pgfplotsset{every axis plot/.append style={very thick}}

Make sure to also use "every axis plot" in the \pgfplotsset in order to work properly.


text:
Q: Android linear layout for horizontal dependent view I have a layout defined below which render two views - view1 and view2. For smaller screen sizes, the view2 is distorted.
Question - View2 needs to appear in the right side and view1 will accommodate whatever spaces remains at the left side. View2 is very constant in terms of dimension, drawable is well defined.
How can i achieve that? Thanks in advance.
<LinearLayout
          android:orientation="horizontal"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">

            <TextView
              android:id="@+id/view1"
              android:layout_height="wrap_content"
              android:layout_width="wrap_content"
              android:maxLines="1"
              android:ellipsize="end"
              android:textSize="9pt"
              android:layout_weight = "0"
              android:maxWidth="260dp"
              android:minWidth="260dp"/>

            <TextView
              android:id="@+id/view2"
              android:textStyle="bold"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_gravity="end"
              android:paddingStart="10dp"
              android:paddingEnd="10dp"
              android:background="@drawable/some_drawable"/>
</LinearLayout>

I tried layout_width but couldn't achieve the result I am looking for. I'm newbie to android, any pointer would also be very helpful.

A:  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/view1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="7"
        tools:text="view1" />

    <TextView
        android:id="@+id/view2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        tools:text="view2" />
</LinearLayout>

use

android:layout_weight=""

view1 use 70% of screen (android:layout_weight="7")
view2 use 30% of screen (android:layout_weight="3")

A: for view2 keep
android:layout_width="wrap_content"
android:layout_height="wrap_content"

and set this for view1:
android:layout_width="0dp"
android:layout_weight="1"

this will make view 1 expand in the remaining width


text:
Q: Python - Get second smallest number without using array I want to print the second smallest number without using any array but it doesn't work. This is what I've done so far.
numbers = 5
print('Enter your numbers\n')

for x in range(0, numbers):
    use = input('Enter #' + str(x + 1) + ': ')
    if x == 0:
        small = int(use)
        second = small
    if int(use) < small:
        small = int(use)
        if small > second:
            second = int(use)

print('\nSecond smallest number is ' + str(second))

A: code:
numbers = 5
min = 2**32
second_min = 2**32
print('Enter your numbers\n')

for x in range(numbers):
    use = input('Enter #' + str(x + 1) + ': ')
    if int(use) < min:
        min = int(use)
    elif int(use) >= min and int(use) < second_min:
        second_min = int(use)

print('\nSecond smallest number is ' + str(second_min))

result:
Enter your numbers

Enter #1: 5
Enter #2: 6
Enter #3: 7
Enter #4: 8
Enter #5: 9

Second smallest number is 6

A: numbers = 5
print('Enter your numbers\n')

small = float('inf')
second = float('inf')

for x in range(0, numbers):
    use = int(input('Enter #' + str(x + 1) + ': '))
    if use < small:
       small = use
    if use > small and use < second:
        second = use

print('\nSecond smallest number is ' + str(second))

P.S. float('inf') is most biggest number

A: This works without lists and for number in any order.
numbers = 5
print('Enter your numbers\n')
#Instead of using lists, we'll use variables to store the smallest numbers. We'll give them the initial value of 0.
smallest = 0
secondsmallest = 0

for x in range(0, numbers):
    #We get the user input and convert it to int.
    use = int(input('Enter #' + str(x + 1) + ': '))
    #If the smallest variable hasn't been touched, i.e., it's the first time the for loop is run, we assign the current input to be the smallest number.
    if smallest == 0:
        smallest = use
    #Else if the current input is smaller than the current smallest number, then it should be the new smallest number.
    elif use < smallest:
        smallest = use
    #Else if the current input is greater than the smallest and the secondsmallest number still is untouched then the current input should be the secondsmallest.
    elif use > smallest and secondsmallest == 0:
        secondsmallest = use
    #Else if the current input is less than the secondsmallest, then it should be the new secondsmallest.
    elif use < secondsmallest:
        secondsmallest = use

print(secondsmallest)

A: Code:
nums = [1, 2, 9, 11, 13]
for counter,num in enumerate(nums):

    if counter == 0:
        smallest = num
    if counter == 1:
        second = num
    if counter > 1:
        if second == smallest:
            second = num
        if num < second:
            second = num
        if second < smallest:
            smallest, second = second, smallest

print(second)

Here is the algorithm of my approach :

*

*First initialise the smallest and second smallest numbers to be the first two inputs. That is, Smallest=First_Input and second_smallest = Second_Input. These lines do that:

    if counter == 0:
        smallest = num
    if counter == 1:
        second = num

*Next See the third number. If the third number is smaller than the second_smallest number, then swap them. These lines do that

    # This part is executed only when the counter exceeds 1
    # That is, from the third input onwards.
    if num < second:
        second = num

*Now See the smallest and second_smallest number. If second_smallest < smallest , then swap them. These lines do that:

    if second < smallest:
        smallest, second = second, smallest

*Now, there will be an edgecase for inputs [smallest, smallest, x, y, z] . That is, when smallest number is repeated. It is because, the smallest and second variables store the first smallest and second smallest numbers respectively. But when the smallest number is repeated, they both store the same value(i.e the smallest value). Therefore in this case, the actual second_smallest value will not be able to replace the value in second(since second stores the smallest in this case)
To fix this, We have this line of code :

     if second == smallest:
         second = num

A: We can solve the problem by using another one temp variable.
Let's assume to input one variable - v.
First, compare v with the smallest number.
If v is smaller than the smallest number, the smallest number will be v and the second small number will be a previous smallest number.
Second, if v is equal or bigger than the smallest number, compare with the second small number and handle it.
import sys
numbers = 5
second = sys.maxsize
smallest = sys.maxsize

for x in range(0, numbers):
    use = int(input('Enter #' + str(x + 1) + ': '))
    if use < smallest:
      second = smallest
      smallest = use
    elif use < second:
      second = use

print('\nSecond smallest number is ' + str(second))


text:
Q: Errno 1 Operation not permitted kivy selenium python buildozer I'm trying to use selenium with kivy and buildozer, to run selenium automation on my phone.
So for this code I tried to have selenium get google.com and get a text from an xpath.
The code:
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.utils import platform
if platform == "android":
    from android.permissions import request_permissions, Permission
    request_permissions([Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE])
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

try:
    PATH = "C:\Program Files (x86)\chromedriver.exe"
    options = Options()
    options.add_argument("--headless")
    options.add_experimental_option('androidPackage', 'com.android.chrome')
    driver = webdriver.Chrome(PATH, options=options)

    kivy.require("1.9.1")

    class MyRoot(BoxLayout):

        def __init__(self):
            super(MyRoot, self).__init__()

        def get_codes(self):
            driver.get("https://google.com") # getting google with selenium
            codes = driver.find_element(By.XPATH, /html/body/div[1]/div[3]/form/div[1]/div[1]/div[3]/center/input[1]).text # getting the text
            self.code1.text = codes # Showing the text in the app

    class application_(App):
        def build(self):
            return MyRoot()

    application_ = application_()
    application_.run()

except Exception as err: # Handling expectation and showing the error in the app
    kivy.require("1.9.1")

    class application_(App):
        def build(self):
            return Label(text=f"Crash {err}")

    application_ = application_()
    application_.run()

compiling is successful but when I try to run it on my phone I get an exception:

[Errno 1] Operation not permitted

LOGS

java.lang.ClassCastException: android.os.AsyncTask$AsyncTaskResult
cannot be cast to android.app.servertransaction.ClientTransaction

    at android.app.ActivityInjector.checkAccessControl(ActivityInjector.java:24)
    at android.app.Activity.onResume(Activity.java:2011)
    at org.libsdl.app.SDLActivity.onResume(SDLActivity.java:315)
    at org.kivy.android.PythonActivity.onResume(PythonActivity.java:551)
    at org.kivy.android.PythonActivity$UnpackFilesTask.onPostExecute(PythonActivity.java:202)
    at org.kivy.android.PythonActivity$UnpackFilesTask.onPostExecute(PythonActivity.java:102)
    at android.os.AsyncTask.finish(AsyncTask.java:771)
    at android.os.AsyncTask.access$900(AsyncTask.java:199)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:788)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:236)
    at android.app.ActivityThread.main(ActivityThread.java:8061)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)

I've done some debugging and what seems to cause the problem is the line:
driver = webdriver.Chrome(PATH, options=options)

What I have tried:

*

*I tried to remove the options=options to see if it will work, as expected it didn't

*I tried to import android permissions to write and read storage, didn't work

*Tried to add options.add_experimental_option('androidPackage', 'com.android.chrome') to chrome options, didnt work

*I gave all the requirements in the buildozer.spec:
requirements = python3,kivy,selenium,urllib3,android

*I looked up info online but I couldn't find anything that would help me.
Thanks in advance.